I'm working on a rapidly growing Python project. Lately, our test suite started being somewhat unmanageable. Some tests fail when the modules they are in get executed in the wrong order, despite being seemingly well-isolated.
I found some other questions about this, but they were concerned with fixtures:
Pytest fixtures interfering with each other
test isolation between pytest-hypothesis runs
While we're using fixtures as well, I do not think the problem lies within them, but more likely in the fact that we use libraries where classes have internal state which gets changed by the test run, for example by mockito-python
.
I originally come from Java world where this does not happen unless you explicitly make your tests depend on each other or do some crazy and unusual things. Following the same set of practices in Python led me to these problems, so I realize I might be missing some crucial rule of Python test development.
Is it possible to tell pytest
to drop/revert/reinitialize the internal state of all classes between various module runs?
If not, which rules should we follow during test development to prevent these issues?
Edit: One of the issues we identified was that we had some objects set up at top level in the test file, which were created by mockito-python
. When the tests were executed, the files are first all imported and then the tests are executed. What happened was that one test was calling mockito.unstub()
which tears down all mocks in mockito's mock registry. So when the test was actually executed, another test had already torn down its mocks. This behavior is quite counter-intuitive, especially for unexperienced developers.