从pytest_generate_tests()获取参数化参数的pytest会话作用域夹具

时间:2020-09-02 16:56:59

标签: python-3.x pytest fixtures

下午好,

我有一个可以加载大量数据的设备,这些数据将在一夜之间记录下来。然后将其用于分析数据不同方面的各种测试中。

加载此数据需要花费相当长的时间,所以我只希望灯具运行一次并将相同的数据传递给每个测试。我读到的方法是将设备范围标记为会话问题,然后是由于设备接受了通过pytest_generate_tests()传递的命令行参数(测试数据的位置),因此出现以下错误: ScopeMismatch:您尝试通过涉及工厂的“会话”范围内的请求对象访问“功能”范围内的灯具“路径”

这是一种简化的娱乐活动:

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption("--path", action="store", required=True, help='Path to folder containing the data for the tests to inspect, e.g. ncom files.')


def pytest_generate_tests(metafunc):
    # This is called for every test. Only get/set command line arguments
    # if the argument is specified in the list of test "fixturenames".
    if "path" in metafunc.fixturenames:
        metafunc.parametrize("path", ['../temp/' + metafunc.config.getoption("--path")])

测试文件

import pytest

@pytest.fixture(scope='session')
def supply_data(path):
    data = path
    return data

def test_one(supply_data):
    assert supply_data=='a path', 'Failed'

有人可以建议如何做这项工作,或者提出一种更好的方法来实现我的目标吗?

非常感谢

塞恩

1 个答案:

答案 0 :(得分:1)

如果我正确理解这一点,那么您的路径在测试会话期间不会更改,因此从命令行参数在固定装置中读取它就足够了:

@pytest.fixture(scope='session')
def supply_data(request):
    path = '../temp/' + request.config.getoption("--path")
    data = read_data_from_path(path)
    yield data