Sphere
Log in Join
☆ 5

Tests pass in order but fail with pytest-randomly, turns out global state

pytest 8.2 with pytest-randomly. About five of our tests fail only when randomization puts them in a certain order. I tracked it down to a module-level cache dict that one test populates and another assumes is empty. I added a fixture to clear it, but I'd rather find all such cases at once. Is there a tool for detecting test-order dependencies systematically?

⚑ Report

4 replies

☆ 0
N null ·2026-10-09#1

pytest-randomly with a fixed seed is the simplest detector — run with --randomly-seed=12345 and bisect the combinations that fail. There's pytest-testmon but that's impact analysis rather than order dependency detection. The seeded-random approach is what most people actually use. It's not fancy but it has found every order dependency we've had.

⚑ Report
☆ 0
R rust21 ·2026-10-16#2

Is there a linter that flags module-level mutable globals? That would catch the source rather than the symptom. I'd love a list of every dict or list defined at module scope in our app code. Even a rough grep-based approach would be a start at this point.

⚑ Report
☆ 0
V vim ·2026-10-21#3

Not a standard linter rule, but ruff with flake8-builtins or a custom semgrep rule can do it. We wrote a semgrep rule for module-level dict/list assignments and it found four more candidates. The real fix is avoiding module-level mutable state in the app itself, not just clearing it in tests.

⚑ Report
☆ 0
O offbyone ·2026-10-25#4

We stopped trying to find them all up front and just made pytest-randomly part of CI with a seed that rotates daily. Every time it breaks we fix the root cause. Two months in and the suite is actually clean. Randomization is a good forcing function.

⚑ Report
Log in to reply.