一、引言

在测试开发领域,pytest 是一款广受欢迎的测试框架。其中,pytest.mark 更是功能强大,它能为测试函数添加各种标记,实现对测试用例的分类、筛选及行为修改。本文将结合丰富示例,带你深入了解 pytest.mark 的常见使用场景。

二、pytest.mark 基本用法:标记测试用例

(一)标记测试用例为 slow

import pytest@pytest.mark.slowdef test_slow_operation():    assert 1 + 1 == 2

在此例中,test_slow_operation 被标记为 slow。运行测试时,使用 -m 选项筛选标记为 slow 的测试用例,指令如下:

pytest -m slow

(二)标记测试用例为 fast

import pytest@pytest.mark.fastdef test_fast_operation():    assert 1 + 1 == 2

运行时筛选标记为 fast 的测试用例,同样使用 -m 选项:

pytest -m fast

三、使用多个标记

(一)示例:同时标记为 slow 和 database​​​​​​​

import pytest@pytest.mark.slow@pytest.mark.databasedef test_database_operation():    assert 1 + 1 == 2

运行测试时,若要同时筛选这两个标记的测试用例,指令为:

pytest -m "slow and database"

四、使用自定义标记

(一)示例:自定义标记 integration​​​​​​​

import pytest@pytest.mark.integrationdef test_integration_test():    assert 1 + 1 == 2

运行测试筛选标记为 integration 的测试用例,指令:

pytest -m integration

五、使用参数化标记

(一)示例:参数化测试用例​​​​​​​

import pytest@pytest.mark.parametrize("input, expected", [    (1, 2),    (2, 3),    (3, 4)])def test_addition(input, expected):    assert input + 1 == expected

此例中,test_addition 测试用例被参数化,每次运行使用不同输入值。参数化测试用例也能结合其他标记,如:​​​​​​​

@pytest.mark.slow@pytest.mark.parametrize("input, expected", [    (1, 2),    (2, 3),    (3, 4)])def test_addition(input, expected):    assert input + 1 == expected

六、使用标记跳过测试用例

(一)示例:跳过某些测试用例​​​​​​​

import pytest@pytest.mark.skip(reason="This test is not ready yet")def test_not_ready():    assert 1 + 1 == 3

运行测试时,test_not_ready 会被跳过,并显示跳过原因。

(二)示例:条件跳过​​​​​​​

import pytestimport sys@pytest.mark.skipif(sys.platform == "win32", reason="Does not run on Windows")def test_linux_only():    assert 1 + 1 == 2

若当前系统是 Windows,test_linux_only 会被跳过。

七、使用标记标记预期失败的测试用例

(一)示例:预期失败​​​​​​​

import pytest@pytest.mark.xfail(reason="This test is expected to fail")def test_expected_to_fail():    assert 1 + 1 == 3

若测试失败,pytest 会标记为预期失败(XFAIL),而非失败(FAIL)。

八、使用标记运行特定的测试用例

(一)运行标记为 slow 的测试用例

pytest -m slow

(二)运行标记为 fast 的测试用例

pytest -m fast

(三)运行标记为 slow 或 fast 的测试用例

pytest -m "slow or fast"

(四)运行标记为 slow 且 database 的测试用例

pytest -m "slow and database"

九、使用标记过滤测试用例

(一)示例:跳过标记为 slow 的测试用例

pytest -m "not slow"

(二)示例:跳过标记为 integration 的测试用例

pytest -m "not integration"

十、总结

pytest.mark 为测试开发提供了极大便利,通过它,我们能轻松:

 

  1. 分类测试用例

    如用 slow、fast、integration 等标记区分不同类型测试。

  2. 跳过测试用例

    针对未完成或特定条件下才运行的测试进行跳过处理。

  3. 标记预期失败测试

    明确告知 pytest 哪些测试预期会失败。

  4. 动态选择测试
    灵活筛选出要运行的测试用例,提升测试效率。

 

希望本文能助你熟练掌握 pytest.mark,让测试开发工作更加高效、有序。

视频教材可见bilibili:测试黎明

 

更多推荐