pytest study
发布人:shili8
发布时间:2025-03-11 23:30
阅读次数:0
**Pytest Study**
###什么是 Pytest?
Pytest 是一个 Python 的测试框架,旨在替代 unittest 库。它提供了更灵活、更高效的测试方式。
### 为什么选择 Pytest?
1. **灵活性**: Pytest 支持多种测试风格,包括 BDD(行为驱动开发)、TDD(测试驱动开发)和 fixture-based testing。
2. **高效性**: Pytest 使用缓存机制来减少测试执行时间,并且支持并行测试。
3. **易用性**: Pytest 提供了友好的 API 和命令行工具,方便用户使用。
### 安装 Pytest可以通过 pip 来安装 Pytest:
bashpip install pytest
### 基本概念#### 测试文件Pytest 的测试文件以 `test_` 开头的 Python 文件为主。例如:`test_math.py`。
#### 测试函数测试函数应该是独立的,且不修改全局状态。它们通常使用 `@pytest.mark.test_name` 来标记。
#### FixturesFixtures 是一种用于设置和清理测试环境的机制。它们可以被多个测试函数共享。
###例子:简单的加法测试
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.test_adddef test_add(): assert add(1,2) ==3@pytest.mark.test_add_negativedef test_add_negative(): assert add(-1, -2) == -3
### Fixtures 示例
# conftest.pyimport pytest@pytest.fixturedef setup(): print("Setup") yield print("Teardown") @pytest.fixturedef teardown(): print("Teardown")
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.test_adddef test_add(setup): assert add(1,2) ==3@pytest.mark.test_add_negativedef test_add_negative(teardown): assert add(-1, -2) == -3
### 参数化测试
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.parametrize("a, b, expected", [ (1,2,3), (-1, -2, -3) ]) def test_add(a, b, expected): assert add(a, b) == expected
### 测试类
# test_math.pyimport pytestclass Math: def __init__(self): self.value =0 def add(self, a, b): return a + b@pytest.fixturedef math(): return Math() @pytest.mark.test_adddef test_add(math): assert math.add(1,2) ==3@pytest.mark.test_add_negativedef test_add_negative(math): assert math.add(-1, -2) == -3
### 测试异常
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.test_adddef test_add(): with pytest.raises(TypeError): add("a",2) @pytest.mark.test_add_negativedef test_add_negative(): with pytest.raises(ValueError): add(-1, "b")
### 测试性能
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.performancedef test_performance(): for _ in range(10000): assert add(1,2) ==3
### 总结Pytest 是一个强大的测试框架,提供了灵活性、高效性和易用性的特点。通过使用 fixtures、参数化测试、测试类和测试异常等功能,可以更好地组织和执行测试。最后,通过测试性能可以评估代码的运行速度。
### 参考* [Pytest 文档]( />* [Fixtures]( />* [Parameterization]( />* [Testing Classes](