python中pytest有那些装饰器
时间: 2025-04-06 09:15:42 浏览: 33
### Python 中 pytest 支持的装饰器及其功能
#### 装饰器 `@pytest.mark.parametrize`
此装饰器用于参数化测试案例,允许开发者在一个测试函数中运行多个输入组合并验证其行为。它简化了重复测试逻辑的需求,使代码更加简洁和可维护[^1]。
```python
import pytest
@pytest.mark.parametrize("input, expected_output", [
(1, 2),
(2, 3),
(3, 4)
])
def test_add_one(input, expected_output):
assert input + 1 == expected_output
```
---
#### 装饰器 `@pytest.fixture`
`@pytest.fixture` 是 pytest 的核心装饰器之一,主要用于创建测试固件(test fixtures),这些固件可以在测试前后执行特定的操作,比如初始化资源或清理环境。它可以替代传统的 setup 和 teardown 方法[^2]。
```python
import pytest
@pytest.fixture
def sample_fixture():
print("\nSetup executed")
yield "Fixture Value"
print("\nTeardown executed")
def test_sample(sample_fixture):
assert sample_fixture == "Fixture Value"
```
---
#### 装饰器 `@pytest.mark.skip`
该装饰器用于跳过某些不需要运行的测试用例。通常适用于那些依赖于外部条件或者暂时不可用的情况。
```python
import pytest
@pytest.mark.skip(reason="Skipping this test due to external dependency issues.")
def test_skip_example():
pass
```
---
#### 装饰器 `@pytest.mark.xfail`
当预期某个测试会失败时,可以使用这个装饰器标记测试为“期望失败”。即使测试实际通过了,也不会影响整体测试结果的状态报告。
```python
import pytest
@pytest.mark.xfail(reason="Known issue with the function under test.")
def test_xfail_example():
assert False
```
---
#### 装饰器 `@pytest.mark.usefixtures`
如果需要在不显式传递的情况下使用 fixture,则可以通过此装饰器间接调用它们[^3]。
```python
import pytest
@pytest.fixture
def prepare_environment():
print("\nPreparing environment...")
yield
print("\nCleaning up...")
@pytest.mark.usefixtures("prepare_environment")
def test_with_usefixtures():
pass
```
---
#### 装饰器 `@pytest.mark.timeout`
设置超时时间来限制单个测试的最大执行周期。一旦超过指定的时间范围,测试会被强制终止。
```python
import pytest
from time import sleep
@pytest.mark.timeout(2)
def test_timeout_example():
sleep(3) # This will cause a failure as it exceeds timeout limit.
```
---
#### 其他常用装饰器
除了上述提到的主要装饰器外,还有其他一些辅助性的装饰器可供扩展用途:
- **`@pytest.hookimpl`**: 定义自定义插件钩子实现。
- **`@pytest.yield_fixture`** *(已废弃)*: 替代旧版本中的 `yield` 风格 fixtures。
---
### 总结
以上列举了一些常见的 pytest 装饰器以及它们的应用场景。每种装饰器都有独特的功能定位,在不同的开发需求下发挥重要作用。合理运用这些工具能够显著提升单元测试的质量与效率。
阅读全文
相关推荐




















