背景
我正在使用 pytest 来测试将数据推送到数据库的网络抓取工具。该类仅拉取 html 并将 html 推送到数据库以供稍后解析。我的大多数测试都使用虚拟数据来表示 html。
Question
我想做一个测试,从网站上抓取网页,但我希望测试自动关闭,除非指定。如果您不想总是运行一项昂贵或耗时的测试,则可能会出现类似的情况。
预期解决方案
我期待某种标记来抑制测试,除非我让 pytest 运行所有抑制的测试,但我在文档中没有看到这一点。
我做了什么
- 我目前正在使用跳过标记并将其注释掉。
-
尝试使用skipif标记并在命令提示符下使用此命令向 python 脚本提供参数pytest test_file.py 1
以及测试文件中的以下代码。问题是,当我尝试向 test_file 提供参数时,pytest 期望这是另一个文件名,因此我收到错误“0.00 秒内没有运行测试,错误:找不到文件:1”
if len(sys.argv) == 1:
RUN_ALL_TESTS = False
else:
RUN_ALL_TESTS = True
...
# other tests
...
@pytest.mark.skipif(RUN_ALL_TESTS)
def test_scrape_website():
...
我也许可以将测试视为固定装置并使用@pytest.fixture(autouse=False)
,但不确定如何覆盖 autouse 变量
类似的解决方案在如何使用外部夹具跳过 pytest?但这个解决方案似乎比我需要的更复杂。
该文档准确描述了您的问题: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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)