例如,假設您正在使用 fastapi.testclient.TestClient 來執行 GET。在定義該 GET 方法的 API 代碼中,如果您獲得 request.client.host,您將獲得字串“testclient”。
測驗,使用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
端點 /my_ip 假設回傳客戶端 IP,但在運行 pytest 時,它將回傳“testclient”字串。有沒有辦法將 TestClient 上的客戶端 IP(主機)更改為“testclient”以外的其他內容?
uj5u.com熱心網友回復:
你可以嘲笑這個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"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372020.html
