【问题标题】:pytest session scoped fixture that takes parameterized argument from pytest_generate_tests()从 pytest_generate_tests() 获取参数化参数的 pytest 会话范围固定装置
【发布时间】:2020-09-02 16:56:59
【问题描述】:

下午好,

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

加载这些数据需要很长时间,所以我只希望夹具运行一次并将相同的数据传递给每个测试。我读到这样做的方法是将夹具范围标记为会话,然后问题是因为夹具接受了通过 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'

任何人都可以建议如何使这项工作或更好的方法来实现我正在尝试做的事情吗?

非常感谢

肖恩

【问题讨论】:

    标签: python-3.x pytest fixtures


    【解决方案1】:

    如果我理解正确,您的路径在测试会话期间不会改变,因此从命令行参数中读取它就足够了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多