1

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

Jaxx
  • 1,355
  • 2
  • 11
  • 19

1 Answers1

1

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
Guy
  • 46,488
  • 10
  • 44
  • 88
  • You are right. May be I do not need to use a fixture. In my case my_list and test_item are part of a class TestParent. I want to create a new class TestChild in another file and override only my_list function to return different list of elements. Do you think this is possible (with or without fixtures)? – Jaxx Jun 14 '23 at 09:24
  • @Jaxx `@pytest.mark.parametrize` is executed in test collection time and is not in the class scope, so you can't really override `my_list` as a parameter. – Guy Jun 14 '23 at 10:04
  • I mark your answer as solution to this question and I will open another question with more details on the related issue – Jaxx Jun 14 '23 at 10:12