Debian Codegraph @

pypy/module/_hpy_universal/test/_vendored/test_hpyfield.py

raw symbols SCIP
1 """
2 NOTE: these 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 import pytest
10 from .support import HPyTest, DefaultExtensionTemplate
11
12 class PairTemplate(DefaultExtensionTemplate):
13
14 def DEFINE_PairObject(self):
15 return """
16 typedef struct {
17 HPyField a;
18 HPyField b;
19 } PairObject;
20
21 HPyType_HELPERS(PairObject);
22 """
23
24 def DEFINE_Pair_new(self):
25 return """
26 HPyDef_SLOT(Pair_new, HPy_tp_new)
27 static HPy Pair_new_impl(HPyContext *ctx, HPy cls, const HPy *args,
28 HPy_ssize_t nargs, HPy kw)
29 {
30 HPy a;
31 HPy b;
32 if (!HPyArg_Parse(ctx, NULL, args, nargs, "OO", &a, &b))
33 return HPy_NULL;
34 PairObject *pair;
35 HPy h_obj = HPy_New(ctx, cls, &pair);
36 HPyField_Store(ctx, h_obj, &pair->a, a);
37 HPyField_Store(ctx, h_obj, &pair->b, b);
38 return h_obj;
39 }
40 """
41
42 def DEFINE_Pair_traverse(self):
43 return """
44 HPyDef_SLOT(Pair_traverse, HPy_tp_traverse)
45 static int Pair_traverse_impl(void *self, HPyFunc_visitproc visit, void *arg)
46 {
47 PairObject *p = (PairObject *)self;
48 HPy_VISIT(&p->a);
49 HPy_VISIT(&p->b);
50 return 0;
51 }
52 """
53
54 def DEFINE_Pair_set_a(self):
55 return """
56 HPyDef_METH(Pair_set_a, "set_a", HPyFunc_O)
57 static HPy Pair_set_a_impl(HPyContext *ctx, HPy self, HPy arg)
58 {
59 PairObject *pair = PairObject_AsStruct(ctx, self);
60 HPyField_Store(ctx, self, &pair->a, arg);
61 return HPy_Dup(ctx, ctx->h_None);
62 }
63 """
64
65 def DEFINE_Pair_get_ab(self):
66 return """
67 HPyDef_METH(Pair_get_a, "get_a", HPyFunc_NOARGS)
68 static HPy Pair_get_a_impl(HPyContext *ctx, HPy self)
69 {
70 PairObject *pair = PairObject_AsStruct(ctx, self);
71 if (HPy_IsNull(pair->a))
72 return HPyUnicode_FromString(ctx, "<NULL>");
73 return HPyField_Load(ctx, self, pair->a);
74 }
75
76 HPyDef_METH(Pair_get_b, "get_b", HPyFunc_NOARGS)
77 static HPy Pair_get_b_impl(HPyContext *ctx, HPy self)
78 {
79 PairObject *pair = PairObject_AsStruct(ctx, self);
80 if (HPy_IsNull(pair->b))
81 return HPyUnicode_FromString(ctx, "<NULL>");
82 return HPyField_Load(ctx, self, pair->b);
83 }
84 """
85
86 pair_type_flags = 'HPy_TPFLAGS_DEFAULT | HPy_TPFLAGS_HAVE_GC'
87 def PAIR_TYPE_FLAGS(self, flags):
88 self.pair_type_flags = flags
89
90 def EXPORT_PAIR_TYPE(self, *defines):
91 defines += ('NULL',)
92 defines = ', '.join(defines)
93 self.EXPORT_TYPE('"Pair"', "Pair_spec")
94 return """
95 static HPyDef *Pair_defines[] = { %s };
96 static HPyType_Spec Pair_spec = {
97 .name = "mytest.Pair",
98 .basicsize = sizeof(PairObject),
99 .flags = %s,
100 .defines = Pair_defines
101 };
102 """ % (defines, self.pair_type_flags)
103
104 class TestHPyField(HPyTest):
105
106 ExtensionTemplate = PairTemplate
107
108 def test_gc_track(self):
109 if not self.supports_refcounts():
110 import pytest
111 pytest.skip("CPython only")
112 import sys
113 # Test that we correctly call PyObject_GC_Track on CPython. The
114 # easiest way is to check whether the object is in
115 # gc.get_objects().
116 import gc
117 mod = self.make_module("""
118 @DEFINE_PairObject
119 @DEFINE_Pair_new
120 @DEFINE_Pair_traverse
121
122 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse)
123 @INIT
124 """)
125 p = mod.Pair("hello", "world")
126 assert gc.is_tracked(p)
127
128 def test_gc_track_no_gc_flag(self):
129 if not self.supports_refcounts():
130 import pytest
131 pytest.skip("CPython only")
132 # Same code as test_gc_track, but without HPy_TPFLAGS_HAVE_GC. On
133 # CPython, the object is NOT tracked.
134 import gc
135 mod = self.make_module("""
136 @DEFINE_PairObject
137 @DEFINE_Pair_new
138 @DEFINE_Pair_traverse
139
140 @PAIR_TYPE_FLAGS(HPy_TPFLAGS_DEFAULT)
141 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse)
142 @INIT
143 """)
144 p = mod.Pair("hello", "world")
145 assert not gc.is_tracked(p)
146
147 def test_tp_traverse(self):
148 import sys
149 import gc
150 mod = self.make_module("""
151 @DEFINE_PairObject
152 @DEFINE_Pair_new
153 @DEFINE_Pair_traverse
154
155 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse)
156 @INIT
157 """)
158 p = mod.Pair("hello", "world")
159 referents = gc.get_referents(p)
160 referents.sort()
161 assert referents == ['hello', 'world']
162
163 def test_tp_traverse_sanity_check(self):
164 import pytest
165 with pytest.raises(ValueError):
166 self.make_module("""
167 @DEFINE_PairObject
168 @DEFINE_Pair_new
169
170 // here we are defining a type with HPy_TPFLAGS_HAVE_GC but
171 // without providing a tp_traverse
172 @EXPORT_PAIR_TYPE(&Pair_new)
173 @INIT
174 """)
175
176 def test_store_load(self):
177 import sys
178 mod = self.make_module("""
179 @DEFINE_PairObject
180 @DEFINE_Pair_new
181 @DEFINE_Pair_get_ab
182 @DEFINE_Pair_traverse
183
184 @PAIR_TYPE_FLAGS(HPy_TPFLAGS_DEFAULT)
185 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse, &Pair_get_a, &Pair_get_b)
186 @INIT
187 """)
188 p = mod.Pair("hello", "world")
189 assert p.get_a() == 'hello'
190 assert p.get_b() == 'world'
191 #
192 # check the refcnt
193 if self.supports_refcounts():
194 a = object()
195 a_refcnt = sys.getrefcount(a)
196 p2 = mod.Pair(a, None)
197 assert sys.getrefcount(a) == a_refcnt + 1
198 assert p2.get_a() is a
199 assert sys.getrefcount(a) == a_refcnt + 1
200
201 def test_store_overwrite(self):
202 import sys
203 mod = self.make_module("""
204 #include <assert.h>
205 @DEFINE_PairObject
206 @DEFINE_Pair_new
207 @DEFINE_Pair_get_ab
208 @DEFINE_Pair_traverse
209 @DEFINE_Pair_set_a
210
211 HPyDef_METH(Pair_clear_a, "clear_a", HPyFunc_NOARGS)
212 static HPy Pair_clear_a_impl(HPyContext *ctx, HPy self)
213 {
214 PairObject *pair = PairObject_AsStruct(ctx, self);
215 HPyField_Store(ctx, self, &pair->a, HPy_NULL);
216 return HPy_Dup(ctx, ctx->h_None);
217 }
218
219 @PAIR_TYPE_FLAGS(HPy_TPFLAGS_DEFAULT)
220 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse, &Pair_get_a, &Pair_get_b, &Pair_set_a, &Pair_clear_a)
221 @INIT
222 """)
223 p = mod.Pair("hello", "world")
224 assert p.get_a() == 'hello'
225 assert p.get_b() == 'world'
226 p.set_a('foo')
227 assert p.get_a() == 'foo'
228 p.clear_a()
229 assert p.get_a() == '<NULL>'
230 p.set_a('bar')
231 assert p.get_a() == 'bar'
232 #
233 # check the refcnt
234 if self.supports_refcounts():
235 a = object()
236 a_refcnt = sys.getrefcount(a)
237 p2 = mod.Pair(a, None)
238 assert sys.getrefcount(a) == a_refcnt + 1
239 assert p2.get_a() is a
240 p2.set_a('foo')
241 assert sys.getrefcount(a) == a_refcnt
242 p2.set_a(a)
243 assert sys.getrefcount(a) == a_refcnt + 1
244 p2.clear_a()
245 assert sys.getrefcount(a) == a_refcnt
246 p2.clear_a()
247 assert sys.getrefcount(a) == a_refcnt
248
249 def test_automatic_tp_dealloc(self):
250 import sys
251 if not self.supports_refcounts():
252 import pytest
253 pytest.skip("CPython only")
254
255 import sys
256 mod = self.make_module("""
257 @DEFINE_PairObject
258 @DEFINE_Pair_new
259 @DEFINE_Pair_traverse
260
261 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse)
262 @INIT
263 """)
264 a = object()
265 b = object()
266 p = mod.Pair(a, b)
267 a_cnt = sys.getrefcount(a)
268 b_cnt = sys.getrefcount(b)
269 del p
270 assert sys.getrefcount(a) == a_cnt - 1
271 assert sys.getrefcount(b) == b_cnt - 1
272
273 @pytest.mark.syncgc
274 def test_automatic_tp_clear(self):
275 if not self.supports_refcounts():
276 import pytest
277 pytest.skip("CPython only")
278 import sys
279
280 import gc
281 mod = self.make_module("""
282 @DEFINE_PairObject
283 @DEFINE_Pair_new
284 @DEFINE_Pair_traverse
285 @DEFINE_Pair_set_a
286
287 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse, &Pair_set_a)
288 @INIT
289 """)
290 def count_pairs():
291 return len([obj for obj in gc.get_objects() if type(obj) is mod.Pair])
292 assert count_pairs() == 0
293 p1 = mod.Pair(None, 'hello')
294 p2 = mod.Pair(None, 'world')
295 p1.set_a(p2)
296 p2.set_a(p1)
297 assert count_pairs() == 2
298 #
299 try:
300 gc.disable()
301 del p1
302 del p2
303 assert count_pairs() == 2
304 finally:
305 gc.enable()
306 #
307 self.debug_collect()
308 assert count_pairs() == 0
309
310 def test_tp_finalize(self):
311 # Tests the contract of tp_finalize: what it should see
312 # if called from within HPyField_Store
313 mod = self.make_module("""
314 #include <stdio.h>
315
316 @DEFINE_PairObject
317 @DEFINE_Pair_new
318 @DEFINE_Pair_traverse
319 @DEFINE_Pair_set_a
320
321 static bool saw_expected_finalize_call;
322 static bool unexpected_finalize_call;
323 static bool test_finished;
324
325 // During the test we check our assumptions with an assert to play
326 // nicely with pytest, but if the finalizer gets called after the
327 // test has finished, we have no choice but to abort to signal
328 // the error
329 static void on_unexpected_finalize_call(void);
330 static void on_unexpected_finalize_call() {
331 if (test_finished)
332 abort();
333 else
334 unexpected_finalize_call = true;
335 }
336
337 HPyDef_SLOT(Pair_finalize, HPy_tp_finalize)
338 static void Pair_finalize_impl(HPyContext *ctx, HPy to_be_finalized)
339 {
340 PairObject *pair = PairObject_AsStruct(ctx, to_be_finalized);
341
342 // Check that we were called on the right object: 'to_be_finalized'
343 HPy to_be_finalized_b = HPyField_Load(ctx, to_be_finalized, pair->b);
344 if (!HPy_Is(ctx, to_be_finalized_b, ctx->h_True)) {
345 HPy_Close(ctx, to_be_finalized_b);
346 // This is OK to happen after the test was finished
347 unexpected_finalize_call = true;
348 return;
349 }
350 HPy_Close(ctx, to_be_finalized_b);
351
352 // Check that we were not called twice
353 if (saw_expected_finalize_call) {
354 printf("tp_finalize called twice for 'to_be_finalized'\\\n");
355 on_unexpected_finalize_call();
356 return;
357 }
358
359 HPy owner = HPy_NULL, owner_a = HPy_NULL, owner_b = HPy_NULL;
360 owner = HPyField_Load(ctx, to_be_finalized, pair->a);
361 PairObject *owner_pair = PairObject_AsStruct(ctx, owner);
362
363 // Check that 'to_be_finalized'->a really points to 'owner'
364 owner_b = HPyField_Load(ctx, owner, owner_pair->b);
365 if (!HPy_Is(ctx, owner_b, ctx->h_False)) {
366 printf("to_be_finalized'->a != 'owner'\\\n");
367 on_unexpected_finalize_call();
368 goto owner_cleanup;
369 }
370
371 // Whatever we see in owner->a must not be 'to_be_finalized'
372 // For CPython it should be NULL, because Pair_finalize should
373 // be called immediately when the field is swapped to new value
374 if (HPyField_IsNull(owner_pair->a)) {
375 saw_expected_finalize_call = true;
376 goto owner_cleanup;
377 }
378
379 // For GC based implementations, it can be already the 42 if
380 // Pair_finalize gets called later
381 owner_a = HPyField_Load(ctx, owner, owner_pair->a);
382 if (HPyLong_AsLong(ctx, owner_a) == 42) {
383 saw_expected_finalize_call = true;
384 goto owner_cleanup;
385 }
386
387 HPyErr_Clear(ctx); // if the field was not a long at all
388 printf("unexpected value of the field: %p\\\n", (void*) owner_a._i);
389 on_unexpected_finalize_call();
390 owner_cleanup:
391 HPy_Close(ctx, owner);
392 HPy_Close(ctx, owner_a);
393 HPy_Close(ctx, owner_b);
394 }
395
396 HPyDef_METH(check_finalize_calls, "check_finalize_calls", HPyFunc_NOARGS)
397 static HPy check_finalize_calls_impl(HPyContext *ctx, HPy self)
398 {
399 test_finished = true;
400 if (!unexpected_finalize_call && saw_expected_finalize_call)
401 return HPy_Dup(ctx, ctx->h_True);
402 else
403 return HPy_Dup(ctx, ctx->h_False);
404 }
405
406 @EXPORT(check_finalize_calls)
407 @EXPORT_PAIR_TYPE(&Pair_new, &Pair_traverse, &Pair_finalize, &Pair_set_a)
408 @INIT
409 """)
410 to_be_finalized = mod.Pair(None, True)
411 owner = mod.Pair(to_be_finalized, False)
412 to_be_finalized.set_a(owner)
413 del to_be_finalized
414 # Now 'to_be_finalized' is referenced only by 'owner'.
415 # By setting the field to the new value, the object originally pointed
416 # by 'to_be_finalized' becomes garbage. In CPython, this should
417 # immediately trigger tp_finalize, in other impls it may also
418 # trigger tp_finalize at that point or any later point.
419 # In any case, tp_finalize should not see the original value of the
420 # field anymore.
421 owner.set_a(42)
422 from gc import collect
423 collect()
424 assert mod.check_finalize_calls()