python-2.5.2/win32/Lib/test/test_repr.py
changeset 0 ae805ac0140d
equal deleted inserted replaced
-1:000000000000 0:ae805ac0140d
       
     1 """
       
     2   Test cases for the repr module
       
     3   Nick Mathewson
       
     4 """
       
     5 
       
     6 import sys
       
     7 import os
       
     8 import shutil
       
     9 import unittest
       
    10 
       
    11 from test.test_support import run_unittest
       
    12 from repr import repr as r # Don't shadow builtin repr
       
    13 from repr import Repr
       
    14 
       
    15 
       
    16 def nestedTuple(nesting):
       
    17     t = ()
       
    18     for i in range(nesting):
       
    19         t = (t,)
       
    20     return t
       
    21 
       
    22 class ReprTests(unittest.TestCase):
       
    23 
       
    24     def test_string(self):
       
    25         eq = self.assertEquals
       
    26         eq(r("abc"), "'abc'")
       
    27         eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
       
    28 
       
    29         s = "a"*30+"b"*30
       
    30         expected = repr(s)[:13] + "..." + repr(s)[-14:]
       
    31         eq(r(s), expected)
       
    32 
       
    33         eq(r("\"'"), repr("\"'"))
       
    34         s = "\""*30+"'"*100
       
    35         expected = repr(s)[:13] + "..." + repr(s)[-14:]
       
    36         eq(r(s), expected)
       
    37 
       
    38     def test_tuple(self):
       
    39         eq = self.assertEquals
       
    40         eq(r((1,)), "(1,)")
       
    41 
       
    42         t3 = (1, 2, 3)
       
    43         eq(r(t3), "(1, 2, 3)")
       
    44 
       
    45         r2 = Repr()
       
    46         r2.maxtuple = 2
       
    47         expected = repr(t3)[:-2] + "...)"
       
    48         eq(r2.repr(t3), expected)
       
    49 
       
    50     def test_container(self):
       
    51         from array import array
       
    52         from collections import deque
       
    53 
       
    54         eq = self.assertEquals
       
    55         # Tuples give up after 6 elements
       
    56         eq(r(()), "()")
       
    57         eq(r((1,)), "(1,)")
       
    58         eq(r((1, 2, 3)), "(1, 2, 3)")
       
    59         eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
       
    60         eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
       
    61 
       
    62         # Lists give up after 6 as well
       
    63         eq(r([]), "[]")
       
    64         eq(r([1]), "[1]")
       
    65         eq(r([1, 2, 3]), "[1, 2, 3]")
       
    66         eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
       
    67         eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
       
    68 
       
    69         # Sets give up after 6 as well
       
    70         eq(r(set([])), "set([])")
       
    71         eq(r(set([1])), "set([1])")
       
    72         eq(r(set([1, 2, 3])), "set([1, 2, 3])")
       
    73         eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])")
       
    74         eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])")
       
    75 
       
    76         # Frozensets give up after 6 as well
       
    77         eq(r(frozenset([])), "frozenset([])")
       
    78         eq(r(frozenset([1])), "frozenset([1])")
       
    79         eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])")
       
    80         eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])")
       
    81         eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])")
       
    82 
       
    83         # collections.deque after 6
       
    84         eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
       
    85 
       
    86         # Dictionaries give up after 4.
       
    87         eq(r({}), "{}")
       
    88         d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
       
    89         eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
       
    90         d['arthur'] = 1
       
    91         eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
       
    92 
       
    93         # array.array after 5.
       
    94         eq(r(array('i')), "array('i', [])")
       
    95         eq(r(array('i', [1])), "array('i', [1])")
       
    96         eq(r(array('i', [1, 2])), "array('i', [1, 2])")
       
    97         eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
       
    98         eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
       
    99         eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
       
   100         eq(r(array('i', [1, 2, 3, 4, 5, 6])),
       
   101                    "array('i', [1, 2, 3, 4, 5, ...])")
       
   102 
       
   103     def test_numbers(self):
       
   104         eq = self.assertEquals
       
   105         eq(r(123), repr(123))
       
   106         eq(r(123L), repr(123L))
       
   107         eq(r(1.0/3), repr(1.0/3))
       
   108 
       
   109         n = 10L**100
       
   110         expected = repr(n)[:18] + "..." + repr(n)[-19:]
       
   111         eq(r(n), expected)
       
   112 
       
   113     def test_instance(self):
       
   114         eq = self.assertEquals
       
   115         i1 = ClassWithRepr("a")
       
   116         eq(r(i1), repr(i1))
       
   117 
       
   118         i2 = ClassWithRepr("x"*1000)
       
   119         expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
       
   120         eq(r(i2), expected)
       
   121 
       
   122         i3 = ClassWithFailingRepr()
       
   123         eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
       
   124 
       
   125         s = r(ClassWithFailingRepr)
       
   126         self.failUnless(s.startswith("<class "))
       
   127         self.failUnless(s.endswith(">"))
       
   128         self.failUnless(s.find("...") == 8)
       
   129 
       
   130     def test_file(self):
       
   131         fp = open(unittest.__file__)
       
   132         self.failUnless(repr(fp).startswith(
       
   133             "<open file '%s', mode 'r' at 0x" % unittest.__file__))
       
   134         fp.close()
       
   135         self.failUnless(repr(fp).startswith(
       
   136             "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
       
   137 
       
   138     def test_lambda(self):
       
   139         self.failUnless(repr(lambda x: x).startswith(
       
   140             "<function <lambda"))
       
   141         # XXX anonymous functions?  see func_repr
       
   142 
       
   143     def test_builtin_function(self):
       
   144         eq = self.assertEquals
       
   145         # Functions
       
   146         eq(repr(hash), '<built-in function hash>')
       
   147         # Methods
       
   148         self.failUnless(repr(''.split).startswith(
       
   149             '<built-in method split of str object at 0x'))
       
   150 
       
   151     def test_xrange(self):
       
   152         import warnings
       
   153         eq = self.assertEquals
       
   154         eq(repr(xrange(1)), 'xrange(1)')
       
   155         eq(repr(xrange(1, 2)), 'xrange(1, 2)')
       
   156         eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
       
   157 
       
   158     def test_nesting(self):
       
   159         eq = self.assertEquals
       
   160         # everything is meant to give up after 6 levels.
       
   161         eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
       
   162         eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
       
   163 
       
   164         eq(r(nestedTuple(6)), "(((((((),),),),),),)")
       
   165         eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
       
   166 
       
   167         eq(r({ nestedTuple(5) : nestedTuple(5) }),
       
   168            "{((((((),),),),),): ((((((),),),),),)}")
       
   169         eq(r({ nestedTuple(6) : nestedTuple(6) }),
       
   170            "{((((((...),),),),),): ((((((...),),),),),)}")
       
   171 
       
   172         eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
       
   173         eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
       
   174 
       
   175     def test_buffer(self):
       
   176         # XXX doesn't test buffers with no b_base or read-write buffers (see
       
   177         # bufferobject.c).  The test is fairly incomplete too.  Sigh.
       
   178         x = buffer('foo')
       
   179         self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
       
   180 
       
   181     def test_cell(self):
       
   182         # XXX Hmm? How to get at a cell object?
       
   183         pass
       
   184 
       
   185     def test_descriptors(self):
       
   186         eq = self.assertEquals
       
   187         # method descriptors
       
   188         eq(repr(dict.items), "<method 'items' of 'dict' objects>")
       
   189         # XXX member descriptors
       
   190         # XXX attribute descriptors
       
   191         # XXX slot descriptors
       
   192         # static and class methods
       
   193         class C:
       
   194             def foo(cls): pass
       
   195         x = staticmethod(C.foo)
       
   196         self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
       
   197         x = classmethod(C.foo)
       
   198         self.failUnless(repr(x).startswith('<classmethod object at 0x'))
       
   199 
       
   200     def test_unsortable(self):
       
   201         # Repr.repr() used to call sorted() on sets, frozensets and dicts
       
   202         # without taking into account that not all objects are comparable
       
   203         x = set([1j, 2j, 3j])
       
   204         y = frozenset(x)
       
   205         z = {1j: 1, 2j: 2}
       
   206         r(x)
       
   207         r(y)
       
   208         r(z)
       
   209 
       
   210 def touch(path, text=''):
       
   211     fp = open(path, 'w')
       
   212     fp.write(text)
       
   213     fp.close()
       
   214 
       
   215 def zap(actions, dirname, names):
       
   216     for name in names:
       
   217         actions.append(os.path.join(dirname, name))
       
   218 
       
   219 class LongReprTest(unittest.TestCase):
       
   220     def setUp(self):
       
   221         longname = 'areallylongpackageandmodulenametotestreprtruncation'
       
   222         self.pkgname = os.path.join(longname)
       
   223         self.subpkgname = os.path.join(longname, longname)
       
   224         # Make the package and subpackage
       
   225         shutil.rmtree(self.pkgname, ignore_errors=True)
       
   226         os.mkdir(self.pkgname)
       
   227         touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
       
   228         shutil.rmtree(self.subpkgname, ignore_errors=True)
       
   229         os.mkdir(self.subpkgname)
       
   230         touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
       
   231         # Remember where we are
       
   232         self.here = os.getcwd()
       
   233         sys.path.insert(0, self.here)
       
   234 
       
   235     def tearDown(self):
       
   236         actions = []
       
   237         os.path.walk(self.pkgname, zap, actions)
       
   238         actions.append(self.pkgname)
       
   239         actions.sort()
       
   240         actions.reverse()
       
   241         for p in actions:
       
   242             if os.path.isdir(p):
       
   243                 os.rmdir(p)
       
   244             else:
       
   245                 os.remove(p)
       
   246         del sys.path[0]
       
   247 
       
   248     def test_module(self):
       
   249         eq = self.assertEquals
       
   250         touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
       
   251         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
       
   252         eq(repr(areallylongpackageandmodulenametotestreprtruncation),
       
   253            "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
       
   254         eq(repr(sys), "<module 'sys' (built-in)>")
       
   255 
       
   256     def test_type(self):
       
   257         eq = self.assertEquals
       
   258         touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
       
   259 class foo(object):
       
   260     pass
       
   261 ''')
       
   262         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
       
   263         eq(repr(foo.foo),
       
   264                "<class '%s.foo'>" % foo.__name__)
       
   265 
       
   266     def test_object(self):
       
   267         # XXX Test the repr of a type with a really long tp_name but with no
       
   268         # tp_repr.  WIBNI we had ::Inline? :)
       
   269         pass
       
   270 
       
   271     def test_class(self):
       
   272         touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
       
   273 class bar:
       
   274     pass
       
   275 ''')
       
   276         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
       
   277         # Module name may be prefixed with "test.", depending on how run.
       
   278         self.failUnless(repr(bar.bar).startswith(
       
   279             "<class %s.bar at 0x" % bar.__name__))
       
   280 
       
   281     def test_instance(self):
       
   282         touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
       
   283 class baz:
       
   284     pass
       
   285 ''')
       
   286         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
       
   287         ibaz = baz.baz()
       
   288         self.failUnless(repr(ibaz).startswith(
       
   289             "<%s.baz instance at 0x" % baz.__name__))
       
   290 
       
   291     def test_method(self):
       
   292         eq = self.assertEquals
       
   293         touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
       
   294 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
       
   295     def amethod(self): pass
       
   296 ''')
       
   297         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
       
   298         # Unbound methods first
       
   299         eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
       
   300         '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
       
   301         # Bound method next
       
   302         iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
       
   303         self.failUnless(repr(iqux.amethod).startswith(
       
   304             '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
       
   305             % (qux.__name__,) ))
       
   306 
       
   307     def test_builtin_function(self):
       
   308         # XXX test built-in functions and methods with really long names
       
   309         pass
       
   310 
       
   311 class ClassWithRepr:
       
   312     def __init__(self, s):
       
   313         self.s = s
       
   314     def __repr__(self):
       
   315         return "ClassWithLongRepr(%r)" % self.s
       
   316 
       
   317 
       
   318 class ClassWithFailingRepr:
       
   319     def __repr__(self):
       
   320         raise Exception("This should be caught by Repr.repr_instance")
       
   321 
       
   322 
       
   323 def test_main():
       
   324     run_unittest(ReprTests)
       
   325     if os.name != 'mac':
       
   326         run_unittest(LongReprTest)
       
   327 
       
   328 
       
   329 if __name__ == "__main__":
       
   330     test_main()