test_weakref.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 574 行 · 第 1/2 页

PY
574
字号
import sysimport unittestimport UserListimport weakrefimport test_supportclass C:    def method(self):        passclass Callable:    bar = None    def __call__(self, x):        self.bar = xdef create_function():    def f(): pass    return fdef create_bound_method():    return C().methoddef create_unbound_method():    return C.methodclass TestBase(unittest.TestCase):    def setUp(self):        self.cbcalled = 0    def callback(self, ref):        self.cbcalled += 1class ReferencesTestCase(TestBase):    def test_basic_ref(self):        self.check_basic_ref(C)        self.check_basic_ref(create_function)        self.check_basic_ref(create_bound_method)        self.check_basic_ref(create_unbound_method)    def test_basic_callback(self):        self.check_basic_callback(C)        self.check_basic_callback(create_function)        self.check_basic_callback(create_bound_method)        self.check_basic_callback(create_unbound_method)    def test_multiple_callbacks(self):        o = C()        ref1 = weakref.ref(o, self.callback)        ref2 = weakref.ref(o, self.callback)        del o        self.assert_(ref1() is None,                     "expected reference to be invalidated")        self.assert_(ref2() is None,                     "expected reference to be invalidated")        self.assert_(self.cbcalled == 2,                     "callback not called the right number of times")    def test_multiple_selfref_callbacks(self):        """Make sure all references are invalidated before callbacks        are called."""        #        # What's important here is that we're using the first        # reference in the callback invoked on the second reference        # (the most recently created ref is cleaned up first).  This        # tests that all references to the object are invalidated        # before any of the callbacks are invoked, so that we only        # have one invocation of _weakref.c:cleanup_helper() active        # for a particular object at a time.        #        def callback(object, self=self):            self.ref()        c = C()        self.ref = weakref.ref(c, callback)        ref1 = weakref.ref(c, callback)        del c    def test_proxy_ref(self):        o = C()        o.bar = 1        ref1 = weakref.proxy(o, self.callback)        ref2 = weakref.proxy(o, self.callback)        del o        def check(proxy):            proxy.bar        self.assertRaises(weakref.ReferenceError, check, ref1)        self.assertRaises(weakref.ReferenceError, check, ref2)        self.assert_(self.cbcalled == 2)    def check_basic_ref(self, factory):        o = factory()        ref = weakref.ref(o)        self.assert_(ref() is not None,                     "weak reference to live object should be live")        o2 = ref()        self.assert_(o is o2,                     "<ref>() should return original object if live")    def check_basic_callback(self, factory):        self.cbcalled = 0        o = factory()        ref = weakref.ref(o, self.callback)        del o        self.assert_(self.cbcalled == 1,                     "callback did not properly set 'cbcalled'")        self.assert_(ref() is None,                     "ref2 should be dead after deleting object reference")    def test_ref_reuse(self):        o = C()        ref1 = weakref.ref(o)        # create a proxy to make sure that there's an intervening creation        # between these two; it should make no difference        proxy = weakref.proxy(o)        ref2 = weakref.ref(o)        self.assert_(ref1 is ref2,                     "reference object w/out callback should be re-used")        o = C()        proxy = weakref.proxy(o)        ref1 = weakref.ref(o)        ref2 = weakref.ref(o)        self.assert_(ref1 is ref2,                     "reference object w/out callback should be re-used")        self.assert_(weakref.getweakrefcount(o) == 2,                     "wrong weak ref count for object")        del proxy        self.assert_(weakref.getweakrefcount(o) == 1,                     "wrong weak ref count for object after deleting proxy")    def test_proxy_reuse(self):        o = C()        proxy1 = weakref.proxy(o)        ref = weakref.ref(o)        proxy2 = weakref.proxy(o)        self.assert_(proxy1 is proxy2,                     "proxy object w/out callback should have been re-used")    def test_basic_proxy(self):        o = C()        self.check_proxy(o, weakref.proxy(o))        L = UserList.UserList()        p = weakref.proxy(L)        self.failIf(p, "proxy for empty UserList should be false")        p.append(12)        self.assertEqual(len(L), 1)        self.failUnless(p, "proxy for non-empty UserList should be true")        p[:] = [2, 3]        self.assertEqual(len(L), 2)        self.assertEqual(len(p), 2)        self.failUnless(3 in p, "proxy didn't support __contains__() properly")        p[1] = 5        self.assertEqual(L[1], 5)        self.assertEqual(p[1], 5)        L2 = UserList.UserList(L)        p2 = weakref.proxy(L2)        self.assertEqual(p, p2)    def test_callable_proxy(self):        o = Callable()        ref1 = weakref.proxy(o)        self.check_proxy(o, ref1)        self.assert_(type(ref1) is weakref.CallableProxyType,                     "proxy is not of callable type")        ref1('twinkies!')        self.assert_(o.bar == 'twinkies!',                     "call through proxy not passed through to original")        ref1(x='Splat.')        self.assert_(o.bar == 'Splat.',                     "call through proxy not passed through to original")        # expect due to too few args        self.assertRaises(TypeError, ref1)        # expect due to too many args        self.assertRaises(TypeError, ref1, 1, 2, 3)    def check_proxy(self, o, proxy):        o.foo = 1        self.assert_(proxy.foo == 1,                     "proxy does not reflect attribute addition")        o.foo = 2        self.assert_(proxy.foo == 2,                     "proxy does not reflect attribute modification")        del o.foo        self.assert_(not hasattr(proxy, 'foo'),                     "proxy does not reflect attribute removal")        proxy.foo = 1        self.assert_(o.foo == 1,                     "object does not reflect attribute addition via proxy")        proxy.foo = 2        self.assert_(            o.foo == 2,            "object does not reflect attribute modification via proxy")        del proxy.foo        self.assert_(not hasattr(o, 'foo'),                     "object does not reflect attribute removal via proxy")    def test_getweakrefcount(self):        o = C()        ref1 = weakref.ref(o)        ref2 = weakref.ref(o, self.callback)        self.assert_(weakref.getweakrefcount(o) == 2,                     "got wrong number of weak reference objects")        proxy1 = weakref.proxy(o)        proxy2 = weakref.proxy(o, self.callback)        self.assert_(weakref.getweakrefcount(o) == 4,                     "got wrong number of weak reference objects")    def test_getweakrefs(self):        o = C()        ref1 = weakref.ref(o, self.callback)        ref2 = weakref.ref(o, self.callback)        del ref1        self.assert_(weakref.getweakrefs(o) == [ref2],                     "list of refs does not match")        o = C()        ref1 = weakref.ref(o, self.callback)        ref2 = weakref.ref(o, self.callback)        del ref2        self.assert_(weakref.getweakrefs(o) == [ref1],                     "list of refs does not match")    def test_newstyle_number_ops(self):        class F(float):            pass        f = F(2.0)        p = weakref.proxy(f)        self.assert_(p + 1.0 == 3.0)        self.assert_(1.0 + p == 3.0)  # this used to SEGV    def test_callbacks_protected(self):        """Callbacks protected from already-set exceptions?"""        # Regression test for SF bug #478534.        class BogusError(Exception):            pass        data = {}        def remove(k):            del data[k]        def encapsulate():            f = lambda : ()            data[weakref.ref(f, remove)] = None            raise BogusError        try:            encapsulate()        except BogusError:            pass        else:            self.fail("exception not properly restored")        try:            encapsulate()        except BogusError:            pass        else:            self.fail("exception not properly restored")class Object:    def __init__(self, arg):        self.arg = arg    def __repr__(self):        return "<Object %r>" % self.argclass MappingTestCase(TestBase):    COUNT = 10    def test_weak_values(self):        #        #  This exercises d.copy(), d.items(), d[], del d[], len(d).

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?