Debian Codegraph @

extra_tests/hpy_tests/_vendored/test_hpylist.py

raw symbols SCIP
1 from .support import HPyTest
2
3 class TestList(HPyTest):
4
5 def test_Check(self):
6 mod = self.make_module("""
7 HPyDef_METH(f, "f", HPyFunc_O)
8 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
9 {
10 if (HPyList_Check(ctx, arg))
11 return HPy_Dup(ctx, ctx->h_True);
12 return HPy_Dup(ctx, ctx->h_False);
13 }
14 @EXPORT(f)
15 @INIT
16 """)
17 class MyList(list):
18 pass
19
20 assert mod.f([]) is True
21 assert mod.f('hello') is False
22 assert mod.f(MyList()) is True
23
24 def test_New(self):
25 mod = self.make_module("""
26 HPyDef_METH(f, "f", HPyFunc_NOARGS)
27 static HPy f_impl(HPyContext *ctx, HPy self)
28 {
29 return HPyList_New(ctx, 0);
30 }
31 @EXPORT(f)
32 @INIT
33 """)
34 assert mod.f() == []
35
36 def test_Append(self):
37 mod = self.make_module("""
38 HPyDef_METH(f, "f", HPyFunc_O)
39 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
40 {
41 HPy list = HPyList_New(ctx, 0);
42 if (HPy_IsNull(list))
43 return HPy_NULL;
44 if (HPyList_Append(ctx, list, arg) == -1)
45 return HPy_NULL;
46 if (HPyList_Append(ctx, list, arg) == -1)
47 return HPy_NULL;
48 return list;
49 }
50 @EXPORT(f)
51 @INIT
52 """)
53 assert mod.f(42) == [42, 42]
54
55 def test_ListBuilder(self):
56 mod = self.make_module("""
57 HPyDef_METH(f, "f", HPyFunc_O)
58 static HPy f_impl(HPyContext *ctx, HPy h_self, HPy h_arg)
59 {
60 HPyListBuilder builder = HPyListBuilder_New(ctx, 3);
61 HPyListBuilder_Set(ctx, builder, 0, h_arg);
62 HPyListBuilder_Set(ctx, builder, 1, ctx->h_True);
63 HPy h_num = HPyLong_FromLong(ctx, -42);
64 if (HPy_IsNull(h_num))
65 {
66 HPyListBuilder_Cancel(ctx, builder);
67 return HPy_NULL;
68 }
69 HPyListBuilder_Set(ctx, builder, 2, h_num);
70 HPy_Close(ctx, h_num);
71 HPy h_list = HPyListBuilder_Build(ctx, builder);
72 return h_list;
73 }
74 @EXPORT(f)
75 @INIT
76 """)
77 assert mod.f("xy") == ["xy", True, -42]
78
79 def test_Insert(self):
80 import pytest
81 mod = self.make_module("""
82 HPyDef_METH(f, "f", HPyFunc_VARARGS)
83 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
84 {
85 HPy_ssize_t index;
86 if (nargs != 3) {
87 HPyErr_SetString(ctx, ctx->h_ValueError, "expected exactly three arguments");
88 return HPy_NULL;
89 }
90 index = HPyLong_AsSsize_t(ctx, args[1]);
91 if (index == -1 && HPyErr_Occurred(ctx)) {
92 return HPy_NULL;
93 }
94 if (HPyList_Insert(ctx, args[0], index, args[2]) == -1)
95 return HPy_NULL;
96 return HPy_Dup(ctx, args[0]);
97 }
98 @EXPORT(f)
99 @INIT
100 """)
101 l = []
102 assert mod.f(l, 0, 0) == [0]
103 l = []
104 assert mod.f(l, -1, 0) == [0]
105 l = [1, 2, 4]
106 assert mod.f(l, 0, 0) == [0, 1, 2, 4]
107 assert mod.f(l, -1, 3) == [0, 1, 2, 3, 4]
108 assert mod.f(l, -3, 1.5) == [0, 1, 1.5, 2, 3, 4]
109 assert mod.f(l, 1000, 5) == [0, 1, 1.5, 2, 3, 4, 5]
110 assert mod.f(l, -1000, -1) == [-1, 0, 1, 1.5, 2, 3, 4, 5]
111 with pytest.raises(SystemError):
112 mod.f(None, 0, 0)