【问题标题】:How to mock client IP on fastapi.testclient.TestClient?如何在 fastapi.testclient.TestClient 上模拟客户端 IP?
【发布时间】:2021-11-27 01:20:00
【问题描述】:

例如,假设您正在使用 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

endpoit /my_ip 假设返回客户端 IP,但是在运行 pytest 时,它将返回“testclient”字符串。有没有办法将 TestClient 上的客户端 IP(主机)更改为“testclient”以外的其他内容?

【问题讨论】:

    标签: python testing fastapi


    【解决方案1】:

    您可以将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"}
    

    【讨论】:

    • 什么是“嘲笑者”夹具?我如何获得它?
    • 你需要安装pytest-mock包
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多