pytest:如何从文件中读取固定装置列表?

pytest: How do I read a list of fixtures from a file?

我想通过 pytest(通过 TestInfra)来断言主机上存在包。 我有一个应该在文本文件中的包列表,我可以读取它并将其放入一个数组中。我想使用该数组来参数化夹具,以便我可以在测试中使用它。

类似于:

@pytest.fixture
def packages():
    listfile = open("list.txt", "r")
    packages = listfile.read().splitlines()
   return packages

然后用它来参数化测试:

@pytest.mark.parametrize("name", packages)
    def test_packages(host, name):
    assert host.package(name).is_installed

我得到的错误是

    /home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:617: in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
/home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:222: in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
/home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:216: in <lambda>
    firstresult=hook.spec_opts.get('firstresult'),
/home/becker/molecule/local/lib/python2.7/site-packages/_pytest/python.py:197: in pytest_pycollect_makeitem
    res = list(collector._genfunctions(name, obj))
/home/becker/molecule/local/lib/python2.7/site-packages/_pytest/python.py:390: in _genfunctions
    self.ihook.pytest_generate_tests(metafunc=metafunc)
/home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:617: in __call__
    return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
/home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:222: in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
/home/becker/molecule/local/lib/python2.7/site-packages/pluggy/__init__.py:216: in <lambda>
    firstresult=hook.spec_opts.get('firstresult'),
/home/becker/molecule/local/lib/python2.7/site-packages/_pytest/python.py:122: in pytest_generate_tests
    metafunc.parametrize(*marker.args, **marker.kwargs)
/home/becker/molecule/local/lib/python2.7/site-packages/_pytest/python.py:809: in parametrize
    argnames, argvalues, self.function, self.config)
/home/becker/molecule/local/lib/python2.7/site-packages/_pytest/mark/structures.py:102: in _for_parametrize
    for x in argvalues]
E   TypeError: 'function' object is not iterable
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.41 seconds ============================

目前,pytest 不支持将灯具作为参数传递给 pytest.mark.parametrize。您可以在issue #349.

中跟踪相关讨论的当前状态

然而,固定装置也是函数。因此,正如评论中所建议的,您可以简单地调用 parametrize:

中的 fixture 函数
@pytest.mark.parametrize("name", packages())
def test_packages(host, name):
    ...

您可以使用 pytest-cases 将夹具作为参数传递:https://smarie.github.io/python-pytest-cases/(在 pytest 的许多其他非常有用的扩展中)