问题:课程上讲的pytest_generate_tests的用法中,为什么把参数放到class类里面,就会报错呢?
# 测试代码:
import yaml
# param1 要与conftest.py 里面处理的param1 保持一致
class TestParam:
with open('datas/a.yml') as f:
datas = yaml.safe_load(f)
# myids 和mydatas 要与conftest.py 勾子函数里面的
# metafunc.module.datas, ids=metafunc.module.myids 保持一致
myids = datas.keys()
mydatas = datas.values()
def test_param(self, param1):
print(f"param = {param1}")
print("动态生成测试用例")
# conftest.py
def pytest_generate_tests(metafunc: "Metafunc") -> None:
if "param1" in metafunc.fixturenames:
metafunc.parametrize("param1",
metafunc.module.mydatas,
ids=metafunc.module.myids,
scope='function')
# 执行结果:
test_param.py:None (test_param.py)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/hooks.py:286: in __call__
return self._hookexec(self, self.get_hookimpls(), kwargs)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/manager.py:93: in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/manager.py:87: in <lambda>
firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/_pytest/python.py:246: in pytest_pycollect_makeitem
res = list(collector._genfunctions(name, obj))
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/_pytest/python.py:454: in _genfunctions
self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/hooks.py:324: in call_extra
return self(**kwargs)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/hooks.py:286: in __call__
return self._hookexec(self, self.get_hookimpls(), kwargs)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/manager.py:93: in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
../../../new_test_data/mno_test/venv/lib/python3.7/site-packages/pluggy/manager.py:87: in <lambda>
firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
conftest.py:74: in pytest_generate_tests
metafunc.module.mydatas,
E AttributeError: module 'test_param' has no attribute 'mydatas'
感谢!!