How to run a pytest test for each item in a list of arguments

时光毁灭记忆、已成空白 提交于 2021-01-05 07:18:26

问题


Suppose I have a list of HTTP URLs like

endpoints = ["e_1", "e_2", ..., "e_n"]

And I want to run n tests, one for each endpoint. How can I do that?

A simple way to test all the endpoints at once would be

def test_urls():
    for e in endpoints:
        r = get(e)
        assert r.status_code < 400

or something like that. But as you can see, this is one test for all the n endpoints and I would like a little more granularity than that.

I have tried using a fixture like

@fixture
def endpoint():
    for e in endpoints:
        yield e

but, apparently, Pytest is not really fond of "multiple yields" in a fixture and returns a yield_fixture function has more than one 'yield' error


回答1:


Following the example in Parametrizing fixtures and test functions, you can implement the test as:

import pytest

endpoints = ['e_1', 'e_2', ..., 'e_n']

@pytest.mark.parametrize('endpoint', endpoints)
def test_urls(endpoint):
    r = get(endpoint)
    assert r.status_code < 400

This will run test_urls n times, once per endpoint:

test_spam::test_urls[e_1] PASSED
test_spam::test_urls[e_2] PASSED
...
test_spam::test_urls[e_n] PASSED


来源:https://stackoverflow.com/questions/56754769/how-to-run-a-pytest-test-for-each-item-in-a-list-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!