我有一些测试代码来检查目标文件的内容,如:
sc = samplechecker(json_root, 'target_file_to_check', {params})
result = sc.run()
res = sc.getId()
taskIds.append(res['data']['Id'])
assert result
如果目标文件不存在,则希望跳过测试,因此修改了代码:
try :
sc = samplechecker(json_root, 'target_file_to_check', {params})
except FileNotFoundError as exc:
pytest.skip(f"!!! Target file {exc.filename} not found !!!")
result = sc.run()
res = sc.getId()
taskIds.append(res['data']['Id'])
assert result
这对于这一种情况很好,但我有几个类似的测试模块,所以我想把它也应用到所有其他情况。因此,尝试在conftest.py中添加pytest\u exception\u interact:
in conftest.py :
import pytest
@pytest.hookimpl()
def pytest_exception_interact(node, call, report):
excinfo = call.excinfo
excvalue = excinfo.value
if excinfo.type == FileNotFoundError:
pytest.skip(f"!!! Target file {excvalue.filename} not found !!!")
但这不是我想要的方式。只是失败了很多内部错误
...
INTERNALERROR> File "/home/jyoun/work/venv_xdr-ac/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR> return outcome.get_result()
INTERNALERROR> File "/home/jyoun/work/venv_xdr-ac/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR> raise ex[1].with_traceback(ex[2])
INTERNALERROR> File "/home/jyoun/work/venv_xdr-ac/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "/home/jyoun/work/venv_xdr-ac/git/SOC-SampleCode/api_reference/test/conftest.py", line 26, in pytest_exception_interact
INTERNALERROR> pytest.skip(f"!!! Target file {excvalue.filename} not found !!!")
INTERNALERROR> File "/home/jyoun/work/venv_xdr-ac/lib/python3.7/site-packages/_pytest/outcomes.py", line 112, in skip
INTERNALERROR> raise Skipped(msg=msg, allow_module_level=allow_module_level)
INTERNALERROR> Skipped: !!! Target file ../sample/targetfile1 not found !!!
我怎样才能达到我想要的目标
你看到这个内部错误的原因是因为你在钩子实现中引发了一个异常,这个钩子实现是pytest的一个小插件
换句话说,您实现了一个小插件来检查测试是否由于给定的异常而失败,如果这是真的,您将引发一个异常。相反,您应该了解如何将该测试(我认为它在这里表示为节点)设置为跳过,并在适当的位置添加跳过描述
如果这是您将在许多其他测试中使用的东西,我建议您投入一些时间来这样做
另一方面,如果偶尔使用它,并且您希望看到它更接近您的测试,那么您可以实现一个函数装饰器来捕获异常,并在测试运行时引发跳过异常
例如:
然后将您的测试方法装饰如下:
相关问题 更多 >
编程相关推荐