File: test_weakref.py

package info (click to toggle)
pypy3 7.0.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 111,848 kB
  • sloc: python: 1,291,746; ansic: 74,281; asm: 5,187; cpp: 3,017; sh: 2,533; makefile: 544; xml: 243; lisp: 45; csh: 21; awk: 4
file content (547 lines) | stat: -rw-r--r-- 14,867 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
class AppTestWeakref(object):
    spaceconfig = dict(usemodules=('_weakref',))

    def setup_class(cls):
        cls.w_runappdirect = cls.space.wrap(cls.runappdirect)

    def test_simple(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        assert _weakref.getweakrefcount(a) == 0
        ref = _weakref.ref(a)
        assert ref() is a
        assert a.__weakref__ is ref
        assert _weakref.getweakrefcount(a) == 1
        del a
        gc.collect()
        assert ref() is None

    def test_missing_arg(self):
        import _weakref
        raises(TypeError, _weakref.ref)

    def test_no_kwargs(self):
        import _weakref
        class C(object):
            pass
        raises(TypeError, _weakref.ref, C(), callback=None)

    def test_callback(self):
        import _weakref, gc
        class A(object):
            pass
        a1 = A()
        a2 = A()
        def callback(ref):
            a2.ref = ref()
        ref1 = _weakref.ref(a1, callback)
        ref2 = _weakref.ref(a1)
        assert ref1.__callback__ is callback
        assert ref2.__callback__ is None
        assert _weakref.getweakrefcount(a1) == 2
        del a1
        gc.collect()
        assert ref1() is None
        assert ref1.__callback__ is None
        assert a2.ref is None

    def test_callback_order(self):
        import _weakref, gc
        class A(object):
            pass
        a1 = A()
        a2 = A()
        def callback1(ref):
            a2.x = 42
        def callback2(ref):
            a2.x = 43
        ref1 = _weakref.ref(a1, callback1)
        ref2 = _weakref.ref(a1, callback2)
        del a1
        gc.collect()
        assert a2.x == 42
        
    def test_dont_callback_if_weakref_dead(self):
        import _weakref, gc
        class A(object):
            pass
        a1 = A()
        a1.x = 40
        a2 = A()
        def callback(ref):
            a1.x = 42
        assert _weakref.getweakrefcount(a2) == 0
        ref = _weakref.ref(a2, callback)
        assert _weakref.getweakrefcount(a2) == 1
        ref = None
        gc.collect()
        assert _weakref.getweakrefcount(a2) == 0
        a2 = None
        gc.collect()
        assert a1.x == 40

    def test_callback_cannot_ressurect(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        alive = A()
        alive.a = 1
        def callback(ref2):
            alive.a = ref1()
        ref1 = _weakref.ref(a, callback)
        ref2 = _weakref.ref(a, callback)
        del a
        gc.collect()
        assert alive.a is None

    def test_weakref_reusing(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        ref1 = _weakref.ref(a)
        ref2 = _weakref.ref(a)
        assert ref1 is ref2
        class wref(_weakref.ref):
            pass
        wref1 = wref(a)
        assert isinstance(wref1, wref)

    def test_correct_weakrefcount_after_death(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        ref1 = _weakref.ref(a)
        ref2 = _weakref.ref(a)
        assert _weakref.getweakrefcount(a) == 1
        del ref1
        gc.collect()
        assert _weakref.getweakrefcount(a) == 1
        del ref2
        gc.collect()
        assert _weakref.getweakrefcount(a) == 0

    def test_weakref_equality(self):
        import _weakref, gc
        class A(object):
            def __eq__(self, other):
                return True
            def __ne__(self, other):
                return False
        a1 = A()
        a2 = A()
        ref1 = _weakref.ref(a1)
        ref2 = _weakref.ref(a2)
        assert ref1 == ref2
        assert not (ref1 != ref2)
        assert not (ref1 == [])
        assert ref1 != []
        del a1
        gc.collect()
        assert not ref1 == ref2
        assert ref1 != ref2
        assert not (ref1 == [])
        assert ref1 != []
        del a2
        gc.collect()
        assert not ref1 == ref2
        assert ref1 != ref2
        assert not (ref1 == [])
        assert ref1 != []

    def test_ne(self):
        import _weakref
        class X(object):
            pass
        ref1 = _weakref.ref(X())
        assert ref1.__eq__(X()) is NotImplemented
        assert ref1.__ne__(X()) is NotImplemented

    def test_getweakrefs(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        assert _weakref.getweakrefs(a) == []
        assert _weakref.getweakrefs(None) == []
        ref1 = _weakref.ref(a)
        assert _weakref.getweakrefs(a) == [ref1]

    def test_hashing(self):
        import _weakref, gc
        class A(object):
            def __hash__(self):
                return 42
        a = A()
        w = _weakref.ref(a)
        assert hash(a) == hash(w)
        del a
        gc.collect()
        assert hash(w) == 42
        w = _weakref.ref(A())
        gc.collect()
        raises(TypeError, hash, w)

    def test_weakref_subclassing(self):
        import _weakref, gc
        class A(object):
            pass
        class Ref(_weakref.ref):
            def __init__(self, ob, callback=None, **other):
                self.__dict__.update(other)
        def callable(ref):
            b.a = 42
        a = A()
        b = A()
        b.a = 1
        w = Ref(a, callable, x=1, y=2)
        assert w.x == 1
        assert w.y == 2
        assert a.__weakref__ is w
        assert b.__weakref__ is None
        w1 = _weakref.ref(a)
        w2 = _weakref.ref(a, callable)
        assert a.__weakref__ is w1
        del a
        gc.collect()
        assert w1() is None
        assert w() is None
        assert w2() is None
        assert b.a == 42

    def test_function_weakrefable(self):
        import _weakref, gc
        def f(x):
            return 42
        wf = _weakref.ref(f)
        assert wf()(63) == 42
        del f
        gc.collect()
        assert wf() is None

    def test_method_weakrefable(self):
        import _weakref, gc
        class A(object):
            def f(self):
                return 42
        a = A()
        meth = A.f
        w_unbound = _weakref.ref(meth)
        assert w_unbound()(A()) == 42
        meth = A().f
        w_bound = _weakref.ref(meth)
        assert w_bound()() == 42
        del meth
        gc.collect()
        # it used to be None on py2, but now there is no longer a newly
        # created unbound method object
        assert w_unbound() is A.f
        assert w_bound() is None

    def test_set_weakrefable(self):
        import _weakref, gc
        s = set([1, 2, 3, 4])
        w = _weakref.ref(s)
        assert w() is s
        del s
        gc.collect()
        assert w() is None

    def test_generator_weakrefable(self):
        import _weakref, gc
        def f(x):
            for i in range(x):
                yield i
        g = f(10)
        w = _weakref.ref(g)
        r = next(w())
        assert r == 0
        r = next(g)
        assert r == 1
        del g
        gc.collect()
        assert w() is None
        g = f(10)
        w = _weakref.ref(g)
        assert list(g) == list(range(10))
        del g
        gc.collect()
        assert w() is None

    def test_weakref_subclass_with_del(self):
        import _weakref, gc
        class Ref(_weakref.ref):
            def __del__(self):
                b.a = 42
        class A(object):
            pass
        a = A()
        b = A()
        b.a = 1
        w = Ref(a)
        del w
        gc.collect()
        assert b.a == 42
        if _weakref.getweakrefcount(a) > 0:
            # the following can crash if the presence of the applevel __del__
            # leads to the fact that the __del__ of _weakref.ref is not called.
            assert _weakref.getweakrefs(a)[0]() is a

    def test_buggy_case(self):
        import gc, weakref
        gone = []
        class A(object):
            def __del__(self):
                gone.append(True)
        a = A()
        w = weakref.ref(a)
        del a
        tries = 5
        for i in range(5):
            if not gone:
                gc.collect()
        if gone:
            a1 = w()
            assert a1 is None

    def test_del_and_callback_and_id(self):
        if not self.runappdirect:
            skip("the id() doesn't work correctly in __del__ and "
                 "callbacks before translation")
        import gc, weakref
        seen_del = []
        class A(object):
            def __del__(self):
                seen_del.append(id(self))
                seen_del.append(w1() is None)
                seen_del.append(w2() is None)
        seen_callback = []
        def callback(r):
            seen_callback.append(r is w2)
            seen_callback.append(w1() is None)
            seen_callback.append(w2() is None)
        a = A()
        w1 = weakref.ref(a)
        w2 = weakref.ref(a, callback)
        aid = id(a)
        del a
        for i in range(5):
            gc.collect()
        if seen_del:
            assert seen_del == [aid, True, True]
        if seen_callback:
            assert seen_callback == [True, True, True]

    def test_type_weakrefable(self):
        import _weakref, gc
        w = _weakref.ref(list)
        assert w() is list
        gc.collect()
        assert w() is list


class AppTestProxy(object):
    spaceconfig = dict(usemodules=('_weakref',))
                    
    def test_simple(self):
        import _weakref, gc
        class A(object):
            def __init__(self, x):
                self.x = x
        a = A(1)
        p = _weakref.proxy(a)
        assert p.x == 1
        assert str(p) == str(a)
        raises(TypeError, p)

    def test_caching(self):
        import _weakref, gc
        class A(object): pass
        a = A()
        assert _weakref.proxy(a) is _weakref.proxy(a)
        assert _weakref.proxy(a) is _weakref.proxy(a, None)

    def test_callable_proxy(self):
        import _weakref, gc
        class A(object):
            def __call__(self):
                global_a.x = 1
        global_a = A()
        global_a.x = 41
        A_ = _weakref.proxy(A)
        a = A_()
        assert isinstance(a, A)
        a_ = _weakref.proxy(a)
        a_()
        assert global_a.x == 1

    def test_callable_proxy_type(self):
        import _weakref, gc
        class Callable(object):
            def __call__(self, x):
                pass
        o = Callable()
        ref1 = _weakref.proxy(o)
        assert type(ref1) is _weakref.CallableProxyType

    def test_dont_create_directly(self):
        import _weakref, gc
        raises(TypeError, _weakref.ProxyType, [])
        raises(TypeError, _weakref.CallableProxyType, [])

    def test_dont_hash(self):
        import _weakref, gc
        class A(object):
            pass
        a = A()
        p = _weakref.proxy(a)
        raises(TypeError, hash, p)

    def test_subclassing_not_allowed(self):
        import _weakref, gc
        def tryit():
            class A(_weakref.ProxyType):
                pass
            return A
        raises(TypeError, tryit)

    def test_proxy_to_dead_object(self):
        import _weakref, gc
        class A(object):
            pass
        p = _weakref.proxy(A())
        gc.collect()
        raises(ReferenceError, "p + 1")

    def test_proxy_with_callback(self):
        import _weakref, gc
        class A(object):
            pass
        a2 = A()
        def callback(proxy):
            a2.seen = proxy
        p = _weakref.proxy(A(), callback)
        gc.collect()
        raises(ReferenceError, "p + 1")
        assert a2.seen is p

    def test_repr(self):
        import _weakref, gc
        for kind in ('ref', 'proxy'):
            def foobaz():
                "A random function not returning None."
                return 42
            w = getattr(_weakref, kind)(foobaz)
            s = repr(w)
            print(s)
            if kind == 'ref':
                assert s.startswith('<weakref at ')
            else:
                assert (s.startswith('<weakproxy at ') or
                        s.startswith('<weakcallableproxy at '))
            assert "function" in s
            del foobaz
            try:
                for i in range(10):
                    if w() is None:
                        break     # only reachable if kind == 'ref'
                    gc.collect()
            except ReferenceError:
                pass    # only reachable if kind == 'proxy'
            s = repr(w)
            print(s)
            assert "dead" in s

    def test_bytes(self):
        import _weakref
        class C(object):
            def __bytes__(self):
                return b"string"
        instance = C()
        assert "__bytes__" in dir(_weakref.proxy(instance))
        assert bytes(_weakref.proxy(instance)) == b"string"

    def test_eq(self):
        import _weakref
        class A(object):
            pass

        a = A()
        assert not(_weakref.ref(a) == a)
        assert _weakref.ref(a) != a

        class A(object):
            def __eq__(self, other):
                return True
            def __ne__(self, other):
                return False

        a = A()
        assert _weakref.ref(a) == a

    def test_callback_raises(self):
        import _weakref, gc
        class A(object):
            pass
        a1 = A()
        def callback(ref):
            explode
        ref1 = _weakref.ref(a1, callback)
        del a1
        gc.collect()
        assert ref1() is None

    def test_init(self):
        import _weakref, gc
        # Issue 3634
        # <weakref to class>.__init__() doesn't check errors correctly
        r = _weakref.ref(Exception)
        raises(TypeError, r.__init__, 0, 0, 0, 0, 0)
        # No exception should be raised here
        gc.collect()

    def test_add(self):
        import _weakref
        class A(object):
            def __add__(self, other):
                return other
        a1 = A()
        a2 = A()
        p1 = _weakref.proxy(a1)
        p2 = _weakref.proxy(a2)
        a3 = p1 + p2
        assert a3 is a2

    def test_inplace_add(self):
        import _weakref
        class A(object):
            def __add__(self, other):
                return other
        a1 = A()
        a2 = A()
        p1 = _weakref.proxy(a1)
        p2 = _weakref.proxy(a2)
        p1 += p2
        assert p1 is a2

    def test_setattr(self):
        import _weakref
        class A(object):
            def __setitem__(self, key, value):
                self.setkey = key
                self.setvalue = value
        a1 = A()
        a2 = A()
        p1 = _weakref.proxy(a1)
        p2 = _weakref.proxy(a2)
        p1[p2] = 42
        assert a1.setkey is p2
        assert a1.setvalue == 42
        #
        p1[42] = p2
        assert a1.setkey == 42
        assert a1.setvalue is p2