blob: 90347113cc9f8c736ede07b07cdfe5751cc24603 [file] [log] [blame]
Fred Drake8e6669a2001-07-19 22:27:56 +00001"""
2 Test cases for the repr module
3 Nick Mathewson
4"""
5
6import unittest
7from test_support import run_unittest
8from repr import repr as r # Don't shadow builtin repr
9
10
11def nestedTuple(nesting):
12 t = ()
13 for i in range(nesting):
14 t = (t,)
15 return t
16
17class ReprTests(unittest.TestCase):
18
19 def test_string(self):
20 eq = self.assertEquals
21 eq(r("abc"), "'abc'")
22 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
23
24 s = "a"*30+"b"*30
25 expected = `s`[:13] + "..." + `s`[-14:]
26 eq(r(s), expected)
27
28 eq(r("\"'"), repr("\"'"))
29 s = "\""*30+"'"*100
30 expected = `s`[:13] + "..." + `s`[-14:]
31 eq(r(s), expected)
32
33 def test_container(self):
34 eq = self.assertEquals
35 # Tuples give up after 6 elements
36 eq(r(()), "()")
37 eq(r((1,)), "(1,)")
38 eq(r((1, 2, 3)), "(1, 2, 3)")
39 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
40 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
41
42 # Lists give up after 6 as well
43 eq(r([]), "[]")
44 eq(r([1]), "[1]")
45 eq(r([1, 2, 3]), "[1, 2, 3]")
46 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
47 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
48
49 # Dictionaries give up after 4.
50 eq(r({}), "{}")
51 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
52 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
53 d['arthur'] = 1
54 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
55
56 def test_numbers(self):
57 eq = self.assertEquals
58 eq(r(123), repr(123))
59 eq(r(123L), repr(123L))
60 eq(r(1.0/3), repr(1.0/3))
61
62 n = 10L**100
63 expected = `n`[:18] + "..." + `n`[-19:]
64 eq(r(n), expected)
65
66 def test_instance(self):
67 eq = self.assertEquals
68 i1 = ClassWithRepr("a")
69 eq(r(i1), repr(i1))
70
71 i2 = ClassWithRepr("x"*1000)
72 expected = `i2`[:13] + "..." + `i2`[-14:]
73 eq(r(i2), expected)
74
75 i3 = ClassWithFailingRepr()
76 eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
77
78 def test_nesting(self):
79 eq = self.assertEquals
80 # everything is meant to give up after 6 levels.
81 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
82 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
83
84 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
85 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
86
87 eq(r({ nestedTuple(5) : nestedTuple(5) }),
88 "{((((((),),),),),): ((((((),),),),),)}")
89 eq(r({ nestedTuple(6) : nestedTuple(6) }),
90 "{((((((...),),),),),): ((((((...),),),),),)}")
91
92 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
93 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
94
95
96class ClassWithRepr:
97 def __init__(self, s):
98 self.s = s
99 def __repr__(self):
100 return "ClassWithLongRepr(%r)" % self.s
101
102
103class ClassWithFailingRepr:
104 def __repr__(self):
105 raise Exception("This should be caught by Repr.repr_instance")
106
107
108run_unittest(ReprTests)