使用pytest测试Azure Functions时,如何解决相对路径URL的MissingSchema错误?
解决pytest测试Azure Functions时相对路径URL报错的问题
问题根源
requests库发起请求时必须接收完整的URL(包含协议头如http://和主机地址如localhost:7071),直接传入/marketplace这类相对路径会因缺少协议和主机信息,触发requests.exceptions.MissingSchema错误。
解决方案
1. 提取基础URL常量,拼接相对路径
将本地Azure Functions的基础地址抽成常量,每次请求时拼接相对路径,既保持代码整洁,也方便后续切换测试/生产环境。
示例代码:
import pytest import requests # 定义基础URL常量 BASE_API_URL = "http://localhost:7071" def test_marketplace_root(): # 拼接基础URL和相对路径 response = requests.get(f"{BASE_API_URL}/marketplace") assert response.status_code == 200 def test_marketplace_themes(): response = requests.get(f"{BASE_API_URL}/marketplace/themes") assert response.status_code == 200 def test_marketplace_item_detail(): response = requests.get(f"{BASE_API_URL}/marketplace/2") assert response.status_code == 200
2. 封装API客户端类(推荐)
如果测试用例较多,可封装一个API客户端类,统一处理URL拼接和会话管理,减少重复代码:
import requests import pytest class AzureFunctionsAPIClient: def __init__(self, base_url): self.base_url = base_url self.session = requests.Session() # 复用会话提升性能 def get(self, endpoint): # 自动拼接基础URL和相对路径 return self.session.get(f"{self.base_url}{endpoint}") # 可扩展post、put等其他请求方法 def post(self, endpoint, json=None): return self.session.post(f"{self.base_url}{endpoint}", json=json) # 定义pytest fixture,复用客户端实例 @pytest.fixture(scope="module") def api_client(): return AzureFunctionsAPIClient("http://localhost:7071") # 测试用例中直接使用封装后的客户端 def test_marketplace_root(api_client): response = api_client.get("/marketplace") assert response.status_code == 200 def test_marketplace_themes(api_client): response = api_client.get("/marketplace/themes") assert response.status_code == 200
3. 使用第三方库简化URL管理(可选)
如果允许引入第三方依赖,可使用requests-toolbelt的BaseUrlSession,它原生支持基础URL与相对路径的拼接:
首先安装依赖:
pip install requests-toolbelt
示例代码:
from requests_toolbelt.sessions import BaseUrlSession import pytest @pytest.fixture(scope="module") def api_session(): # 初始化会话时指定基础URL session = BaseUrlSession(base_url="http://localhost:7071") return session def test_marketplace_root(api_session): # 直接传入相对路径即可 response = api_session.get("/marketplace") assert response.status_code == 200
内容的提问来源于stack exchange,提问作者aca1803
相关产品推荐
相关产品推荐

