Python raise和raise fromPython 之间的区别是什么?
try:
raise ValueError
except Exception as e:
raise IndexError
Run Code Online (Sandbox Code Playgroud)
产量
Traceback (most recent call last):
File "tmp.py", line 2, in <module>
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "tmp.py", line 4, in <module>
raise IndexError
IndexError
Run Code Online (Sandbox Code Playgroud)
和
try:
raise ValueError
except Exception as e:
raise IndexError from e
Run Code Online (Sandbox Code Playgroud)
产量
Traceback (most recent call last):
File "tmp.py", line 2, in <module>
raise ValueError …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个pytest插件来自定义特定异常的外观 - 更具体地说,模拟异常(预期被调用的方法没有被调用等),因为在这些异常的追溯中存在大量无用的噪声.
这是我到目前为止所做的,它有效,但非常黑客:
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]
Run Code Online (Sandbox Code Playgroud)
我认为我正在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:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ …Run Code Online (Sandbox Code Playgroud)