I am trying to teach myself Pytest and am trying to understand the differences between parametrizing test data with @pytest.fixture(params=[])
and @pytest.mark.parametrization()
.
I've set up the code below to see how both work and they both return the same result. However, I'm not sure if there are use cases where one method is preferred over the other. Are there benefits to using one over the other?
import pytest
@pytest.fixture(params=["first parameter", "second parameter", "third parameter"])
def param_fixture(request):
return request.param
def parametrize_list():
return ["first parameter", "second parameter", "third parameter"]
def test_using_fixture_params(param_fixture):
"""Tests parametrization with fixture(params=[])"""
assert "parameter" in param_fixture
@pytest.mark.parametrize("param", parametrize_list())
def test_using_mark_parametrize(param):
"""Tests parametrization with mark.parametrize()"""
assert "parameter" in param
The above code has the following result:
test_parametrization.py::test_using_fixture_params[first parameter] PASSED
test_parametrization.py::test_using_fixture_params[second parameter] PASSED
test_parametrization.py::test_using_fixture_params[third parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[first parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[second parameter] PASSED
test_parametrization.py::test_using_mark_parametrize[third parameter] PASSED
Fixtures are typically used to load data structures into the test and pass to testing functions. @pytest.mark.parametrize is the preferred way to test lots of iterations with different inputs (as you have above).
This was a handy resource when starting : https://realpython.com/pytest-python-testing/
from data_module import Data
class TestData:
"""
Load and Test data
"""
@pytest.fixture(autouse=True)
def data(test):
return Data()
def test_fixture(data):
result = do_test(data)
assert result
@pytest.mark.parametrize('options', ['option1', 'option2', 'option3'])
def test_with_parameterisation(data, options)
result_with_paramaterisation(data, options)
assert result_with_paramaterisation
``