You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在fastapi.testclient.TestClient中模拟自定义客户端IP地址?

解决方案

这里提供两种可直接落地的方案,按需选择即可:

方案1:仅修改测试代码,无需调整业务逻辑(纯测试场景推荐)

TestClient 发起请求时支持直接传入 client 参数自定义客户端地址,参数格式为(自定义IP字符串, 端口号),端口可任意填写,不影响request.client.host的取值:

def test_success_with_custom_ip(self):
    client = TestClient(app)
    # 自定义客户端IP为 192.168.1.100
    response = client.get(
        "/my_ip",
        client=("192.168.1.100", 12345)
    )
    # 验证返回值符合预期
    assert response.text == '"192.168.1.100"'

方案2:兼容生产+测试场景,通过请求头传递IP

如果你的服务会部署在Nginx等反向代理后,建议直接在业务代码中适配X-Forwarded-For请求头,一套逻辑同时覆盖测试和生产环境:

调整后的业务接口代码

@router.get('/my_ip')
def my_ip(request: Request):
    # 优先取X-Forwarded-For头的IP,处理多代理场景下取第一个值为真实客户端IP
    if x_forwarded_for := request.headers.get("X-Forwarded-For"):
        return x_forwarded_for.split(",")[0].strip()
    return request.client.host

对应测试代码

def test_success_with_custom_ip(self):
    client = TestClient(app)
    response = client.get(
        "/my_ip",
        headers={"X-Forwarded-For": "192.168.1.100"}
    )
    assert response.text == '"192.168.1.100"'

内容的提问来源于stack exchange,提问作者Diogo Melo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:54:02