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 from pybind11_tests import exceptions as m
8 
9 
11  with pytest.raises(RuntimeError) as excinfo:
12  m.throw_std_exception()
13  assert msg(excinfo.value) == "This exception was intentionally thrown."
14 
15 
17  with pytest.raises(RuntimeError) as excinfo:
18  m.throw_already_set(False)
19  assert (
20  msg(excinfo.value)
21  == "Internal error: pybind11::error_already_set called while Python error indicator not set."
22  )
23 
24  with pytest.raises(ValueError) as excinfo:
25  m.throw_already_set(True)
26  assert msg(excinfo.value) == "foo"
27 
28 
29 def test_raise_from(msg):
30  with pytest.raises(ValueError) as excinfo:
31  m.raise_from()
32  assert msg(excinfo.value) == "outer"
33  assert msg(excinfo.value.__cause__) == "inner"
34 
35 
37  with pytest.raises(ValueError) as excinfo:
38  m.raise_from_already_set()
39  assert msg(excinfo.value) == "outer"
40  assert msg(excinfo.value.__cause__) == "inner"
41 
42 
44  with pytest.raises(RuntimeError) as excinfo:
45  cm.raise_runtime_error()
46  assert str(excinfo.value) == "My runtime error"
47 
48  with pytest.raises(ValueError) as excinfo:
49  cm.raise_value_error()
50  assert str(excinfo.value) == "My value error"
51 
52  with pytest.raises(ValueError) as excinfo:
53  cm.throw_pybind_value_error()
54  assert str(excinfo.value) == "pybind11 value error"
55 
56  with pytest.raises(TypeError) as excinfo:
57  cm.throw_pybind_type_error()
58  assert str(excinfo.value) == "pybind11 type error"
59 
60  with pytest.raises(StopIteration) as excinfo:
61  cm.throw_stop_iteration()
62 
63  with pytest.raises(cm.LocalSimpleException) as excinfo:
64  cm.throw_local_simple_error()
65  assert msg(excinfo.value) == "external mod"
66 
67  with pytest.raises(KeyError) as excinfo:
68  cm.throw_local_error()
69  # KeyError is a repr of the key, so it has an extra set of quotes
70  assert str(excinfo.value) == "'just local'"
71 
72 
73 # TODO: FIXME
74 @pytest.mark.xfail(
75  "env.PYPY and env.MACOS",
76  raises=RuntimeError,
77  reason="Expected failure with PyPy and libc++ (Issue #2847 & PR #2999)",
78 )
80  with pytest.raises(KeyError):
81  # translator registered in cross_module_tests
82  m.throw_should_be_translated_to_key_error()
83 
84 
86  d = {}
87  assert m.python_call_in_destructor(d) is True
88  assert d["good"] is True
89 
90 
92  unraisable = "PytestUnraisableExceptionWarning"
93  if hasattr(pytest, unraisable): # Python >= 3.8 and pytest >= 6
94  dec = pytest.mark.filterwarnings(f"ignore::pytest.{unraisable}")
95  return dec(f)
96  else:
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:
186  try:
187  m.throws5()
188  except m.MyException5_1:
189  raise RuntimeError("Exception error: caught child from parent")
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):
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 
278 class FlakyException(Exception):
279  def __init__(self, failure_point):
280  if failure_point == "failure_point_init":
281  raise ValueError("triggered_failure_point_init")
282  self.failure_point = failure_point
283 
284  def __str__(self):
285  if self.failure_point == "failure_point_str":
286  raise ValueError("triggered_failure_point_str")
287  return "FlakyException.__str__"
288 
289 
290 @pytest.mark.parametrize(
291  "exc_type, exc_value, expected_what",
292  (
293  (ValueError, "plain_str", "ValueError: plain_str"),
294  (ValueError, ("tuple_elem",), "ValueError: tuple_elem"),
295  (FlakyException, ("happy",), "FlakyException: FlakyException.__str__"),
296  ),
297 )
299  exc_type, exc_value, expected_what
300 ):
301  what, py_err_set_after_what = m.error_already_set_what(exc_type, exc_value)
302  assert not py_err_set_after_what
303  assert what == expected_what
304 
305 
306 @pytest.mark.skipif("env.PYPY", reason="PyErr_NormalizeException Segmentation fault")
308  with pytest.raises(RuntimeError) as excinfo:
309  m.error_already_set_what(FlakyException, ("failure_point_init",))
310  lines = str(excinfo.value).splitlines()
311  # PyErr_NormalizeException replaces the original FlakyException with ValueError:
312  assert lines[:3] == [
313  "pybind11::error_already_set: MISMATCH of original and normalized active exception types:"
314  " ORIGINAL FlakyException REPLACED BY ValueError: triggered_failure_point_init",
315  "",
316  "At:",
317  ]
318  # Checking the first two lines of the traceback as formatted in error_string():
319  assert "test_exceptions.py(" in lines[3]
320  assert lines[3].endswith("): __init__")
321  assert lines[4].endswith("): test_flaky_exception_failure_point_init")
322 
323 
325  what, py_err_set_after_what = m.error_already_set_what(
326  FlakyException, ("failure_point_str",)
327  )
328  assert not py_err_set_after_what
329  lines = what.splitlines()
330  if env.PYPY and len(lines) == 3:
331  n = 3 # Traceback is missing.
332  else:
333  n = 5
334  assert (
335  lines[:n]
336  == [
337  "FlakyException: <MESSAGE UNAVAILABLE DUE TO ANOTHER EXCEPTION>",
338  "",
339  "MESSAGE UNAVAILABLE DUE TO EXCEPTION: ValueError: triggered_failure_point_str",
340  "",
341  "At:",
342  ][:n]
343  )
344 
345 
347  with pytest.raises(RuntimeError) as excinfo:
348  m.test_cross_module_interleaved_error_already_set()
349  assert str(excinfo.value) in (
350  "2nd error.", # Almost all platforms.
351  "RuntimeError: 2nd error.", # Some PyPy builds (seen under macOS).
352  )
353 
354 
356  m.test_error_already_set_double_restore(True) # dry_run
357  with pytest.raises(RuntimeError) as excinfo:
358  m.test_error_already_set_double_restore(False)
359  assert str(excinfo.value) == (
360  "Internal error: pybind11::detail::error_fetch_and_normalize::restore()"
361  " called a second time. ORIGINAL ERROR: ValueError: Random error."
362  )
def test_flaky_exception_failure_point_init()
def test_cross_module_exceptions(msg)
def test_error_already_set_double_restore()
def test_std_exception(msg)
def test_flaky_exception_failure_point_str()
bool hasattr(handle obj, handle name)
Definition: pytypes.h:728
def test_cross_module_exception_translator()
def test_exception_matches()
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
def ignore_pytest_unraisable_warning(f)
def test_error_already_set(msg)
def __init__(self, failure_point)
bool isinstance(handle obj)
Definition: pytypes.h:700
def test_python_alreadyset_in_destructor(monkeypatch, capsys)
def test_local_translator(msg)
def test_throw_nested_exception()
Definition: pytypes.h:1403
def test_cross_module_interleaved_error_already_set()
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
def test_python_call_in_catch()
def test_raise_from_already_set(msg)
def test_error_already_set_what_with_happy_exceptions(exc_type, exc_value, expected_what)
def test_nested_throws(capture)
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2244
def test_raise_from(msg)


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:45