Pytest是一个功能强大且易于使用的Python测试框架,它提供了简洁、灵活和可读性强的测试代码编写方式,以及丰富的断言支持、参数化测试、夹具系统和插件系统等特性。这些特性使得Pytest成为许多Python开发者首选的单元测试框架。
以下是一些常用的Pytest API:
-
pytest.mark
:用于创建自定义的标记(Mark)以标记测试用例,例如对特定功能、特定条件或特定环境的测试进行标记。import pytest @pytest.mark.slow def test_slow_function(): # 测试代码 pass
-
pytest.fixture
:用于定义夹具(Fixture),即为测试函数提供预置条件或资源。夹具可以在测试函数中通过参数注入的方式使用。import pytest @pytest.fixture def my_fixture(): # 准备资源或预置条件 yield resource # 清理资源或还原状态 def test_my_function(my_fixture): # 使用my_fixture pass
-
pytest.param
:用于在参数化测试中定义测试参数。可以通过将pytest.param
与测试参数值一起使用,为每组参数提供自定义的标签、ids和条件。import pytest @pytest.mark.parametrize("input, expected", [ pytest.param(1, 2, id="Test case 1"), pytest.param(3, 4, id="Test case 2"), ]) def test_my_function(input, expected): # 测试代码 pass
-
pytest.raises
:用于断言预期的异常是否被抛出。可以使用pytest.raises
作为上下文管理器,检查是否抛出了特定类型的异常,并在需要时访问异常的详细信息。import pytest def my_function(): raise ValueError("Some error") def test_my_function(): with pytest.raises(ValueError) as excinfo: my_function() assert str(excinfo.value) == "Some error"
-
pytest.skip
:用于跳过特定的测试用例。可以使用pytest.skip
装饰器或在测试函数内部使用pytest.skip()
函数。import pytest @pytest.mark.skip(reason="Test case not implemented yet") def test_my_function(): # 跳过测试用例 pass def test_another_function(): if condition: pytest.skip("Skipping this test conditionally") # 其他测试代码 pass