A B
A B

Reputation: 29

How to Parameterize Test Function: Pytest?

How do I pass a list of data, to a Test Function using Pytest? Each Test Case is pretty similar, except for this input parameter. I have tried the following but to no avail:

import pytest

@pytest.fixture
def List_of_Numbers():
    list = [1,2,3,4,5,6,7,8]


@pytest.parametrize("number", [i for item in list])
def test_eval(number):
    assert eval(number%2) == 0

pytest output:

==================================== ERRORS ====================================
_________________________ ERROR collecting sample4.py __________________________
sample4.py:8: in <module>
@pytest.parametrize("number", [i for item in list])
E   AttributeError: module 'pytest' has no attribute 'parametrize'
 !!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.30 seconds ============================

Upvotes: 2

Views: 2286

Answers (1)

Max Voitko
Max Voitko

Reputation: 1629

You have problem with the code:

  1. The fixture should be not @pytest.parametrize, but @pytest.mark.parametrize:

    @pytest.mark.parametrize("number", [i for item in list])
    def test_eval(number):
        assert eval(number%2) == 0
  1. You are trying to reach variable list defined in local scope of another function. Better not to use variable and function names reserved for built-in variables and functions in Python according to common sense and PEP-8. You don't need extra fixture just for a list of numbers without any logic. I propose you to use a constant instead:

    TEST_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8]

  2. You need to pass a string to eval:

eval(f"{number} % 2")

Putting it all together:


import pytest


TEST_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8]


@pytest.mark.parametrize("number", TEST_NUMBERS)
def test_eval(number):
    assert eval(f"{number} % 2") == 0

Upvotes: 1

Related Questions