Why does a unittest pass alone but fail with the whole test suite?
Quick answer
A test that passes alone but fails in the suite may depend on state another test changed, assume a particular execution order, or leave something behind. Check what the failing test reads and changes, then make its starting state explicit. Use setUp() to create fresh per-test data where practical, and clean up changes reliably. unittest orders test methods by name, so avoid relying on another test to prepare state. [S1]
The question, the details, the next step.
A practical checklist
Record the failing test name and the complete failure message.
List shared values, fixtures, files, or settings the test reads or changes.
Check whether the test assumes another test runs first; unittest methods are ordered by name. [S1]
Create fresh per-test state in setUp() where practical. [S1]
Restore changed state in cleanup, including when the test assertion fails.
A few more useful answers
Does unittest always run tests in the same order?
The unittest documentation says test methods are ordered by name. Avoid making one test depend on another having prepared state. [S1]
Is tearDown() enough to fix a suite-only failure?
Only if incomplete cleanup is the cause and cleanup restores the relevant state. For ordinary test data, creating a fresh value in setUp() may be simpler. unittest documents that tearDown() runs after a test method even if it fails, provided setup succeeded. [S1]
What if the test uses a shared class or module fixture?
Inspect whether the fixture is changed and whether its lifecycle leaves state for other tests. Shared fixtures are separate from per-test setup and can break isolation if used carelessly. [S1]
Sources
References used for this guide.
- [S1] Python unittest: Test independence, fixtures, order, and cleanup docs.python.org · Checked
