Debian Codegraph @

extra_tests/hpy_tests/_vendored/test_object.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
11
12 class TestObject(HPyTest):
13 def test_getattr(self):
14 import pytest
15 mod = self.make_module("""
16 HPyDef_METH(f, "f", HPyFunc_O)
17 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
18 {
19 HPy name, result;
20 name = HPyUnicode_FromString(ctx, "foo");
21 if (HPy_IsNull(name))
22 return HPy_NULL;
23 result = HPy_GetAttr(ctx, arg, name);
24 HPy_Close(ctx, name);
25 if (HPy_IsNull(result))
26 return HPy_NULL;
27 return result;
28 }
29 @EXPORT(f)
30 @INIT
31 """)
32
33 class Attrs:
34 def __init__(self, **kw):
35 for k, v in kw.items():
36 setattr(self, k, v)
37
38 class ClassAttr:
39 foo = 10
40
41 class PropAttr:
42 @property
43 def foo(self):
44 return 11
45
46 assert mod.f(Attrs(foo=5)) == 5
47 with pytest.raises(AttributeError):
48 mod.f(Attrs())
49 with pytest.raises(AttributeError):
50 mod.f(42)
51 assert mod.f(ClassAttr) == 10
52 assert mod.f(ClassAttr()) == 10
53 assert mod.f(PropAttr()) == 11
54
55 def test_getattr_s(self):
56 import pytest
57 mod = self.make_module("""
58 HPyDef_METH(f, "f", HPyFunc_O)
59 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
60 {
61 HPy result;
62 result = HPy_GetAttr_s(ctx, arg, "foo");
63 if (HPy_IsNull(result))
64 return HPy_NULL;
65 return result;
66 }
67 @EXPORT(f)
68 @INIT
69 """)
70
71 class Attrs:
72 def __init__(self, **kw):
73 for k, v in kw.items():
74 setattr(self, k, v)
75
76 class ClassAttr:
77 foo = 10
78
79 class PropAttr:
80 @property
81 def foo(self):
82 return 11
83
84 assert mod.f(Attrs(foo=5)) == 5
85 with pytest.raises(AttributeError):
86 mod.f(Attrs())
87 with pytest.raises(AttributeError):
88 mod.f(42)
89 assert mod.f(ClassAttr) == 10
90 assert mod.f(ClassAttr()) == 10
91 assert mod.f(PropAttr()) == 11
92
93 def test_hasattr(self):
94 mod = self.make_module("""
95 HPyDef_METH(f, "f", HPyFunc_O)
96 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
97 {
98 HPy name;
99 int result;
100 name = HPyUnicode_FromString(ctx, "foo");
101 if (HPy_IsNull(name))
102 return HPy_NULL;
103 result = HPy_HasAttr(ctx, arg, name);
104 HPy_Close(ctx, name);
105 if (result == -1)
106 return HPy_NULL;
107 if (result)
108 return HPy_Dup(ctx, ctx->h_True);
109 return HPy_Dup(ctx, ctx->h_False);
110 }
111 @EXPORT(f)
112 @INIT
113 """)
114
115 class Attrs:
116 def __init__(self, **kw):
117 for k, v in kw.items():
118 setattr(self, k, v)
119
120 class ClassAttr:
121 foo = 10
122
123 class PropAttr:
124 @property
125 def foo(self):
126 return 11
127
128 class PropAttrRaising:
129 @property
130 def foo(self):
131 raise RuntimeError
132
133
134 assert mod.f(Attrs(foo=5)) is True
135 assert mod.f(Attrs()) is False
136 assert mod.f(42) is False
137 assert mod.f(ClassAttr) is True
138 assert mod.f(ClassAttr()) is True
139 assert mod.f(PropAttr()) is True
140 assert mod.f(PropAttrRaising()) is False
141
142
143 def test_hasattr_s(self):
144 mod = self.make_module("""
145 HPyDef_METH(f, "f", HPyFunc_O)
146 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
147 {
148 int result;
149 result = HPy_HasAttr_s(ctx, arg, "foo");
150 if (result == -1)
151 return HPy_NULL;
152 if (result)
153 return HPy_Dup(ctx, ctx->h_True);
154 return HPy_Dup(ctx, ctx->h_False);
155 }
156 @EXPORT(f)
157 @INIT
158 """)
159
160 class Attrs:
161 def __init__(self, **kw):
162 for k, v in kw.items():
163 setattr(self, k, v)
164
165 class ClassAttr:
166 foo = 10
167
168 class PropAttr:
169 @property
170 def foo(self):
171 return 11
172
173 class PropAttrRaising:
174 @property
175 def foo(self):
176 raise RuntimeError
177
178 assert mod.f(Attrs(foo=5)) is True
179 assert mod.f(Attrs()) is False
180 assert mod.f(42) is False
181 assert mod.f(ClassAttr) is True
182 assert mod.f(ClassAttr()) is True
183 assert mod.f(PropAttr()) is True
184 assert mod.f(PropAttrRaising()) is False
185
186 def test_setattr(self):
187 import pytest
188 mod = self.make_module("""
189 HPyDef_METH(f, "f", HPyFunc_O)
190 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
191 {
192 HPy name;
193 int result;
194 name = HPyUnicode_FromString(ctx, "foo");
195 if (HPy_IsNull(name))
196 return HPy_NULL;
197 result = HPy_SetAttr(ctx, arg, name, ctx->h_True);
198 HPy_Close(ctx, name);
199 if (result < 0)
200 return HPy_NULL;
201 return HPy_Dup(ctx, ctx->h_None);
202 }
203 @EXPORT(f)
204 @INIT
205 """)
206
207 class Attrs:
208 pass
209
210 class ClassAttr:
211 pass
212
213 class ReadOnlyPropAttr:
214 @property
215 def foo(self):
216 return 11
217
218 class WritablePropAttr:
219 @property
220 def foo(self):
221 return self._foo
222
223 @foo.setter
224 def foo(self, value):
225 self._foo = value
226
227 a = Attrs()
228 mod.f(a)
229 assert a.foo is True
230
231 mod.f(ClassAttr)
232 assert ClassAttr.foo is True
233 assert ClassAttr().foo is True
234
235 with pytest.raises(AttributeError):
236 mod.f(object())
237
238 with pytest.raises(AttributeError):
239 mod.f(ReadOnlyPropAttr())
240
241 b = WritablePropAttr()
242 mod.f(b)
243 assert b.foo is True
244
245 def test_setattr_s(self):
246 import pytest
247 mod = self.make_module("""
248 HPyDef_METH(f, "f", HPyFunc_O)
249 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
250 {
251 int result;
252 result = HPy_SetAttr_s(ctx, arg, "foo", ctx->h_True);
253 if (result < 0)
254 return HPy_NULL;
255 return HPy_Dup(ctx, ctx->h_None);
256 }
257 @EXPORT(f)
258 @INIT
259 """)
260
261 class Attrs:
262 pass
263
264 class ClassAttr:
265 pass
266
267 class ReadOnlyPropAttr:
268 @property
269 def foo(self):
270 return 11
271
272 class WritablePropAttr:
273 @property
274 def foo(self):
275 return self._foo
276
277 @foo.setter
278 def foo(self, value):
279 self._foo = value
280
281 a = Attrs()
282 mod.f(a)
283 assert a.foo is True
284
285 mod.f(ClassAttr)
286 assert ClassAttr.foo is True
287 assert ClassAttr().foo is True
288
289 with pytest.raises(AttributeError):
290 mod.f(object())
291
292 with pytest.raises(AttributeError):
293 mod.f(ReadOnlyPropAttr())
294
295 b = WritablePropAttr()
296 mod.f(b)
297 assert b.foo is True
298
299 def test_delattr(self):
300 import pytest
301 mod = self.make_module("""
302 HPyDef_METH(del_foo, "del_foo", HPyFunc_O)
303 static HPy del_foo_impl(HPyContext *ctx, HPy self, HPy arg)
304 {
305 HPy name;
306 int result;
307 name = HPyUnicode_FromString(ctx, "foo");
308 if (HPy_IsNull(name))
309 return HPy_NULL;
310 result = HPy_DelAttr(ctx, arg, name);
311 HPy_Close(ctx, name);
312 if (result < 0)
313 return HPy_NULL;
314 return HPy_Dup(ctx, ctx->h_None);
315 }
316 @EXPORT(del_foo)
317 @INIT
318 """)
319
320 class Attrs:
321 pass
322
323 class ClassAttr:
324 pass
325
326 class WritablePropAttr:
327 @property
328 def foo(self):
329 return self._foo
330
331 @foo.setter
332 def foo(self, value):
333 self._foo = value
334
335 class DeletablePropAttr:
336 @property
337 def foo(self):
338 return self._foo
339
340 @foo.setter
341 def foo(self, value):
342 self._foo = value
343
344 @foo.deleter
345 def foo(self):
346 del self._foo
347
348 def set_foo(obj):
349 obj.foo = True
350
351 a = Attrs()
352 set_foo(a)
353 assert a.foo is True
354 mod.del_foo(a)
355 with pytest.raises(AttributeError):
356 a.foo
357
358 set_foo(ClassAttr)
359 assert ClassAttr.foo is True
360 assert ClassAttr().foo is True
361 mod.del_foo(ClassAttr)
362 with pytest.raises(AttributeError):
363 ClassAttr.foo
364 with pytest.raises(AttributeError):
365 ClassAttr().foo
366
367 b = WritablePropAttr()
368 set_foo(b)
369 assert b.foo is True
370 with pytest.raises(AttributeError):
371 # does not provide a delete function, so it fails
372 mod.del_foo(b)
373
374 c = DeletablePropAttr()
375 set_foo(c)
376 assert c.foo is True
377 mod.del_foo(c)
378 with pytest.raises(AttributeError):
379 c.foo
380
381 def test_delattr_s(self):
382 import pytest
383 mod = self.make_module("""
384 HPyDef_METH(del_foo, "del_foo", HPyFunc_O)
385 static HPy del_foo_impl(HPyContext *ctx, HPy self, HPy arg)
386 {
387 int result;
388 result = HPy_DelAttr_s(ctx, arg, "foo");
389 if (result < 0)
390 return HPy_NULL;
391 return HPy_Dup(ctx, ctx->h_None);
392 }
393 @EXPORT(del_foo)
394 @INIT
395 """)
396
397 class Attrs:
398 pass
399
400 class ClassAttr:
401 pass
402
403 class WritablePropAttr:
404 @property
405 def foo(self):
406 return self._foo
407
408 @foo.setter
409 def foo(self, value):
410 self._foo = value
411
412 class DeletablePropAttr:
413 @property
414 def foo(self):
415 return self._foo
416
417 @foo.setter
418 def foo(self, value):
419 self._foo = value
420
421 @foo.deleter
422 def foo(self):
423 del self._foo
424
425 def set_foo(obj):
426 obj.foo = True
427
428 a = Attrs()
429 set_foo(a)
430 assert a.foo is True
431 mod.del_foo(a)
432 with pytest.raises(AttributeError):
433 a.foo
434
435 set_foo(ClassAttr)
436 assert ClassAttr.foo is True
437 assert ClassAttr().foo is True
438 mod.del_foo(ClassAttr)
439 with pytest.raises(AttributeError):
440 ClassAttr.foo
441 with pytest.raises(AttributeError):
442 ClassAttr().foo
443
444 b = WritablePropAttr()
445 set_foo(b)
446 assert b.foo is True
447 with pytest.raises(AttributeError):
448 # does not provide a delete function, so it fails
449 mod.del_foo(b)
450
451 c = DeletablePropAttr()
452 set_foo(c)
453 assert c.foo is True
454 mod.del_foo(c)
455 with pytest.raises(AttributeError):
456 c.foo
457
458 def test_getitem(self):
459 import pytest
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 key, result;
465 key = HPyLong_FromLong(ctx, 3);
466 if (HPy_IsNull(key))
467 return HPy_NULL;
468 result = HPy_GetItem(ctx, arg, key);
469 HPy_Close(ctx, key);
470 if (HPy_IsNull(result))
471 return HPy_NULL;
472 return result;
473 }
474 @EXPORT(f)
475 @INIT
476 """)
477 assert mod.f({3: "hello"}) == "hello"
478 with pytest.raises(KeyError) as exc:
479 mod.f({1: "bad"})
480 assert exc.value.args == (3,)
481
482 assert mod.f([0, 1, 2, "hello"]) == "hello"
483 with pytest.raises(IndexError):
484 mod.f([])
485
486 def test_getitem_i(self):
487 import pytest
488 mod = self.make_module("""
489 HPyDef_METH(f, "f", HPyFunc_O)
490 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
491 {
492 HPy result;
493 result = HPy_GetItem_i(ctx, arg, 3);
494 if (HPy_IsNull(result))
495 return HPy_NULL;
496 return result;
497 }
498 @EXPORT(f)
499 @INIT
500 """)
501 assert mod.f({3: "hello"}) == "hello"
502 with pytest.raises(KeyError) as exc:
503 mod.f({1: "bad"})
504 assert exc.value.args == (3,)
505
506 assert mod.f([0, 1, 2, "hello"]) == "hello"
507 with pytest.raises(IndexError):
508 mod.f([])
509
510 def test_getitem_s(self):
511 import pytest
512 mod = self.make_module("""
513 HPyDef_METH(f, "f", HPyFunc_O)
514 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
515 {
516 HPy result;
517 result = HPy_GetItem_s(ctx, arg, "limes");
518 if (HPy_IsNull(result))
519 return HPy_NULL;
520 return result;
521 }
522 @EXPORT(f)
523 @INIT
524 """)
525 assert mod.f({"limes": "hello"}) == "hello"
526 with pytest.raises(KeyError) as exc:
527 mod.f({"oranges": "bad"})
528 assert exc.value.args == ("limes",)
529
530 with pytest.raises(TypeError):
531 mod.f([])
532
533 def test_getslice(self):
534 import pytest
535 mod = self.make_module("""
536 HPyDef_METH(f, "f", HPyFunc_VARARGS)
537 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
538 {
539 HPy seq;
540 HPy_ssize_t i1, i2;
541 if (!HPyArg_Parse(ctx, NULL, args, nargs, "Onn", &seq, &i1, &i2)) {
542 return HPy_NULL;
543 }
544 if (HPy_Is(ctx, seq, ctx->h_None)) {
545 seq = HPy_NULL;
546 }
547 return HPy_GetSlice(ctx, seq, i1, i2);
548 }
549 @EXPORT(f)
550 @INIT
551 """)
552 l = [1,2,3,4,5]
553 assert mod.f(l, 0, 5) == l
554 assert mod.f(l, 2, 3) == [3]
555 assert mod.f(l, 1, 3) == [2, 3]
556
557 s = "hello"
558 assert mod.f(s, 0, 5) == "hello"
559 assert mod.f(s, 1, 3) == "el"
560
561 class Sliceable:
562 def __getitem__(self, key):
563 # assume 'key' is a slice
564 if key.start < 0:
565 raise ValueError
566 return key.start + key.stop
567
568 o = Sliceable()
569 assert mod.f(o, 5, 13) == 18
570
571 # test that errors are propagated
572 with pytest.raises(ValueError):
573 mod.f(o, -1, 1)
574
575 # 'None' will be mapped to 'HPy_NULL' by the C function
576 with pytest.raises(SystemError):
577 mod.f(None, 0, 1)
578 with pytest.raises(TypeError):
579 mod.f(123, 0, 1)
580
581 def test_setitem(self):
582 import pytest
583 mod = self.make_module("""
584 HPyDef_METH(f, "f", HPyFunc_O)
585 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
586 {
587 HPy key;
588 int result;
589 key = HPyLong_FromLong(ctx, 3);
590 if (HPy_IsNull(key))
591 return HPy_NULL;
592 result = HPy_SetItem(ctx, arg, key, ctx->h_True);
593 HPy_Close(ctx, key);
594 if (result < 0)
595 return HPy_NULL;
596 return HPy_Dup(ctx, arg);
597 }
598 @EXPORT(f)
599 @INIT
600 """)
601 assert mod.f({}) == {3: True}
602 assert mod.f({"a": 1}) == {"a": 1, 3: True}
603 assert mod.f({3: False}) == {3: True}
604
605 assert mod.f([0, 1, 2, False]) == [0, 1, 2, True]
606 with pytest.raises(IndexError):
607 mod.f([])
608
609 def test_setitem_i(self):
610 import pytest
611 mod = self.make_module("""
612 HPyDef_METH(f, "f", HPyFunc_O)
613 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
614 {
615 int result;
616 result = HPy_SetItem_i(ctx, arg, 3, ctx->h_True);
617 if (result < 0)
618 return HPy_NULL;
619 return HPy_Dup(ctx, arg);
620 }
621 @EXPORT(f)
622 @INIT
623 """)
624 assert mod.f({}) == {3: True}
625 assert mod.f({"a": 1}) == {"a": 1, 3: True}
626 assert mod.f({3: False}) == {3: True}
627
628 assert mod.f([0, 1, 2, False]) == [0, 1, 2, True]
629 with pytest.raises(IndexError):
630 mod.f([])
631
632 def test_setitem_s(self):
633 import pytest
634 mod = self.make_module("""
635 HPyDef_METH(f, "f", HPyFunc_O)
636 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
637 {
638 int result;
639 result = HPy_SetItem_s(ctx, arg, "limes", ctx->h_True);
640 if (result < 0)
641 return HPy_NULL;
642 return HPy_Dup(ctx, arg);
643 }
644 @EXPORT(f)
645 @INIT
646 """)
647 assert mod.f({}) == {"limes": True}
648 assert mod.f({"a": 1}) == {"a": 1, "limes": True}
649 assert mod.f({"limes": False}) == {"limes": True}
650
651 with pytest.raises(TypeError):
652 mod.f([])
653
654 def test_setslice(self):
655 import pytest
656 mod = self.make_module("""
657 HPyDef_METH(f, "f", HPyFunc_VARARGS)
658 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
659 {
660 int res;
661 HPy seq, value;
662 HPy_ssize_t i1, i2;
663 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OnnO", &seq, &i1, &i2, &value)) {
664 return HPy_NULL;
665 }
666 if (HPy_Is(ctx, seq, ctx->h_None)) {
667 seq = HPy_NULL;
668 }
669 res = HPy_SetSlice(ctx, seq, i1, i2, value);
670 if (res == 0) {
671 return HPy_Dup(ctx, seq);
672 } else if (res == -1) {
673 return HPy_NULL;
674 }
675 HPyErr_SetString(ctx, ctx->h_SystemError,
676 "HPy_SetSlice returned an invalid result code");
677 return HPy_NULL;
678 }
679 @EXPORT(f)
680 @INIT
681 """)
682 l = [1,2,3,4,5]
683 val = [11,22,33,44,55]
684 x = mod.f(l, 0, 5, val)
685 assert x is l
686 assert x is not val
687 assert l == val
688
689 l = [1,2,3,4,5]
690 assert mod.f(l, 0, 5, []) == []
691
692 l = [1,2,3,4,5]
693 assert mod.f(l, 1, 3, [10, 11, 12]) == [1, 10, 11, 12, 4, 5]
694
695 class Sliceable:
696 def __setitem__(self, key, value):
697 # assume 'key' is a slice
698 if key.start < 0:
699 raise ValueError
700 self.value = (key.start, key.stop, value)
701
702 o = Sliceable()
703 assert mod.f(o, 5, 13, [7, 8, 9]).value == (5, 13, [7, 8, 9])
704
705 # test that errors are propagated
706 with pytest.raises(ValueError):
707 mod.f(o, -1, 1, [])
708
709 # 'None' will be mapped to 'HPy_NULL' by the C function
710 with pytest.raises(SystemError):
711 mod.f(None, 0, 1, [])
712 with pytest.raises(TypeError):
713 mod.f(123, 0, 1, [])
714
715 def test_delitem(self):
716 import pytest
717 mod = self.make_module("""
718 HPyDef_METH(delitem3, "delitem3", HPyFunc_O)
719 static HPy delitem3_impl(HPyContext *ctx, HPy self, HPy arg)
720 {
721 HPy key;
722 int result;
723 key = HPyLong_FromLong(ctx, 3);
724 if (HPy_IsNull(key))
725 return HPy_NULL;
726 result = HPy_DelItem(ctx, arg, key);
727 HPy_Close(ctx, key);
728 if (result < 0)
729 return HPy_NULL;
730 return HPy_Dup(ctx, arg);
731 }
732
733 HPyDef_METH(delitem_i3, "delitem_i3", HPyFunc_O)
734 static HPy delitem_i3_impl(HPyContext *ctx, HPy self, HPy arg)
735 {
736 int result;
737 result = HPy_DelItem_i(ctx, arg, 3);
738 if (result < 0)
739 return HPy_NULL;
740 return HPy_Dup(ctx, arg);
741 }
742
743 HPyDef_METH(delitem_s3, "delitem_s3", HPyFunc_O)
744 static HPy delitem_s3_impl(HPyContext *ctx, HPy self, HPy arg)
745 {
746 int result;
747 result = HPy_DelItem_s(ctx, arg, "3");
748 if (result < 0)
749 return HPy_NULL;
750 return HPy_Dup(ctx, arg);
751 }
752
753 @EXPORT(delitem3)
754 @EXPORT(delitem_i3)
755 @EXPORT(delitem_s3)
756 @INIT
757 """)
758 # HPy_DelItem
759 assert mod.delitem3({3: False, 4: True}) == {4: True}
760 with pytest.raises(KeyError):
761 mod.delitem3({})
762 with pytest.raises(TypeError):
763 mod.delitem3((1, 2, 3, 4))
764 assert mod.delitem3([0, 1, 2, False]) == [0, 1, 2]
765 with pytest.raises(IndexError):
766 mod.delitem3([])
767
768 # HPy_DelItem_i
769 assert mod.delitem_i3({3: False, 4: True}) == {4: True}
770 with pytest.raises(KeyError):
771 mod.delitem_i3({})
772 with pytest.raises(TypeError):
773 mod.delitem_i3((1, 2, 3, 4))
774 assert mod.delitem_i3([0, 1, 2, False]) == [0, 1, 2]
775 with pytest.raises(IndexError):
776 mod.delitem_i3([])
777
778 # HPy_DelItem_s
779 assert mod.delitem_s3({'3': False, '4': True}) == {'4': True}
780 with pytest.raises(KeyError):
781 mod.delitem_s3({})
782 with pytest.raises(TypeError):
783 mod.delitem_s3((1, 2, 3, 4))
784 with pytest.raises(TypeError):
785 mod.delitem_s3([1, 2, 3, 4])
786
787 def test_delslice(self):
788 import pytest
789 mod = self.make_module("""
790 HPyDef_METH(f, "f", HPyFunc_VARARGS)
791 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
792 {
793 int res;
794 HPy seq;
795 HPy_ssize_t i1, i2;
796 if (!HPyArg_Parse(ctx, NULL, args, nargs, "Onn", &seq, &i1, &i2)) {
797 return HPy_NULL;
798 }
799 if (HPy_Is(ctx, seq, ctx->h_None)) {
800 seq = HPy_NULL;
801 }
802 res = HPy_DelSlice(ctx, seq, i1, i2);
803 if (res == 0) {
804 return HPy_Dup(ctx, seq);
805 } else if (res == -1) {
806 return HPy_NULL;
807 }
808 HPyErr_SetString(ctx, ctx->h_SystemError,
809 "HPy_DelSlice returned an invalid result code");
810 return HPy_NULL;
811 }
812 @EXPORT(f)
813 @INIT
814 """)
815 l = [1,2,3,4,5]
816 x = mod.f(l, 0, 5)
817 assert x is l
818 assert l == []
819
820 l = [1,2,3,4,5]
821 assert mod.f(l, 1, 3) == [1, 4, 5]
822
823 class Sliceable:
824 def __delitem__(self, key):
825 # assume 'key' is a slice
826 if key.start < 0:
827 raise ValueError
828 self.value = key.start + key.stop
829
830 o = Sliceable()
831 assert mod.f(o, 5, 13).value == 18
832
833 # test that errors are propagated
834 with pytest.raises(ValueError):
835 mod.f(o, -1, 1)
836
837 # 'None' will be mapped to 'HPy_NULL' by the C function
838 with pytest.raises(SystemError):
839 mod.f(None, 0, 1)
840 with pytest.raises(TypeError):
841 mod.f(123, 0, 1)
842
843 def test_length(self):
844 mod = self.make_module("""
845 HPyDef_METH(f, "f", HPyFunc_O)
846 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
847 {
848 HPy_ssize_t result;
849 result = HPy_Length(ctx, arg);
850 if (result < 0)
851 return HPy_NULL;
852 return HPyLong_FromSsize_t(ctx, result);
853 }
854 @EXPORT(f)
855 @INIT
856 """)
857 assert mod.f([5,6,7,8]) == 4
858 assert mod.f({"a": 1}) == 1
859
860 def test_contains(self):
861 mod = self.make_module("""
862 HPyDef_METH(f, "f", HPyFunc_VARARGS)
863 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
864 {
865 int result = HPy_Contains(ctx, args[0], args[1]);
866 if (result == -1) {
867 return HPy_NULL;
868 }
869 return HPyLong_FromLong(ctx, result);
870 }
871 @EXPORT(f)
872 @INIT
873 """)
874
875 class WithContains:
876 def __contains__(self, item):
877 return item == 42
878
879 class WithIter:
880 def __iter__(self):
881 return [1, 2, 3].__iter__()
882
883 class WithGetitem:
884 def __getitem__(self, item):
885 if item > 3:
886 raise IndexError()
887 else:
888 return item
889
890 class Dummy:
891 pass
892
893 assert mod.f([5, 6, 42, 7, 8], 42)
894 assert not mod.f([5, 6, 42, 7, 8], 4)
895
896 assert mod.f(WithContains(), 42)
897 assert not mod.f(WithContains(), 1)
898
899 assert mod.f(WithIter(), 2)
900 assert not mod.f(WithIter(), 33)
901
902 assert mod.f(WithGetitem(), 2)
903 assert not mod.f(WithGetitem(), 33)
904
905 import pytest
906 with pytest.raises(TypeError):
907 mod.f(Dummy(), 42)
908
909 def test_getiter(self):
910 mod = self.make_module("""
911 HPyDef_METH(f, "f", HPyFunc_O)
912 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
913 {
914 HPy iterator;
915 iterator = HPy_GetIter(ctx, arg);
916 if HPy_IsNull(iterator)
917 return HPy_NULL;
918 return iterator;
919 }
920 @EXPORT(f)
921 @INIT
922 """)
923
924 def test_for_loop(iterator):
925 results = []
926 for obj in iterator:
927 results.append(obj)
928 return results
929
930 class WithIter:
931 def __iter__(self):
932 return (1, 2, 3).__iter__()
933
934 class WithoutIter:
935 pass
936
937 case = [1, 2, 3]
938 result = mod.f(case)
939 assert result
940 assert test_for_loop(result) == [1, 2, 3]
941
942 case = iter([1, 2, 3])
943 result = mod.f(case)
944 assert result
945 assert test_for_loop(result) == [1, 2, 3]
946
947 case = zip((1, 2, 3), [4, 5, 6])
948 result = mod.f(case)
949 assert result
950 assert test_for_loop(result) == [(1, 4), (2, 5), (3, 6)]
951
952 case = range(10)
953 result = mod.f(case)
954 assert result
955 assert test_for_loop(result) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
956
957 case = WithIter()
958 result = mod.f(case)
959 assert result
960 assert test_for_loop(result) == [1, 2, 3]
961
962 import pytest
963 with pytest.raises(TypeError):
964 assert mod.f(WithoutIter())
965
966
967 def test_dump(self):
968 # _HPy_Dump is supposed to be used e.g. inside a gdb session: it
969 # prints various about the given handle to stdout, and it's
970 # implementation-specific. As such, it's hard to write a meaningful
971 # test: let's just call it an check it doesn't crash.
972 mod = self.make_module("""
973 HPyDef_METH(f, "f", HPyFunc_O)
974 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
975 {
976 _HPy_Dump(ctx, arg);
977 return HPy_Dup(ctx, ctx->h_None);
978 }
979 @EXPORT(f)
980 @INIT
981 """)
982 mod.f('hello')
983
984 def test_type(self):
985 mod = self.make_module("""
986 HPyDef_METH(f, "f", HPyFunc_O)
987 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
988 {
989 return HPy_Type(ctx, arg);
990 }
991 @EXPORT(f)
992 @INIT
993 """)
994 assert mod.f('hello') is str
995 assert mod.f(42) is int
996
997 def test_typecheck(self):
998 mod = self.make_module("""
999 HPyDef_METH(f, "f", HPyFunc_VARARGS)
1000 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
1001 {
1002 HPy a, b;
1003 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OO", &a, &b))
1004 return HPy_NULL;
1005 int res = HPy_TypeCheck(ctx, a, b);
1006 return HPyBool_FromLong(ctx, res);
1007 }
1008 @EXPORT(f)
1009 @INIT
1010 """)
1011 class MyStr(str):
1012 pass
1013 assert mod.f('hello', str)
1014 assert not mod.f('hello', int)
1015 assert mod.f(MyStr('hello'), str)
1016
1017 def test_is(self):
1018 mod = self.make_module("""
1019 HPyDef_METH(f, "f", HPyFunc_VARARGS)
1020 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
1021 {
1022 HPy obj, other;
1023 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OO", &obj, &other))
1024 return HPy_NULL;
1025 int res = HPy_Is(ctx, obj, other);
1026 return HPyBool_FromLong(ctx, res);
1027 }
1028 @EXPORT(f)
1029 @INIT
1030 """)
1031 assert mod.f(None, None)
1032 a = object()
1033 assert mod.f(a, a)
1034 assert not mod.f(a, None)