代码之家  ›  专栏  ›  技术社区  ›  thinwybk

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

  •  1
  • thinwybk  · 技术社区  · 6 年前

    我尝试跳过依赖于命令行参数值的特定测试。我试图用 pytest.config.getoption("--some-custom-argument") 就像这里描述的 related question suggestion 在测试文件中,并通过 skipif . 但是 pyest 没有 config . 并通过 request.config.getoption("--some-custom-argument") 似乎只在fixture函数中工作。在测试执行之前,我能不能得到一些不同的命令行参数,以便签入它们 斯基普夫 在文件范围级别上?

    3 回复  |  直到 6 年前
        1
  •  1
  •   hoefling    6 年前

    由于测试是在配置阶段之后和测试收集之前(也就是在测试执行之前)收集的,因此 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 =============================
    
        2
  •  0
  •   Julia Aleksandrova    6 年前

    你可以试着那样做

    @pytest.mark.skipif(pytest.config.option.some-custom-argument=='foo', 
                        reason='i do not want to run this test')
    

    但为什么不使用标记表达式呢?

        3
  •  0
  •   Sergey Makhonin    5 年前

    如果我理解得对,你可能想看看这个 answer .

    建议使用带有 request 对象,并从中读取输入参数值 request.config.getoption("--option_name") request.config.option.name .

    代码段(记入ipetrik):

    # test.py
    def test_name(name):
        assert name == 'almond'
    
    
    # conftest.py
    def pytest_addoption(parser):
        parser.addoption("--name", action="store")
    
    @pytest.fixture(scope='session')
    def name(request):
        name_value = request.config.option.name
        if name_value is None:
            pytest.skip()
        return name_value