test_repr.py 12 KB

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