是否可以在pytest_generate_tests()内部使用固定装置?

时间:2019-12-12 17:06:27

标签: pytest

我在conftest.py中有一些固定装置,可以在实际测试功能中正常工作。但是,我想根据其中一些灯具的数据使用pytest_generate_tests()参数化一些测试。

我想做的事情(简体):

-- conftest.py --
# my fixture returns a list of device names.
@pytest.fixture(scope="module")
def device_list(something):
    device_list = ['dev1', 'dev2', 'dev3', 'test']
    return device_list

-- test001.py --
# generate tests using the device_list fixture I defined above.
def pytest_generate_tests(metafunc):
    metafunc.parametrize('devices', itertools.chain(device_list), ids=repr)

# A test that is parametrized by the above function.
def test_do_stuff(devices):
    assert "dev" in devices

# Output should/would be:
dev1: pass
dev2: pass
dev3: pass
test: FAIL

当然,我遇到的问题是在pytest_generate_tests()中,它抱怨device_list未定义。如果我尝试将其传递给pytest_generate_tests(metafunc,device_list),则会收到错误消息。

我要这样做的原因是,我在不同文件中的一堆不同测试中使用了该“ device_list”列表,在该文件中,我想使用pytest_generate_tests()对使用同一列表的测试进行参数化。

这不可能吗?如果我必须在该函数中复制我的灯具,那么使用pytest_generate_tests()有什么意义?

3 个答案:

答案 0 :(得分:0)

根据我多年来收集的资料,固定装置与pytest的后期收集阶段紧密相关。我已经尝试过很多次来做类似的事情,但是从来没有真正解决过。

相反,您可以创建一个函数来执行固定装置要执行的操作,然后在generate_tests挂钩中调用该函数。然后,如果您仍然需要将其用作固定装置,请再次调用它(或保存结果等)。

答案 1 :(得分:0)

遇到同样的问题,同时得到了 this article,它以某种方式提供了一种解决方法。只需查看救援的钩子标题下的底部,您就会明白:

66

看,这里是通过调用前缀为'data_'的fixture来加载数据。

答案 2 :(得分:0)

@pytest.fixture(scope="module", autouse=True)
def device_list(something):
    device_list = ['dev1', 'dev2', 'dev3', 'test']
    return device_list

通过在 pytest 固定装置装饰器中使用 autouse=True,您可以确保 pytest_generate_tests 可以访问 device_list

相关问题