[Tutor] Testing classes with class variables: How best to reset class state between tests?
Mats Wichmann
mats at wichmann.us
Thu Jun 25 11:20:42 EDT 2020
On 6/24/20 12:53 AM, Peter Otten wrote:
> boB Stepp wrote:
>
>> class MyClass:
>> class_var1 = value1
>> class_var2 = value2
>> ...
>>
>> methods some which may affect class variables
>>
>> This is a spinoff of my earlier questions about creating an instance
>> counter for a class. I started to implement this in my actual code
>> and started to write tests for the counter. I quickly realized that
>> the counter variable retained state between tests, and, in fact,
>> already written tests would now populate the counter before I ever got
>> around to the new counter tests. So how to best deal with this? Two
>> ideas come immediately to mind:
>>
>> 1) Use setup and/or teardown methods to manually reset all class
>> variables to their desired initial state. A downside of this is that
>> I will have to go back to all previous tests involving this class and
>> add these methods.
>
> setUp()/tearDown() seems fine. Put them into a base class that you can
> derive from to avoid repetition.
the concept of setup and teardown in testing is pretty fundamental,
without it tests which affect state will cause your overall test run to
be a mess, so you shouldn't be uncomfortable with it.
autouse seems to be pytest's way to go a bit beyond the "classic {x}Unit
way" and make things a bit more usable. I had to look it up, was new to
me :) See, we all learn something from these interactions!
This example seems to fit your case fairly well:
https://docs.pytest.org/en/stable/fixture.html#autouse-fixtures
More information about the Tutor
mailing list