Debian Codegraph @

extra_tests/hpy_tests/_vendored/test_00_basic.py

raw symbols SCIP
1 """
2 NOTE: this tests are also meant to be run as PyPy "applevel" tests.
3
4 This means that global imports will NOT be visible inside the test
5 functions. In particular, you have to "import pytest" inside the test in order
6 to be able to use e.g. pytest.raises (which on PyPy will be implemented by a
7 "fake pytest module")
8 """
9 from .support import HPyTest
10 from hpy.devel.abitag import HPY_ABI_VERSION, HPY_ABI_VERSION_MINOR
11
12
13 class TestBasic(HPyTest):
14
15 def test_get_version(self):
16 if self.compiler.hpy_abi != 'universal':
17 return
18 import hpy.universal
19 version, gitrev = hpy.universal.get_version()
20 # it's a bit hard to test the CONTENT of these values. Let's just
21 # check that they are strings...
22 assert isinstance(version, str)
23 assert isinstance(gitrev, str)
24
25 def test_empty_module(self):
26 import sys
27 mod = self.make_module("""
28 @INIT
29 """)
30 assert type(mod) is type(sys)
31
32 def test_abi_version_check(self):
33 if self.compiler.hpy_abi != 'universal':
34 return
35 try:
36 self.make_module("""
37 // hack: we redefine the version
38 #undef HPY_ABI_VERSION
39 #define HPY_ABI_VERSION 999
40 @INIT
41 """)
42 except RuntimeError as ex:
43 assert str(ex) == "HPy extension module 'mytest' requires unsupported " \
44 "version of the HPy runtime. Requested version: 999.0. " \
45 "Current HPy version: {}.{}.".format(HPY_ABI_VERSION, HPY_ABI_VERSION_MINOR)
46 else:
47 assert False, "Expected exception"
48
49 def test_abi_tag_check(self):
50 import shutil
51 if self.compiler.hpy_abi != 'universal':
52 return
53
54 from hpy.universal import MODE_UNIVERSAL
55 def assert_load_raises(filename, message):
56 try:
57 self.compiler.load_universal_module('mytest', filename, mode=MODE_UNIVERSAL)
58 except RuntimeError as ex:
59 assert str(ex) == message
60 else:
61 assert False, "Expected exception"
62
63 module = self.compile_module("@INIT")
64 filename = module.so_filename
65 hpy_tag = ".hpy{}".format(HPY_ABI_VERSION)
66
67 filename_wrong_tag = filename.replace(hpy_tag, ".hpy999")
68 shutil.move(filename, filename_wrong_tag)
69 assert_load_raises(filename_wrong_tag,
70 "HPy extension module 'mytest' at path '{}': mismatch "
71 "between the HPy ABI tag encoded in the filename and "
72 "the major version requested by the HPy extension itself. "
73 "Major version tag parsed from filename: 999. "
74 "Requested version: {}.{}.".format(filename_wrong_tag, HPY_ABI_VERSION, HPY_ABI_VERSION_MINOR))
75
76 filename_no_tag = filename.replace(hpy_tag, "")
77 shutil.move(filename_wrong_tag, filename_no_tag)
78 assert_load_raises(filename_no_tag,
79 "HPy extension module 'mytest' at path '{}': "
80 "could not find HPy ABI tag encoded in the filename. "
81 "The extension claims to be compiled with HPy ABI version: "
82 "{}.{}.".format(filename_no_tag, HPY_ABI_VERSION, HPY_ABI_VERSION_MINOR))
83
84 def test_different_name(self):
85 mod = self.make_module("""
86 @INIT
87 """, name="foo")
88 assert mod.__name__ == "foo"
89
90 def test_noop_function(self):
91 mod = self.make_module("""
92 HPyDef_METH(f, "f", HPyFunc_NOARGS, .doc="hello world")
93 static HPy f_impl(HPyContext *ctx, HPy self)
94 {
95 return HPy_Dup(ctx, ctx->h_None);
96 }
97
98 @EXPORT(f)
99 @INIT
100 """)
101 assert mod.f() is None
102 assert mod.f.__doc__ == 'hello world'
103
104 def test_self_is_module(self):
105 mod = self.make_module("""
106 HPyDef_METH(f, "f", HPyFunc_NOARGS)
107 static HPy f_impl(HPyContext *ctx, HPy self)
108 {
109 return HPy_Dup(ctx, self);
110 }
111 @EXPORT(f)
112 @INIT
113 """)
114 assert mod.f() is mod
115
116 def test_identity_function(self):
117 mod = self.make_module("""
118 HPyDef_METH(f, "f", HPyFunc_O)
119 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
120 {
121 return HPy_Dup(ctx, arg);
122 }
123 @EXPORT(f)
124 @INIT
125 """)
126 x = object()
127 assert mod.f(x) is x
128
129 def test_float_asdouble(self):
130 mod = self.make_module("""
131 HPyDef_METH(f, "f", HPyFunc_O)
132 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
133 {
134 double a = HPyFloat_AsDouble(ctx, arg);
135 return HPyFloat_FromDouble(ctx, a * 2.);
136 }
137 @EXPORT(f)
138 @INIT
139 """)
140 assert mod.f(1.) == 2.
141
142 def test_wrong_number_of_arguments(self):
143 import pytest
144 mod = self.make_module("""
145 HPyDef_METH(f_noargs, "f_noargs", HPyFunc_NOARGS)
146 static HPy f_noargs_impl(HPyContext *ctx, HPy self)
147 {
148 return HPy_Dup(ctx, ctx->h_None);
149 }
150 HPyDef_METH(f_o, "f_o", HPyFunc_O)
151 static HPy f_o_impl(HPyContext *ctx, HPy self, HPy arg)
152 {
153 return HPy_Dup(ctx, ctx->h_None);
154 }
155 @EXPORT(f_noargs)
156 @EXPORT(f_o)
157 @INIT
158 """)
159 with pytest.raises(TypeError):
160 mod.f_noargs(1)
161 with pytest.raises(TypeError):
162 mod.f_o()
163 with pytest.raises(TypeError):
164 mod.f_o(1, 2)
165
166 def test_close(self):
167 mod = self.make_module("""
168 HPyDef_METH(f, "f", HPyFunc_O)
169 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
170 {
171 HPy one = HPyLong_FromLong(ctx, 1);
172 if (HPy_IsNull(one))
173 return HPy_NULL;
174 HPy res = HPy_Add(ctx, arg, one);
175 HPy_Close(ctx, one);
176 return res;
177 }
178 @EXPORT(f)
179 @INIT
180 """)
181 assert mod.f(41.5) == 42.5
182
183 def test_bool(self):
184 mod = self.make_module("""
185 HPyDef_METH(f, "f", HPyFunc_O)
186 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
187 {
188 int cond = HPyLong_AsLong(ctx, arg) > 5;
189 return HPy_Dup(ctx, cond ? ctx->h_True : ctx->h_False);
190 }
191 @EXPORT(f)
192 @INIT
193 """)
194 assert mod.f(4) is False
195 assert mod.f(6) is True
196
197 def test_exception(self):
198 import pytest
199 mod = self.make_module("""
200 HPyDef_METH(f, "f", HPyFunc_O)
201 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
202 {
203 long x = HPyLong_AsLong(ctx, arg);
204 if (x < 5) {
205 return HPyLong_FromLong(ctx, -x);
206 }
207 else {
208 HPyErr_SetString(ctx, ctx->h_ValueError, "hello world");
209 return HPy_NULL;
210 }
211 }
212 @EXPORT(f)
213 @INIT
214 """)
215 assert mod.f(-10) == 10
216 with pytest.raises(ValueError) as exc:
217 mod.f(20)
218 assert str(exc.value) == 'hello world'
219
220 def test_varargs(self):
221 mod = self.make_module("""
222 HPyDef_METH(f, "f", HPyFunc_VARARGS)
223 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
224 {
225 long a, b;
226 if (!HPyArg_Parse(ctx, NULL, args, nargs, "ll", &a, &b))
227 return HPy_NULL;
228 return HPyLong_FromLong(ctx, 10*a + b);
229 }
230 @EXPORT(f)
231 @INIT
232 """)
233 assert mod.f(4, 5) == 45
234
235 def test_builtin_handles(self):
236 mod = self.make_module("""
237 HPyDef_METH(f, "f", HPyFunc_O)
238 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
239 {
240 long i = HPyLong_AsLong(ctx, arg);
241 HPy h;
242 switch(i) {
243 case 1: h = ctx->h_None; break;
244 case 2: h = ctx->h_False; break;
245 case 3: h = ctx->h_True; break;
246 case 4: h = ctx->h_ValueError; break;
247 case 5: h = ctx->h_TypeError; break;
248 case 6: h = ctx->h_IndexError; break;
249 case 7: h = ctx->h_SystemError; break;
250 case 8: h = ctx->h_BaseObjectType; break;
251 case 9: h = ctx->h_TypeType; break;
252 case 10: h = ctx->h_BoolType; break;
253 case 11: h = ctx->h_LongType; break;
254 case 12: h = ctx->h_FloatType; break;
255 case 13: h = ctx->h_UnicodeType; break;
256 case 14: h = ctx->h_TupleType; break;
257 case 15: h = ctx->h_ListType; break;
258 case 16: h = ctx->h_NotImplemented; break;
259 case 17: h = ctx->h_Ellipsis; break;
260 case 18: h = ctx->h_ComplexType; break;
261 case 19: h = ctx->h_BytesType; break;
262 case 20: h = ctx->h_MemoryViewType; break;
263 case 21: h = ctx->h_SliceType; break;
264 case 22: h = ctx->h_Builtins; break;
265 case 23: h = ctx->h_DictType; break;
266 case 2048: h = ctx->h_CapsuleType; break;
267 default:
268 HPyErr_SetString(ctx, ctx->h_ValueError, "invalid choice");
269 return HPy_NULL;
270 }
271 return HPy_Dup(ctx, h);
272 }
273 @EXPORT(f)
274 @INIT
275 """)
276 import builtins
277
278 builtin_objs = (
279 '<NULL>', None, False, True, ValueError, TypeError, IndexError,
280 SystemError, object, type, bool, int, float, str, tuple, list,
281 NotImplemented, Ellipsis, complex, bytes, memoryview, slice,
282 builtins.__dict__, dict
283 )
284 for i, obj in enumerate(builtin_objs):
285 if i == 0:
286 continue
287 assert mod.f(i) is obj
288
289 # we cannot be sure if 'datetime_CAPI' is available
290 import datetime
291 if hasattr(datetime, "datetime_CAPI"):
292 assert mod.f(2048) is type(datetime.datetime_CAPI)
293
294 def test_extern_def(self):
295 import pytest
296 main = """
297 extern HPyDef f;
298 extern HPyDef g;
299 extern HPyDef h;
300 extern HPyDef i;
301
302 @EXPORT(f)
303 @EXPORT(g)
304 @EXPORT(h)
305 @EXPORT(i)
306 @INIT
307 """
308 extra = """
309 HPyDef_METH(f, "f", HPyFunc_NOARGS)
310 static HPy f_impl(HPyContext *ctx, HPy self)
311 {
312 return HPyLong_FromLong(ctx, 12345);
313 }
314 HPyDef_METH(g, "g", HPyFunc_O)
315 static HPy g_impl(HPyContext *ctx, HPy self, HPy arg)
316 {
317 return HPy_Dup(ctx, arg);
318 }
319 HPyDef_METH(h, "h", HPyFunc_VARARGS)
320 static HPy h_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
321 {
322 long a, b;
323 if (!HPyArg_Parse(ctx, NULL, args, nargs, "ll", &a, &b))
324 return HPy_NULL;
325 return HPyLong_FromLong(ctx, 10*a + b);
326 }
327 HPyDef_METH(i, "i", HPyFunc_KEYWORDS)
328 static HPy i_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs,
329 HPy kwnames)
330 {
331 long a, b;
332 static const char *kwlist[] = { "a", "b", NULL };
333 if (!HPyArg_ParseKeywords(ctx, NULL, args, nargs, kwnames, "ll", kwlist, &a, &b))
334 return HPy_NULL;
335 return HPyLong_FromLong(ctx, 10*a + b);
336 }
337 """
338 mod = self.make_module(main, extra_sources=[extra])
339 assert mod.f() == 12345
340 assert mod.g(42) == 42
341 assert mod.h(5, 6) == 56
342 assert mod.i(4, 3) == 43
343 assert mod.i(a=2, b=5) == 25
344 with pytest.raises(TypeError):
345 mod.h("not an integer", "not an integer either")
346
347 def test_Float_FromDouble(self):
348 mod = self.make_module("""
349 HPyDef_METH(f, "f", HPyFunc_NOARGS)
350 static HPy f_impl(HPyContext *ctx, HPy self)
351 {
352 return HPyFloat_FromDouble(ctx, 123.45);
353 }
354 @EXPORT(f)
355 @INIT
356 """)
357 assert mod.f() == 123.45
358
359 def test_unsupported_signature(self):
360 import pytest
361 with pytest.raises(ValueError) as exc:
362 self.make_module("""
363 HPyDef f = {
364 .kind = HPyDef_Kind_Meth,
365 .meth = {
366 .name = "f",
367 .signature = (HPyFunc_Signature)1234,
368 }
369 };
370 @EXPORT(f)
371 @INIT
372 """)
373 assert str(exc.value) == 'Unsupported HPyMeth signature'
374
375 def test_repr_str_ascii_bytes(self):
376 mod = self.make_module("""
377 HPyDef_METH(f1, "f1", HPyFunc_O)
378 static HPy f1_impl(HPyContext *ctx, HPy self, HPy arg)
379 {
380 return HPy_Repr(ctx, arg);
381 }
382 HPyDef_METH(f2, "f2", HPyFunc_O)
383 static HPy f2_impl(HPyContext *ctx, HPy self, HPy arg)
384 {
385 return HPy_Str(ctx, arg);
386 }
387 HPyDef_METH(f3, "f3", HPyFunc_O)
388 static HPy f3_impl(HPyContext *ctx, HPy self, HPy arg)
389 {
390 return HPy_ASCII(ctx, arg);
391 }
392 HPyDef_METH(f4, "f4", HPyFunc_O)
393 static HPy f4_impl(HPyContext *ctx, HPy self, HPy arg)
394 {
395 return HPy_Bytes(ctx, arg);
396 }
397 @EXPORT(f1)
398 @EXPORT(f2)
399 @EXPORT(f3)
400 @EXPORT(f4)
401 @INIT
402 """)
403 assert mod.f1("\u1234") == "'\u1234'"
404 assert mod.f2(42) == "42"
405 assert mod.f3("\u1234") == "'\\u1234'"
406 assert mod.f4(bytearray(b"foo")) == b"foo"
407
408 def test_is_true(self):
409 mod = self.make_module("""
410 HPyDef_METH(f, "f", HPyFunc_O)
411 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
412 {
413 int cond = HPy_IsTrue(ctx, arg);
414 return HPy_Dup(ctx, cond ? ctx->h_True : ctx->h_False);
415 }
416 @EXPORT(f)
417 @INIT
418 """)
419 assert mod.f("1234") is True
420 assert mod.f("") is False
421
422 def test_richcompare(self):
423 mod = self.make_module("""
424 HPyDef_METH(f, "f", HPyFunc_O)
425 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
426 {
427 HPy arg2 = HPyLong_FromLong(ctx, 100);
428 HPy result = HPy_RichCompare(ctx, arg, arg2, HPy_GT);
429 HPy_Close(ctx, arg2);
430 return result;
431 }
432 @EXPORT(f)
433 @INIT
434 """)
435 assert mod.f(100) is False
436 assert mod.f(150) is True
437
438 def test_richcomparebool(self):
439 mod = self.make_module("""
440 HPyDef_METH(f, "f", HPyFunc_O)
441 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
442 {
443 HPy arg2 = HPyLong_FromLong(ctx, 100);
444 int result = HPy_RichCompareBool(ctx, arg, arg2, HPy_GE);
445 HPy_Close(ctx, arg2);
446 return HPyLong_FromLong(ctx, -result);
447 }
448 @EXPORT(f)
449 @INIT
450 """)
451 assert mod.f(50) == 0
452 assert mod.f(100) == -1
453
454 def test_hash(self):
455 mod = self.make_module("""
456 HPyDef_METH(f, "f", HPyFunc_O)
457 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
458 {
459 HPy_hash_t hash = HPy_Hash(ctx, arg);
460 return HPyLong_FromSsize_t(ctx, hash);
461 }
462 @EXPORT(f)
463 @INIT
464 """)
465 x = object()
466 assert mod.f(x) == hash(x)
467
468 def test_ctx_name(self):
469 mod = self.make_module("""
470 HPyDef_METH(f, "f", HPyFunc_NOARGS)
471 static HPy f_impl(HPyContext *ctx, HPy self)
472 {
473 return HPyUnicode_FromString(ctx, ctx->name);
474 }
475
476 @EXPORT(f)
477 @INIT
478 """)
479 ctx_name = mod.f()
480 hpy_abi = self.compiler.hpy_abi
481 if hpy_abi == 'cpython':
482 assert ctx_name == 'HPy CPython ABI'
483 elif hpy_abi == 'universal':
484 # this can be "HPy Universal ABI (CPython backend)" or
485 # "... (PyPy backend)", etc.
486 assert ctx_name.startswith('HPy Universal ABI')
487 elif hpy_abi == 'debug':
488 assert ctx_name.startswith('HPy Debug Mode ABI')
489 elif hpy_abi == 'trace':
490 assert ctx_name.startswith('HPy Trace Mode ABI')
491 else:
492 assert False, 'unexpected hpy_abi: %s' % hpy_abi
493
494 def test_abi_version(self):
495 """
496 Check that all the various ABI version info that we have around match.
497 """
498 from hpy.devel import abitag
499 mod = self.make_module(
500 """
501 HPyDef_METH(get_ABI_VERSION, "get_ABI_VERSION", HPyFunc_NOARGS)
502 static HPy get_ABI_VERSION_impl(HPyContext *ctx, HPy self)
503 {
504 return HPyLong_FromLong(ctx, HPY_ABI_VERSION);
505 }
506
507 HPyDef_METH(get_ABI_TAG, "get_ABI_TAG", HPyFunc_NOARGS)
508 static HPy get_ABI_TAG_impl(HPyContext *ctx, HPy self)
509 {
510 return HPyUnicode_FromString(ctx, HPY_ABI_TAG);
511 }
512
513 HPyDef_METH(get_ctx_version, "get_ctx_version", HPyFunc_NOARGS)
514 static HPy get_ctx_version_impl(HPyContext *ctx, HPy self)
515 {
516 return HPyLong_FromLong(ctx, ctx->abi_version);
517 }
518
519 @EXPORT(get_ABI_VERSION)
520 @EXPORT(get_ABI_TAG)
521 @EXPORT(get_ctx_version)
522 @INIT
523 """)
524 c_HPY_ABI_VERSION = mod.get_ABI_VERSION()
525 c_HPY_ABI_TAG = mod.get_ABI_TAG()
526 ctx_version = mod.get_ctx_version()
527 assert c_HPY_ABI_VERSION == ctx_version == abitag.HPY_ABI_VERSION
528 assert c_HPY_ABI_TAG == abitag.HPY_ABI_TAG
529
530 def test_FromVoidP_AsVoidP(self):
531 mod = self.make_module("""
532 HPyDef_METH(f, "f", HPyFunc_O)
533 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
534 {
535 void *p = HPy_AsVoidP(arg);
536 HPy h = HPy_FromVoidP(p);
537 return HPy_Dup(ctx, h);
538 }
539 @EXPORT(f)
540 @INIT
541 """)
542 assert mod.f(42) == 42
543
544 def test_leave_python(self):
545 mod = self.make_module("""
546 HPyDef_METH(f, "f", HPyFunc_O)
547 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
548 {
549 HPy_ssize_t data_len;
550 const char* data = HPyUnicode_AsUTF8AndSize(ctx, arg, &data_len);
551 HPy_ssize_t acount = 0;
552 HPy_BEGIN_LEAVE_PYTHON(ctx);
553 for (HPy_ssize_t i = 0; i < data_len; ++i) {
554 if (data[i] == 'a')
555 acount++;
556 }
557 HPy_END_LEAVE_PYTHON(ctx);
558 return HPyLong_FromSize_t(ctx, acount);
559 }
560 @EXPORT(f)
561 @INIT
562 """)
563 assert mod.f("abraka") == 3
564
565 def test_dup_null(self):
566 mod = self.make_module("""
567 HPyDef_METH(f, "f", HPyFunc_NOARGS)
568 static HPy f_impl(HPyContext *ctx, HPy self)
569 {
570 HPy h = HPy_Dup(ctx, HPy_NULL);
571 if (HPy_IsNull(h)) {
572 return HPyLong_FromSize_t(ctx, 0);
573 }
574 HPy_Close(ctx, h);
575 return HPyLong_FromSize_t(ctx, -1);
576 }
577 @EXPORT(f)
578 @INIT
579 """)
580 assert mod.f() == 0