Debian Codegraph @

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