Calling class level variables using "@pytest.mark.parametrize" fixture

Viewed 951

I'm trying to iterate a pytest test over a list of values which i generate inside another method in the test class.

The problem is that i get: "@pytest.mark.parametrize("number",TestScratch.list_testing) NameError: name 'TestScratch' is not defined" error when i try to run.I know for a fact that when i pass the list as a hard coded list i.e [0,3,54,90] it works. Below is my code :

class TestScratch(object):

    @classmethod
    def setup_class(cls):
        cls.list_testing = []

    @classmethod
    def setup_method(cls):
        pass


    def test_populate_list(self):
        for i in range(100):
            self.list_testing.append(i)

    @pytest.mark.parametrize("number",TestScratch.list_testing)
    def test_pytest_param(self, number):
        assert type(number) == int

    @classmethod
    def teardown_class(cls):
        '''
        pass
        '''

I also tried self.class.list_testing but i get the same error

Environment details:

Python: 3.6.8

Pytest: 5.2.1

1 Answers

You can't use the class in the class definition. As the decorator is read at import time, e. g. while loading the class definition, and not at runtime, the class is not known at this point. You have to define the list outside the class instead:

import pytest

def populate_list():
    test_list = []
    for i in range(100):
        test_list.append(i)
    return test_list


list_testing = populate_list()


class TestScratch:
    def test_populate_list(self):
        # this will fail if list_testing could not be populated
        assert len(list_testing) > 50

    @pytest.mark.parametrize("number", list_testing)
    def test_pytest_param(self, number):
        # this will be skipped if list_testing could not be populated
        assert type(number) == int

Any parameter you use in a decorator is read only once at load time, so trying to intialize it at runtime won't work. For example here you can find an explanation how parametrization works and why it is not possible to add parameters at runtime.

Related