python
runtime_error
ai_generated
true
AssertionError: 3 != 5 : 期望 5 但得到 3
AssertionError: 3 != 5 : expected 5 but got 3
ID: python/unittest-assert-equal-order
80%修复率
85%置信度
0证据数
2024-01-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
在 unittest 中,`assertEqual(first, second)` 报告的消息格式是 `first != second`。开发者常把消息从右往左读,从而修改了断言错误的一侧,或误以为被测函数有问题,而实际是参数顺序写反了。
English
In unittest, `assertEqual(first, second)` reports the message as `first != second`. Developers often read the message right-to-left and fix the wrong side of the assertion, or assume the function under test is broken when the arguments were swapped.
解决方案
-
95% 成功率
Always put the actual value first and add a msg for clarity: self.assertEqual(result, 5, f'unexpected result: {result!r}') -
98% 成功率
Use pytest's rich assertion rewriting instead, which prints both operands clearly: assert result == 5
无效尝试
常见但无效的做法:
-
60% 失败
The test expectation was reversed; changing production code introduces a bug to satisfy a wrong assertion.
-
90% 失败
Silences the test and hides real regressions; the CI still reports green while behavior is wrong.