Home > other >  How to mock client IP on fastapi.testclient.TestClient?
How to mock client IP on fastapi.testclient.TestClient?

Time:11-29

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

CodePudding user response:

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"}
  • Related