AssertionError: assert False + 其中 False = <built-in method __eq__ of type object at 0x...>(1, 2) # 注意:断言重写已禁用;使用 --assert=rewrite 启用
AssertionError: assert False + where False = <built-in method __eq__ of type object at 0x...>(1, 2) # note: assertion rewriting is disabled; enable with --assert=rewrite
ID: python/pytest-assertion-introspection-disabled
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 6.x | active | — | — | — |
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 的断言重写被禁用,可能是因为传入了 --assert=plain、测试模块通过 importlib 导入而未经过 pytest 的 meta path finder,或 PYTEST_DISABLE_PLUGIN_AUTOLOAD 干扰。
English
pytest's assertion rewriting is disabled, either because --assert=plain was passed, the test module was imported via importlib without pytest's meta path finder, or PYTEST_DISABLE_PLUGIN_AUTOLOAD interfered.
解决方案
-
95% 成功率
# pytest.ini [pytest] addopts = --assert=rewrite # verify with: pytest --version -v | grep assertion
-
85% 成功率
# Instead of: import tests.test_foo # Run: pytest tests/test_foo.py # and remove any `importlib.import_module('tests.test_foo')` from conftest.py
无效尝试
常见但无效的做法:
-
90% 失败
Verbosity increases output but does not re-enable assertion rewriting; the useful diff remains missing.
-
65% 失败
Manual prints work but clutter tests and don't restore pytest's rich introspection for all assertions.