Debian Codegraph @

pypy/module/_hpy_universal/test/_vendored/debug/apptest_handles.py

raw symbols SCIP
1 # spaceconfig = {"usemodules":["_hpy_universal"], "objspace.hpy_cpyext_API":false}
2 import pytest
3
4 @pytest.fixture
5 def hpy_abi():
6 return "debug"
7
8 def make_leak_module(compiler):
9 # for convenience
10 return compiler.make_module("""
11 HPyDef_METH(leak, "leak", HPyFunc_O)
12 static HPy leak_impl(HPyContext *ctx, HPy self, HPy arg)
13 {
14 HPy_Dup(ctx, arg); // leak!
15 return HPy_Dup(ctx, ctx->h_None);
16 }
17 @EXPORT(leak)
18 @INIT
19 """)
20
21
22 def test_debug_ctx_name(compiler):
23 # this is very similar to the one in test_00_basic, but:
24 # 1. by doing the same here, we ensure that we are actually using
25 # the debug ctx in these tests
26 # 2. in pypy we run HPyTest with only hpy_abi==universal, so this
27 # tests something which is NOT tested by test_00_basic
28 mod = compiler.make_module("""
29 HPyDef_METH(f, "f", HPyFunc_NOARGS)
30 static HPy f_impl(HPyContext *ctx, HPy self)
31 {
32 return HPyUnicode_FromString(ctx, ctx->name);
33 }
34
35 @EXPORT(f)
36 @INIT
37 """)
38 ctx_name = mod.f()
39 assert ctx_name.startswith('HPy Debug Mode ABI')
40
41 def test_get_open_handles(compiler):
42 from hpy.universal import _debug
43 mod = make_leak_module(compiler)
44 gen1 = _debug.new_generation()
45 mod.leak('hello')
46 mod.leak('world')
47 gen2 = _debug.new_generation()
48 mod.leak('a younger leak')
49 leaks1 = _debug.get_open_handles(gen1)
50 leaks2 = _debug.get_open_handles(gen2)
51 leaks1 = [dh.obj for dh in leaks1]
52 leaks2 = [dh.obj for dh in leaks2]
53 assert leaks1 == ['hello', 'world', 'a younger leak']
54 assert leaks2 == ['a younger leak']
55
56 def test_leak_from_method(compiler):
57 from hpy.universal import _debug
58 mod = compiler.make_module("""
59 HPyDef_METH(Dummy_leak, "leak", HPyFunc_O)
60 static HPy Dummy_leak_impl(HPyContext *ctx, HPy self, HPy arg) {
61 HPy_Dup(ctx, arg); // leak!
62 return HPy_Dup(ctx, ctx->h_None);
63 }
64 static HPyDef *Dummy_defines[] = {
65 &Dummy_leak,
66 NULL
67 };
68 static HPyType_Spec Dummy_spec = {
69 .name = "mytest.Dummy",
70 .defines = Dummy_defines,
71 };
72 @EXPORT_TYPE("Dummy", Dummy_spec)
73 @INIT
74 """)
75 gen = _debug.new_generation()
76 obj = mod.Dummy()
77 obj.leak("a")
78 leaks = [dh.obj for dh in _debug.get_open_handles(gen)]
79 assert leaks == ["a"]
80
81 def test_DebugHandle_id(compiler):
82 from hpy.universal import _debug
83 mod = make_leak_module(compiler)
84 gen = _debug.new_generation()
85 mod.leak('a')
86 mod.leak('b')
87 a1, b1 = _debug.get_open_handles(gen)
88 a2, b2 = _debug.get_open_handles(gen)
89 assert a1.obj == a2.obj == 'a'
90 assert b1.obj == b2.obj == 'b'
91 #
92 assert a1 is not a2
93 assert b1 is not b2
94 #
95 assert a1.id == a2.id
96 assert b1.id == b2.id
97 assert a1.id != b1.id
98
99 def test_DebugHandle_compare(compiler):
100 import pytest
101 from hpy.universal import _debug
102 mod = make_leak_module(compiler)
103 gen = _debug.new_generation()
104 mod.leak('a')
105 mod.leak('a')
106 a2, a1 = _debug.get_open_handles(gen)
107 assert a1 != a2 # same underlying object, but different DebugHandle
108 #
109 a2_new, a1_new = _debug.get_open_handles(gen)
110 assert a1 is not a1_new # different objects...
111 assert a2 is not a2_new
112 assert a1 == a1_new # ...but same DebugHandle
113 assert a2 == a2_new
114 #
115 with pytest.raises(TypeError):
116 a1 < a2
117 with pytest.raises(TypeError):
118 a1 <= a2
119 with pytest.raises(TypeError):
120 a1 > a2
121 with pytest.raises(TypeError):
122 a1 >= a2
123
124 assert not a1 == 'hello'
125 assert a1 != 'hello'
126 with pytest.raises(TypeError):
127 a1 < 'hello'
128
129 def test_DebugHandle_repr(compiler):
130 from hpy.universal import _debug
131 mod = make_leak_module(compiler)
132 gen = _debug.new_generation()
133 mod.leak('hello')
134 h_hello, = _debug.get_open_handles(gen)
135 assert repr(h_hello).startswith("<DebugHandle 0x%x for 'hello'>" % h_hello.id)
136
137 def test_LeakDetector(compiler):
138 import pytest
139 from hpy.debug import LeakDetector, HPyLeakError
140 mod = make_leak_module(compiler)
141 ld = LeakDetector()
142 ld.start()
143 mod.leak('hello')
144 with pytest.raises(HPyLeakError) as exc:
145 ld.stop()
146 assert str(exc.value).startswith('1 unclosed handle:')
147 #
148 with pytest.raises(HPyLeakError) as exc:
149 with LeakDetector():
150 mod.leak('foo')
151 mod.leak('bar')
152 mod.leak('baz')
153 msg = str(exc.value)
154 assert msg.startswith('3 unclosed handles:')
155 assert 'foo' in msg
156 assert 'bar' in msg
157 assert 'baz' in msg
158 assert 'hello' not in msg
159 assert 'world' not in msg
160
161 def test_closed_handles(compiler):
162 from hpy.universal import _debug
163 mod = make_leak_module(compiler)
164 gen = _debug.new_generation()
165 mod.leak('hello')
166 h_hello, = _debug.get_open_handles(gen)
167 assert not h_hello.is_closed
168 h_hello._force_close()
169 assert h_hello.is_closed
170 assert _debug.get_open_handles(gen) == []
171 assert h_hello in _debug.get_closed_handles()
172 assert repr(h_hello).startswith("<DebugHandle 0x%x CLOSED>" % h_hello.id)
173
174 def test_closed_handles_queue_max_size(compiler):
175 from hpy.universal import _debug
176 mod = compiler.make_module("""
177 HPyDef_METH(f, "f", HPyFunc_O)
178 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
179 {
180 return HPy_Dup(ctx, ctx->h_None);
181 }
182 @EXPORT(f)
183 @INIT
184 """)
185 old_size = _debug.get_closed_handles_queue_max_size()
186 try:
187 # by calling "f" we open and close 3 handles: 1 for self, 1 for arg
188 # and 1 for the result. So, every call to f() increases the size of
189 # closed_handles() by 3
190 n1 = len(_debug.get_closed_handles())
191 _debug.set_closed_handles_queue_max_size(n1+7)
192 assert _debug.get_closed_handles_queue_max_size() == n1+7
193 #
194 mod.f('aaa')
195 n2 = len(_debug.get_closed_handles())
196 assert n2 == n1+3
197 #
198 mod.f('bbb')
199 n3 = len(_debug.get_closed_handles())
200 assert n3 == n2+3
201 # with the next call we reach the maximum size of the queue
202 mod.f('ccc')
203 n4 = len(_debug.get_closed_handles())
204 assert n4 == n1+7
205 #
206 # same as before
207 mod.f('ddd')
208 n5 = len(_debug.get_closed_handles())
209 assert n5 == n1+7
210 finally:
211 _debug.set_closed_handles_queue_max_size(old_size)
212
213 def test_reuse_closed_handles(compiler):
214 from hpy.universal import _debug
215 mod = compiler.make_module("""
216 HPyDef_METH(f, "f", HPyFunc_O)
217 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
218 {
219 return HPy_Dup(ctx, ctx->h_None);
220 }
221 HPyDef_METH(leak, "leak", HPyFunc_O)
222 static HPy leak_impl(HPyContext *ctx, HPy self, HPy arg)
223 {
224 HPy_Dup(ctx, arg); // leak!
225 return HPy_Dup(ctx, ctx->h_None);
226 }
227 @EXPORT(f)
228 @EXPORT(leak)
229 @INIT
230 """)
231
232 old_size = _debug.get_closed_handles_queue_max_size()
233 try:
234 gen = _debug.new_generation()
235 # call f twice to open/closes a bunch of handles
236 mod.f('hello')
237 mod.f('world')
238 #
239 # make sure that the closed_handles queue is considered full: this
240 # will force the reuse of existing closed handles
241 _debug.set_closed_handles_queue_max_size(1)
242 # during the call to leak, we create handles for:
243 # 1. self
244 # 2. arg
245 # 3. HPy_Dup(arg) (leaking)
246 # 4. result
247 # So the leaked handle will be 3rd in the old closed_handles queue
248 closed_handles = _debug.get_closed_handles()
249 mod.leak('foo')
250 assert not closed_handles[2].is_closed
251 assert closed_handles[2].obj == 'foo'
252
253 closed_handles = _debug.get_closed_handles()
254 mod.leak('bar')
255 assert not closed_handles[2].is_closed
256 assert closed_handles[2].obj == 'bar'
257
258 leaks = _debug.get_open_handles(gen)
259 for h in leaks:
260 h._force_close()
261 finally:
262 _debug.set_closed_handles_queue_max_size(old_size)
263
264
265 @pytest.mark.skipif(True, "Does not raise, even on CPython")
266 def test_set_on_invalid_handle(compiler):
267 from hpy.universal import _debug
268 def callback():
269 pass
270
271 with pytest.raises(RuntimeError):
272 _debug.set_on_invalid_handle(callback)
273
274
275 @pytest.mark.skipif(True,
276 reason="It's impossible to recover from use-after-close on pypy")
277 def test_cant_use_closed_handle(compiler):
278 from hpy.universal import _debug
279 mod = compiler.make_module("""
280 HPyDef_METH(f, "f", HPyFunc_O, .doc="double close")
281 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
282 {
283 HPy h = HPy_Dup(ctx, arg);
284 HPy_Close(ctx, h);
285 HPy_Close(ctx, h); // double close
286 return HPy_Dup(ctx, ctx->h_None);
287 }
288
289 HPyDef_METH(g, "g", HPyFunc_O, .doc="use after close")
290 static HPy g_impl(HPyContext *ctx, HPy self, HPy arg)
291 {
292 HPy h = HPy_Dup(ctx, arg);
293 HPy_Close(ctx, h);
294 return HPy_Repr(ctx, h);
295 }
296
297 @EXPORT(f)
298 @EXPORT(g)
299 @INIT
300 """)
301 n = 0
302 def callback():
303 nonlocal n
304 n += 1
305 _debug.set_on_invalid_handle(callback)
306 mod.f('foo') # double close
307 assert n == 1
308 mod.g('bar') # use-after-close
309 assert n == 2
310
311 @pytest.mark.skipif(True,
312 reason="It's impossible to recover from use-after-close on pypy")
313 def test_keeping_and_reusing_argument_handle(compiler):
314 mod = compiler.make_module("""
315 HPy keep;
316
317 HPyDef_METH(f, "f", HPyFunc_O)
318 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
319 {
320 keep = arg;
321 HPy_ssize_t len = HPy_Length(ctx, keep);
322 return HPyLong_FromSsize_t(ctx, len);
323 }
324
325 HPyDef_METH(g, "g", HPyFunc_NOARGS)
326 static HPy g_impl(HPyContext *ctx, HPy self)
327 {
328 HPy_ssize_t len = HPy_Length(ctx, keep);
329 if (len == -1)
330 return HPy_NULL;
331 return HPyLong_FromSsize_t(ctx, len);
332 }
333
334 @EXPORT(f)
335 @EXPORT(g)
336 @INIT
337 """)
338 class HPyDebugCapture:
339 """
340 Context manager that sets HPy debug invalid handle hook and remembers the
341 number of invalid handles reported. Once closed, sets the invalid handle
342 hook back to None.
343 """
344 def __init__(self):
345 self.invalid_handles_count = 0
346
347 def _capture_report(self):
348 self.invalid_handles_count += 1
349
350 def __enter__(self):
351 from hpy.universal import _debug
352 _debug.set_on_invalid_handle(self._capture_report)
353 return self
354
355 def __exit__(self, exc_type, exc_val, exc_tb):
356 from hpy.universal import _debug
357 # _debug.set_on_invalid_handle(None)
358
359
360 s = "hello leaks!"
361 with HPyDebugCapture() as hpy_debug_capture:
362 assert mod.f(s) == len(s)
363 assert hpy_debug_capture.invalid_handles_count == 0
364 assert mod.g() == len(s)
365 assert hpy_debug_capture.invalid_handles_count == 1
366