AssertionError: assert 200 == 404 + 其中 200 = <Response [200]>.status_code
AssertionError: assert 200 == 404 + where 200 = <Response [200]>.status_code
ID: python/pytest-assertion-rewrite-failure
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
测试期望返回404状态码但收到了200。这表明API端点返回了成功响应而不是预期的错误。常见原因包括URL错误、缺少身份验证,或者资源实际存在而测试假设它不存在。
English
The test expected a 404 status code but received 200. This indicates the API endpoint returned a successful response instead of the expected error. Common causes include incorrect URL, missing authentication, or the resource actually existing when the test assumes it doesn't.
解决方案
-
90% 成功率
Print the full URL and check if the resource exists: print(response.url) # Manually query the database or use curl to confirm the resource is missing before the test.
-
85% 成功率
Use fixtures to guarantee the resource does not exist: @pytest.fixture def cleanup_user(): User.objects.filter(id=123).delete() yield User.objects.filter(id=123).delete() -
80% 成功率
If the endpoint returns 200 for authorized users, adjust the test to use an unauthorized client or a different user without access.
无效尝试
常见但无效的做法:
-
95% 失败
This masks the real issue and makes the test useless for detecting regressions; the test will always pass regardless of actual behavior.
-
80% 失败
If the resource is immediately available, sleeping won't change the status code from 200 to 404; it just slows down tests.
-
75% 失败
This bypasses the real integration and may hide bugs in the actual endpoint; the test no longer validates real behavior.