首页 > 解决方案 > Python - 除非指定,否则使用 pytest 跳过测试

问题描述

背景

我正在使用 pytest 测试将数据推送到数据库的网络爬虫。该类只提取 html 并将 html 推送到数据库以供稍后解析。我的大多数测试都使用虚拟数据来表示 html。

问题

我想做一个测试,从网站上抓取一个网页,但除非指定,否则我希望自动关闭测试。如果您不想始终运行昂贵或耗时的测试,则可能会出现类似的情况。

预期解决方案

我期待某种标记会抑制测试,除非我让 pytest 运行所有抑制的测试,但我在文档中没有看到。

我做了什么

标签: pythonpython-3.xtestingpytest

解决方案


文档准确描述了您的问题:https ://docs.pytest.org/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option 。从那里复制:

这是一个 conftest.py 文件,添加了一个 --runslow 命令行选项来控制跳过 pytest.mark.slow 标记的测试:

# content of conftest.py

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--runslow", action="store_true", default=False, help="run slow tests"
    )


def pytest_collection_modifyitems(config, items):
    if config.getoption("--runslow"):
        # --runslow given in cli: do not skip slow tests
        return
    skip_slow = pytest.mark.skip(reason="need --runslow option to run")
    for item in items:
        if "slow" in item.keywords:
            item.add_marker(skip_slow)

我们现在可以像这样编写一个测试模块:

# content of test_module.py
import pytest


def test_func_fast():
    pass


@pytest.mark.slow
def test_func_slow():
    pass

推荐阅读