+++ /dev/null
-import test.test_support\r
-compiler = test.test_support.import_module('compiler', deprecated=True)\r
-from compiler.ast import flatten\r
-import os, sys, time, unittest\r
-from random import random\r
-from StringIO import StringIO\r
-\r
-# How much time in seconds can pass before we print a 'Still working' message.\r
-_PRINT_WORKING_MSG_INTERVAL = 5 * 60\r
-\r
-class TrivialContext(object):\r
- def __enter__(self):\r
- return self\r
- def __exit__(self, *exc_info):\r
- pass\r
-\r
-class CompilerTest(unittest.TestCase):\r
-\r
- def testCompileLibrary(self):\r
- # A simple but large test. Compile all the code in the\r
- # standard library and its test suite. This doesn't verify\r
- # that any of the code is correct, merely the compiler is able\r
- # to generate some kind of code for it.\r
-\r
- next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL\r
- # warning: if 'os' or 'test_support' are moved in some other dir,\r
- # they should be changed here.\r
- libdir = os.path.dirname(os.__file__)\r
- testdir = os.path.dirname(test.test_support.__file__)\r
-\r
- for dir in [libdir, testdir]:\r
- for basename in os.listdir(dir):\r
- # Print still working message since this test can be really slow\r
- if next_time <= time.time():\r
- next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL\r
- print >>sys.__stdout__, \\r
- ' testCompileLibrary still working, be patient...'\r
- sys.__stdout__.flush()\r
-\r
- if not basename.endswith(".py"):\r
- continue\r
- if not TEST_ALL and random() < 0.98:\r
- continue\r
- path = os.path.join(dir, basename)\r
- if test.test_support.verbose:\r
- print "compiling", path\r
- f = open(path, "U")\r
- buf = f.read()\r
- f.close()\r
- if "badsyntax" in basename or "bad_coding" in basename:\r
- self.assertRaises(SyntaxError, compiler.compile,\r
- buf, basename, "exec")\r
- else:\r
- try:\r
- compiler.compile(buf, basename, "exec")\r
- except Exception, e:\r
- args = list(e.args)\r
- args.append("in file %s]" % basename)\r
- #args[0] += "[in file %s]" % basename\r
- e.args = tuple(args)\r
- raise\r
-\r
- def testNewClassSyntax(self):\r
- compiler.compile("class foo():pass\n\n","<string>","exec")\r
-\r
- def testYieldExpr(self):\r
- compiler.compile("def g(): yield\n\n", "<string>", "exec")\r
-\r
- def testKeywordAfterStarargs(self):\r
- def f(*args, **kwargs):\r
- self.assertEqual((args, kwargs), ((2,3), {'x': 1, 'y': 4}))\r
- c = compiler.compile('f(x=1, *(2, 3), y=4)', '<string>', 'exec')\r
- exec c in {'f': f}\r
-\r
- self.assertRaises(SyntaxError, compiler.parse, "foo(a=1, b)")\r
- self.assertRaises(SyntaxError, compiler.parse, "foo(1, *args, 3)")\r
-\r
- def testTryExceptFinally(self):\r
- # Test that except and finally clauses in one try stmt are recognized\r
- c = compiler.compile("try:\n 1//0\nexcept:\n e = 1\nfinally:\n f = 1",\r
- "<string>", "exec")\r
- dct = {}\r
- exec c in dct\r
- self.assertEqual(dct.get('e'), 1)\r
- self.assertEqual(dct.get('f'), 1)\r
-\r
- def testDefaultArgs(self):\r
- self.assertRaises(SyntaxError, compiler.parse, "def foo(a=1, b): pass")\r
-\r
- def testDocstrings(self):\r
- c = compiler.compile('"doc"', '<string>', 'exec')\r
- self.assertIn('__doc__', c.co_names)\r
- c = compiler.compile('def f():\n "doc"', '<string>', 'exec')\r
- g = {}\r
- exec c in g\r
- self.assertEqual(g['f'].__doc__, "doc")\r
-\r
- def testLineNo(self):\r
- # Test that all nodes except Module have a correct lineno attribute.\r
- filename = __file__\r
- if filename.endswith((".pyc", ".pyo")):\r
- filename = filename[:-1]\r
- tree = compiler.parseFile(filename)\r
- self.check_lineno(tree)\r
-\r
- def check_lineno(self, node):\r
- try:\r
- self._check_lineno(node)\r
- except AssertionError:\r
- print node.__class__, node.lineno\r
- raise\r
-\r
- def _check_lineno(self, node):\r
- if not node.__class__ in NOLINENO:\r
- self.assertIsInstance(node.lineno, int,\r
- "lineno=%s on %s" % (node.lineno, node.__class__))\r
- self.assertTrue(node.lineno > 0,\r
- "lineno=%s on %s" % (node.lineno, node.__class__))\r
- for child in node.getChildNodes():\r
- self.check_lineno(child)\r
-\r
- def testFlatten(self):\r
- self.assertEqual(flatten([1, [2]]), [1, 2])\r
- self.assertEqual(flatten((1, (2,))), [1, 2])\r
-\r
- def testNestedScope(self):\r
- c = compiler.compile('def g():\n'\r
- ' a = 1\n'\r
- ' def f(): return a + 2\n'\r
- ' return f()\n'\r
- 'result = g()',\r
- '<string>',\r
- 'exec')\r
- dct = {}\r
- exec c in dct\r
- self.assertEqual(dct.get('result'), 3)\r
-\r
- def testGenExp(self):\r
- c = compiler.compile('list((i,j) for i in range(3) if i < 3'\r
- ' for j in range(4) if j > 2)',\r
- '<string>',\r
- 'eval')\r
- self.assertEqual(eval(c), [(0, 3), (1, 3), (2, 3)])\r
-\r
- def testSetLiteral(self):\r
- c = compiler.compile('{1, 2, 3}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1,2,3})\r
- c = compiler.compile('{1, 2, 3,}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1,2,3})\r
-\r
- def testDictLiteral(self):\r
- c = compiler.compile('{1:2, 2:3, 3:4}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1:2, 2:3, 3:4})\r
- c = compiler.compile('{1:2, 2:3, 3:4,}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1:2, 2:3, 3:4})\r
-\r
- def testSetComp(self):\r
- c = compiler.compile('{x for x in range(1, 4)}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1, 2, 3})\r
- c = compiler.compile('{x * y for x in range(3) if x != 0'\r
- ' for y in range(4) if y != 0}',\r
- '<string>',\r
- 'eval')\r
- self.assertEqual(eval(c), {1, 2, 3, 4, 6})\r
-\r
- def testDictComp(self):\r
- c = compiler.compile('{x:x+1 for x in range(1, 4)}', '<string>', 'eval')\r
- self.assertEqual(eval(c), {1:2, 2:3, 3:4})\r
- c = compiler.compile('{(x, y) : y for x in range(2) if x != 0'\r
- ' for y in range(3) if y != 0}',\r
- '<string>',\r
- 'eval')\r
- self.assertEqual(eval(c), {(1, 2): 2, (1, 1): 1})\r
-\r
- def testWith(self):\r
- # SF bug 1638243\r
- c = compiler.compile('from __future__ import with_statement\n'\r
- 'def f():\n'\r
- ' with TrivialContext():\n'\r
- ' return 1\n'\r
- 'result = f()',\r
- '<string>',\r
- 'exec' )\r
- dct = {'TrivialContext': TrivialContext}\r
- exec c in dct\r
- self.assertEqual(dct.get('result'), 1)\r
-\r
- def testWithAss(self):\r
- c = compiler.compile('from __future__ import with_statement\n'\r
- 'def f():\n'\r
- ' with TrivialContext() as tc:\n'\r
- ' return 1\n'\r
- 'result = f()',\r
- '<string>',\r
- 'exec' )\r
- dct = {'TrivialContext': TrivialContext}\r
- exec c in dct\r
- self.assertEqual(dct.get('result'), 1)\r
-\r
- def testWithMult(self):\r
- events = []\r
- class Ctx:\r
- def __init__(self, n):\r
- self.n = n\r
- def __enter__(self):\r
- events.append(self.n)\r
- def __exit__(self, *args):\r
- pass\r
- c = compiler.compile('from __future__ import with_statement\n'\r
- 'def f():\n'\r
- ' with Ctx(1) as tc, Ctx(2) as tc2:\n'\r
- ' return 1\n'\r
- 'result = f()',\r
- '<string>',\r
- 'exec' )\r
- dct = {'Ctx': Ctx}\r
- exec c in dct\r
- self.assertEqual(dct.get('result'), 1)\r
- self.assertEqual(events, [1, 2])\r
-\r
- def testGlobal(self):\r
- code = compiler.compile('global x\nx=1', '<string>', 'exec')\r
- d1 = {'__builtins__': {}}\r
- d2 = {}\r
- exec code in d1, d2\r
- # x should be in the globals dict\r
- self.assertEqual(d1.get('x'), 1)\r
-\r
- def testPrintFunction(self):\r
- c = compiler.compile('from __future__ import print_function\n'\r
- 'print("a", "b", sep="**", end="++", '\r
- 'file=output)',\r
- '<string>',\r
- 'exec' )\r
- dct = {'output': StringIO()}\r
- exec c in dct\r
- self.assertEqual(dct['output'].getvalue(), 'a**b++')\r
-\r
- def _testErrEnc(self, src, text, offset):\r
- try:\r
- compile(src, "", "exec")\r
- except SyntaxError, e:\r
- self.assertEqual(e.offset, offset)\r
- self.assertEqual(e.text, text)\r
-\r
- def testSourceCodeEncodingsError(self):\r
- # Test SyntaxError with encoding definition\r
- sjis = "print '\x83\x70\x83\x43\x83\x5c\x83\x93', '\n"\r
- ascii = "print '12345678', '\n"\r
- encdef = "#! -*- coding: ShiftJIS -*-\n"\r
-\r
- # ascii source without encdef\r
- self._testErrEnc(ascii, ascii, 19)\r
-\r
- # ascii source with encdef\r
- self._testErrEnc(encdef+ascii, ascii, 19)\r
-\r
- # non-ascii source with encdef\r
- self._testErrEnc(encdef+sjis, sjis, 19)\r
-\r
- # ShiftJIS source without encdef\r
- self._testErrEnc(sjis, sjis, 19)\r
-\r
-\r
-NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)\r
-\r
-###############################################################################\r
-# code below is just used to trigger some possible errors, for the benefit of\r
-# testLineNo\r
-###############################################################################\r
-\r
-class Toto:\r
- """docstring"""\r
- pass\r
-\r
-a, b = 2, 3\r
-[c, d] = 5, 6\r
-l = [(x, y) for x, y in zip(range(5), range(5,10))]\r
-l[0]\r
-l[3:4]\r
-d = {'a': 2}\r
-d = {}\r
-d = {x: y for x, y in zip(range(5), range(5,10))}\r
-s = {x for x in range(10)}\r
-s = {1}\r
-t = ()\r
-t = (1, 2)\r
-l = []\r
-l = [1, 2]\r
-if l:\r
- pass\r
-else:\r
- a, b = b, a\r
-\r
-try:\r
- print yo\r
-except:\r
- yo = 3\r
-else:\r
- yo += 3\r
-\r
-try:\r
- a += b\r
-finally:\r
- b = 0\r
-\r
-from math import *\r
-\r
-###############################################################################\r
-\r
-def test_main():\r
- global TEST_ALL\r
- TEST_ALL = test.test_support.is_resource_enabled("cpu")\r
- test.test_support.run_unittest(CompilerTest)\r
-\r
-if __name__ == "__main__":\r
- test_main()\r