我想进行 pytest(通过 TestInfra )来断言主机上是否存在软件包。 我有一个应该位于文本文件中的包列表,我可以读取该列表并将其放入数组中。我想使用该数组来参数化 fixture ,以便我可以在测试中使用它。
类似于:
@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
中调用固定功能:
@pytest.mark.parametrize("name", packages())
def test_packages(host, name):
...
关于pytest:如何从文件中读取灯具列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51191251/