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

使用HTTPX+RESPX+Pytest测试时遭遇URL类型错误

错误原因分析

从报错栈可以看到,核心问题是respx在模拟请求时将URL解析成了字节元组(b'http', b'127.0.0.1', 8080, b'/geoserver/rest/workspaces'),但httpx的URL构造函数只接受字符串或httpx.URL对象,导致类型不匹配抛出TypeError。

这个问题通常出现在respx对带base URL的客户端请求进行匹配时,内部URL解析逻辑出现异常,或者测试代码中URL拼接的方式和客户端实际请求的URL格式不兼容。

解决方法

以下是几种可行的修复方案:

方案1:改用精确字符串匹配

直接使用完整的URL字符串进行匹配,避免respx内部解析URL时出错:

baseUrl = "http://127.0.0.1:8080/geoserver/rest/"

def test_get_all_workspaces_validation(
    client: SyncGeoServerX, bad_workspaces_connection, respx_mock):
    # 直接用完整的URL字符串匹配
    respx_mock.get("http://127.0.0.1:8080/geoserver/rest/workspaces").mock(
        return_value=httpx.Response(404, json=bad_workspaces_connection)
    )
    response = client.get_all_workspaces()
    assert response.code == 404

方案2:使用httpx.URL对象构造匹配目标

显式用httpx.URL包装匹配的URL,确保respx使用正确的URL类型:

from httpx import URL

baseUrl = "http://127.0.0.1:8080/geoserver/rest/"

def test_get_all_workspaces_validation(
    client: SyncGeoServerX, bad_workspaces_connection, respx_mock):
    target_url = URL(f"{baseUrl}workspaces")
    respx_mock.get(target_url).mock(
        return_value=httpx.Response(404, json=bad_workspaces_connection)
    )
    response = client.get_all_workspaces()
    assert response.code == 404

方案3:升级respx到最新稳定版

部分旧版本的respx存在URL解析的bug,升级到最新版本可以解决此类问题:

pip install --upgrade respx

方案4:检查客户端base URL配置

确保SyncGeoServerX的http_client的base URL是标准字符串格式,没有多余的斜杠或编码问题,比如确认base URL末尾的斜杠和请求路径workspaces拼接后是正确的格式(http://127.0.0.1:8080/geoserver/rest/workspaces)。


内容的提问来源于stack exchange,提问作者krishna lodha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:24:54