Debian Codegraph @

pypy/module/_hpy_universal/test/_vendored/test_hpyerr.py

raw symbols SCIP
1 from .support import HPyTest, SUPPORTS_SYS_EXECUTABLE, trampoline
2
3
4 class TestErr(HPyTest):
5
6 def test_NoMemory(self):
7 import pytest
8 mod = self.make_module("""
9 HPyDef_METH(f, "f", HPyFunc_NOARGS)
10 static HPy f_impl(HPyContext *ctx, HPy self)
11 {
12 return HPyErr_NoMemory(ctx);
13 }
14 @EXPORT(f)
15 @INIT
16 """)
17 with pytest.raises(MemoryError):
18 mod.f()
19
20 def test_FatalError(self, python_subprocess, fatal_exit_code):
21 mod = self.compile_module("""
22 HPyDef_METH(f, "f", HPyFunc_NOARGS)
23 static HPy f_impl(HPyContext *ctx, HPy self)
24 {
25 HPy_FatalError(ctx, "boom!");
26 // note: no 'return' statement. This also tests that
27 // the call above is known to never return---otherwise,
28 // we get a warning from the missing 'return' and it is
29 // turned into an error.
30 }
31 @EXPORT(f)
32 @INIT
33 """)
34 if not SUPPORTS_SYS_EXECUTABLE:
35 # if sys.executable is not available (e.g. inside pypy app-level)
36 # tests, then skip the rest of this test
37 return
38 # subprocess is not importable in pypy app-level tests
39 result = python_subprocess.run(mod, "mod.f()")
40 assert result.returncode == fatal_exit_code
41 assert result.stdout == b""
42 # In Python 3.9, the Py_FatalError() function was replaced with a macro
43 # which automatically prepends the name of the current function, so
44 # we have to allow for that difference here:
45 stderr_msg = result.stderr.splitlines()[0]
46 assert stderr_msg.startswith(b"Fatal Python error: ")
47 assert stderr_msg.endswith(b": boom!")
48
49 def test_HPyErr_Occurred(self):
50 import pytest
51 mod = self.make_module("""
52 HPyDef_METH(f, "f", HPyFunc_O)
53 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
54 {
55 HPyLong_AsLong(ctx, arg);
56 if (HPyErr_Occurred(ctx)) {
57 return HPyErr_SetString(ctx, ctx->h_ValueError, "hello world");
58 }
59 return HPyLong_FromLong(ctx, -1002);
60 }
61 @EXPORT(f)
62 @INIT
63 """)
64 assert mod.f(-10) == -1002
65 with pytest.raises(ValueError) as exc:
66 mod.f("not an integer")
67 assert str(exc.value) == 'hello world'
68
69 def test_HPyErr_Cleared(self):
70 import sys
71 mod = self.make_module("""
72 HPyDef_METH(f, "f", HPyFunc_NOARGS)
73 static HPy f_impl(HPyContext *ctx, HPy self)
74 {
75 HPyErr_SetString(ctx, ctx->h_ValueError, "hello world");
76 HPyErr_Clear(ctx);
77 return HPy_Dup(ctx, ctx->h_None);
78 }
79 @EXPORT(f)
80 @INIT
81 """)
82 assert mod.f() is None
83 assert sys.exc_info() == (None, None, None)
84
85 def test_HPyErr_SetString(self):
86 import pytest
87 mod = self.make_module("""
88 HPyDef_METH(f, "f", HPyFunc_NOARGS)
89 static HPy f_impl(HPyContext *ctx, HPy self)
90 {
91 return HPyErr_SetString(ctx, ctx->h_ValueError, "error message");
92 }
93
94 HPyDef_METH(g, "g", HPyFunc_NOARGS)
95 static HPy g_impl(HPyContext *ctx, HPy self)
96 {
97 HPyErr_SetString(ctx, ctx->h_ValueError, "error message");
98 return HPy_NULL;
99 }
100
101 @EXPORT(g)
102 @EXPORT(f)
103 @INIT
104 """)
105 with pytest.raises(ValueError) as err:
106 mod.f()
107 assert str(err.value) == "error message"
108
109 with pytest.raises(ValueError) as err:
110 mod.g()
111 assert str(err.value) == "error message"
112
113 def test_HPyErr_SetObject(self):
114 import pytest
115 mod = self.make_module("""
116 HPyDef_METH(f, "f", HPyFunc_O)
117 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
118 {
119 return HPyErr_SetObject(ctx, ctx->h_ValueError, arg);
120 }
121 @EXPORT(f)
122 @INIT
123 """)
124 with pytest.raises(ValueError) as err:
125 mod.f(ValueError("error message"))
126 assert str(err.value) == "error message"
127
128 def test_HPyErr_SetFromErrno(self):
129 import pytest
130 import errno
131 mod = self.make_module("""
132 #include <errno.h>
133
134 HPyDef_METH(f, "f", HPyFunc_O)
135 static HPy f_impl(HPyContext *ctx, HPy self, HPy type)
136 {{
137 errno = {errno};
138 return HPyErr_SetFromErrno(ctx, type);
139 }}
140 @EXPORT(f)
141 @INIT
142 """.format(errno = errno.EINVAL))
143 for type in [OSError, TimeoutError]:
144 with pytest.raises(type) as err:
145 mod.f(type)
146
147 if self.runappdirect:
148 # untranslated the errno can get reset by the calls to ll2ctypes
149 assert err.value.errno == errno.EINVAL
150
151 def test_HPyErr_SetFromErrnoWithFilenameObjects(self):
152 import pytest
153 import errno
154 mod = self.make_module("""
155 #include <errno.h>
156
157 HPyDef_METH(f, "f", HPyFunc_VARARGS)
158 static HPy f_impl(HPyContext *ctx, HPy self,
159 const HPy *args, size_t nargs)
160 {{
161 HPy type, file1, file2;
162 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OOO", &type, &file1, &file2))
163 return HPy_NULL;
164
165 errno = {errno};
166 if (HPy_Is(ctx, file2, ctx->h_None)) {{
167 return HPyErr_SetFromErrnoWithFilenameObject(ctx, type, file1);
168 }} else {{
169 return HPyErr_SetFromErrnoWithFilenameObjects(ctx, type, file1, file2);
170 }}
171 }}
172 @EXPORT(f)
173 @INIT
174 """.format(errno = errno.EINVAL))
175 file1 = "some/file/name/to/be/asserted"
176 with pytest.raises(OSError) as err:
177 mod.f(OSError, file1, None)
178 if self.runappdirect:
179 # untranslated the errno can get reset by the calls to ll2ctypes
180 assert err.value.errno == errno.EINVAL
181 assert err.value.filename == file1
182
183 file2 = "some/different/file/name/to/be/asserted"
184 with pytest.raises(OSError) as err:
185 mod.f(OSError, file1, file2)
186 if self.runappdirect:
187 # untranslated the errno can get reset by the calls to ll2ctypes
188 assert err.value.errno == errno.EINVAL
189 assert err.value.filename == file1
190 assert err.value.filename2 == file2
191
192 def test_HPyErr_SetFromErrnoWithFilename(self):
193 import pytest
194 import errno
195 mod = self.make_module("""
196 #include <errno.h>
197
198 HPyDef_METH(f, "f", HPyFunc_O)
199 static HPy f_impl(HPyContext *ctx, HPy self, HPy type)
200 {{
201 errno = {errno};
202 return HPyErr_SetFromErrnoWithFilename(ctx, type, "Some message that will be asserted");
203 }}
204 @EXPORT(f)
205 @INIT
206 """.format(errno = errno.EINVAL))
207 with pytest.raises(OSError) as err:
208 mod.f(OSError)
209
210 if self.runappdirect:
211 # untranslated the errno can get reset by the calls to ll2ctypes
212 assert err.value.errno == errno.EINVAL
213 assert "Some message that will be asserted" in str(err.value)
214
215 def test_h_exceptions(self):
216 import pytest
217 mod = self.make_module("""
218 HPyDef_METH(f, "f", HPyFunc_O)
219 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
220 {
221 HPy h_dict, h_err;
222 h_dict = HPyDict_New(ctx);
223 HPy_SetItem_s(ctx, h_dict, "BaseException", ctx->h_BaseException);
224 HPy_SetItem_s(ctx, h_dict, "Exception", ctx->h_Exception);
225 HPy_SetItem_s(ctx, h_dict, "StopAsyncIteration", ctx->h_StopAsyncIteration);
226 HPy_SetItem_s(ctx, h_dict, "StopIteration", ctx->h_StopIteration);
227 HPy_SetItem_s(ctx, h_dict, "GeneratorExit", ctx->h_GeneratorExit);
228 HPy_SetItem_s(ctx, h_dict, "ArithmeticError", ctx->h_ArithmeticError);
229 HPy_SetItem_s(ctx, h_dict, "LookupError", ctx->h_LookupError);
230 HPy_SetItem_s(ctx, h_dict, "AssertionError", ctx->h_AssertionError);
231 HPy_SetItem_s(ctx, h_dict, "AttributeError", ctx->h_AttributeError);
232 HPy_SetItem_s(ctx, h_dict, "BufferError", ctx->h_BufferError);
233 HPy_SetItem_s(ctx, h_dict, "EOFError", ctx->h_EOFError);
234 HPy_SetItem_s(ctx, h_dict, "FloatingPointError", ctx->h_FloatingPointError);
235 HPy_SetItem_s(ctx, h_dict, "OSError", ctx->h_OSError);
236 HPy_SetItem_s(ctx, h_dict, "ImportError", ctx->h_ImportError);
237 HPy_SetItem_s(ctx, h_dict, "ModuleNotFoundError", ctx->h_ModuleNotFoundError);
238 HPy_SetItem_s(ctx, h_dict, "IndexError", ctx->h_IndexError);
239 HPy_SetItem_s(ctx, h_dict, "KeyError", ctx->h_KeyError);
240 HPy_SetItem_s(ctx, h_dict, "KeyboardInterrupt", ctx->h_KeyboardInterrupt);
241 HPy_SetItem_s(ctx, h_dict, "MemoryError", ctx->h_MemoryError);
242 HPy_SetItem_s(ctx, h_dict, "NameError", ctx->h_NameError);
243 HPy_SetItem_s(ctx, h_dict, "OverflowError", ctx->h_OverflowError);
244 HPy_SetItem_s(ctx, h_dict, "RuntimeError", ctx->h_RuntimeError);
245 HPy_SetItem_s(ctx, h_dict, "RecursionError", ctx->h_RecursionError);
246 HPy_SetItem_s(ctx, h_dict, "NotImplementedError", ctx->h_NotImplementedError);
247 HPy_SetItem_s(ctx, h_dict, "SyntaxError", ctx->h_SyntaxError);
248 HPy_SetItem_s(ctx, h_dict, "IndentationError", ctx->h_IndentationError);
249 HPy_SetItem_s(ctx, h_dict, "TabError", ctx->h_TabError);
250 HPy_SetItem_s(ctx, h_dict, "ReferenceError", ctx->h_ReferenceError);
251 HPy_SetItem_s(ctx, h_dict, "SystemError", ctx->h_SystemError);
252 HPy_SetItem_s(ctx, h_dict, "SystemExit", ctx->h_SystemExit);
253 HPy_SetItem_s(ctx, h_dict, "TypeError", ctx->h_TypeError);
254 HPy_SetItem_s(ctx, h_dict, "UnboundLocalError", ctx->h_UnboundLocalError);
255 HPy_SetItem_s(ctx, h_dict, "ValueError", ctx->h_ValueError);
256 HPy_SetItem_s(ctx, h_dict, "ZeroDivisionError", ctx->h_ZeroDivisionError);
257 HPy_SetItem_s(ctx, h_dict, "BlockingIOError", ctx->h_BlockingIOError);
258 HPy_SetItem_s(ctx, h_dict, "BrokenPipeError", ctx->h_BrokenPipeError);
259 HPy_SetItem_s(ctx, h_dict, "ChildProcessError", ctx->h_ChildProcessError);
260 HPy_SetItem_s(ctx, h_dict, "ConnectionError", ctx->h_ConnectionError);
261 HPy_SetItem_s(ctx, h_dict, "ConnectionAbortedError", ctx->h_ConnectionAbortedError);
262 HPy_SetItem_s(ctx, h_dict, "ConnectionRefusedError", ctx->h_ConnectionRefusedError);
263 HPy_SetItem_s(ctx, h_dict, "ConnectionResetError", ctx->h_ConnectionResetError);
264 HPy_SetItem_s(ctx, h_dict, "FileExistsError", ctx->h_FileExistsError);
265 HPy_SetItem_s(ctx, h_dict, "FileNotFoundError", ctx->h_FileNotFoundError);
266 HPy_SetItem_s(ctx, h_dict, "InterruptedError", ctx->h_InterruptedError);
267 HPy_SetItem_s(ctx, h_dict, "IsADirectoryError", ctx->h_IsADirectoryError);
268 HPy_SetItem_s(ctx, h_dict, "NotADirectoryError", ctx->h_NotADirectoryError);
269 HPy_SetItem_s(ctx, h_dict, "PermissionError", ctx->h_PermissionError);
270 HPy_SetItem_s(ctx, h_dict, "ProcessLookupError", ctx->h_ProcessLookupError);
271 HPy_SetItem_s(ctx, h_dict, "TimeoutError", ctx->h_TimeoutError);
272 h_err = HPy_GetItem(ctx, h_dict, arg);
273 if (HPy_IsNull(h_err)) {
274 HPy_FatalError(ctx, "missing exception type");
275 }
276 HPyErr_SetString(ctx, h_err, "error message");
277 HPy_Close(ctx, h_dict);
278 HPy_Close(ctx, h_err);
279 return HPy_NULL;
280 }
281 @EXPORT(f)
282 @INIT
283 """)
284
285 def check_exception(cls):
286 with pytest.raises(cls):
287 mod.f(cls.__name__)
288
289 check_exception(BaseException)
290 check_exception(Exception)
291 check_exception(StopAsyncIteration)
292 check_exception(StopIteration)
293 check_exception(GeneratorExit)
294 check_exception(ArithmeticError)
295 check_exception(LookupError)
296 check_exception(AssertionError)
297 check_exception(AttributeError)
298 check_exception(BufferError)
299 check_exception(EOFError)
300 check_exception(FloatingPointError)
301 check_exception(OSError)
302 check_exception(ImportError)
303 check_exception(ModuleNotFoundError)
304 check_exception(IndexError)
305 check_exception(KeyError)
306 check_exception(KeyboardInterrupt)
307 check_exception(MemoryError)
308 check_exception(NameError)
309 check_exception(OverflowError)
310 check_exception(RuntimeError)
311 check_exception(RecursionError)
312 check_exception(NotImplementedError)
313 check_exception(SyntaxError)
314 check_exception(IndentationError)
315 check_exception(TabError)
316 check_exception(ReferenceError)
317 check_exception(SystemError)
318 check_exception(SystemExit)
319 check_exception(TypeError)
320 check_exception(UnboundLocalError)
321 check_exception(ValueError)
322 check_exception(ZeroDivisionError)
323 check_exception(BlockingIOError)
324 check_exception(BrokenPipeError)
325 check_exception(ChildProcessError)
326 check_exception(ConnectionError)
327 check_exception(ConnectionAbortedError)
328 check_exception(ConnectionRefusedError)
329 check_exception(ConnectionResetError)
330 check_exception(FileExistsError)
331 check_exception(FileNotFoundError)
332 check_exception(InterruptedError)
333 check_exception(IsADirectoryError)
334 check_exception(NotADirectoryError)
335 check_exception(PermissionError)
336 check_exception(ProcessLookupError)
337 check_exception(TimeoutError)
338 # EnvironmentError and IOError are not explicitly defined by HPy
339 # but they work because they are actually OSError.
340 check_exception(EnvironmentError)
341 check_exception(IOError)
342
343 def test_h_unicode_exceptions(self):
344 import pytest
345 mod = self.make_module("""
346 HPyDef_METH(f, "f", HPyFunc_VARARGS)
347 static HPy f_impl(HPyContext *ctx, HPy self,
348 const HPy *args, size_t nargs)
349 {
350 HPy h_key, h_args, h_kw;
351 HPy h_dict, h_err, h_err_value;
352
353 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OOO", &h_key, &h_args, &h_kw))
354 return HPy_NULL;
355
356 h_dict = HPyDict_New(ctx);
357 if (HPy_IsNull(h_dict)) {
358 return HPy_NULL;
359 }
360 HPy_SetItem_s(ctx, h_dict, "UnicodeError", ctx->h_UnicodeError);
361 HPy_SetItem_s(ctx, h_dict, "UnicodeEncodeError", ctx->h_UnicodeEncodeError);
362 HPy_SetItem_s(ctx, h_dict, "UnicodeDecodeError", ctx->h_UnicodeDecodeError);
363 HPy_SetItem_s(ctx, h_dict, "UnicodeTranslateError", ctx->h_UnicodeTranslateError);
364
365 h_err = HPy_GetItem(ctx, h_dict, h_key);
366 if (HPy_IsNull(h_err)) {
367 HPy_Close(ctx, h_dict);
368 return HPy_NULL;
369 }
370 h_err_value = HPy_CallTupleDict(ctx, h_err, h_args, h_kw);
371 if (HPy_IsNull(h_err_value)) {
372 HPy_Close(ctx, h_dict);
373 HPy_Close(ctx, h_err);
374 return HPy_NULL;
375 }
376
377 HPyErr_SetObject(ctx, h_err, h_err_value);
378 HPy_Close(ctx, h_dict);
379 HPy_Close(ctx, h_err);
380 HPy_Close(ctx, h_err_value);
381 return HPy_NULL;
382 }
383 @EXPORT(f)
384 @INIT
385 """)
386
387 def check_exception(cls, *args, **kw):
388 with pytest.raises(cls):
389 mod.f(cls.__name__, args, kw)
390
391 check_exception(UnicodeError)
392 check_exception(
393 UnicodeEncodeError, "utf-8", "object", 0, 2, "reason"
394 )
395 check_exception(
396 UnicodeDecodeError, "utf-8", b"object", 0, 2, "reason"
397 )
398 check_exception(UnicodeTranslateError, "object", 0, 2, "reason")
399
400 def test_h_warnings(self):
401 import pytest
402 mod = self.make_module("""
403 HPyDef_METH(f, "f", HPyFunc_O)
404 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
405 {
406 HPy h_dict, h_err;
407 h_dict = HPyDict_New(ctx);
408 HPy_SetItem_s(ctx, h_dict, "Warning", ctx->h_Warning);
409 HPy_SetItem_s(ctx, h_dict, "UserWarning", ctx->h_UserWarning);
410 HPy_SetItem_s(ctx, h_dict, "DeprecationWarning", ctx->h_DeprecationWarning);
411 HPy_SetItem_s(ctx, h_dict, "PendingDeprecationWarning", ctx->h_PendingDeprecationWarning);
412 HPy_SetItem_s(ctx, h_dict, "SyntaxWarning", ctx->h_SyntaxWarning);
413 HPy_SetItem_s(ctx, h_dict, "RuntimeWarning", ctx->h_RuntimeWarning);
414 HPy_SetItem_s(ctx, h_dict, "FutureWarning", ctx->h_FutureWarning);
415 HPy_SetItem_s(ctx, h_dict, "ImportWarning", ctx->h_ImportWarning);
416 HPy_SetItem_s(ctx, h_dict, "UnicodeWarning", ctx->h_UnicodeWarning);
417 HPy_SetItem_s(ctx, h_dict, "BytesWarning", ctx->h_BytesWarning);
418 HPy_SetItem_s(ctx, h_dict, "ResourceWarning", ctx->h_ResourceWarning);
419 h_err = HPy_GetItem(ctx, h_dict, arg);
420 if (HPy_IsNull(h_err)) {
421 HPy_FatalError(ctx, "missing exception type");
422 }
423 HPyErr_SetString(ctx, h_err, "error message");
424 HPy_Close(ctx, h_dict);
425 HPy_Close(ctx, h_err);
426 return HPy_NULL;
427 }
428 @EXPORT(f)
429 @INIT
430 """)
431
432 def check_warning(cls):
433 with pytest.raises(cls):
434 mod.f(cls.__name__)
435
436 check_warning(Warning)
437 check_warning(UserWarning)
438 check_warning(DeprecationWarning)
439 check_warning(PendingDeprecationWarning)
440 check_warning(SyntaxWarning)
441 check_warning(RuntimeWarning)
442 check_warning(FutureWarning)
443 check_warning(ImportWarning)
444 check_warning(UnicodeWarning)
445 check_warning(BytesWarning)
446 check_warning(ResourceWarning)
447
448 def test_HPyErr_WarnEx(self):
449 import warnings
450 mod = self.make_module("""
451 HPyDef_METH(f, "f", HPyFunc_O)
452 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
453 {
454 switch (HPyLong_AsLong(ctx, arg)) {
455 case 0:
456 HPyErr_WarnEx(ctx, ctx->h_RuntimeWarning, "warn qzp", 1);
457 break;
458 case 1:
459 HPyErr_WarnEx(ctx, ctx->h_FutureWarning, "warn rtq", 2);
460 break;
461 case 2:
462 HPyErr_WarnEx(ctx, HPy_NULL, "warn null", 1);
463 break;
464 }
465 return HPy_Dup(ctx, ctx->h_None);
466 }
467 @EXPORT(f)
468 @INIT
469 """)
470
471 # NOTE: trampoline is defined in support.py
472 import sys
473 ISPYPY = "__pypy__" in sys.modules
474 def check_warning(arg, category, message, file):
475 with warnings.catch_warnings(record=True) as warnings_list:
476 if ISPYPY:
477 mod.f(arg)
478 else:
479 trampoline(mod.f, arg)
480 assert len(warnings_list) == 1, str(category)
481 w = warnings_list[-1]
482 assert issubclass(w.category, category), str(category)
483 assert str(w.message) == message, str(category)
484 if not ISPYPY:
485 assert w.filename.endswith(file), str(category)
486
487 check_warning(0, RuntimeWarning, "warn qzp", "support.py")
488 check_warning(1, FutureWarning, "warn rtq", "test_hpyerr.py")
489 check_warning(2, Warning, "warn null", "support.py")
490
491
492 def test_errorval_returned_by_api_functions_hpy(self):
493 mod = self.make_module("""
494 HPyDef_METH(f, "f", HPyFunc_VARARGS)
495 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
496 {
497 HPy a = HPy_NULL;
498 HPy b = HPy_NULL;
499 HPy res;
500 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OO", &a, &b))
501 return HPy_NULL;
502 res = HPy_TrueDivide(ctx, a, b);
503
504 // the point of the test is to check that in case of error
505 // HPy_Div returns HPy_NULL
506 if (HPy_IsNull(res)) {
507 HPyErr_Clear(ctx);
508 return HPyLong_FromLong(ctx, -42);
509 }
510 return res;
511 }
512 @EXPORT(f)
513 @INIT
514 """)
515 assert mod.f(21, 3) == 7
516 assert mod.f(21, 0) == -42
517
518 def test_errorval_returned_by_api_functions_int(self):
519 mod = self.make_module("""
520 HPyDef_METH(f, "f", HPyFunc_O)
521 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
522 {
523 HPy_ssize_t length = HPy_Length(ctx, arg);
524 if (length == -1) {
525 HPyErr_Clear(ctx);
526 return HPyLong_FromLong(ctx, -42);
527 }
528 return HPyLong_FromLong(ctx, (long) length);
529 }
530 @EXPORT(f)
531 @INIT
532 """)
533 assert mod.f([100, 200, 300]) == 3
534 assert mod.f(None) == -42
535
536 def test_HPyErr_NewException(self):
537 import pytest
538 mod = self.make_module("""
539 HPyDef_METH(f, "f", HPyFunc_VARARGS)
540 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
541 {
542 // MSVC doesn't allow "static HPy h_FooErr = HPy_NULL"
543 // so we do an initialization dance instead.
544 static int foo_error_initialized = 0;
545 static HPy h_FooError;
546 HPy arg;
547 HPy h_base = HPy_NULL;
548 HPy h_dict = HPy_NULL;
549 HPy h_doc = HPy_NULL;
550
551 if (!foo_error_initialized) {
552 foo_error_initialized = 1;
553 h_FooError = HPy_NULL;
554 }
555
556 if (!HPyArg_Parse(ctx, NULL, args, nargs, "O|OOO", &arg, &h_base, &h_dict, &h_doc)) {
557 return HPy_NULL;
558 }
559
560 if (!HPy_IsTrue(ctx, arg)) {
561 // cleanup and close the FooError which we created earlier
562 if (!HPy_IsNull(h_FooError))
563 HPy_Close(ctx, h_FooError);
564 return HPy_Dup(ctx, ctx->h_None);
565 }
566
567 if(HPy_Is(ctx, h_base, ctx->h_None)) {
568 h_base = HPy_NULL;
569 }
570
571 if(HPy_Is(ctx, h_dict, ctx->h_None)) {
572 h_dict = HPy_NULL;
573 }
574
575 if(HPy_Is(ctx, h_doc, ctx->h_None)) {
576 h_FooError = HPyErr_NewException(ctx, "mytest.FooError", h_base, h_dict);
577 } else {
578 // we use bytes because ATM we don't have HPyUnicode_AsUTF8 or similar
579 h_FooError = HPyErr_NewExceptionWithDoc(ctx, "mytest.FooError",
580 HPyBytes_AsString(ctx, h_doc), h_base, h_dict);
581 }
582
583 if (HPy_IsNull(h_FooError))
584 return HPy_NULL;
585 HPyErr_SetString(ctx, h_FooError, "hello");
586 return HPy_NULL;
587 }
588 @EXPORT(f)
589 @INIT
590 """)
591
592 def check(base, dict_, doc):
593 with pytest.raises(Exception) as exc:
594 mod.f(True, base, dict_, doc)
595 assert issubclass(exc.type, RuntimeError if base else Exception)
596 assert exc.type.__name__ == 'FooError', exc.value
597 assert exc.type.__module__ == 'mytest'
598 if doc is None:
599 assert exc.type.__doc__ is None
600 else:
601 assert exc.type.__doc__ == doc.decode("utf-8")
602
603 if dict_:
604 assert exc.type.__dict__["test"] == "pass"
605 mod.f(False, None, None, None) # cleanup
606
607 check(base=None, dict_=None, doc=None)
608 check(base=None, dict_=None, doc=b'mytest')
609 check(base=None, dict_={"test": "pass"}, doc=None)
610 check(base=None, dict_={"test": "pass"}, doc=b'mytest')
611 check(base=RuntimeError, dict_=None, doc=None)
612 check(base=RuntimeError, dict_=None, doc=b'mytest')
613 check(base=RuntimeError, dict_={"test": "pass"}, doc=None)
614 check(base=RuntimeError, dict_={"test": "pass"}, doc=b'mytest')
615
616 def test_exception_matches(self):
617 import pytest
618 mod = self.make_module("""
619 HPyDef_METH(f, "f", HPyFunc_VARARGS)
620 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
621 {
622 HPyTracker ht;
623 HPy fun, fun_args;
624 HPy expected_exc_type;
625 HPy tmp;
626 HPy result;
627
628 if (!HPyArg_Parse(ctx, &ht, args, nargs, "OOO", &fun, &fun_args, &expected_exc_type)) {
629 return HPy_NULL;
630 }
631
632 tmp = HPy_CallTupleDict(ctx, fun, fun_args, HPy_NULL);
633 if (HPy_IsNull(tmp)) {
634 if (HPyErr_ExceptionMatches(ctx, expected_exc_type)) {
635 HPyErr_Clear(ctx);
636 result = HPy_Dup(ctx, ctx->h_True);
637 } else {
638 // propagate the unexpected exception to the caller
639 result = HPy_NULL;
640 }
641 } else {
642 HPy_Close(ctx, tmp);
643 result = HPy_Dup(ctx, ctx->h_False);
644 }
645
646 HPyTracker_Close(ctx, ht);
647 return result;
648 }
649 @EXPORT(f)
650 @INIT
651 """)
652
653 class DummyException(Exception):
654 pass
655
656 def raise_exception(e):
657 raise e
658
659 def do_not_raise_exception(*args):
660 return None
661
662 exc_types = (StopAsyncIteration, StopIteration, GeneratorExit, ArithmeticError, LookupError, AssertionError,
663 AttributeError, BufferError, EOFError, FloatingPointError, OSError, ImportError, ModuleNotFoundError, IndexError,
664 KeyError, KeyboardInterrupt, MemoryError, NameError, OverflowError, RuntimeError, RecursionError, NotImplementedError,
665 SyntaxError, IndentationError, TabError, ReferenceError, SystemError, SystemExit, TypeError, UnboundLocalError,
666 ValueError, ZeroDivisionError, BlockingIOError, BrokenPipeError, ChildProcessError, ConnectionError, ConnectionAbortedError,
667 ConnectionRefusedError, ConnectionResetError, FileExistsError, FileNotFoundError, InterruptedError, IsADirectoryError,
668 NotADirectoryError, PermissionError, ProcessLookupError, TimeoutError)
669
670 # just a sanity check of the extension function
671 assert not mod.f(do_not_raise_exception, tuple(), DummyException)
672
673 # test with "leaf" exception
674 assert mod.f(raise_exception, (DummyException, ), DummyException)
675 with pytest.raises(DummyException):
676 mod.f(raise_exception, (DummyException, ), StopIteration)
677
678 # test exception subclass
679 for exc_type in exc_types:
680 assert mod.f(raise_exception, (exc_type, ), BaseException)
681 assert mod.f(raise_exception, (DummyException, ), BaseException)
682
683 # match whole tuple
684 for exc_type in exc_types:
685 res = mod.f(raise_exception, (exc_type, ), exc_types)
686 with pytest.raises(DummyException):
687 mod.f(raise_exception, (DummyException, ), exc_types)
688
689 def test_HPyErr_WriteUnraisable(self, python_subprocess):
690 mod = self.compile_module("""
691 HPyDef_METH(f, "f", HPyFunc_NOARGS)
692 static HPy f_impl(HPyContext *ctx, HPy self)
693 {
694 HPyErr_SetString(ctx, ctx->h_ValueError, "error message");
695 HPyErr_WriteUnraisable(ctx, HPy_NULL);
696 return HPyBool_FromLong(ctx, HPyErr_Occurred(ctx));
697 }
698 @EXPORT(f)
699 @INIT
700 """)
701 if not SUPPORTS_SYS_EXECUTABLE:
702 # if sys.executable is not available (e.g. inside pypy app-level)
703 # tests, then skip the rest of this test
704 return
705 # subprocess is not importable in pypy app-level tests
706 result = python_subprocess.run(mod, "mod.f()")
707 assert result.returncode == 0
708
709
710 def test_HPyErr_Format(self):
711 import pytest
712 mod = self.make_module("""
713 HPyDef_METH(f, "f", HPyFunc_O)
714 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
715 {
716 return HPyErr_Format(ctx, ctx->h_ValueError, "Formatted '%S' and %d", arg, 42);
717 }
718 @EXPORT(f)
719 @INIT
720 """)
721 with pytest.raises(ValueError, match="Formatted 'error message' and 42"):
722 mod.f("error message")