Using setUp defined variables in parametrized.expand

Viewed 138

Suppose that I have the following unit test class:

class Test(unittest.TestCase)
    def setUp(self) -> None:
        self.test_parameter1 = 'A'
        self.test_parameter2 = 'B'
    
    @parametrized.expand([('A',), ('B',)])
    def test_function1(self, test_param):
        * Do tests here *

Is there a way how can I use self.test_parameter1 and self.test_parameter2 in parameterized.expand instead of the literals A and B? Imagine A and B are large dicts, the tests would be very messy in this case if two large dicts are given to parametrized_expand.

2 Answers

Yes - test_function is a method on your Test class so in your test_function you just need to use self.test_parameter1 & self.test_parameter2 where you would use A & B.

For example:

    @parametrized_expand([('A',), ('B',)])
    def test_function1(self, test_param):
       self.assertEqual(test.parameter1 + self.test_paramter2, 10)

Perhaps you can set them up to be references outside of the test class (they'll be executed on import by unittest) and expand (*) or unzip 'em in the decorator args

test_parameter1 = dict_A
test_parameter2 = dict_B

expanded_args = list(zip(test_parameter1.items(), test_parameter2.items()))

class Test(unittest.TestCase)
    @parametrized.expand(expanded_args)
    def test_function1(self, test_param):
        * Do tests here *
Related