PageRenderTime 128ms CodeModel.GetById 83ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_repr.py

https://bitbucket.org/glix/python
Python | 327 lines | 272 code | 32 blank | 23 comment | 3 complexity | 7572a0352d69aebaf4d2365d90ca7b4d MD5 | raw file
  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
  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.assertEquals
  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.assertEquals
  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.assertEquals
  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.assertEquals
  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.assertEquals
  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.failUnless(s.startswith("<class "))
  102. self.failUnless(s.endswith(">"))
  103. self.failUnless(s.find("...") == 8)
  104. def test_file(self):
  105. fp = open(unittest.__file__)
  106. self.failUnless(repr(fp).startswith(
  107. "<open file '%s', mode 'r' at 0x" % unittest.__file__))
  108. fp.close()
  109. self.failUnless(repr(fp).startswith(
  110. "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
  111. def test_lambda(self):
  112. self.failUnless(repr(lambda x: x).startswith(
  113. "<function <lambda"))
  114. # XXX anonymous functions? see func_repr
  115. def test_builtin_function(self):
  116. eq = self.assertEquals
  117. # Functions
  118. eq(repr(hash), '<built-in function hash>')
  119. # Methods
  120. self.failUnless(repr(''.split).startswith(
  121. '<built-in method split of str object at 0x'))
  122. def test_xrange(self):
  123. eq = self.assertEquals
  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.assertEquals
  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. x = buffer('foo')
  144. self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
  145. def test_cell(self):
  146. # XXX Hmm? How to get at a cell object?
  147. pass
  148. def test_descriptors(self):
  149. eq = self.assertEquals
  150. # method descriptors
  151. eq(repr(dict.items), "<method 'items' of 'dict' objects>")
  152. # XXX member descriptors
  153. # XXX attribute descriptors
  154. # XXX slot descriptors
  155. # static and class methods
  156. class C:
  157. def foo(cls): pass
  158. x = staticmethod(C.foo)
  159. self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
  160. x = classmethod(C.foo)
  161. self.failUnless(repr(x).startswith('<classmethod object at 0x'))
  162. def test_unsortable(self):
  163. # Repr.repr() used to call sorted() on sets, frozensets and dicts
  164. # without taking into account that not all objects are comparable
  165. x = set([1j, 2j, 3j])
  166. y = frozenset(x)
  167. z = {1j: 1, 2j: 2}
  168. r(x)
  169. r(y)
  170. r(z)
  171. def touch(path, text=''):
  172. fp = open(path, 'w')
  173. fp.write(text)
  174. fp.close()
  175. class LongReprTest(unittest.TestCase):
  176. def setUp(self):
  177. longname = 'areallylongpackageandmodulenametotestreprtruncation'
  178. self.pkgname = os.path.join(longname)
  179. self.subpkgname = os.path.join(longname, longname)
  180. # Make the package and subpackage
  181. shutil.rmtree(self.pkgname, ignore_errors=True)
  182. os.mkdir(self.pkgname)
  183. touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
  184. shutil.rmtree(self.subpkgname, ignore_errors=True)
  185. os.mkdir(self.subpkgname)
  186. touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
  187. # Remember where we are
  188. self.here = os.getcwd()
  189. sys.path.insert(0, self.here)
  190. def tearDown(self):
  191. actions = []
  192. for dirpath, dirnames, filenames in os.walk(self.pkgname):
  193. for name in dirnames + filenames:
  194. actions.append(os.path.join(dirpath, name))
  195. actions.append(self.pkgname)
  196. actions.sort()
  197. actions.reverse()
  198. for p in actions:
  199. if os.path.isdir(p):
  200. os.rmdir(p)
  201. else:
  202. os.remove(p)
  203. del sys.path[0]
  204. def test_module(self):
  205. eq = self.assertEquals
  206. touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
  207. from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
  208. eq(repr(areallylongpackageandmodulenametotestreprtruncation),
  209. "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
  210. eq(repr(sys), "<module 'sys' (built-in)>")
  211. def test_type(self):
  212. eq = self.assertEquals
  213. touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
  214. class foo(object):
  215. pass
  216. ''')
  217. from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
  218. eq(repr(foo.foo),
  219. "<class '%s.foo'>" % foo.__name__)
  220. def test_object(self):
  221. # XXX Test the repr of a type with a really long tp_name but with no
  222. # tp_repr. WIBNI we had ::Inline? :)
  223. pass
  224. def test_class(self):
  225. touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
  226. class bar:
  227. pass
  228. ''')
  229. from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
  230. # Module name may be prefixed with "test.", depending on how run.
  231. self.failUnless(repr(bar.bar).startswith(
  232. "<class %s.bar at 0x" % bar.__name__))
  233. def test_instance(self):
  234. touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
  235. class baz:
  236. pass
  237. ''')
  238. from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
  239. ibaz = baz.baz()
  240. self.failUnless(repr(ibaz).startswith(
  241. "<%s.baz instance at 0x" % baz.__name__))
  242. def test_method(self):
  243. eq = self.assertEquals
  244. touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
  245. class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
  246. def amethod(self): pass
  247. ''')
  248. from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
  249. # Unbound methods first
  250. eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
  251. '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
  252. # Bound method next
  253. iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
  254. self.failUnless(repr(iqux.amethod).startswith(
  255. '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
  256. % (qux.__name__,) ))
  257. def test_builtin_function(self):
  258. # XXX test built-in functions and methods with really long names
  259. pass
  260. class ClassWithRepr:
  261. def __init__(self, s):
  262. self.s = s
  263. def __repr__(self):
  264. return "ClassWithLongRepr(%r)" % self.s
  265. class ClassWithFailingRepr:
  266. def __repr__(self):
  267. raise Exception("This should be caught by Repr.repr_instance")
  268. def test_main():
  269. run_unittest(ReprTests)
  270. if os.name != 'mac':
  271. run_unittest(LongReprTest)
  272. if __name__ == "__main__":
  273. test_main()