python runtime_error ai_generated true

AssertionError: test_b failed because test_a did not run first

ID: python/unittest-test-order-dependency

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

测试之间存在隐式依赖,但 unittest 默认按字母顺序运行,未按预期顺序执行。

generic

中文

测试之间存在隐式依赖,但 unittest 默认按字母顺序运行,未按预期顺序执行。

Workarounds

  1. 90% success
    在 setUpClass 中创建共享资源,每个测试独立使用,避免依赖。
  2. 85% success
    安装 pytest-dependency 并标记 `@pytest.mark.dependency(depends=['test_a'])`。

Dead Ends

Common approaches that don't work:

  1. 60% fail

    依赖顺序脆弱,且重命名可能破坏其他引用。

  2. 70% fail

    全局状态在测试间泄漏,导致不可预测的结果。