pytest中的cm
时间: 2023-11-08 08:04:58 浏览: 117
pytest中的`cm`是上下文管理器(Context Manager)的缩写,用于在测试中创建和管理临时的上下文。它通常与`with`语句一起使用,可以方便地设置和恢复测试环境。
在pytest中,`cm`常用于以下场景:
1. 创建临时文件或目录:使用pytest的`tmp_path`或`tmpdir`夹具创建临时文件或目录,并在测试结束后自动清理。
2. 模拟外部资源:使用pytest的`monkeypatch`夹具修改、模拟或替换外部资源的行为。
3. 控制测试用例执行顺序:使用pytest的`pytest.mark.parametrize`标记和`pytest.fixture`装饰器来控制测试用例的执行顺序。
示例代码如下:
```python
import pytest
def test_temp_file(tmp_path):
# 使用tmp_path创建临时文件
file_path = tmp_path / "test.txt"
file_path.write_text("Hello, World!")
# 断言文件内容
assert file_path.read_text() == "Hello, World!"
def test_monkeypatch(monkeypatch):
# 使用monkeypatch模拟外部资源
monkeypatch.setattr("path.to.module.function", lambda: "mocked value")
# 调用被模拟的函数
assert module.function() == "mocked value"
@pytest.mark.parametrize("input, expected", [("a", "A"), ("b", "B")])
def test_parametrize(input, expected):
# 使用pytest.mark.parametrize标记控制测试用例参数化
assert input.upper() == expected
```
阅读全文