gpt4 book ai didi

python - 为 pytest 中的特定异常自定义错误消息

转载 作者:IT老高 更新时间:2023-10-28 21:14:27 26 4
gpt4 key购买 nike

我正在尝试编写一个 pytest 插件来自定义特定异常的外观 - 更具体地说,模拟异常(预期调用的方法没有被调用等),因为在那些的回溯中有很多无用的噪音异常(exception)。

这是我到目前为止所得到的,它有效,但非常hacky:

import pytest
import flexmock

@pytest.hookimpl()
def pytest_exception_interact(node, call, report):
exc_type = call.excinfo.type

if exc_type == flexmock.MethodCallError:
entry = report.longrepr.reprtraceback.reprentries[-1]
entry.style = 'short'
entry.lines = [entry.lines[-1]]
report.longrepr.reprtraceback.reprentries = [entry]

我认为我使用 hookimpl 做正确的事情并使用简单的 if 语句检查异常类型。

我尝试用一​​个简单的字符串替换 report.longrepr,这也有效,但后来我失去了格式(终端中的颜色)。

作为我想要缩短的输出类型的示例,这里是一个模拟断言失败:

=================================== FAILURES ====================================
_______________________ test_session_calls_remote_client ________________________

def test_session_calls_remote_client():
remote_client = mock.Mock()
session = _make_session(remote_client)
session.connect()
remote_client.connect.assert_called_once_with()
session.run_action('asdf')
> remote_client.run_action.assert_called_once_with('asdff')

tests/unit/executor/remote_test.py:22:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/opt/python-3.6.3/lib/python3.6/unittest/mock.py:825: in assert_called_once_with
return self.assert_called_with(*args, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

_mock_self = <Mock name='mock.run_action' id='139987553103944'>
args = ('asdff',), kwargs = {}, expected = (('asdff',), {})
_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7f51646269d8>
actual = call('asdf'), cause = None

def assert_called_with(_mock_self, *args, **kwargs):
"""assert that the mock was called with the specified arguments.

Raises an AssertionError if the args and keyword args passed in are
different to the last call to the mock."""
self = _mock_self
if self.call_args is None:
expected = self._format_mock_call_signature(args, kwargs)
raise AssertionError('Expected call: %s\nNot called' % (expected,))

def _error_message():
msg = self._format_mock_failure_message(args, kwargs)
return msg
expected = self._call_matcher((args, kwargs))
actual = self._call_matcher(self.call_args)
if expected != actual:
cause = expected if isinstance(expected, Exception) else None
> raise AssertionError(_error_message()) from cause
E AssertionError: Expected call: run_action('asdff')
E Actual call: run_action('asdf')

/opt/python-3.6.3/lib/python3.6/unittest/mock.py:814: AssertionError
====================== 1 failed, 30 passed in 0.28 seconds ======================

最佳答案

如果您的目标是使堆栈跟踪更易于阅读,那么您可以使用以下代码块来输出自定义错误消息。此自定义错误消息显示在堆栈跟踪的末尾,因此您无需向上滚动:

with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
pass
--> Failed: Expecting ZeroDivisionError

来源:pytest's documentation .因此,您可以通过 grep 之类的方式将 pytest 的输出通过管道传输并过滤掉堆栈跟踪中无用的部分,而不是制作插件。

根据我在文档中阅读的内容,您正在使用正确的 pytest 装饰器和 Hook 函数 (pytest_exception_interact)。但是,可能不需要对错误进行类型检查。 This section of the documentation表示“只有在引发不是内部异常(如 skip.Exception)的异常时才调用此钩子(Hook)。”

关于python - 为 pytest 中的特定异常自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com