The pytest fixture is a very useful tool when you want to repeat the test under the same conditions. When I wanted to use fixture as a test parameter to write a test that is common to various conditions, the information was unexpectedly not gathered on the net, so I will describe it here.
By the way, for information on how to use fixture as a test parameter, see Official Page and GitHub. / pytest-dev / pytest / issues / 349), so it's possible that a slightly easier way will be offered in the near future.
import pytest
@pytest.fixture
def fixture_a():
yield 1
@pytest.fixture
def fixture_b():
yield 2
@pytest.fixture
def fixture_c():
yield 3
@pytest.mark.parametrize("expected, generated", [
(1, fixture_a),
(2, fixture_b),
(5, fixture_c),
])
def test_fail(expected, generated):
assert expected == generated
However, this doesn't work.
Put together fixtures by using the decorator pytest.fixture
.
test.py
#Other functions are the same as above
@pytest.fixture(params=['a', 'b', 'c'])
def context(request):
if request.param == 'a':
return (1, request.getfixturevalue('fixture_a'))
elif request.param == 'b':
return (2, request.getfixturevalue('fixture_b'))
elif request.param == 'c':
return (4, request.getfixturevalue('fixture_c'))
def test_fixture_parameterize(context):
expected, generated = context
assert expected == generated
$ pytest test.py
========================================= test session starts =========================================
platform linux2 -- Python 2.7.12, pytest-3.1.0, py-1.4.33, pluggy-0.4.0
rootdir: /home/koreyou/work/pytest_fixture_parameterize, inifile:
collected 3 items
test.py ..F
============================================== FAILURES ===============================================
____________________________________ test_fixture_parameterize[c] _____________________________________
context = (4, 3)
def test_fixture_parameterize(context):
expected, generated = context
> assert expected == generated
E assert 4 == 3
test.py:31: AssertionError
================================= 1 failed, 2 passed in 0.02 seconds ==================================
It fails as expected.