接口测试 [求助] pytest hook 函数 pytest_generate_tests, 数据位置问题

爱吃米饭 · 2020年10月29日 · 最后由 爱吃米饭 回复于 2020年12月31日 · 1922 次阅读

pytest 中开放了一些内置 hook 函数,可以实现定制。在研究的过程中,有一些问题不懂,求大佬指教:
问题是:将下面代码的 myids, mydatas 的赋值放到 class 下面,就会报如下错误;但是如果把赋值位置放到 class 外面,就能够成功。
求问这是什么原因呢?
任何帮助都将感激不尽🎀

# 测试代码:
import yaml

class TestParam:

    with open('datas/a.yml') as f:
        datas = yaml.safe_load(f)
        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'

共收到 2 条回复 时间 点赞

"metafunc.module"是指正在被 collect 测试用例的模块
举例:
1.定义在模块中

通过 [module].[attribute] 的方式可以正常调用

2.定义在类中

通过 [module].[attribute] 的方式调用报错

通过 [module].[cls].[attribute] 的方式调用

或者通过类的实例化对象调用

lion_smile 回复

明白了,谢谢~

爱吃米饭 关闭了讨论 12月31日 17:30
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册