test_descr.py
来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 2,316 行 · 第 1/5 页
PY
2,316 行
verify((octlong(0) >> 12).__class__ is long) verify(abs(octlong(0)).__class__ is long) # Because octlong overrides __add__, we can't check the absence of +0 # optimizations using octlong. class longclone(long): pass a = longclone(1) verify((a + 0).__class__ is long) verify((0 + a).__class__ is long) # Check that negative clones don't segfault a = longclone(-1) vereq(a.__dict__, {}) vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit class precfloat(float): __slots__ = ['prec'] def __init__(self, value=0.0, prec=12): self.prec = int(prec) float.__init__(value) def __repr__(self): return "%.*g" % (self.prec, self) vereq(repr(precfloat(1.1)), "1.1") a = precfloat(12345) vereq(a, 12345.0) vereq(float(a), 12345.0) verify(float(a).__class__ is float) vereq(hash(a), hash(12345.0)) verify((+a).__class__ is float) class madcomplex(complex): def __repr__(self): return "%.17gj%+.17g" % (self.imag, self.real) a = madcomplex(-3, 4) vereq(repr(a), "4j-3") base = complex(-3, 4) veris(base.__class__, complex) vereq(a, base) vereq(complex(a), base) veris(complex(a).__class__, complex) a = madcomplex(a) # just trying another form of the constructor vereq(repr(a), "4j-3") vereq(a, base) vereq(complex(a), base) veris(complex(a).__class__, complex) vereq(hash(a), hash(base)) veris((+a).__class__, complex) veris((a + 0).__class__, complex) vereq(a + 0, base) veris((a - 0).__class__, complex) vereq(a - 0, base) veris((a * 1).__class__, complex) vereq(a * 1, base) veris((a / 1).__class__, complex) vereq(a / 1, base) class madtuple(tuple): _rev = None def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(L) return self._rev a = madtuple((1,2,3,4,5,6,7,8,9,0)) vereq(a, (1,2,3,4,5,6,7,8,9,0)) vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) for i in range(512): t = madtuple(range(i)) u = t.rev() v = u.rev() vereq(v, t) a = madtuple((1,2,3,4,5)) vereq(tuple(a), (1,2,3,4,5)) verify(tuple(a).__class__ is tuple) vereq(hash(a), hash((1,2,3,4,5))) verify(a[:].__class__ is tuple) verify((a * 1).__class__ is tuple) verify((a * 0).__class__ is tuple) verify((a + ()).__class__ is tuple) a = madtuple(()) vereq(tuple(a), ()) verify(tuple(a).__class__ is tuple) verify((a + a).__class__ is tuple) verify((a * 0).__class__ is tuple) verify((a * 1).__class__ is tuple) verify((a * 2).__class__ is tuple) verify(a[:].__class__ is tuple) class madstring(str): _rev = None def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev s = madstring("abcdefghijklmnopqrstuvwxyz") vereq(s, "abcdefghijklmnopqrstuvwxyz") vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) for i in range(256): s = madstring("".join(map(chr, range(i)))) t = s.rev() u = t.rev() vereq(u, s) s = madstring("12345") vereq(str(s), "12345") verify(str(s).__class__ is str) base = "\x00" * 5 s = madstring(base) vereq(s, base) vereq(str(s), base) verify(str(s).__class__ is str) vereq(hash(s), hash(base)) vereq({s: 1}[base], 1) vereq({base: 1}[s], 1) verify((s + "").__class__ is str) vereq(s + "", base) verify(("" + s).__class__ is str) vereq("" + s, base) verify((s * 0).__class__ is str) vereq(s * 0, "") verify((s * 1).__class__ is str) vereq(s * 1, base) verify((s * 2).__class__ is str) vereq(s * 2, base + base) verify(s[:].__class__ is str) vereq(s[:], base) verify(s[0:0].__class__ is str) vereq(s[0:0], "") verify(s.strip().__class__ is str) vereq(s.strip(), base) verify(s.lstrip().__class__ is str) vereq(s.lstrip(), base) verify(s.rstrip().__class__ is str) vereq(s.rstrip(), base) identitytab = ''.join([chr(i) for i in range(256)]) verify(s.translate(identitytab).__class__ is str) vereq(s.translate(identitytab), base) verify(s.translate(identitytab, "x").__class__ is str) vereq(s.translate(identitytab, "x"), base) vereq(s.translate(identitytab, "\x00"), "") verify(s.replace("x", "x").__class__ is str) vereq(s.replace("x", "x"), base) verify(s.ljust(len(s)).__class__ is str) vereq(s.ljust(len(s)), base) verify(s.rjust(len(s)).__class__ is str) vereq(s.rjust(len(s)), base) verify(s.center(len(s)).__class__ is str) vereq(s.center(len(s)), base) verify(s.lower().__class__ is str) vereq(s.lower(), base) s = madstring("x y") vereq(s, "x y") verify(intern(s).__class__ is str) verify(intern(s) is intern("x y")) vereq(intern(s), "x y") i = intern("y x") s = madstring("y x") vereq(s, i) verify(intern(s).__class__ is str) verify(intern(s) is i) s = madstring(i) verify(intern(s).__class__ is str) verify(intern(s) is i) class madunicode(unicode): _rev = None def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(u"".join(L)) return self._rev u = madunicode("ABCDEF") vereq(u, u"ABCDEF") vereq(u.rev(), madunicode(u"FEDCBA")) vereq(u.rev().rev(), madunicode(u"ABCDEF")) base = u"12345" u = madunicode(base) vereq(unicode(u), base) verify(unicode(u).__class__ is unicode) vereq(hash(u), hash(base)) vereq({u: 1}[base], 1) vereq({base: 1}[u], 1) verify(u.strip().__class__ is unicode) vereq(u.strip(), base) verify(u.lstrip().__class__ is unicode) vereq(u.lstrip(), base) verify(u.rstrip().__class__ is unicode) vereq(u.rstrip(), base) verify(u.replace(u"x", u"x").__class__ is unicode) vereq(u.replace(u"x", u"x"), base) verify(u.replace(u"xy", u"xy").__class__ is unicode) vereq(u.replace(u"xy", u"xy"), base) verify(u.center(len(u)).__class__ is unicode) vereq(u.center(len(u)), base) verify(u.ljust(len(u)).__class__ is unicode) vereq(u.ljust(len(u)), base) verify(u.rjust(len(u)).__class__ is unicode) vereq(u.rjust(len(u)), base) verify(u.lower().__class__ is unicode) vereq(u.lower(), base) verify(u.upper().__class__ is unicode) vereq(u.upper(), base) verify(u.capitalize().__class__ is unicode) vereq(u.capitalize(), base) verify(u.title().__class__ is unicode) vereq(u.title(), base) verify((u + u"").__class__ is unicode) vereq(u + u"", base) verify((u"" + u).__class__ is unicode) vereq(u"" + u, base) verify((u * 0).__class__ is unicode) vereq(u * 0, u"") verify((u * 1).__class__ is unicode) vereq(u * 1, base) verify((u * 2).__class__ is unicode) vereq(u * 2, base + base) verify(u[:].__class__ is unicode) vereq(u[:], base) verify(u[0:0].__class__ is unicode) vereq(u[0:0], u"") class sublist(list): pass a = sublist(range(5)) vereq(a, range(5)) a.append("hello") vereq(a, range(5) + ["hello"]) a[5] = 5 vereq(a, range(6)) a.extend(range(6, 20)) vereq(a, range(20)) a[-5:] = [] vereq(a, range(15)) del a[10:15] vereq(len(a), 10) vereq(a, range(10)) vereq(list(a), range(10)) vereq(a[0], 0) vereq(a[9], 9) vereq(a[-10], 0) vereq(a[-1], 9) vereq(a[:5], range(5)) class CountedInput(file): """Counts lines read by self.readline(). self.lineno is the 0-based ordinal of the last line read, up to a maximum of one greater than the number of lines in the file. self.ateof is true if and only if the final "" line has been read, at which point self.lineno stops incrementing, and further calls to readline() continue to return "". """ lineno = 0 ateof = 0 def readline(self): if self.ateof: return "" s = file.readline(self) # Next line works too. # s = super(CountedInput, self).readline() self.lineno += 1 if s == "": self.ateof = 1 return s f = file(name=TESTFN, mode='w') lines = ['a\n', 'b\n', 'c\n'] try: f.writelines(lines) f.close() f = CountedInput(TESTFN) for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): got = f.readline() vereq(expected, got) vereq(f.lineno, i) vereq(f.ateof, (i > len(lines))) f.close() finally: try: f.close() except: pass try: import os os.unlink(TESTFN) except: passdef keywords(): if verbose: print "Testing keyword args to basic type constructors ..." vereq(int(x=1), 1) vereq(float(x=2), 2.0) vereq(long(x=3), 3L) vereq(complex(imag=42, real=666), complex(666, 42)) vereq(str(object=500), '500') vereq(unicode(string='abc', errors='strict'), u'abc') vereq(tuple(sequence=range(3)), (0, 1, 2)) vereq(list(sequence=(0, 1, 2)), range(3)) vereq(dict(items={1: 2}), {1: 2}) for constructor in (int, float, long, complex, str, unicode, tuple, list, dict, file): try: constructor(bogus_keyword_arg=1) except TypeError: pass else: raise TestFailed("expected TypeError from bogus keyword " "argument to %r" % constructor)def restricted(): # XXX This test is disabled because rexec is not deemed safe return import rexec if verbose: print "Testing interaction with restricted execution ..." sandbox = rexec.RExec() code1 = """f = open(%r, 'w')""" % TESTFN code2 = """f = file(%r, 'w')""" % TESTFN code3 = """\f = open(%r)t = type(f) # a sneaky way to get the file() constructorf.close()f = t(%r, 'w') # rexec can't catch this by itself""" % (TESTFN, TESTFN) f = open(TESTFN, 'w') # Create the file so code3 can find it. f.close() try: for code in code1, code2, code3: try: sandbox.r_exec(code) except IOError, msg: if str(msg).find("restricted") >= 0: outcome = "OK" else: outcome = "got an exception, but not an expected one" else: outcome = "expected a restricted-execution exception" if outcome != "OK": raise TestFailed("%s, in %r" % (outcome, code)) finally: try: import os os.unlink(TESTFN) except: passdef str_subclass_as_dict_key(): if verbose: print "Testing a str subclass used as dict key .." class cistr(str): """Sublcass of str that computes __eq__ case-insensitively. Also computes a hash code of the string in canonical form. """ def __init__(self, value): self.canonical = value.lower() self.hashcode = hash(self.canonical) def __eq__(self, other): if not isinstance(other, cistr): other = cistr(other) return self.canonical == other.canonical def __hash__(self): return self.hashcode vereq(cistr('ABC'), 'abc') vereq('aBc', cistr('ABC')) vereq(str(cistr('ABC')), 'ABC') d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} vereq(d[cistr('one')], 1) vereq(d[cistr('tWo')], 2) vereq(d[cistr('THrEE')], 3) verify(cistr('ONe') in d) vereq(d.get(cistr('thrEE')), 3)def classic_comparisons(): if verbose: print "Testing classic comparisons..." class classic: pass for base in (classic, int, object): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): if isinstance(other, C): return cmp(self.value, other.value) if isinstance(other, int) or isinstance(other, long): return cmp(self.value, other) return NotImplemented c1 = C(1) c2 = C(2) c3 = C(3) vereq(c1, 1) c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): pass z = Z(1) vereq(z, 1+0j) vereq(1+0j, z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) vereq(zz, 1+0j) vereq(1+0j, zz) class classic: pass for base in (classic, int, object, list): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): raise TestFailed, "shouldn't call __cmp__" def __eq__(self, other): if isinstance(other, C)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?