温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pytest中如何使用标记

发布时间:2025-09-11 20:14:09 来源:亿速云 阅读:128 作者:小樊 栏目:编程语言

在 Pytest 中,你可以使用标记(markers)来对测试函数进行分类或添加额外的信息。这对于选择性地运行特定的测试用例非常有用。以下是如何在 Pytest 中使用标记的步骤:

  1. 定义标记: 首先,你需要在 conftest.py 文件中定义标记。如果项目中没有 conftest.py 文件,你可以创建一个。在 conftest.py 中,使用 pytest.mark 来定义标记。

    # conftest.py
    import pytest
    
    def pytest_addoption(parser):
        parser.addoption("--slow", action="store_true", help="run slow tests")
    
    @pytest.fixture(scope="session")
    def slow_tests(request):
        if request.config.getoption("--slow"):
            return True
        return False
    
    def pytest_collection_modifyitems(config, items):
        if config.getoption("--slow"):
            return
        keep = [item for item in items if "slow" not in item.keywords]
        items[:] = keep
    
  2. 在测试函数中使用标记: 在你的测试函数上使用 @pytest.mark 装饰器来添加标记。

    # test_example.py
    import pytest
    
    @pytest.mark.smoke
    def test_example1():
        assert 1 + 1 == 2
    
    @pytest.mark.slow
    def test_example2():
        # This is a slow test
        assert 2 + 2 == 4
    
  3. 运行带有特定标记的测试: 你可以使用 -m 或 --markers 选项来运行带有特定标记的测试。

    pytest -m smoke
    pytest -m "not slow"
    

    这些命令将分别运行带有 smoke 标记的测试和不带有 slow 标记的测试。

  4. 查看所有可用的标记: 你可以使用 pytest --markers 命令来查看所有已定义的标记。

    pytest --markers
    

通过这些步骤,你可以在 Pytest 中有效地使用标记来管理和运行特定的测试用例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手