pytestfixturesparametrized-testing

Problem with using a fixture in pytest parametrize


What is the correct syntax to use my_list fixture with parametrize in pytest? I would like test_item() to be run 5 times (based on the list returned by my_list fixture)


@pytest.fixture
def my_list():
    return [1, 2, 3, 4, 5]

@pytest.mark.parametrize("item", my_list())
def test_item(item):
    print(item)
    assert item < 6

I tried also this, but did not succeed:

import pytest

@pytest.fixture
def my_list():
    return [1, 2, 3, 4, 5]

@pytest.mark.parametrize("item", "my_list")
def test_item(item, request):
    item = request.getfixturevalue("item")
    print(item)
    assert item < 6

Thanks in advance


Solution

  • You can't call a fixture directly, my_list() should be a regular function. If you still want it as a fixture extract the functionality to another function

    def my_list_imp():
        return [1, 2, 3, 4, 5]
    
    
    @pytest.fixture
    def my_list():
        return my_list_imp()
    
    
    @pytest.mark.parametrize("item", my_list_imp())
    def test_item(item):
        print(item)
        assert item < 6
    

    Output

    example.py::test_item[1] PASSED                                          [ 20%]1
    
    example.py::test_item[2] PASSED                                          [ 40%]2
    
    example.py::test_item[3] PASSED                                          [ 60%]3
    
    example.py::test_item[4] PASSED                                          [ 80%]4
    
    example.py::test_item[5] PASSED                                          [100%]5