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

Pytest参数化测试中如何每次使用原始请求数据?

解决Pytest测试用例间全局字典数据污染问题

你遇到的问题根源是:variables.myrequest_data是全局可变字典对象,所有测试用例会共享这个对象的引用,每次修改都会永久改变它的内容,导致后续用例使用的是被修改后的数据,而非原始数据。

以下是两种直接有效的解决方法:

方案1:每次测试创建原始字典的副本

在测试用例中不直接修改全局字典,而是先复制一份原始数据,再修改副本(浅拷贝足够,因为你的字典值都是字符串类型):

修改test_person_api.py的测试方法:

class TestPersonAPI:

   @pytest.mark.parametrize("request_key", variables.key_list)
   @pytest.mark.parametrize("negative_values", variables.negative_values)
   def test_person_api_negative_verification(self, request_key, negative_values):
        headers = {'Content-Type': 'application/json'}
        url = "http://person-api-request-url/endpoint"
        # 复制原始数据,避免修改全局对象
        req_data = variables.myrequest_data.copy()
        req_data[request_key] = negative_values
        # 修复原代码中未定义的req变量问题
        response = requests.put(url, data=json.dumps(req_data), headers=headers)
        print("Response:----->>" + response.text)
        assert response.status_code == 400

如果后续原始字典包含嵌套结构,需要使用深拷贝:

import copy

# 替换复制语句
req_data = copy.deepcopy(variables.myrequest_data)

方案2:将原始数据封装为函数返回新字典

修改variables.py,把原始数据定义成函数,每次调用都会生成全新的字典实例:

# variables.py
def get_myrequest_data():
    return { 
     "name" : "Test User",
     "age" : "20",
     "city" : "Bengaluru"
    }

negative_values = ["123456", "@$%$Dev", "xsdcsv", "-4565432", "45f"]
key_list = ["name", "age", "city"]

然后在测试用例中调用函数获取原始数据:

# test_person_api.py
class TestPersonAPI:

   @pytest.mark.parametrize("request_key", variables.key_list)
   @pytest.mark.parametrize("negative_values", variables.negative_values)
   def test_person_api_negative_verification(self, request_key, negative_values):
        headers = {'Content-Type': 'application/json'}
        url = "http://person-api-request-url/endpoint"
        # 每次获取全新的原始字典
        req_data = variables.get_myrequest_data()
        req_data[request_key] = negative_values
        response = requests.put(url, data=json.dumps(req_data), headers=headers)
        print("Response:----->>" + response.text)
        assert response.status_code == 400

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:10:36