test_descr.py

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

PY
2,316
字号
# Test enhancements related to descriptors and new-style classesfrom test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdoutfrom copy import deepcopyimport warningswarnings.filterwarnings("ignore",         r'complex divmod\(\), // and % are deprecated$',         DeprecationWarning, r'(<string>|test_descr)$')def veris(a, b):    if a is not b:        raise TestFailed, "%r is %r" % (a, b)def testunop(a, res, expr="len(a)", meth="__len__"):    if verbose: print "checking", expr    dict = {'a': a}    vereq(eval(expr, dict), res)    t = type(a)    m = getattr(t, meth)    while meth not in t.__dict__:        t = t.__bases__[0]    vereq(m, t.__dict__[meth])    vereq(m(a), res)    bm = getattr(a, meth)    vereq(bm(), res)def testbinop(a, b, res, expr="a+b", meth="__add__"):    if verbose: print "checking", expr    dict = {'a': a, 'b': b}    # XXX Hack so this passes before 2.3 when -Qnew is specified.    if meth == "__div__" and 1/2 == 0.5:        meth = "__truediv__"    vereq(eval(expr, dict), res)    t = type(a)    m = getattr(t, meth)    while meth not in t.__dict__:        t = t.__bases__[0]    vereq(m, t.__dict__[meth])    vereq(m(a, b), res)    bm = getattr(a, meth)    vereq(bm(b), res)def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):    if verbose: print "checking", expr    dict = {'a': a, 'b': b, 'c': c}    vereq(eval(expr, dict), res)    t = type(a)    m = getattr(t, meth)    while meth not in t.__dict__:        t = t.__bases__[0]    vereq(m, t.__dict__[meth])    vereq(m(a, b, c), res)    bm = getattr(a, meth)    vereq(bm(b, c), res)def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):    if verbose: print "checking", stmt    dict = {'a': deepcopy(a), 'b': b}    exec stmt in dict    vereq(dict['a'], res)    t = type(a)    m = getattr(t, meth)    while meth not in t.__dict__:        t = t.__bases__[0]    vereq(m, t.__dict__[meth])    dict['a'] = deepcopy(a)    m(dict['a'], b)    vereq(dict['a'], res)    dict['a'] = deepcopy(a)    bm = getattr(dict['a'], meth)    bm(b)    vereq(dict['a'], res)def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):    if verbose: print "checking", stmt    dict = {'a': deepcopy(a), 'b': b, 'c': c}    exec stmt in dict    vereq(dict['a'], res)    t = type(a)    m = getattr(t, meth)    while meth not in t.__dict__:        t = t.__bases__[0]    vereq(m, t.__dict__[meth])    dict['a'] = deepcopy(a)    m(dict['a'], b, c)    vereq(dict['a'], res)    dict['a'] = deepcopy(a)    bm = getattr(dict['a'], meth)    bm(b, c)    vereq(dict['a'], res)def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):    if verbose: print "checking", stmt    dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}    exec stmt in dict    vereq(dict['a'], res)    t = type(a)    while meth not in t.__dict__:        t = t.__bases__[0]    m = getattr(t, meth)    vereq(m, t.__dict__[meth])    dict['a'] = deepcopy(a)    m(dict['a'], b, c, d)    vereq(dict['a'], res)    dict['a'] = deepcopy(a)    bm = getattr(dict['a'], meth)    bm(b, c, d)    vereq(dict['a'], res)def class_docstrings():    class Classic:        "A classic docstring."    vereq(Classic.__doc__, "A classic docstring.")    vereq(Classic.__dict__['__doc__'], "A classic docstring.")    class Classic2:        pass    verify(Classic2.__doc__ is None)    class NewStatic(object):        "Another docstring."    vereq(NewStatic.__doc__, "Another docstring.")    vereq(NewStatic.__dict__['__doc__'], "Another docstring.")    class NewStatic2(object):        pass    verify(NewStatic2.__doc__ is None)    class NewDynamic(object):        "Another docstring."    vereq(NewDynamic.__doc__, "Another docstring.")    vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")    class NewDynamic2(object):        pass    verify(NewDynamic2.__doc__ is None)def lists():    if verbose: print "Testing list operations..."    testbinop([1], [2], [1,2], "a+b", "__add__")    testbinop([1,2,3], 2, 1, "b in a", "__contains__")    testbinop([1,2,3], 4, 0, "b in a", "__contains__")    testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")    testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")    testsetop([1], [2], [1,2], "a+=b", "__iadd__")    testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")    testunop([1,2,3], 3, "len(a)", "__len__")    testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")    testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")    testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")    testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")def dicts():    if verbose: print "Testing dict operations..."    testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")    testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")    testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")    testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")    d = {1:2,3:4}    l1 = []    for i in d.keys(): l1.append(i)    l = []    for i in iter(d): l.append(i)    vereq(l, l1)    l = []    for i in d.__iter__(): l.append(i)    vereq(l, l1)    l = []    for i in dict.__iter__(d): l.append(i)    vereq(l, l1)    d = {1:2, 3:4}    testunop(d, 2, "len(a)", "__len__")    vereq(eval(repr(d), {}), d)    vereq(eval(d.__repr__(), {}), d)    testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")def dict_constructor():    if verbose:        print "Testing dict constructor ..."    d = dict()    vereq(d, {})    d = dict({})    vereq(d, {})    d = dict(items={})    vereq(d, {})    d = dict({1: 2, 'a': 'b'})    vereq(d, {1: 2, 'a': 'b'})    vereq(d, dict(d.items()))    vereq(d, dict(items=d.iteritems()))    for badarg in 0, 0L, 0j, "0", [0], (0,):        try:            dict(badarg)        except TypeError:            pass        except ValueError:            if badarg == "0":                # It's a sequence, and its elements are also sequences (gotta                # love strings <wink>), but they aren't of length 2, so this                # one seemed better as a ValueError than a TypeError.                pass            else:                raise TestFailed("no TypeError from dict(%r)" % badarg)        else:            raise TestFailed("no TypeError from dict(%r)" % badarg)    try:        dict(senseless={})    except TypeError:        pass    else:        raise TestFailed("no TypeError from dict(senseless={})")    try:        dict({}, {})    except TypeError:        pass    else:        raise TestFailed("no TypeError from dict({}, {})")    class Mapping:        # Lacks a .keys() method; will be added later.        dict = {1:2, 3:4, 'a':1j}    try:        dict(Mapping())    except TypeError:        pass    else:        raise TestFailed("no TypeError from dict(incomplete mapping)")    Mapping.keys = lambda self: self.dict.keys()    Mapping.__getitem__ = lambda self, i: self.dict[i]    d = dict(items=Mapping())    vereq(d, Mapping.dict)    # Init from sequence of iterable objects, each producing a 2-sequence.    class AddressBookEntry:        def __init__(self, first, last):            self.first = first            self.last = last        def __iter__(self):            return iter([self.first, self.last])    d = dict([AddressBookEntry('Tim', 'Warsaw'),              AddressBookEntry('Barry', 'Peters'),              AddressBookEntry('Tim', 'Peters'),              AddressBookEntry('Barry', 'Warsaw')])    vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})    d = dict(zip(range(4), range(1, 5)))    vereq(d, dict([(i, i+1) for i in range(4)]))    # Bad sequence lengths.    for bad in [('tooshort',)], [('too', 'long', 'by 1')]:        try:            dict(bad)        except ValueError:            pass        else:            raise TestFailed("no ValueError from dict(%r)" % bad)def test_dir():    if verbose:        print "Testing dir() ..."    junk = 12    vereq(dir(), ['junk'])    del junk    # Just make sure these don't blow up!    for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:        dir(arg)    # Try classic classes.    class C:        Cdata = 1        def Cmethod(self): pass    cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']    vereq(dir(C), cstuff)    verify('im_self' in dir(C.Cmethod))    c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.    vereq(dir(c), cstuff)    c.cdata = 2    c.cmethod = lambda self: 0    vereq(dir(c), cstuff + ['cdata', 'cmethod'])    verify('im_self' in dir(c.Cmethod))    class A(C):        Adata = 1        def Amethod(self): pass    astuff = ['Adata', 'Amethod'] + cstuff    vereq(dir(A), astuff)    verify('im_self' in dir(A.Amethod))    a = A()    vereq(dir(a), astuff)    verify('im_self' in dir(a.Amethod))    a.adata = 42    a.amethod = lambda self: 3    vereq(dir(a), astuff + ['adata', 'amethod'])    # The same, but with new-style classes.  Since these have object as a    # base class, a lot more gets sucked in.    def interesting(strings):        return [s for s in strings if not s.startswith('_')]    class C(object):        Cdata = 1        def Cmethod(self): pass    cstuff = ['Cdata', 'Cmethod']    vereq(interesting(dir(C)), cstuff)    c = C()    vereq(interesting(dir(c)), cstuff)    verify('im_self' in dir(C.Cmethod))    c.cdata = 2    c.cmethod = lambda self: 0    vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])    verify('im_self' in dir(c.Cmethod))    class A(C):        Adata = 1        def Amethod(self): pass    astuff = ['Adata', 'Amethod'] + cstuff    vereq(interesting(dir(A)), astuff)    verify('im_self' in dir(A.Amethod))    a = A()    vereq(interesting(dir(a)), astuff)    a.adata = 42    a.amethod = lambda self: 3    vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])    verify('im_self' in dir(a.Amethod))    # Try a module subclass.    import sys    class M(type(sys)):        pass    minstance = M()    minstance.b = 2    minstance.a = 1    vereq(dir(minstance), ['a', 'b'])    class M2(M):        def getdict(self):            return "Not a dict!"        __dict__ = property(getdict)    m2instance = M2()    m2instance.b = 2    m2instance.a = 1    vereq(m2instance.__dict__, "Not a dict!")    try:        dir(m2instance)    except TypeError:        pass    # Two essentially featureless objects, just inheriting stuff from    # object.    vereq(dir(None), dir(Ellipsis))    # Nasty test case for proxied objects    class Wrapper(object):        def __init__(self, obj):            self.__obj = obj        def __repr__(self):            return "Wrapper(%s)" % repr(self.__obj)        def __getitem__(self, key):            return Wrapper(self.__obj[key])        def __len__(self):            return len(self.__obj)        def __getattr__(self, name):            return Wrapper(getattr(self.__obj, name))    class C(object):        def __getclass(self):            return Wrapper(type(self))        __class__ = property(__getclass)    dir(C()) # This used to segfaultbinops = {    'add': '+',    'sub': '-',    'mul': '*',    'div': '/',    'mod': '%',    'divmod': 'divmod',    'pow': '**',    'lshift': '<<',    'rshift': '>>',    'and': '&',    'xor': '^',    'or': '|',    'cmp': 'cmp',    'lt': '<',    'le': '<=',    'eq': '==',    'ne': '!=',    'gt': '>',    'ge': '>=',    }for name, expr in binops.items():    if expr.islower():        expr = expr + "(a, b)"    else:        expr = 'a %s b' % expr    binops[name] = exprunops = {    'pos': '+',    'neg': '-',    'abs': 'abs',    'invert': '~',    'int': 'int',    'long': 'long',    'float': 'float',    'oct': 'oct',    'hex': 'hex',    }for name, expr in unops.items():    if expr.islower():        expr = expr + "(a)"    else:        expr = '%s a' % expr    unops[name] = exprdef numops(a, b, skip=[]):    dict = {'a': a, 'b': b}    for name, expr in binops.items():        if name not in skip:            name = "__%s__" % name            if hasattr(a, name):                res = eval(expr, dict)                testbinop(a, b, res, expr, name)    for name, expr in unops.items():        if name not in skip:            name = "__%s__" % name            if hasattr(a, name):                res = eval(expr, dict)                testunop(a, res, expr, name)def ints():    if verbose: print "Testing int operations..."    numops(100, 3)    # The following crashes in Python 2.2    vereq((1).__nonzero__(), 1)    vereq((0).__nonzero__(), 0)    # This returns 'NotImplemented' in Python 2.2    class C(int):        def __add__(self, other):            return NotImplemented    try:        C() + ""    except TypeError:        pass

⌨️ 快捷键说明

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