为了账号安全,请及时绑定邮箱和手机立即绑定

使用函数为pytest测试提供参数

使用函数为pytest测试提供参数

FFIVE 2024-01-27 15:29:19
我有一个正在运行的基本端点测试pytest filename.py:ENDPOINTS = ['/users']def test_get_requests(application_headers):    """ Test all endpoints with a GET method """    for endpoint in ENDPOINTS:        response = requests.get(API_URL + endpoint, headers=application_headers)    assert response.status_code == 200这使用ENDPOINTS列表和application_headers固定装置将 HTTP 请求发送到指定端点并断言其成功状态代码。这很好用。我在远程 JSON 文件中有一个端点列表,我想加载该端点,然后从中筛选端点进行测试,而不是使用手动定义的 ENDPOINTS list。我创建了一个这样的装置:@pytest.fixture(scope='module')def application_endpoints():    endpoints = []    with request.urlopen('https://my.endpoint.file.json') as response:        if response.getcode() == 200:            source = response.read()            data = json.loads(source)    for path in data["paths"]:        endpoints.append(path)    return endpoints然后我将测试定义更改为def test_get_requests(application_headers, application_endpoints),但这会导致错误TypeError: can only concatenate str (not "list") to str。我还尝试了一种不同的方法,使用参数化,但这也失败了:@pytest.mark.parametrize('endpoint', application_endpoints)def test_get_requests(application_headers):    """ Test all endpoints with a GET method """    for endpoint in ENDPOINTS:        response = requests.get(API_URL + endpoint, headers=application_headers)    assert response.status_code == 200该故障的错误是NameError: name 'application_endpoints' is not defined。感觉就像我在这里做了一些非常简单的事情,却弄错了。我是否以错误的方式思考这个问题,或者我的语法不正确?
查看完整描述

1 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

您可以使用该parametrize方法,但不能使用参数的固定装置 - 只能使用函数。endpoints另外,您的代码中存在一些混淆application_headers。忽略application_headers来自哪里,您可以尝试以下操作:


def application_endpoints():  # not a fixture!

    endpoints = []

    ...

    return endpoints


@pytest.mark.parametrize('endpoint', application_endpoints())

def test_get_requests(endpoint):

    response = requests.get(API_URL + endpoint, headers=application_headers)

    assert response.status_code == 200

无需自己迭代端点 - 这mark.parametrize已经通过为每个端点创建单独的测试来完成。


查看完整回答
反对 回复 2024-01-27
  • 1 回答
  • 0 关注
  • 23 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信