[Python-checkins] python/dist/src/Lib/test test_compile.py, 1.10.10.3, 1.10.10.4

bcannon at users.sourceforge.net bcannon at users.sourceforge.net
Mon Apr 25 00:06:14 CEST 2005


Update of /cvsroot/python/python/dist/src/Lib/test
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17237/Lib/test

Modified Files:
      Tag: ast-branch
	test_compile.py 
Log Message:
Backport test_compile from the 2.4 branch by copying that version over and
committing.


Index: test_compile.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_compile.py,v
retrieving revision 1.10.10.3
retrieving revision 1.10.10.4
diff -u -d -r1.10.10.3 -r1.10.10.4
--- test_compile.py	23 Apr 2004 04:35:57 -0000	1.10.10.3
+++ test_compile.py	24 Apr 2005 22:05:56 -0000	1.10.10.4
@@ -1,199 +1,268 @@
-"""Test a variety of compilation edge cases.
-
-Several ways to assign to __debug__
------------------------------------
-
->>> __debug__ = 1
-Traceback (most recent call last):
- ...
-SyntaxError: can not assign to __debug__ (<string>, line 1)
-
->>> import __debug__
-Traceback (most recent call last):
- ...
-SyntaxError: can not assign to __debug__ (<string>, line 1)
-
->>> try:
-...     1
-... except MemoryError, __debug__:
-...     pass
-Traceback (most recent call last):
- ...
-SyntaxError: can not assign to __debug__ (<string>, line 2)
-
-Shouldn't that be line 3?
-
->>> def __debug__():
-...     pass
-Traceback (most recent call last):
- ...
-SyntaxError: can not assign to __debug__ (<string>, line 1)
-
-Not sure what the next few lines is trying to test.
-
->>> import __builtin__
->>> prev = __builtin__.__debug__
->>> setattr(__builtin__, "__debug__", "sure")
->>> setattr(__builtin__, "__debug__", prev)
-
-Parameter passing
------------------
-
->>> def f(a = 0, a = 1):
-...     pass
-Traceback (most recent call last):
- ...
-SyntaxError: duplicate argument 'a' in function definition (<string>, line 1)
-
->>> def f(a):
-...     global a
-...     a = 1
-Traceback (most recent call last):
- ...
-SyntaxError: name 'a' is local and global
+import unittest
+import warnings
+import sys
+from test import test_support
 
-XXX How hard would it be to get the location in the error?
+class TestSpecifics(unittest.TestCase):
 
->>> def f(a=1, (b, c)):
-...     pass
-Traceback (most recent call last):
- ...
-SyntaxError: non-default argument follows default argument (<string>, line 1)
+    def test_debug_assignment(self):
+        # catch assignments to __debug__
+        self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
+        import __builtin__
+        prev = __builtin__.__debug__
+        setattr(__builtin__, '__debug__', 'sure')
+        setattr(__builtin__, '__debug__', prev)
 
+    def test_argument_handling(self):
+        # detect duplicate positional and keyword arguments
+        self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
+        self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
+        self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
+        try:
+            exec 'def f(a, a): pass'
+            self.fail("duplicate arguments")
+        except SyntaxError:
+            pass
+        try:
+            exec 'def f(a = 0, a = 1): pass'
+            self.fail("duplicate keyword arguments")
+        except SyntaxError:
+            pass
+        try:
+            exec 'def f(a): global a; a = 1'
+            self.fail("variable is global and local")
+        except SyntaxError:
+            pass
 
-Details of SyntaxError object
------------------------------
+    def test_syntax_error(self):
+        self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
 
->>> 1+*3
-Traceback (most recent call last):
- ...
-SyntaxError: invalid syntax
+    def test_duplicate_global_local(self):
+        try:
+            exec 'def f(a): global a; a = 1'
+            self.fail("variable is global and local")
+        except SyntaxError:
+            pass
 
-In this case, let's explore the details fields of the exception object.
->>> try:
-...     compile("1+*3", "filename", "exec")
-... except SyntaxError, err:
-...     pass
->>> err.filename, err.lineno, err.offset
-('filename', 1, 3)
->>> err.text, err.msg
-('1+*3', 'invalid syntax')
+    def test_exec_with_general_mapping_for_locals(self):
 
-Complex parameter passing
--------------------------
+        class M:
+            "Test mapping interface versus possible calls from eval()."
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                raise KeyError
+            def __setitem__(self, key, value):
+                self.results = (key, value)
+            def keys(self):
+                return list('xyz')
 
->>> def comp_params((a, b)):
-...     print a, b
->>> comp_params((1, 2))
-1 2
+        m = M()
+        g = globals()
+        exec 'z = a' in g, m
+        self.assertEqual(m.results, ('z', 12))
+        try:
+            exec 'z = b' in g, m
+        except NameError:
+            pass
+        else:
+            self.fail('Did not detect a KeyError')
+        exec 'z = dir()' in g, m
+        self.assertEqual(m.results, ('z', list('xyz')))
+        exec 'z = globals()' in g, m
+        self.assertEqual(m.results, ('z', g))
+        exec 'z = locals()' in g, m
+        self.assertEqual(m.results, ('z', m))
+        try:
+            exec 'z = b' in m
+        except TypeError:
+            pass
+        else:
+            self.fail('Did not validate globals as a real dict')
 
->>> def comp_params((a, b)=(3, 4)):
-...     print a, b
->>> comp_params((1, 2))
-1 2
->>> comp_params()
-3 4
+        class A:
+            "Non-mapping"
+            pass
+        m = A()
+        try:
+            exec 'z = a' in g, m
+        except TypeError:
+            pass
+        else:
+            self.fail('Did not validate locals as a mapping')
 
->>> def comp_params(a, (b, c)):
-...     print a, b, c
->>> comp_params(1, (2, 3))
-1 2 3
+        # Verify that dict subclasses work as well
+        class D(dict):
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                return dict.__getitem__(self, key)
+        d = D()
+        exec 'z = a' in g, d
+        self.assertEqual(d['z'], 12)
 
->>> def comp_params(a=2, (b, c)=(3, 4)):
-...     print a, b, c
->>> comp_params(1, (2, 3))
-1 2 3
->>> comp_params()
-2 3 4
+    def test_complex_args(self):
 
-"""
+        def comp_args((a, b)):
+            return a,b
+        self.assertEqual(comp_args((1, 2)), (1, 2))
 
-from test.test_support import verbose, TestFailed, run_doctest
+        def comp_args((a, b)=(3, 4)):
+            return a, b
+        self.assertEqual(comp_args((1, 2)), (1, 2))
+        self.assertEqual(comp_args(), (3, 4))
 
-# It takes less space to deal with bad float literals using a helper
-# function than it does with doctest.  The doctest needs to include
-# the exception every time.
+        def comp_args(a, (b, c)):
+            return a, b, c
+        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
 
-def expect_error(s):
-    try:
-        eval(s)
-        raise TestFailed("%r accepted" % s)
-    except SyntaxError:
-        pass
+        def comp_args(a=2, (b, c)=(3, 4)):
+            return a, b, c
+        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
+        self.assertEqual(comp_args(), (2, 3, 4))
 
-expect_error("2e")
-expect_error("2.0e+")
-expect_error("1e-")
-expect_error("3-4e/21")
+    def test_argument_order(self):
+        try:
+            exec 'def f(a=1, (b, c)): pass'
+            self.fail("non-default args after default")
+        except SyntaxError:
+            pass
 
-if verbose:
-    print "testing compile() of indented block w/o trailing newline"
+    def test_float_literals(self):
+        # testing bad float literals
+        self.assertRaises(SyntaxError, eval, "2e")
+        self.assertRaises(SyntaxError, eval, "2.0e+")
+        self.assertRaises(SyntaxError, eval, "1e-")
+        self.assertRaises(SyntaxError, eval, "3-4e/21")
 
-s = """
+    def test_indentation(self):
+        # testing compile() of indented block w/o trailing newline"
+        s = """
 if 1:
     if 2:
         pass"""
-compile(s, "<string>", "exec")
+        compile(s, "<string>", "exec")
 
+    def test_literals_with_leading_zeroes(self):
+        for arg in ["077787", "0xj", "0x.", "0e",  "090000000000000",
+                    "080000000000000", "000000000000009", "000000000000008"]:
+            self.assertRaises(SyntaxError, eval, arg)
 
-if verbose:
-    print "testing literals with leading zeroes"
+        self.assertEqual(eval("0777"), 511)
+        self.assertEqual(eval("0777L"), 511)
+        self.assertEqual(eval("000777"), 511)
+        self.assertEqual(eval("0xff"), 255)
+        self.assertEqual(eval("0xffL"), 255)
+        self.assertEqual(eval("0XfF"), 255)
+        self.assertEqual(eval("0777."), 777)
+        self.assertEqual(eval("0777.0"), 777)
+        self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
+        self.assertEqual(eval("0777e1"), 7770)
+        self.assertEqual(eval("0e0"), 0)
+        self.assertEqual(eval("0000E-012"), 0)
+        self.assertEqual(eval("09.5"), 9.5)
+        self.assertEqual(eval("0777j"), 777j)
+        self.assertEqual(eval("00j"), 0j)
+        self.assertEqual(eval("00.0"), 0)
+        self.assertEqual(eval("0e3"), 0)
+        self.assertEqual(eval("090000000000000."), 90000000000000.)
+        self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
+        self.assertEqual(eval("090000000000000e0"), 90000000000000.)
+        self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
+        self.assertEqual(eval("090000000000000j"), 90000000000000j)
+        self.assertEqual(eval("000000000000007"), 7)
+        self.assertEqual(eval("000000000000008."), 8.)
+        self.assertEqual(eval("000000000000009."), 9.)
 
-def expect_same(test_source, expected):
-    got = eval(test_source)
-    if got != expected:
-        raise TestFailed("eval(%r) gave %r, but expected %r" %
-                         (test_source, got, expected))
+    def test_unary_minus(self):
+        # Verify treatment of unary minus on negative numbers SF bug #660455
+        if sys.maxint == 2147483647:
+            # 32-bit machine
+            all_one_bits = '0xffffffff'
+            self.assertEqual(eval(all_one_bits), 4294967295L)
+            self.assertEqual(eval("-" + all_one_bits), -4294967295L)
+        elif sys.maxint == 9223372036854775807:
+            # 64-bit machine
+            all_one_bits = '0xffffffffffffffff'
+            self.assertEqual(eval(all_one_bits), 18446744073709551615L)
+            self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L)
+        else:
+            self.fail("How many bits *does* this machine have???")
 
-expect_error("077787")
-expect_error("0xj")
-expect_error("0x.")
-expect_error("0e")
-expect_same("0777", 511)
-expect_same("0777L", 511)
-expect_same("000777", 511)
-expect_same("0xff", 255)
-expect_same("0xffL", 255)
-expect_same("0XfF", 255)
-expect_same("0777.", 777)
-expect_same("0777.0", 777)
-expect_same("000000000000000000000000000000000000000000000000000777e0", 777)
-expect_same("0777e1", 7770)
-expect_same("0e0", 0)
-expect_same("0000E-012", 0)
-expect_same("09.5", 9.5)
-expect_same("0777j", 777j)
-expect_same("00j", 0j)
-expect_same("00.0", 0)
-expect_same("0e3", 0)
-expect_same("090000000000000.", 90000000000000.)
-expect_same("090000000000000.0000000000000000000000", 90000000000000.)
-expect_same("090000000000000e0", 90000000000000.)
-expect_same("090000000000000e-0", 90000000000000.)
-expect_same("090000000000000j", 90000000000000j)
-expect_error("090000000000000")  # plain octal literal w/ decimal digit
-expect_error("080000000000000")  # plain octal literal w/ decimal digit
-expect_error("000000000000009")  # plain octal literal w/ decimal digit
-expect_error("000000000000008")  # plain octal literal w/ decimal digit
-expect_same("000000000000007", 7)
-expect_same("000000000000008.", 8.)
-expect_same("000000000000009.", 9.)
+    def test_sequence_unpacking_error(self):
+        # Verify sequence packing/unpacking with "or".  SF bug #757818
+        i,j = (1, -1) or (-1, 1)
+        self.assertEqual(i, 1)
+        self.assertEqual(j, -1)
 
-# Verify treatment of unary minus on negative numbers SF bug #660455
-import warnings
-warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning)
-warnings.filterwarnings("ignore", "hex.* of negative int", FutureWarning)
-# XXX Of course the following test will have to be changed in Python 2.4
-# This test is in a <string> so the filterwarnings() can affect it
-import sys
-all_one_bits = '0xffffffff'
-if sys.maxint != 2147483647:
-    all_one_bits = '0xffffffffffffffff'
-exec """
-expect_same(all_one_bits, -1)
-expect_same("-" + all_one_bits, 1)
-"""
+    def test_none_assignment(self):
+        stmts = [
+            'None = 0',
+            'None += 0',
+            '__builtins__.None = 0',
+            'def None(): pass',
+            'class None: pass',
+            '(a, None) = 0, 0',
+            'for None in range(10): pass',
+            'def f(None): pass',
+        ]
+        for stmt in stmts:
+            stmt += "\n"
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
 
-def test_main(verbose=None):
-    from test import test_compile
-    run_doctest(test_compile, verbose)
+    def test_import(self):
+        succeed = [
+            'import sys',
+            'import os, sys',
+            'from __future__ import nested_scopes, generators',
+            'from __future__ import (nested_scopes,\ngenerators)',
+            'from __future__ import (nested_scopes,\ngenerators,)',
+            'from sys import stdin, stderr, stdout',
+            'from sys import (stdin, stderr,\nstdout)',
+            'from sys import (stdin, stderr,\nstdout,)',
+            'from sys import (stdin\n, stderr, stdout)',
+            'from sys import (stdin\n, stderr, stdout,)',
+            'from sys import stdin as si, stdout as so, stderr as se',
+            'from sys import (stdin as si, stdout as so, stderr as se)',
+            'from sys import (stdin as si, stdout as so, stderr as se,)',
+            ]
+        fail = [
+            'import (os, sys)',
+            'import (os), (sys)',
+            'import ((os), (sys))',
+            'import (sys',
+            'import sys)',
+            'import (os,)',
+            'from (sys) import stdin',
+            'from __future__ import (nested_scopes',
+            'from __future__ import nested_scopes)',
+            'from __future__ import nested_scopes,\ngenerators',
+            'from sys import (stdin',
+            'from sys import stdin)',
+            'from sys import stdin, stdout,\nstderr',
+            'from sys import stdin si',
+            'from sys import stdin,'
+            'from sys import (*)',
+            'from sys import (stdin,, stdout, stderr)',
+            'from sys import (stdin, stdout),',
+            ]
+        for stmt in succeed:
+            compile(stmt, 'tmp', 'exec')
+        for stmt in fail:
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
+
+    def test_for_distinct_code_objects(self):
+        # SF bug 1048870
+        def f():
+            f1 = lambda x=1: x
+            f2 = lambda x=2: x
+            return f1, f2
+        f1, f2 = f()
+        self.assertNotEqual(id(f1.func_code), id(f2.func_code))
+
+def test_main():
+    test_support.run_unittest(TestSpecifics)
+
+if __name__ == "__main__":
+    test_main()



More information about the Python-checkins mailing list