1

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"?

3 Answers 3

2

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"}
Sign up to request clarification or add additional context in comments.

2 Comments

What is the "mocker" fixture? How do I get it?
You need to install the pytest-mock package
0

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')

Comments

0

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():
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.