python - Python - 除非指定,否则使用 pytest 跳过测试
问题描述
背景
我正在使用 pytest 测试将数据推送到数据库的网络爬虫。该类只提取 html 并将 html 推送到数据库以供稍后解析。我的大多数测试都使用虚拟数据来表示 html。
问题
我想做一个测试,从网站上抓取一个网页,但除非指定,否则我希望自动关闭测试。如果您不想始终运行昂贵或耗时的测试,则可能会出现类似的情况。
预期解决方案
我期待某种标记会抑制测试,除非我让 pytest 运行所有抑制的测试,但我在文档中没有看到。
我做了什么
- 我目前正在使用跳过标记并将其注释掉。
尝试使用skipif标记,并使用命令提示符下的此命令
pytest test_file.py 1
和测试文件中的以下代码为python脚本提供参数。问题是,当我尝试为我的 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 变量How to skip a pytest using an external fixture中说明了类似的解决方案?但这个解决方案似乎比我需要的更复杂。
解决方案
文档准确描述了您的问题: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
推荐阅读
- windows - 我可以在 64 个窗口中永久加载未签名的驱动程序吗
- firebase - Google Analytics for Firebase 事件参数数据类型更改
- python - 如何将凭据传递给机器人框架中的 RESTinstance POST 请求?
- r - 乘以不均匀的数据集
- angular - 将自定义组件添加到离子页面
- javascript - Highcharts Gantt (JS) - 删除 x 轴上的日期
- javascript - 导入模块的最佳实践是什么?
- git - Git 在重新排序提交后拒绝推送
- javascript - 我需要使用返回的承诺功能吗?
- c++ - 100位数字的总和