【问题标题】:Pytest parametrization of test for a list generated from cmdline options in conftest.py从 conftest.py 中的 cmdline 选项生成的列表的测试的 Pytest 参数化
【发布时间】:2019-02-09 03:44:04
【问题描述】:

我正在尝试参数化从 conftest.py 中的命令行选项。

#!/usr/bin/env python

import pytest
import test



def pytest_addoption(parser):
    parser.addoption("--low", action="store", type=int, help="low")
    parser.addoption("--high", action="store",type=int,  help="high")


@pytest.fixture(scope="session", autouse=True)
def user(request):
    return request.config.getoption("low")


@pytest.fixture(scope="session", autouse=True)
def rang(request):
    return request.config.getoption("high")




#test_file.py

def data(low, high):
    return list(range(low, high))

@pytest.mark.parametrize("num", data(10, 20))
def test(num):
    assert num < 1000

我想运行类似“pytest --low=10 --high=100 test_file.py”的命令。对于 x 和 y 之间的值范围,代码与 @pytest.mark.parametrize("num", data(x, y)) 一起工作正常。除了低和高之外,我不想提供任何参数化值。如果我编写 @pytest.mark.parametrize("num", data(low, high)) 之类的代码,则会引发错误。有什么办法可以让这个参数化工作?我知道当我们在方法之外生成列表时代码有效。但我想编写一个生成列表的方法,并在参数化中使用该列表。

有什么方法可以在 test_file.py 的任何地方访问这些低和高 cmdline 选项?

【问题讨论】:

    标签: python-3.x pytest


    【解决方案1】:

    您可以使用 pytest_generate_tests 挂钩对测试进行参数化。使用钩子,您将可以访问命令行参数。

    # conftest.py
    def pytest_addoption(parser):
        parser.addoption("--low", action="store", type=int, help="low")
        parser.addoption("--high", action="store",type=int,  help="high")
    
    
    def pytest_generate_tests(metafunc):
        if 'num' in metafunc.fixturenames:
            lo = metafunc.config.getoption('low')
            hi = metafunc.config.getoption('high')
            metafunc.parametrize('num', range(lo, hi))
    


    # test_file.py
    
    def test_spam(num):
        assert num
    

    另一种可能性是通过pytest.config 访问参数,但请注意,这是一个已弃用的功能,很快就会被删除:

    import pytest
    
    
    def data():
        lo = pytest.config.getoption('low')
        hi = pytest.config.getoption('high')
        return list(range(lo, hi))
    
    
    @pytest.mark.parametrize('num', data())
    def test_spam(num):
        assert num
    

    【讨论】:

    • 元函数方法有效。谢谢你。有什么方法可以在没有固定装置的情况下访问 test_xx.py 文件中的 pytest 参数?在旧版本中,我们曾经使用命名空间来做到这一点,但现在它已被弃用,还有其他访问这些变量值的方法吗?我知道 def func(low, high),我正在寻找其他方法。
    • 通过request 夹具访问配置对象看起来是现在最受期待的方式。但是,没有人可以阻止您将自己的属性附加到 pytest 模块本身,例如在pytest_configure钩子中调用pytest.lo = config.getoption('low')。然后,您可以在测试中的任何位置通过pytest.lo 访问参数。
    • Looking at the deprecations docs,将您自己的全局变量附加到 pytest 模块似乎是替换 pytest_namespace 东西的推荐方法。
    • pytest_generate_tests 也适用于特定的测试文件,如果只使用一个地方可能会更好。如果只有一个测试,if 子句似乎就没有必要了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多