File: test_weakref_jy.py

package info (click to toggle)
jython 2.5.3-16%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,772 kB
  • ctags: 106,434
  • sloc: python: 351,322; java: 216,349; xml: 1,584; sh: 330; perl: 114; ansic: 102; makefile: 45
file content (84 lines) | stat: -rw-r--r-- 2,086 bytes parent folder | download | duplicates (7)
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
"""Misc weakref tests

Made for Jython.
"""
import unittest
import weakref
from test import test_support
from test_weakref import extra_collect

class ReferencesTestCase(unittest.TestCase):

    def test___eq__(self):
        class Foo(object):
            def __eq__(self, other):
                return True
            def __hash__(self):
                return hash('foo')
        foo1, foo2 = Foo(), Foo()
        ref1, ref2 = weakref.ref(foo1), weakref.ref(foo2)
        self.assertTrue(ref1() is foo1)
        self.assertTrue(ref2() is foo2)

    def test___hash__call(self):
        hash_called = []
        class Bar(object):
            def __hash__(self):
                hash = object.__hash__(self)
                hash_called.append(hash)
                return hash
        bar = Bar()
        ref = weakref.ref(bar)
        self.assertFalse(hash_called)

        hash(ref)
        self.assertEqual(len(hash_called), 1)
        hash(ref)
        self.assertEqual(len(hash_called), 1)
        self.assertEqual(hash(bar), hash(ref))
        self.assertEqual(len(hash_called), 2)


class ArgsTestCase(unittest.TestCase):

    # XXX consider adding other tests for dict, list, etc

    def test_python_fn_kwargs(self):

        weakrefs = []
        sentinel = []

        def watch(obj, kwarg=True):
            self.assertEqual(kwarg, True)
            # log the death of the reference by appending to the sentinel
            ref = weakref.ref(obj, sentinel.append)
            weakrefs.append(ref)

        self.assert_(not sentinel)

        thunk1 = lambda: None
        watch(thunk1)
        self.assert_(not sentinel)

        del thunk1
        extra_collect()
        self.assert_(sentinel)

        del sentinel[:]

        thunk2 = lambda: None
        watch(thunk2, kwarg=True)  # <--- only difference: called with a kwarg
        self.assert_(not sentinel)

        del thunk2
        extra_collect()
        self.assert_(sentinel)



def test_main():
    test_support.run_unittest(ReferencesTestCase, ArgsTestCase)


if __name__ == '__main__':
    test_main()