Pytest高效测试结构:如何避免接口重复测试?
解决接口测试中Endpoint重复请求的方案
针对你遇到的问题——测试套件执行时Endpoint 1被请求两次(一次是自身测试用例,一次是被Endpoint 2的测试用例调用),这里有两种简便优雅的解决思路:
1. 拆分数据获取与测试逻辑
把Endpoint 1的请求逻辑从测试函数中抽离成独立的公共函数,测试函数只负责断言验证:
修改后的file_1.py:
import requests # 公共函数:仅负责请求并返回数据,不会被测试套件当作测试用例执行 def fetch_endpoint_1_data(): r = requests.get("你的Endpoint1地址") return r # 测试函数:专注于验证Endpoint1的正确性 def test_endpoint_1(): r = fetch_endpoint_1_data() assert r.status_code == 200 # 这里添加JSON Schema验证等测试逻辑
修改后的file_2.py:
import requests from file_1 import fetch_endpoint_1_data def test_endpoint_2(): needed_data = fetch_endpoint_1_data() r = requests.get("你的Endpoint2地址", payload=needed_data.json()) assert r.status_code == 200 # 这里添加JSON Schema验证等测试逻辑
这种方式下,fetch_endpoint_1_data不会被测试套件识别为测试用例,测试套件只会执行test_endpoint_1和test_endpoint_2两个测试用例。如果希望Endpoint1只被请求一次,可以结合下面的*夹具(Fixture)*方案。
2. 使用测试框架的*夹具(Fixture)*缓存结果
如果用的是pytest框架,可以借助fixture的缓存机制,让Endpoint1的请求只执行一次,同时保证两个测试用例都能用到返回的数据:
修改后的file_1.py:
import requests import pytest # 定义夹具,设置作用域(module表示当前模块内只执行一次,session则是整个测试会话) @pytest.fixture(scope="module") def endpoint_1_response(): r = requests.get("你的Endpoint1地址") # 先做基础断言,确保返回数据有效 assert r.status_code == 200 return r # 测试Endpoint1:直接使用夹具返回的数据做验证 def test_endpoint_1(endpoint_1_response): # 这里添加JSON Schema验证等测试逻辑 assert ... # 比如验证返回的JSON结构符合预期
修改后的file_2.py:
import requests from file_1 import endpoint_1_response # 测试Endpoint2:直接注入夹具的结果,无需重复请求 def test_endpoint_2(endpoint_1_response): r = requests.get("你的Endpoint2地址", payload=endpoint_1_response.json()) assert r.status_code == 200 # 这里添加JSON Schema验证等测试逻辑
这种方案下,endpoint_1_response夹具只会在第一次被调用时执行请求,之后的测试用例都会直接使用缓存的结果,彻底避免Endpoint1被重复请求,同时保留了两个测试用例的独立性。
内容的提问来源于stack exchange,提问作者ifeeltiredboss
相关产品推荐
相关产品推荐

