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

我有一个正在运行的基本端点测试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。


感觉就像我在这里做了一些非常简单的事情,却弄错了。我是否以错误的方式思考这个问题,或者我的语法不正确?


FFIVE
浏览 30回答 1
1回答

暮色呼如

您可以使用该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已经通过为每个端点创建单独的测试来完成。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python