test_exceptions.py
Go to the documentation of this file.
1 import sys
2 
3 import pytest
4 
5 import env
6 import pybind11_cross_module_tests as cm
7 import pybind11_tests # noqa: F401
8 from pybind11_tests import exceptions as m
9 
10 
12  with pytest.raises(RuntimeError) as excinfo:
13  m.throw_std_exception()
14  assert msg(excinfo.value) == "This exception was intentionally thrown."
15 
16 
18  with pytest.raises(RuntimeError) as excinfo:
19  m.throw_already_set(False)
20  assert (
21  msg(excinfo.value)
22  == "Internal error: pybind11::error_already_set called while Python error indicator not set."
23  )
24 
25  with pytest.raises(ValueError) as excinfo:
26  m.throw_already_set(True)
27  assert msg(excinfo.value) == "foo"
28 
29 
30 def test_raise_from(msg):
31  with pytest.raises(ValueError) as excinfo:
32  m.raise_from()
33  assert msg(excinfo.value) == "outer"
34  assert msg(excinfo.value.__cause__) == "inner"
35 
36 
38  with pytest.raises(ValueError) as excinfo:
39  m.raise_from_already_set()
40  assert msg(excinfo.value) == "outer"
41  assert msg(excinfo.value.__cause__) == "inner"
42 
43 
45  with pytest.raises(RuntimeError) as excinfo:
46  cm.raise_runtime_error()
47  assert str(excinfo.value) == "My runtime error"
48 
49  with pytest.raises(ValueError) as excinfo:
50  cm.raise_value_error()
51  assert str(excinfo.value) == "My value error"
52 
53  with pytest.raises(ValueError) as excinfo:
54  cm.throw_pybind_value_error()
55  assert str(excinfo.value) == "pybind11 value error"
56 
57  with pytest.raises(TypeError) as excinfo:
58  cm.throw_pybind_type_error()
59  assert str(excinfo.value) == "pybind11 type error"
60 
61  with pytest.raises(StopIteration) as excinfo:
62  cm.throw_stop_iteration()
63 
64  with pytest.raises(cm.LocalSimpleException) as excinfo:
65  cm.throw_local_simple_error()
66  assert msg(excinfo.value) == "external mod"
67 
68  with pytest.raises(KeyError) as excinfo:
69  cm.throw_local_error()
70  # KeyError is a repr of the key, so it has an extra set of quotes
71  assert str(excinfo.value) == "'just local'"
72 
73 
74 # TODO: FIXME
75 @pytest.mark.xfail(
76  "env.MACOS and (env.PYPY or pybind11_tests.compiler_info.startswith('Homebrew Clang'))",
77  raises=RuntimeError,
78  reason="See Issue #2847, PR #2999, PR #4324",
79 )
81  with pytest.raises(KeyError):
82  # translator registered in cross_module_tests
83  m.throw_should_be_translated_to_key_error()
84 
85 
87  d = {}
88  assert m.python_call_in_destructor(d) is True
89  assert d["good"] is True
90 
91 
93  unraisable = "PytestUnraisableExceptionWarning"
94  if hasattr(pytest, unraisable): # Python >= 3.8 and pytest >= 6
95  dec = pytest.mark.filterwarnings(f"ignore::pytest.{unraisable}")
96  return dec(f)
97  return f
98 
99 
100 # TODO: find out why this fails on PyPy, https://foss.heptapod.net/pypy/pypy/-/issues/3583
101 @pytest.mark.xfail(env.PYPY, reason="Failure on PyPy 3.8 (7.3.7)", strict=False)
102 @ignore_pytest_unraisable_warning
103 def test_python_alreadyset_in_destructor(monkeypatch, capsys):
104  hooked = False
105  triggered = False
106 
107  if hasattr(sys, "unraisablehook"): # Python 3.8+
108  hooked = True
109  # Don't take `sys.unraisablehook`, as that's overwritten by pytest
110  default_hook = sys.__unraisablehook__
111 
112  def hook(unraisable_hook_args):
113  exc_type, exc_value, exc_tb, err_msg, obj = unraisable_hook_args
114  if obj == "already_set demo":
115  nonlocal triggered
116  triggered = True
117  default_hook(unraisable_hook_args)
118  return
119 
120  # Use monkeypatch so pytest can apply and remove the patch as appropriate
121  monkeypatch.setattr(sys, "unraisablehook", hook)
122 
123  assert m.python_alreadyset_in_destructor("already_set demo") is True
124  if hooked:
125  assert triggered is True
126 
127  _, captured_stderr = capsys.readouterr()
128  assert captured_stderr.startswith("Exception ignored in: 'already_set demo'")
129  assert captured_stderr.rstrip().endswith("KeyError: 'bar'")
130 
131 
133  assert m.exception_matches()
134  assert m.exception_matches_base()
135  assert m.modulenotfound_exception_matches_base()
136 
137 
138 def test_custom(msg):
139  # Can we catch a MyException?
140  with pytest.raises(m.MyException) as excinfo:
141  m.throws1()
142  assert msg(excinfo.value) == "this error should go to a custom type"
143 
144  # Can we translate to standard Python exceptions?
145  with pytest.raises(RuntimeError) as excinfo:
146  m.throws2()
147  assert msg(excinfo.value) == "this error should go to a standard Python exception"
148 
149  # Can we handle unknown exceptions?
150  with pytest.raises(RuntimeError) as excinfo:
151  m.throws3()
152  assert msg(excinfo.value) == "Caught an unknown exception!"
153 
154  # Can we delegate to another handler by rethrowing?
155  with pytest.raises(m.MyException) as excinfo:
156  m.throws4()
157  assert msg(excinfo.value) == "this error is rethrown"
158 
159  # Can we fall-through to the default handler?
160  with pytest.raises(RuntimeError) as excinfo:
161  m.throws_logic_error()
162  assert (
163  msg(excinfo.value) == "this error should fall through to the standard handler"
164  )
165 
166  # OverFlow error translation.
167  with pytest.raises(OverflowError) as excinfo:
168  m.throws_overflow_error()
169 
170  # Can we handle a helper-declared exception?
171  with pytest.raises(m.MyException5) as excinfo:
172  m.throws5()
173  assert msg(excinfo.value) == "this is a helper-defined translated exception"
174 
175  # Exception subclassing:
176  with pytest.raises(m.MyException5) as excinfo:
177  m.throws5_1()
178  assert msg(excinfo.value) == "MyException5 subclass"
179  assert isinstance(excinfo.value, m.MyException5_1)
180 
181  with pytest.raises(m.MyException5_1) as excinfo:
182  m.throws5_1()
183  assert msg(excinfo.value) == "MyException5 subclass"
184 
185  with pytest.raises(m.MyException5) as excinfo: # noqa: PT012
186  try:
187  m.throws5()
188  except m.MyException5_1 as err:
189  raise RuntimeError("Exception error: caught child from parent") from err
190  assert msg(excinfo.value) == "this is a helper-defined translated exception"
191 
192 
193 def test_nested_throws(capture):
194  """Tests nested (e.g. C++ -> Python -> C++) exception handling"""
195 
196  def throw_myex():
197  raise m.MyException("nested error")
198 
199  def throw_myex5():
200  raise m.MyException5("nested error 5")
201 
202  # In the comments below, the exception is caught in the first step, thrown in the last step
203 
204  # C++ -> Python
205  with capture:
206  m.try_catch(m.MyException5, throw_myex5)
207  assert str(capture).startswith("MyException5: nested error 5")
208 
209  # Python -> C++ -> Python
210  with pytest.raises(m.MyException) as excinfo:
211  m.try_catch(m.MyException5, throw_myex)
212  assert str(excinfo.value) == "nested error"
213 
214  def pycatch(exctype, f, *args): # noqa: ARG001
215  try:
216  f(*args)
217  except m.MyException as e:
218  print(e)
219 
220  # C++ -> Python -> C++ -> Python
221  with capture:
222  m.try_catch(
223  m.MyException5,
224  pycatch,
225  m.MyException,
226  m.try_catch,
227  m.MyException,
228  throw_myex5,
229  )
230  assert str(capture).startswith("MyException5: nested error 5")
231 
232  # C++ -> Python -> C++
233  with capture:
234  m.try_catch(m.MyException, pycatch, m.MyException5, m.throws4)
235  assert capture == "this error is rethrown"
236 
237  # Python -> C++ -> Python -> C++
238  with pytest.raises(m.MyException5) as excinfo:
239  m.try_catch(m.MyException, pycatch, m.MyException, m.throws5)
240  assert str(excinfo.value) == "this is a helper-defined translated exception"
241 
242 
244  with pytest.raises(RuntimeError) as excinfo:
245  m.throw_nested_exception()
246  assert str(excinfo.value) == "Outer Exception"
247  assert str(excinfo.value.__cause__) == "Inner Exception"
248 
249 
250 # This can often happen if you wrap a pybind11 class in a Python wrapper
252  class MyRepr:
253  def __repr__(self):
254  raise AttributeError("Example error")
255 
256  with pytest.raises(TypeError):
257  m.simple_bool_passthrough(MyRepr())
258 
259 
261  """Tests that a local translator works and that the local translator from
262  the cross module is not applied"""
263  with pytest.raises(RuntimeError) as excinfo:
264  m.throws6()
265  assert msg(excinfo.value) == "MyException6 only handled in this module"
266 
267  with pytest.raises(RuntimeError) as excinfo:
268  m.throws_local_error()
269  assert not isinstance(excinfo.value, KeyError)
270  assert msg(excinfo.value) == "never caught"
271 
272  with pytest.raises(Exception) as excinfo:
273  m.throws_local_simple_error()
274  assert not isinstance(excinfo.value, cm.LocalSimpleException)
275  assert msg(excinfo.value) == "this mod"
276 
277 
279  assert m.error_already_set_what(RuntimeError, "\ud927") == (
280  "RuntimeError: \\ud927",
281  False,
282  )
283 
284 
286  assert m.error_already_set_what(RuntimeError, b"\x80") == (
287  "RuntimeError: b'\\x80'",
288  False,
289  )
290 
291 
292 class FlakyException(Exception):
293  def __init__(self, failure_point):
294  if failure_point == "failure_point_init":
295  raise ValueError("triggered_failure_point_init")
296  self.failure_point = failure_point
297 
298  def __str__(self):
299  if self.failure_point == "failure_point_str":
300  raise ValueError("triggered_failure_point_str")
301  return "FlakyException.__str__"
302 
303 
304 @pytest.mark.parametrize(
305  ("exc_type", "exc_value", "expected_what"),
306  [
307  (ValueError, "plain_str", "ValueError: plain_str"),
308  (ValueError, ("tuple_elem",), "ValueError: tuple_elem"),
309  (FlakyException, ("happy",), "FlakyException: FlakyException.__str__"),
310  ],
311 )
313  exc_type, exc_value, expected_what
314 ):
315  what, py_err_set_after_what = m.error_already_set_what(exc_type, exc_value)
316  assert not py_err_set_after_what
317  assert what == expected_what
318 
319 
321  with pytest.raises(RuntimeError) as excinfo:
322  m.error_already_set_what(FlakyException, ("failure_point_init",))
323  lines = str(excinfo.value).splitlines()
324  # PyErr_NormalizeException replaces the original FlakyException with ValueError:
325  assert lines[:3] == [
326  "pybind11::error_already_set: MISMATCH of original and normalized active exception types:"
327  " ORIGINAL FlakyException REPLACED BY ValueError: triggered_failure_point_init",
328  "",
329  "At:",
330  ]
331  # Checking the first two lines of the traceback as formatted in error_string():
332  assert "test_exceptions.py(" in lines[3]
333  assert lines[3].endswith("): __init__")
334  assert lines[4].endswith(
335  "): _test_flaky_exception_failure_point_init_before_py_3_12"
336  )
337 
338 
340  # Behavior change in Python 3.12: https://github.com/python/cpython/issues/102594
341  what, py_err_set_after_what = m.error_already_set_what(
342  FlakyException, ("failure_point_init",)
343  )
344  assert not py_err_set_after_what
345  lines = what.splitlines()
346  assert lines[0].endswith("ValueError[WITH __notes__]: triggered_failure_point_init")
347  assert lines[1] == "__notes__ (len=1):"
348  assert "Normalization failed:" in lines[2]
349  assert "FlakyException" in lines[2]
350 
351 
352 @pytest.mark.skipif(
353  "env.PYPY and sys.version_info[:2] < (3, 12)",
354  reason="PyErr_NormalizeException Segmentation fault",
355 )
357  if sys.version_info[:2] < (3, 12):
359  else:
361 
362 
364  what, py_err_set_after_what = m.error_already_set_what(
365  FlakyException, ("failure_point_str",)
366  )
367  assert not py_err_set_after_what
368  lines = what.splitlines()
369  n = 3 if env.PYPY and len(lines) == 3 else 5
370  assert (
371  lines[:n]
372  == [
373  "FlakyException: <MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>",
374  "",
375  "MESSAGE UNAVAILABLE DUE TO EXCEPTION: ValueError: triggered_failure_point_str",
376  "",
377  "At:",
378  ][:n]
379  )
380 
381 
383  with pytest.raises(RuntimeError) as excinfo:
384  m.test_cross_module_interleaved_error_already_set()
385  assert str(excinfo.value) in (
386  "2nd error.", # Almost all platforms.
387  "RuntimeError: 2nd error.", # Some PyPy builds (seen under macOS).
388  )
389 
390 
392  m.test_error_already_set_double_restore(True) # dry_run
393  with pytest.raises(RuntimeError) as excinfo:
394  m.test_error_already_set_double_restore(False)
395  assert str(excinfo.value) == (
396  "Internal error: pybind11::detail::error_fetch_and_normalize::restore()"
397  " called a second time. ORIGINAL ERROR: ValueError: Random error."
398  )
399 
400 
402  # https://github.com/pybind/pybind11/issues/4075
403  what = m.test_pypy_oserror_normalization()
404  assert "this_filename_must_not_exist" in what
405 
406 
408  with pytest.raises(RuntimeError) as excinfo:
409  m.test_fn_cast_int(lambda: None)
410 
411  assert str(excinfo.value).startswith(
412  "Unable to cast Python instance of type <class 'NoneType'> to C++ type"
413  )
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
test_exceptions.test_std_exception
def test_std_exception(msg)
Definition: test_exceptions.py:11
test_exceptions.test_error_already_set
def test_error_already_set(msg)
Definition: test_exceptions.py:17
test_exceptions.test_raise_from
def test_raise_from(msg)
Definition: test_exceptions.py:30
test_exceptions.FlakyException.failure_point
failure_point
Definition: test_exceptions.py:296
test_exceptions._test_flaky_exception_failure_point_init_before_py_3_12
def _test_flaky_exception_failure_point_init_before_py_3_12()
Definition: test_exceptions.py:320
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:853
test_exceptions.test_error_already_set_message_with_malformed_utf8
def test_error_already_set_message_with_malformed_utf8()
Definition: test_exceptions.py:285
test_exceptions.test_throw_nested_exception
def test_throw_nested_exception()
Definition: test_exceptions.py:243
test_exceptions._test_flaky_exception_failure_point_init_py_3_12
def _test_flaky_exception_failure_point_init_py_3_12()
Definition: test_exceptions.py:339
test_exceptions.test_nested_throws
def test_nested_throws(capture)
Definition: test_exceptions.py:193
test_exceptions.test_raise_from_already_set
def test_raise_from_already_set(msg)
Definition: test_exceptions.py:37
test_exceptions.test_cross_module_exception_translator
def test_cross_module_exception_translator()
Definition: test_exceptions.py:80
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:825
gtwrap.interface_parser.function.__repr__
str __repr__(self)
Definition: interface_parser/function.py:53
test_exceptions.test_flaky_exception_failure_point_init
def test_flaky_exception_failure_point_init()
Definition: test_exceptions.py:356
test_exceptions.test_python_call_in_catch
def test_python_call_in_catch()
Definition: test_exceptions.py:86
test_exceptions.test_error_already_set_message_with_unicode_surrogate
def test_error_already_set_message_with_unicode_surrogate()
Definition: test_exceptions.py:278
test_exceptions.test_exception_matches
def test_exception_matches()
Definition: test_exceptions.py:132
test_exceptions.test_fn_cast_int_exception
def test_fn_cast_int_exception()
Definition: test_exceptions.py:407
test_exceptions.test_pypy_oserror_normalization
def test_pypy_oserror_normalization()
Definition: test_exceptions.py:401
test_exceptions.test_local_translator
def test_local_translator(msg)
Definition: test_exceptions.py:260
test_exceptions.test_python_alreadyset_in_destructor
def test_python_alreadyset_in_destructor(monkeypatch, capsys)
Definition: test_exceptions.py:103
test_exceptions.FlakyException.__str__
def __str__(self)
Definition: test_exceptions.py:298
test_exceptions.ignore_pytest_unraisable_warning
def ignore_pytest_unraisable_warning(f)
Definition: test_exceptions.py:92
test_exceptions.test_cross_module_interleaved_error_already_set
def test_cross_module_interleaved_error_already_set()
Definition: test_exceptions.py:382
str
Definition: pytypes.h:1524
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
test_exceptions.test_invalid_repr
def test_invalid_repr()
Definition: test_exceptions.py:251
test_exceptions.test_flaky_exception_failure_point_str
def test_flaky_exception_failure_point_str()
Definition: test_exceptions.py:363
test_exceptions.test_custom
def test_custom(msg)
Definition: test_exceptions.py:138
test_exceptions.FlakyException.__init__
def __init__(self, failure_point)
Definition: test_exceptions.py:293
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2399
test_exceptions.test_error_already_set_double_restore
def test_error_already_set_double_restore()
Definition: test_exceptions.py:391
test_exceptions.test_error_already_set_what_with_happy_exceptions
def test_error_already_set_what_with_happy_exceptions(exc_type, exc_value, expected_what)
Definition: test_exceptions.py:312
test_exceptions.test_cross_module_exceptions
def test_cross_module_exceptions(msg)
Definition: test_exceptions.py:44
test_exceptions.FlakyException
Definition: test_exceptions.py:292
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:28