如何通过pytest命令行排除多个标记的测试用例?
同时排除多个pytest标记的正确方法
问题背景
在pyproject.toml中配置了两个测试标记:
[tool.pytest.ini_options] markers = [ "plot: marks SLOW plot tests (deselect with '-m \"not plot\"')", "open_tutorial: marks the open_tutorial (which opens VSCode all the times)" ]
单独排除单个标记的命令可正常运行:
coverage run --branch -m pytest -m "not open_tutorial" # 或 coverage run --branch -m pytest -m "not plot"
但尝试多种同时排除两个标记的命令均失败。
正确命令
使用逻辑组合表达式即可实现同时排除,两种写法任选:
- 逻辑与写法:
coverage run --branch -m pytest -m "not open_tutorial and not plot"
- 逻辑或取反写法(更简洁):
coverage run --branch -m pytest -m "not (open_tutorial or plot)"
之前命令失败的原因
- 多次使用
-m参数:pytest仅会识别最后一个-m后的表达式,前面的参数会被忽略,因此-m "not open_tutorial" -m "not plot"实际只生效了not plot。 - 拆分表达式为独立参数:
-m "not open_tutorial" "not plot"会把第二个字符串当成测试文件/目录路径,导致pytest找不到对应路径报错。 - 使用数组格式:
-m ["not open_tutorial","not plot"]不符合命令行参数语法,shell会解析成无效参数,pytest无法识别。
内容的提问来源于stack exchange,提问作者Barzi2001
相关产品推荐
相关产品推荐

