test_descr.py
来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 2,316 行 · 第 1/5 页
PY
2,316 行
class C(B): def __getattr__(self, name): if name == "foo": return ("getattr", name) else: raise AttributeError def __setattr__(self, name, value): if name == "foo": self.setattr = (name, value) else: return B.__setattr__(self, name, value) def __delattr__(self, name): if name == "foo": self.delattr = name else: return B.__delattr__(self, name) def __getitem__(self, key): return ("getitem", key) def __setitem__(self, key, value): self.setitem = (key, value) def __delitem__(self, key): self.delitem = key def __getslice__(self, i, j): return ("getslice", i, j) def __setslice__(self, i, j, value): self.setslice = (i, j, value) def __delslice__(self, i, j): self.delslice = (i, j) a = C() vereq(a.foo, ("getattr", "foo")) a.foo = 12 vereq(a.setattr, ("foo", 12)) del a.foo vereq(a.delattr, "foo") vereq(a[12], ("getitem", 12)) a[12] = 21 vereq(a.setitem, (12, 21)) del a[12] vereq(a.delitem, 12) vereq(a[0:10], ("getslice", 0, 10)) a[0:10] = "foo" vereq(a.setslice, (0, 10, "foo")) del a[0:10] vereq(a.delslice, (0, 10))def methods(): if verbose: print "Testing methods..." class C(object): def __init__(self, x): self.x = x def foo(self): return self.x c1 = C(1) vereq(c1.foo(), 1) class D(C): boo = C.foo goo = c1.foo d2 = D(2) vereq(d2.foo(), 2) vereq(d2.boo(), 2) vereq(d2.goo(), 1) class E(object): foo = C.foo vereq(E().foo, C.foo) # i.e., unbound verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))def specials(): # Test operators like __hash__ for which a built-in default exists if verbose: print "Testing special operators..." # Test the default behavior for static classes class C(object): def __getitem__(self, i): if 0 <= i < 10: return i raise IndexError c1 = C() c2 = C() verify(not not c1) vereq(hash(c1), id(c1)) vereq(cmp(c1, c2), cmp(id(c1), id(c2))) vereq(c1, c1) verify(c1 != c2) verify(not c1 != c1) verify(not c1 == c2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. verify(str(c1).find('C object at ') >= 0) vereq(str(c1), repr(c1)) verify(-1 not in c1) for i in range(10): verify(i in c1) verify(10 not in c1) # Test the default behavior for dynamic classes class D(object): def __getitem__(self, i): if 0 <= i < 10: return i raise IndexError d1 = D() d2 = D() verify(not not d1) vereq(hash(d1), id(d1)) vereq(cmp(d1, d2), cmp(id(d1), id(d2))) vereq(d1, d1) verify(d1 != d2) verify(not d1 != d1) verify(not d1 == d2) # Note that the module name appears in str/repr, and that varies # depending on whether this test is run standalone or from a framework. verify(str(d1).find('D object at ') >= 0) vereq(str(d1), repr(d1)) verify(-1 not in d1) for i in range(10): verify(i in d1) verify(10 not in d1) # Test overridden behavior for static classes class Proxy(object): def __init__(self, x): self.x = x def __nonzero__(self): return not not self.x def __hash__(self): return hash(self.x) def __eq__(self, other): return self.x == other def __ne__(self, other): return self.x != other def __cmp__(self, other): return cmp(self.x, other.x) def __str__(self): return "Proxy:%s" % self.x def __repr__(self): return "Proxy(%r)" % self.x def __contains__(self, value): return value in self.x p0 = Proxy(0) p1 = Proxy(1) p_1 = Proxy(-1) verify(not p0) verify(not not p1) vereq(hash(p0), hash(0)) vereq(p0, p0) verify(p0 != p1) verify(not p0 != p0) vereq(not p0, p1) vereq(cmp(p0, p1), -1) vereq(cmp(p0, p0), 0) vereq(cmp(p0, p_1), 1) vereq(str(p0), "Proxy:0") vereq(repr(p0), "Proxy(0)") p10 = Proxy(range(10)) verify(-1 not in p10) for i in range(10): verify(i in p10) verify(10 not in p10) # Test overridden behavior for dynamic classes class DProxy(object): def __init__(self, x): self.x = x def __nonzero__(self): return not not self.x def __hash__(self): return hash(self.x) def __eq__(self, other): return self.x == other def __ne__(self, other): return self.x != other def __cmp__(self, other): return cmp(self.x, other.x) def __str__(self): return "DProxy:%s" % self.x def __repr__(self): return "DProxy(%r)" % self.x def __contains__(self, value): return value in self.x p0 = DProxy(0) p1 = DProxy(1) p_1 = DProxy(-1) verify(not p0) verify(not not p1) vereq(hash(p0), hash(0)) vereq(p0, p0) verify(p0 != p1) verify(not p0 != p0) vereq(not p0, p1) vereq(cmp(p0, p1), -1) vereq(cmp(p0, p0), 0) vereq(cmp(p0, p_1), 1) vereq(str(p0), "DProxy:0") vereq(repr(p0), "DProxy(0)") p10 = DProxy(range(10)) verify(-1 not in p10) for i in range(10): verify(i in p10) verify(10 not in p10) # Safety test for __cmp__ def unsafecmp(a, b): try: a.__class__.__cmp__(a, b) except TypeError: pass else: raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( a.__class__, a, b) unsafecmp(u"123", "123") unsafecmp("123", u"123") unsafecmp(1, 1.0) unsafecmp(1.0, 1) unsafecmp(1, 1L) unsafecmp(1L, 1) class Letter(str): def __new__(cls, letter): if letter == 'EPS': return str.__new__(cls) return str.__new__(cls, letter) def __str__(self): if not self: return 'EPS' return self # sys.stdout needs to be the original to trigger the recursion bug import sys test_stdout = sys.stdout sys.stdout = get_original_stdout() try: # nothing should actually be printed, this should raise an exception print Letter('w') except RuntimeError: pass else: raise TestFailed, "expected a RuntimeError for print recursion" sys.stdout = test_stdoutdef weakrefs(): if verbose: print "Testing weak references..." import weakref class C(object): pass c = C() r = weakref.ref(c) verify(r() is c) del c verify(r() is None) del r class NoWeak(object): __slots__ = ['foo'] no = NoWeak() try: weakref.ref(no) except TypeError, msg: verify(str(msg).find("weak reference") >= 0) else: verify(0, "weakref.ref(no) should be illegal") class Weak(object): __slots__ = ['foo', '__weakref__'] yes = Weak() r = weakref.ref(yes) verify(r() is yes) del yes verify(r() is None) del rdef properties(): if verbose: print "Testing property..." class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, doc="I'm the x property.") a = C() verify(not hasattr(a, "x")) a.x = 42 vereq(a._C__x, 42) vereq(a.x, 42) del a.x verify(not hasattr(a, "x")) verify(not hasattr(a, "_C__x")) C.x.__set__(a, 100) vereq(C.x.__get__(a), 100) C.x.__delete__(a) verify(not hasattr(a, "x")) raw = C.__dict__['x'] verify(isinstance(raw, property)) attrs = dir(raw) verify("__doc__" in attrs) verify("fget" in attrs) verify("fset" in attrs) verify("fdel" in attrs) vereq(raw.__doc__, "I'm the x property.") verify(raw.fget is C.__dict__['getx']) verify(raw.fset is C.__dict__['setx']) verify(raw.fdel is C.__dict__['delx']) for attr in "__doc__", "fget", "fset", "fdel": try: setattr(raw, attr, 42) except TypeError, msg: if str(msg).find('readonly') < 0: raise TestFailed("when setting readonly attr %r on a " "property, got unexpected TypeError " "msg %r" % (attr, str(msg))) else: raise TestFailed("expected TypeError from trying to set " "readonly %r attr on a property" % attr) class D(object): __getitem__ = property(lambda s: 1/0) d = D() try: for i in d: str(i) except ZeroDivisionError: pass else: raise TestFailed, "expected ZeroDivisionError from bad property"def supers(): if verbose: print "Testing super..." class A(object): def meth(self, a): return "A(%r)" % a vereq(A().meth(1), "A(1)") class B(A): def __init__(self): self.__super = super(B, self) def meth(self, a): return "B(%r)" % a + self.__super.meth(a) vereq(B().meth(2), "B(2)A(2)") class C(A): def meth(self, a): return "C(%r)" % a + self.__super.meth(a) C._C__super = super(C) vereq(C().meth(3), "C(3)A(3)") class D(C, B): def meth(self, a): return "D(%r)" % a + super(D, self).meth(a) vereq(D().meth(4), "D(4)C(4)B(4)A(4)") # Test for subclassing super class mysuper(super): def __init__(self, *args): return super(mysuper, self).__init__(*args) class E(D): def meth(self, a): return "E(%r)" % a + mysuper(E, self).meth(a) vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") class F(E): def meth(self, a): s = self.__super return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) F._F__super = mysuper(F) vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") # Make sure certain errors are raised try: super(D, 42) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D, 42)" try: super(D, C()) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D, C())" try: super(D).__get__(12) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D).__get__(12)" try: super(D).__get__(C()) except TypeError: pass else: raise TestFailed, "shouldn't allow super(D).__get__(C())"def inherits(): if verbose: print "Testing inheritance from basic types..." class hexint(int): def __repr__(self): return hex(self) def __add__(self, other): return hexint(int.__add__(self, other)) # (Note that overriding __radd__ doesn't work, # because the int type gets first dibs.) vereq(repr(hexint(7) + 9), "0x10") vereq(repr(hexint(1000) + 7), "0x3ef") a = hexint(12345) vereq(a, 12345) vereq(int(a), 12345) verify(int(a).__class__ is int) vereq(hash(a), hash(12345)) verify((+a).__class__ is int) verify((a >> 0).__class__ is int) verify((a << 0).__class__ is int) verify((hexint(0) << 12).__class__ is int) verify((hexint(0) >> 12).__class__ is int) class octlong(long): __slots__ = [] def __str__(self): s = oct(self) if s[-1] == 'L': s = s[:-1] return s def __add__(self, other): return self.__class__(super(octlong, self).__add__(other)) __radd__ = __add__ vereq(str(octlong(3) + 5), "010") # (Note that overriding __radd__ here only seems to work # because the example uses a short int left argument.) vereq(str(5 + octlong(3000)), "05675") a = octlong(12345) vereq(a, 12345L) vereq(long(a), 12345L) vereq(hash(a), hash(12345L)) verify(long(a).__class__ is long) verify((+a).__class__ is long) verify((-a).__class__ is long) verify((-octlong(0)).__class__ is long) verify((a >> 0).__class__ is long) verify((a << 0).__class__ is long) verify((a - 0).__class__ is long) verify((a * 1).__class__ is long) verify((a ** 1).__class__ is long) verify((a // 1).__class__ is long) verify((1 * a).__class__ is long) verify((a | 0).__class__ is long) verify((a ^ 0).__class__ is long) verify((a & -1L).__class__ is long) verify((octlong(0) << 12).__class__ is long)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?