Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setUp defined variables in parametrized.expand

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.

like image 280
Dylan Galea Avatar asked Aug 15 '26 03:08

Dylan Galea


1 Answers

Note that I've used the spelling "parameterized" rather than "parametrized" throughout my answer.

You could pass them as strings to @parameterized.expand and then eval them in the function:

class Test(unittest.TestCase)
def setUp(self) -> None:
    self.test_parameter1 = 'A'
    self.test_parameter2 = 'B'

@parameterized.expand([('self.test_parameter1',), ('self.test_parameter2',)])
def test_function1(self, test_param):
    test_param = eval(test_param)
    # * Do tests here *

Presumably you're in control of the entire test file, so eval shouldn't raise the security concerns that it would if it were called on unknown code.

like image 50
Alan Avatar answered Aug 17 '26 17:08

Alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!