pytest - 在测试执行之前无法获取 pytest 命令行参数?

标签 pytest

我尝试跳过依赖于命令行参数值的特定测试。我尝试使用 pytest.config.getoption("--some-custom-argument") 获取参数值,如 related question suggestion 中所述。在测试文件中并通过 skipif 检查参数值。但是 pyest 没有配置。通过 request.config.getoption("--some-custom-argument") 获取参数值似乎只适用于固定功能。我可以在测试执行之前以某种不同的方式获取命令行参数,以便我可以在文件范围级别的 skipif 中检查它们吗?

最佳答案

由于测试是在配置阶段之后和测试收集之前(即也在测试执行之前)收集的,因此 pytest.config 在测试模块的模块级别可用。示例:

# conftest.py
def pytest_addoption(parser):
    parser.addoption('--spam', action='store')

# test_spam.py
import pytest


print(pytest.config.getoption('--spam'))


@pytest.mark.skipif(pytest.config.getoption('--spam') == 'eggs', 
                    reason='spam == eggs')
def test_spam():
    assert True

使用 --spam=eggs 运行会产生:

$ pytest -vs -rs --spam=eggs
============================== test session starts ================================
platform linux -- Python 3.6.5, pytest-3.4.1, py-1.5.3, pluggy-0.6.0 -- /data/gentoo64/usr/bin/python3.6
cachedir: .pytest_cache
rootdir: /data/gentoo64/home/u0_a82/projects/stackoverflow/so-50681407, inifile:
plugins: mock-1.6.3, cov-2.5.1, flaky-3.4.0
collecting 0 items                                                                                                     
eggs
collected 1 item

test_spam.py::test_spam SKIPPED
============================ short test summary info ==============================
SKIP [1] test_spam.py:7: spam == eggs

=========================== 1 skipped in 0.03 seconds =============================

关于pytest - 在测试执行之前无法获取 pytest 命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50681407/

相关文章:

python - 许多 pytest 固定装置与一个大型 "container"固定装置

python - 使用 PyTest fixture 而不通过它们

python - pytest 可以在测试类中运行测试吗?

python - 是否有用于共享运行/测试配置的基于 PyCharm 的工作流?

python - 如何将服务器作为 py.test 的 fixture 运行

Python 覆盖率报告仅覆盖测试文件

django - 如何覆盖 Django 测试中的数据库设置?

python - 尝试使用 pandas 进行 pytest 测试时出现 Keyerror

python - 如何让两个已发布的装置相互依赖?

python - pytest: `foo is Enum.FOO` 在本地测试为 True,在 travis-ci 上测试为 False