Debian Codegraph @

extra_tests/hpy_tests/_vendored/test_hpydict.py

raw symbols SCIP
1 from .support import HPyTest
2
3 class TestDict(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 (HPyDict_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 MyDict(dict):
18 pass
19
20 assert mod.f({}) is True
21 assert mod.f([]) is False
22 assert mod.f(MyDict()) 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 HPyDict_New(ctx);
30 }
31 @EXPORT(f)
32 @INIT
33 """)
34 assert mod.f() == {}
35
36 def test_set_item(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 dict = HPyDict_New(ctx);
42 if (HPy_IsNull(dict))
43 return HPy_NULL;
44 HPy val = HPyLong_FromLong(ctx, 1234);
45 if (HPy_SetItem(ctx, dict, arg, val) == -1)
46 return HPy_NULL;
47 HPy_Close(ctx, val);
48 return dict;
49 }
50 @EXPORT(f)
51 @INIT
52 """)
53 assert mod.f('hello') == {'hello': 1234}
54
55 def test_get_item(self):
56 mod = self.make_module("""
57 HPyDef_METH(f, "f", HPyFunc_O)
58 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
59 {
60 HPy key = HPyUnicode_FromString(ctx, "hello");
61 if (HPy_IsNull(key))
62 return HPy_NULL;
63 HPy val = HPy_GetItem(ctx, arg, key);
64 HPy_Close(ctx, key);
65 if (HPy_IsNull(val)) {
66 HPyErr_Clear(ctx);
67 return HPy_Dup(ctx, ctx->h_None);
68 }
69 return val;
70 }
71 @EXPORT(f)
72 @INIT
73 """)
74 assert mod.f({'hello': 1}) == 1
75 assert mod.f({}) is None
76
77 def test_keys(self):
78 import pytest
79 mod = self.make_module("""
80 HPyDef_METH(f, "f", HPyFunc_O)
81 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
82 {
83 HPy h_dict = HPy_Is(ctx, arg, ctx->h_None) ? HPy_NULL : arg;
84 return HPyDict_Keys(ctx, h_dict);
85 }
86 @EXPORT(f)
87 @INIT
88 """)
89
90 class SubDict(dict):
91 def keys(self):
92 return [1, 2, 3]
93 assert mod.f({}) == []
94 assert mod.f({'hello': 1}) == ['hello']
95 assert mod.f(SubDict(hello=1)) == ['hello']
96 with pytest.raises(SystemError):
97 mod.f(None)
98 with pytest.raises(SystemError):
99 mod.f(42)
100
101 def test_copy(self):
102 import pytest
103 mod = self.make_module("""
104 HPyDef_METH(f, "f", HPyFunc_O)
105 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
106 {
107 HPy h_dict = HPy_Is(ctx, arg, ctx->h_None) ? HPy_NULL : arg;
108 return HPyDict_Copy(ctx, h_dict);
109 }
110 @EXPORT(f)
111 @INIT
112 """)
113 dicts = ({}, {'hello': 1})
114 for d in dicts:
115 d_copy = mod.f(d)
116 assert d_copy == d
117 assert d_copy is not d
118 with pytest.raises(SystemError):
119 mod.f(None)
120 with pytest.raises(SystemError):
121 mod.f(42)