PageRenderTime 118ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/kbe/src/lib/python/Lib/test/test_reprlib.py

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