[Tutor] Testing classes with class variables: How best to reset class state between tests?
boB Stepp
robertvstepp at gmail.com
Tue Jun 23 08:58:36 EDT 2020
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.
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.
Does Python provide a better solution? For the record my test runner
is currently pytest.
TIA!
--
boB
More information about the Tutor
mailing list