如何根据特定异常信息将Pytest测试结果从失败改为跳过?
捕获特定错误时将Pytest测试从失败转为跳过
场景与需求
- 使用Appium进行自动化测试时,偶尔会遇到Appium服务器返回500错误,错误信息为:
"An unknown server-side error occurred while processing the command." - 目前暂时无法彻底修复该问题,需要实现:当测试因该特定错误失败时,将测试结果标记为跳过而非失败
尝试过的无效实现
曾尝试通过pytest_runtest_setup钩子实现,但代码无法正常工作:
def pytest_runtest_setup(item): excinfo = None try: item.obj() except Exception as e: excinfo = sys.exc_info() if excinfo and "An unknown server-side error occurred while processing the command." in str(excinfo[1]): pytest.skip("Skipping test due to error message")
可行方案
经@Teejay提示,使用带hookwrapper=True装饰器的pytest_runtest_call钩子可以实现需求,目前该方案在测试套件中运行良好:
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(item): output = yield if output.excinfo: for potential_error_message in expected_failure_messages.keys(): if output._excinfo[1].stacktrace and potential_error_message in output._excinfo[1].stacktrace: pytest.skip(reason=expected_failure_messages[potential_error_message])
实现说明
该钩子会在测试执行完成后捕获异常信息,遍历预设的错误信息列表,检查异常的堆栈跟踪中是否包含目标错误字符串;若匹配,则调用pytest.skip()将当前测试标记为跳过,并使用预设的原因描述。
内容的提问来源于stack exchange,提问作者Nick H
相关产品推荐
相关产品推荐

