# pytest.fail.Exception：调用 pytest.fail() 时消息为 'Test failed' 且没有活动测试

- **ID:** `python/pytest-fail-with-traceback-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

pytest.fail() 在测试函数外部调用，例如在夹具设置或拆卸中，此时没有测试上下文。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |

## 解决方案

1. **Move the pytest.fail() call inside a test function rather than in fixture code.** (95% 成功率)
   ```
   def test_example(): pytest.fail('Test failed')
   ```
2. **Use assert statements in fixtures instead of pytest.fail.** (90% 成功率)
   ```
   assert condition, 'Fixture condition not met'
   ```

## 无效尝试

- **Using pytest.fail in a conftest.py fixture without test context** — Fixtures are not tests; pytest.fail is intended for test functions only. (80% 失败率)
- **Catching the exception with try-except to continue execution** — pytest.fail raises a special exception that propagates; catching it may hide failures. (70% 失败率)
