pytest:如何从文件中读取灯具列表?

时间:2018-07-05 12:23:54

标签: pytest fixtures

我想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 ============================

2 个答案:

答案 0 :(得分:1)

当前,pytest不支持将夹具作为参数传递到pytest.mark.parametrize。您可以在issue #349中跟踪相关讨论的当前状态。

但是,夹具也是功能。因此,如注释中所建议,您可以简单地在parametrize中调用Fixture函数:

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

答案 1 :(得分:1)

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