问题
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