PageRenderTime 61ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/Win32/Lib/test/test_compiler.py

https://gitlab.com/CoastHeavyIndustries/OSM-stats
Python | 317 lines | 249 code | 45 blank | 23 comment | 28 complexity | d8c014dbfd7dbd29c26c8bce12621110 MD5 | raw file
  1. import test.test_support
  2. compiler = test.test_support.import_module('compiler', deprecated=True)
  3. from compiler.ast import flatten
  4. import os, sys, time, unittest
  5. from random import random
  6. from StringIO import StringIO
  7. # How much time in seconds can pass before we print a 'Still working' message.
  8. _PRINT_WORKING_MSG_INTERVAL = 5 * 60
  9. class TrivialContext(object):
  10. def __enter__(self):
  11. return self
  12. def __exit__(self, *exc_info):
  13. pass
  14. class CompilerTest(unittest.TestCase):
  15. def testCompileLibrary(self):
  16. # A simple but large test. Compile all the code in the
  17. # standard library and its test suite. This doesn't verify
  18. # that any of the code is correct, merely the compiler is able
  19. # to generate some kind of code for it.
  20. next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
  21. # warning: if 'os' or 'test_support' are moved in some other dir,
  22. # they should be changed here.
  23. libdir = os.path.dirname(os.__file__)
  24. testdir = os.path.dirname(test.test_support.__file__)
  25. for dir in [libdir, testdir]:
  26. for basename in os.listdir(dir):
  27. # Print still working message since this test can be really slow
  28. if next_time <= time.time():
  29. next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
  30. print >>sys.__stdout__, \
  31. ' testCompileLibrary still working, be patient...'
  32. sys.__stdout__.flush()
  33. if not basename.endswith(".py"):
  34. continue
  35. if not TEST_ALL and random() < 0.98:
  36. continue
  37. path = os.path.join(dir, basename)
  38. if test.test_support.verbose:
  39. print "compiling", path
  40. f = open(path, "U")
  41. buf = f.read()
  42. f.close()
  43. if "badsyntax" in basename or "bad_coding" in basename:
  44. self.assertRaises(SyntaxError, compiler.compile,
  45. buf, basename, "exec")
  46. else:
  47. try:
  48. compiler.compile(buf, basename, "exec")
  49. except Exception, e:
  50. args = list(e.args)
  51. args.append("in file %s]" % basename)
  52. #args[0] += "[in file %s]" % basename
  53. e.args = tuple(args)
  54. raise
  55. def testNewClassSyntax(self):
  56. compiler.compile("class foo():pass\n\n","<string>","exec")
  57. def testYieldExpr(self):
  58. compiler.compile("def g(): yield\n\n", "<string>", "exec")
  59. def testKeywordAfterStarargs(self):
  60. def f(*args, **kwargs):
  61. self.assertEqual((args, kwargs), ((2,3), {'x': 1, 'y': 4}))
  62. c = compiler.compile('f(x=1, *(2, 3), y=4)', '<string>', 'exec')
  63. exec c in {'f': f}
  64. self.assertRaises(SyntaxError, compiler.parse, "foo(a=1, b)")
  65. self.assertRaises(SyntaxError, compiler.parse, "foo(1, *args, 3)")
  66. def testTryExceptFinally(self):
  67. # Test that except and finally clauses in one try stmt are recognized
  68. c = compiler.compile("try:\n 1//0\nexcept:\n e = 1\nfinally:\n f = 1",
  69. "<string>", "exec")
  70. dct = {}
  71. exec c in dct
  72. self.assertEquals(dct.get('e'), 1)
  73. self.assertEquals(dct.get('f'), 1)
  74. def testDefaultArgs(self):
  75. self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")
  76. def testDocstrings(self):
  77. c = compiler.compile('"doc"', '<string>', 'exec')
  78. self.assertIn('__doc__', c.co_names)
  79. c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
  80. g = {}
  81. exec c in g
  82. self.assertEquals(g['f'].__doc__, "doc")
  83. def testLineNo(self):
  84. # Test that all nodes except Module have a correct lineno attribute.
  85. filename = __file__
  86. if filename.endswith((".pyc", ".pyo")):
  87. filename = filename[:-1]
  88. tree = compiler.parseFile(filename)
  89. self.check_lineno(tree)
  90. def check_lineno(self, node):
  91. try:
  92. self._check_lineno(node)
  93. except AssertionError:
  94. print node.__class__, node.lineno
  95. raise
  96. def _check_lineno(self, node):
  97. if not node.__class__ in NOLINENO:
  98. self.assertIsInstance(node.lineno, int,
  99. "lineno=%s on %s" % (node.lineno, node.__class__))
  100. self.assertTrue(node.lineno > 0,
  101. "lineno=%s on %s" % (node.lineno, node.__class__))
  102. for child in node.getChildNodes():
  103. self.check_lineno(child)
  104. def testFlatten(self):
  105. self.assertEquals(flatten([1, [2]]), [1, 2])
  106. self.assertEquals(flatten((1, (2,))), [1, 2])
  107. def testNestedScope(self):
  108. c = compiler.compile('def g():\n'
  109. ' a = 1\n'
  110. ' def f(): return a + 2\n'
  111. ' return f()\n'
  112. 'result = g()',
  113. '<string>',
  114. 'exec')
  115. dct = {}
  116. exec c in dct
  117. self.assertEquals(dct.get('result'), 3)
  118. def testGenExp(self):
  119. c = compiler.compile('list((i,j) for i in range(3) if i < 3'
  120. ' for j in range(4) if j > 2)',
  121. '<string>',
  122. 'eval')
  123. self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
  124. def testSetLiteral(self):
  125. c = compiler.compile('{1, 2, 3}', '<string>', 'eval')
  126. self.assertEquals(eval(c), {1,2,3})
  127. c = compiler.compile('{1, 2, 3,}', '<string>', 'eval')
  128. self.assertEquals(eval(c), {1,2,3})
  129. def testDictLiteral(self):
  130. c = compiler.compile('{1:2, 2:3, 3:4}', '<string>', 'eval')
  131. self.assertEquals(eval(c), {1:2, 2:3, 3:4})
  132. c = compiler.compile('{1:2, 2:3, 3:4,}', '<string>', 'eval')
  133. self.assertEquals(eval(c), {1:2, 2:3, 3:4})
  134. def testSetComp(self):
  135. c = compiler.compile('{x for x in range(1, 4)}', '<string>', 'eval')
  136. self.assertEquals(eval(c), {1, 2, 3})
  137. c = compiler.compile('{x * y for x in range(3) if x != 0'
  138. ' for y in range(4) if y != 0}',
  139. '<string>',
  140. 'eval')
  141. self.assertEquals(eval(c), {1, 2, 3, 4, 6})
  142. def testDictComp(self):
  143. c = compiler.compile('{x:x+1 for x in range(1, 4)}', '<string>', 'eval')
  144. self.assertEquals(eval(c), {1:2, 2:3, 3:4})
  145. c = compiler.compile('{(x, y) : y for x in range(2) if x != 0'
  146. ' for y in range(3) if y != 0}',
  147. '<string>',
  148. 'eval')
  149. self.assertEquals(eval(c), {(1, 2): 2, (1, 1): 1})
  150. def testWith(self):
  151. # SF bug 1638243
  152. c = compiler.compile('from __future__ import with_statement\n'
  153. 'def f():\n'
  154. ' with TrivialContext():\n'
  155. ' return 1\n'
  156. 'result = f()',
  157. '<string>',
  158. 'exec' )
  159. dct = {'TrivialContext': TrivialContext}
  160. exec c in dct
  161. self.assertEquals(dct.get('result'), 1)
  162. def testWithAss(self):
  163. c = compiler.compile('from __future__ import with_statement\n'
  164. 'def f():\n'
  165. ' with TrivialContext() as tc:\n'
  166. ' return 1\n'
  167. 'result = f()',
  168. '<string>',
  169. 'exec' )
  170. dct = {'TrivialContext': TrivialContext}
  171. exec c in dct
  172. self.assertEquals(dct.get('result'), 1)
  173. def testWithMult(self):
  174. events = []
  175. class Ctx:
  176. def __init__(self, n):
  177. self.n = n
  178. def __enter__(self):
  179. events.append(self.n)
  180. def __exit__(self, *args):
  181. pass
  182. c = compiler.compile('from __future__ import with_statement\n'
  183. 'def f():\n'
  184. ' with Ctx(1) as tc, Ctx(2) as tc2:\n'
  185. ' return 1\n'
  186. 'result = f()',
  187. '<string>',
  188. 'exec' )
  189. dct = {'Ctx': Ctx}
  190. exec c in dct
  191. self.assertEquals(dct.get('result'), 1)
  192. self.assertEquals(events, [1, 2])
  193. def testGlobal(self):
  194. code = compiler.compile('global x\nx=1', '<string>', 'exec')
  195. d1 = {'__builtins__': {}}
  196. d2 = {}
  197. exec code in d1, d2
  198. # x should be in the globals dict
  199. self.assertEquals(d1.get('x'), 1)
  200. def testPrintFunction(self):
  201. c = compiler.compile('from __future__ import print_function\n'
  202. 'print("a", "b", sep="**", end="++", '
  203. 'file=output)',
  204. '<string>',
  205. 'exec' )
  206. dct = {'output': StringIO()}
  207. exec c in dct
  208. self.assertEquals(dct['output'].getvalue(), 'a**b++')
  209. def _testErrEnc(self, src, text, offset):
  210. try:
  211. compile(src, "", "exec")
  212. except SyntaxError, e:
  213. self.assertEquals(e.offset, offset)
  214. self.assertEquals(e.text, text)
  215. def testSourceCodeEncodingsError(self):
  216. # Test SyntaxError with encoding definition
  217. sjis = "print '\x83\x70\x83\x43\x83\x5c\x83\x93', '\n"
  218. ascii = "print '12345678', '\n"
  219. encdef = "#! -*- coding: ShiftJIS -*-\n"
  220. # ascii source without encdef
  221. self._testErrEnc(ascii, ascii, 19)
  222. # ascii source with encdef
  223. self._testErrEnc(encdef+ascii, ascii, 19)
  224. # non-ascii source with encdef
  225. self._testErrEnc(encdef+sjis, sjis, 19)
  226. # ShiftJIS source without encdef
  227. self._testErrEnc(sjis, sjis, 19)
  228. NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
  229. ###############################################################################
  230. # code below is just used to trigger some possible errors, for the benefit of
  231. # testLineNo
  232. ###############################################################################
  233. class Toto:
  234. """docstring"""
  235. pass
  236. a, b = 2, 3
  237. [c, d] = 5, 6
  238. l = [(x, y) for x, y in zip(range(5), range(5,10))]
  239. l[0]
  240. l[3:4]
  241. d = {'a': 2}
  242. d = {}
  243. d = {x: y for x, y in zip(range(5), range(5,10))}
  244. s = {x for x in range(10)}
  245. s = {1}
  246. t = ()
  247. t = (1, 2)
  248. l = []
  249. l = [1, 2]
  250. if l:
  251. pass
  252. else:
  253. a, b = b, a
  254. try:
  255. print yo
  256. except:
  257. yo = 3
  258. else:
  259. yo += 3
  260. try:
  261. a += b
  262. finally:
  263. b = 0
  264. from math import *
  265. ###############################################################################
  266. def test_main():
  267. global TEST_ALL
  268. TEST_ALL = test.test_support.is_resource_enabled("compiler")
  269. test.test_support.run_unittest(CompilerTest)
  270. if __name__ == "__main__":
  271. test_main()