Pytest常用装饰器

在 Pytest 中,有一些常用的装饰器,它们可以帮助你更好地组织和管理测试用例。以下是一些常见的 Pytest 装饰器:

  1. @pytest.mark.parametrize:用于参数化测试用例。它允许你为一个测试函数提供多组参数,从而可以用不同的输入值来测试同一个功能。
    示例:
    `import pytest

    @pytest.mark.parametrize("input_value, expected_result", [
    (5, 10),
    (3, 6),
    (8, 16)
    ])
    def test_double(input_value, expected_result):
    assert input_value * 2 == expected_result`

@pytest.mark.skip:用于跳过某个测试用例。可以指定一个条件,当条件满足时,该测试用例将被跳过。
示例:

     import pytest

     @pytest.mark.skip(reason="This test is currently not working")
     def test_function():
         pass

@pytest.mark.xfail:用于标记一个预期会失败的测试用例。如果该测试用例实际执行失败,将被标记为 xfail(预期失败);如果实际执行通过,将被标记为 unexpected pass(意外通过)。
示例:

     import pytest

     @pytest.mark.xfail
     def test_function():
         assert False

@pytest.fixture:用于定义一个 fixture,它可以在测试用例执行之前或之后进行一些设置和清理工作。Fixture 可以被多个测试用例共享,提高测试代码的可维护性和可重用性。
示例:

     import pytest

     @pytest.fixture
     def setup_data():
         data = [1, 2, 3]
         return data

     def test_function(setup_data):
         assert len(setup_data) == 3

@pytest.mark.usefixtures:用于在测试类或测试函数上应用一个或多个 fixture。它可以让你在不直接传入 fixture 参数的情况下使用 fixture。
示例:

     import pytest

     @pytest.fixture
     def setup_data():
         data = [1, 2, 3]
         return data

     @pytest.mark.usefixtures("setup_data")
     def test_function():
         # 这里可以直接使用 setup_data fixture
         pass

这些装饰器可以大大提高你的测试效率和代码的可读性。在使用 Pytest 进行测试时,可以根据具体的需求选择合适的装饰器来组织和管理你的测试用例。

posted @ 2024-08-29 17:04  布谷鸟的春天  阅读(266)  评论(0)    收藏  举报