如何在fastapi.testclient.testclient上模拟客户端IP


例如,假设您正在使用fastapi.testclient.testclient执行GET。在定义该GET方法的API代码中,如果您得到request.client.host,您将得到字符串";测试客户端";。

测试,使用pytest:

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

现在,让我们假设您的API代码是这样的:

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

endoit/my_ip假定返回客户端ip,但在运行pytest时,它将返回";测试客户端";一串是否有一种方法可以将TestClient上的客户端IP(主机(更改为";testclient";?

您可以将fastapi.Request.client属性模拟为,

# 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"}

最新更新