test_repr.py 12 KB
Newer Older
1 2 3 4 5
"""
  Test cases for the repr module
  Nick Mathewson
"""

6 7
import sys
import os
8
import shutil
9
import unittest
10

11
from test.test_support import run_unittest
Tim Peters's avatar
Tim Peters committed
12
from repr import repr as r # Don't shadow builtin repr
13
from repr import Repr
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29


def nestedTuple(nesting):
    t = ()
    for i in range(nesting):
        t = (t,)
    return t

class ReprTests(unittest.TestCase):

    def test_string(self):
        eq = self.assertEquals
        eq(r("abc"), "'abc'")
        eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")

        s = "a"*30+"b"*30
30
        expected = repr(s)[:13] + "..." + repr(s)[-14:]
31
        eq(r(s), expected)
Tim Peters's avatar
Tim Peters committed
32

33 34
        eq(r("\"'"), repr("\"'"))
        s = "\""*30+"'"*100
35
        expected = repr(s)[:13] + "..." + repr(s)[-14:]
36 37
        eq(r(s), expected)

38 39 40 41 42 43 44 45 46 47 48 49
    def test_tuple(self):
        eq = self.assertEquals
        eq(r((1,)), "(1,)")

        t3 = (1, 2, 3)
        eq(r(t3), "(1, 2, 3)")

        r2 = Repr()
        r2.maxtuple = 2
        expected = repr(t3)[:-2] + "...)"
        eq(r2.repr(t3), expected)

50
    def test_container(self):
51
        from array import array
52
        from collections import deque
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        eq = self.assertEquals
        # Tuples give up after 6 elements
        eq(r(()), "()")
        eq(r((1,)), "(1,)")
        eq(r((1, 2, 3)), "(1, 2, 3)")
        eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
        eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")

        # Lists give up after 6 as well
        eq(r([]), "[]")
        eq(r([1]), "[1]")
        eq(r([1, 2, 3]), "[1, 2, 3]")
        eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
        eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")

69 70 71 72 73 74 75 76 77 78 79 80 81 82
        # Sets give up after 6 as well
        eq(r(set([])), "set([])")
        eq(r(set([1])), "set([1])")
        eq(r(set([1, 2, 3])), "set([1, 2, 3])")
        eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])")
        eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])")

        # Frozensets give up after 6 as well
        eq(r(frozenset([])), "frozenset([])")
        eq(r(frozenset([1])), "frozenset([1])")
        eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])")
        eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])")
        eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])")

83 84 85
        # collections.deque after 6
        eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")

86 87 88 89 90 91 92
        # Dictionaries give up after 4.
        eq(r({}), "{}")
        d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
        eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
        d['arthur'] = 1
        eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")

93 94 95 96 97 98 99 100 101 102
        # array.array after 5.
        eq(r(array('i')), "array('i', [])")
        eq(r(array('i', [1])), "array('i', [1])")
        eq(r(array('i', [1, 2])), "array('i', [1, 2])")
        eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
        eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
        eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
        eq(r(array('i', [1, 2, 3, 4, 5, 6])),
                   "array('i', [1, 2, 3, 4, 5, ...])")

103 104 105 106 107 108 109
    def test_numbers(self):
        eq = self.assertEquals
        eq(r(123), repr(123))
        eq(r(123L), repr(123L))
        eq(r(1.0/3), repr(1.0/3))

        n = 10L**100
110
        expected = repr(n)[:18] + "..." + repr(n)[-19:]
111 112 113 114 115 116
        eq(r(n), expected)

    def test_instance(self):
        eq = self.assertEquals
        i1 = ClassWithRepr("a")
        eq(r(i1), repr(i1))
Tim Peters's avatar
Tim Peters committed
117

118
        i2 = ClassWithRepr("x"*1000)
119
        expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
120 121 122 123 124
        eq(r(i2), expected)

        i3 = ClassWithFailingRepr()
        eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))

125 126 127 128 129
        s = r(ClassWithFailingRepr)
        self.failUnless(s.startswith("<class "))
        self.failUnless(s.endswith(">"))
        self.failUnless(s.find("...") == 8)

130 131 132 133 134 135 136 137 138 139
    def test_file(self):
        fp = open(unittest.__file__)
        self.failUnless(repr(fp).startswith(
            "<open file '%s', mode 'r' at 0x" % unittest.__file__))
        fp.close()
        self.failUnless(repr(fp).startswith(
            "<closed file '%s', mode 'r' at 0x" % unittest.__file__))

    def test_lambda(self):
        self.failUnless(repr(lambda x: x).startswith(
140
            "<function <lambda"))
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        # XXX anonymous functions?  see func_repr

    def test_builtin_function(self):
        eq = self.assertEquals
        # Functions
        eq(repr(hash), '<built-in function hash>')
        # Methods
        self.failUnless(repr(''.split).startswith(
            '<built-in method split of str object at 0x'))

    def test_xrange(self):
        eq = self.assertEquals
        eq(repr(xrange(1)), 'xrange(1)')
        eq(repr(xrange(1, 2)), 'xrange(1, 2)')
        eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    def test_nesting(self):
        eq = self.assertEquals
        # everything is meant to give up after 6 levels.
        eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
        eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")

        eq(r(nestedTuple(6)), "(((((((),),),),),),)")
        eq(r(nestedTuple(7)), "(((((((...),),),),),),)")

        eq(r({ nestedTuple(5) : nestedTuple(5) }),
           "{((((((),),),),),): ((((((),),),),),)}")
        eq(r({ nestedTuple(6) : nestedTuple(6) }),
           "{((((((...),),),),),): ((((((...),),),),),)}")

        eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
        eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")

174 175 176 177 178 179 180 181 182 183 184 185 186
    def test_buffer(self):
        # XXX doesn't test buffers with no b_base or read-write buffers (see
        # bufferobject.c).  The test is fairly incomplete too.  Sigh.
        x = buffer('foo')
        self.failUnless(repr(x).startswith('<read-only buffer for 0x'))

    def test_cell(self):
        # XXX Hmm? How to get at a cell object?
        pass

    def test_descriptors(self):
        eq = self.assertEquals
        # method descriptors
187
        eq(repr(dict.items), "<method 'items' of 'dict' objects>")
188 189 190 191 192 193 194 195 196 197 198
        # XXX member descriptors
        # XXX attribute descriptors
        # XXX slot descriptors
        # static and class methods
        class C:
            def foo(cls): pass
        x = staticmethod(C.foo)
        self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
        x = classmethod(C.foo)
        self.failUnless(repr(x).startswith('<classmethod object at 0x'))

199 200 201 202 203 204 205 206 207 208
    def test_unsortable(self):
        # Repr.repr() used to call sorted() on sets, frozensets and dicts
        # without taking into account that not all objects are comparable
        x = set([1j, 2j, 3j])
        y = frozenset(x)
        z = {1j: 1, 2j: 2}
        r(x)
        r(y)
        r(z)

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
def touch(path, text=''):
    fp = open(path, 'w')
    fp.write(text)
    fp.close()

def zap(actions, dirname, names):
    for name in names:
        actions.append(os.path.join(dirname, name))

class LongReprTest(unittest.TestCase):
    def setUp(self):
        longname = 'areallylongpackageandmodulenametotestreprtruncation'
        self.pkgname = os.path.join(longname)
        self.subpkgname = os.path.join(longname, longname)
        # Make the package and subpackage
224
        shutil.rmtree(self.pkgname, ignore_errors=True)
225
        os.mkdir(self.pkgname)
226
        touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
227
        shutil.rmtree(self.subpkgname, ignore_errors=True)
228
        os.mkdir(self.subpkgname)
229
        touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        # Remember where we are
        self.here = os.getcwd()
        sys.path.insert(0, self.here)

    def tearDown(self):
        actions = []
        os.path.walk(self.pkgname, zap, actions)
        actions.append(self.pkgname)
        actions.sort()
        actions.reverse()
        for p in actions:
            if os.path.isdir(p):
                os.rmdir(p)
            else:
                os.remove(p)
        del sys.path[0]

    def test_module(self):
        eq = self.assertEquals
249
        touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
250 251
        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
        eq(repr(areallylongpackageandmodulenametotestreprtruncation),
252
           "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
253
        eq(repr(sys), "<module 'sys' (built-in)>")
254 255 256

    def test_type(self):
        eq = self.assertEquals
257
        touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
258 259 260 261 262
class foo(object):
    pass
''')
        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
        eq(repr(foo.foo),
263
               "<class '%s.foo'>" % foo.__name__)
264 265 266 267 268 269 270

    def test_object(self):
        # XXX Test the repr of a type with a really long tp_name but with no
        # tp_repr.  WIBNI we had ::Inline? :)
        pass

    def test_class(self):
271
        touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
272 273 274 275
class bar:
    pass
''')
        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
276
        # Module name may be prefixed with "test.", depending on how run.
277
        self.failUnless(repr(bar.bar).startswith(
278
            "<class %s.bar at 0x" % bar.__name__))
279 280

    def test_instance(self):
281
        touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
282 283 284 285 286 287
class baz:
    pass
''')
        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
        ibaz = baz.baz()
        self.failUnless(repr(ibaz).startswith(
288
            "<%s.baz instance at 0x" % baz.__name__))
289 290 291

    def test_method(self):
        eq = self.assertEquals
292
        touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
293 294 295 296 297 298 299 300 301 302
class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
    def amethod(self): pass
''')
        from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
        # Unbound methods first
        eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
        '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
        # Bound method next
        iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
        self.failUnless(repr(iqux.amethod).startswith(
303 304
            '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
            % (qux.__name__,) ))
305 306 307 308

    def test_builtin_function(self):
        # XXX test built-in functions and methods with really long names
        pass
309 310 311 312 313 314 315 316 317 318 319 320 321

class ClassWithRepr:
    def __init__(self, s):
        self.s = s
    def __repr__(self):
        return "ClassWithLongRepr(%r)" % self.s


class ClassWithFailingRepr:
    def __repr__(self):
        raise Exception("This should be caught by Repr.repr_instance")


322 323 324 325 326 327 328 329
def test_main():
    run_unittest(ReprTests)
    if os.name != 'mac':
        run_unittest(LongReprTest)


if __name__ == "__main__":
    test_main()