[Tutor] Testing classes with class variables: How best to reset class state between tests?
Peter Otten
__peter__ at web.de
Wed Jun 24 02:53:45 EDT 2020
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.
>
> 2) Forcibly reloading the import with importlib.reload(myclassmodule).
> This seems like using a sledge hammer to swat a fly. And it would
> seem that it would have to be done repeatedly and added to earlier
> tests as well.
That's a hack; you can never be sure that you have replaced all objects from
the previous import.
> Does Python provide a better solution? For the record my test runner
> is currently pytest.
While I think (1) is fine you may also consider pytest's autouse fixtures.
More information about the Tutor
mailing list