Diogo Melo
Diogo Melo

Reputation: 2163

How to mock client IP on fastapi.testclient.TestClient?

Say you are using fastapi.testclient.TestClient to perform a GET, for instance. Inside the API code that defines that GET method, if you get request.client.host, you will get the string "testclient".

Test, using pytest:

def test_success(self):
    client = TestClient(app)
    client.get('/my_ip')

Now, lets assume your API code is something like this:

@router.get('/my_ip')
def my_ip(request: Request):
    return request.client.host

The endpoit /my_ip is suppose to return the client IP, but when running pytest, it will return "testclient" string. Is there a way to change the client IP (host) on TestClient to something other than "testclient"?

Upvotes: 1

Views: 3727

Answers (3)

Razvan Tudorica
Razvan Tudorica

Reputation: 475

you can patch it directly with unittest.mock library.

from unittest.mock import patch

@patch('fastapi.Request.client', Address('WHATEVER_YOU_WANT', 1234))
def test_success():
...

Upvotes: 0

Aliaksei Protchanka
Aliaksei Protchanka

Reputation: 1

You can mock the fastapi.Request.client.host property by using PropertyMock:

import pytest
from fastapi import FastAPI
from pytest_mock import MockerFixture
from starlette.testclient import TestClient
from fastapi import Request
from starlette.datastructures import Address

app = FastAPI()


@app.get('/my_ip')
def my_ip(request: Request):
    return request.client.host


@pytest.fixture(scope="session")
def client_for_test() -> TestClient:
    client_for_test = TestClient(app=app)
    return client_for_test


def test_success(client_for_test: TestClient, mocker: MockerFixture):
    mocker.patch.object(Address, "host", return_value="114.251.75.235", new_callable=mocker.PropertyMock)
    response = client_for_test.get('/my_ip')

Upvotes: 0

JPG
JPG

Reputation: 88429

You can mock the fastapi.Request.client property as,

# main.py

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
def root(request: Request):
    return {"host": request.client.host}

# test_main.py

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def test_read_main(mocker):
    mock_client = mocker.patch("fastapi.Request.client")
    mock_client.host = "192.168.123.132"
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"host": "192.168.123.132"}

Upvotes: 2

Related Questions