1"""
2   Test cases for codeop.py
3   Nick Mathewson
4"""
5import unittest
6from test.support import is_jython
7
8from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT
9import io
10
11if is_jython:
12    import sys
13
14    def unify_callables(d):
15        for n,v in d.items():
16            if hasattr(v, '__call__'):
17                d[n] = True
18        return d
19
20class CodeopTests(unittest.TestCase):
21
22    def assertValid(self, str, symbol='single'):
23        '''succeed iff str is a valid piece of code'''
24        if is_jython:
25            code = compile_command(str, "<input>", symbol)
26            self.assertTrue(code)
27            if symbol == "single":
28                d,r = {},{}
29                saved_stdout = sys.stdout
30                sys.stdout = io.StringIO()
31                try:
32                    exec(code, d)
33                    exec(compile(str,"<input>","single"), r)
34                finally:
35                    sys.stdout = saved_stdout
36            elif symbol == 'eval':
37                ctx = {'a': 2}
38                d = { 'value': eval(code,ctx) }
39                r = { 'value': eval(str,ctx) }
40            self.assertEqual(unify_callables(r),unify_callables(d))
41        else:
42            expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT)
43            self.assertEqual(compile_command(str, "<input>", symbol), expected)
44
45    def assertIncomplete(self, str, symbol='single'):
46        '''succeed iff str is the start of a valid piece of code'''
47        self.assertEqual(compile_command(str, symbol=symbol), None)
48
49    def assertInvalid(self, str, symbol='single', is_syntax=1):
50        '''succeed iff str is the start of an invalid piece of code'''
51        try:
52            compile_command(str,symbol=symbol)
53            self.fail("No exception raised for invalid code")
54        except SyntaxError:
55            self.assertTrue(is_syntax)
56        except OverflowError:
57            self.assertTrue(not is_syntax)
58
59    def test_valid(self):
60        av = self.assertValid
61
62        # special case
63        if not is_jython:
64            self.assertEqual(compile_command(""),
65                             compile("pass", "<input>", 'single',
66                                     PyCF_DONT_IMPLY_DEDENT))
67            self.assertEqual(compile_command("\n"),
68                             compile("pass", "<input>", 'single',
69                                     PyCF_DONT_IMPLY_DEDENT))
70        else:
71            av("")
72            av("\n")
73
74        av("a = 1")
75        av("\na = 1")
76        av("a = 1\n")
77        av("a = 1\n\n")
78        av("\n\na = 1\n\n")
79
80        av("def x():\n  pass\n")
81        av("if 1:\n pass\n")
82
83        av("\n\nif 1: pass\n")
84        av("\n\nif 1: pass\n\n")
85
86        av("def x():\n\n pass\n")
87        av("def x():\n  pass\n  \n")
88        av("def x():\n  pass\n \n")
89
90        av("pass\n")
91        av("3**3\n")
92
93        av("if 9==3:\n   pass\nelse:\n   pass\n")
94        av("if 1:\n pass\n if 1:\n  pass\n else:\n  pass\n")
95
96        av("#a\n#b\na = 3\n")
97        av("#a\n\n   \na=3\n")
98        av("a=3\n\n")
99        av("a = 9+ \\\n3")
100
101        av("3**3","eval")
102        av("(lambda z: \n z**3)","eval")
103
104        av("9+ \\\n3","eval")
105        av("9+ \\\n3\n","eval")
106
107        av("\n\na**3","eval")
108        av("\n \na**3","eval")
109        av("#a\n#b\na**3","eval")
110
111        av("\n\na = 1\n\n")
112        av("\n\nif 1: a=1\n\n")
113
114        av("if 1:\n pass\n if 1:\n  pass\n else:\n  pass\n")
115        av("#a\n\n   \na=3\n\n")
116
117        av("\n\na**3","eval")
118        av("\n \na**3","eval")
119        av("#a\n#b\na**3","eval")
120
121        av("def f():\n try: pass\n finally: [x for x in (1,2)]\n")
122        av("def f():\n pass\n#foo\n")
123        av("@a.b.c\ndef f():\n pass\n")
124
125    def test_incomplete(self):
126        ai = self.assertIncomplete
127
128        ai("(a **")
129        ai("(a,b,")
130        ai("(a,b,(")
131        ai("(a,b,(")
132        ai("a = (")
133        ai("a = {")
134        ai("b + {")
135
136        ai("if 9==3:\n   pass\nelse:")
137        ai("if 9==3:\n   pass\nelse:\n")
138        ai("if 9==3:\n   pass\nelse:\n   pass")
139        ai("if 1:")
140        ai("if 1:\n")
141        ai("if 1:\n pass\n if 1:\n  pass\n else:")
142        ai("if 1:\n pass\n if 1:\n  pass\n else:\n")
143        ai("if 1:\n pass\n if 1:\n  pass\n else:\n  pass")
144
145        ai("def x():")
146        ai("def x():\n")
147        ai("def x():\n\n")
148
149        ai("def x():\n  pass")
150        ai("def x():\n  pass\n ")
151        ai("def x():\n  pass\n  ")
152        ai("\n\ndef x():\n  pass")
153
154        ai("a = 9+ \\")
155        ai("a = 'a\\")
156        ai("a = '''xy")
157
158        ai("","eval")
159        ai("\n","eval")
160        ai("(","eval")
161        ai("(\n\n\n","eval")
162        ai("(9+","eval")
163        ai("9+ \\","eval")
164        ai("lambda z: \\","eval")
165
166        ai("if True:\n if True:\n  if True:   \n")
167
168        ai("@a(")
169        ai("@a(b")
170        ai("@a(b,")
171        ai("@a(b,c")
172        ai("@a(b,c,")
173
174        ai("from a import (")
175        ai("from a import (b")
176        ai("from a import (b,")
177        ai("from a import (b,c")
178        ai("from a import (b,c,")
179
180        ai("[");
181        ai("[a");
182        ai("[a,");
183        ai("[a,b");
184        ai("[a,b,");
185
186        ai("{");
187        ai("{a");
188        ai("{a:");
189        ai("{a:b");
190        ai("{a:b,");
191        ai("{a:b,c");
192        ai("{a:b,c:");
193        ai("{a:b,c:d");
194        ai("{a:b,c:d,");
195
196        ai("a(")
197        ai("a(b")
198        ai("a(b,")
199        ai("a(b,c")
200        ai("a(b,c,")
201
202        ai("a[")
203        ai("a[b")
204        ai("a[b,")
205        ai("a[b:")
206        ai("a[b:c")
207        ai("a[b:c:")
208        ai("a[b:c:d")
209
210        ai("def a(")
211        ai("def a(b")
212        ai("def a(b,")
213        ai("def a(b,c")
214        ai("def a(b,c,")
215
216        ai("(")
217        ai("(a")
218        ai("(a,")
219        ai("(a,b")
220        ai("(a,b,")
221
222        ai("if a:\n pass\nelif b:")
223        ai("if a:\n pass\nelif b:\n pass\nelse:")
224
225        ai("while a:")
226        ai("while a:\n pass\nelse:")
227
228        ai("for a in b:")
229        ai("for a in b:\n pass\nelse:")
230
231        ai("try:")
232        ai("try:\n pass\nexcept:")
233        ai("try:\n pass\nfinally:")
234        ai("try:\n pass\nexcept:\n pass\nfinally:")
235
236        ai("with a:")
237        ai("with a as b:")
238
239        ai("class a:")
240        ai("class a(")
241        ai("class a(b")
242        ai("class a(b,")
243        ai("class a():")
244
245        ai("[x for")
246        ai("[x for x in")
247        ai("[x for x in (")
248
249        ai("(x for")
250        ai("(x for x in")
251        ai("(x for x in (")
252
253    def test_invalid(self):
254        ai = self.assertInvalid
255        ai("a b")
256
257        ai("a @")
258        ai("a b @")
259        ai("a ** @")
260
261        ai("a = ")
262        ai("a = 9 +")
263
264        ai("def x():\n\npass\n")
265
266        ai("\n\n if 1: pass\n\npass")
267
268        ai("a = 9+ \\\n")
269        ai("a = 'a\\ ")
270        ai("a = 'a\\\n")
271
272        ai("a = 1","eval")
273        ai("a = (","eval")
274        ai("]","eval")
275        ai("())","eval")
276        ai("[}","eval")
277        ai("9+","eval")
278        ai("lambda z:","eval")
279        ai("a b","eval")
280
281        ai("return 2.3")
282        ai("if (a == 1 and b = 2): pass")
283
284        ai("del 1")
285        ai("del (1,)")
286        ai("del [1]")
287        ai("del '1'")
288
289        ai("[i for i in range(10)] = (1, 2, 3)")
290
291    def test_filename(self):
292        self.assertEqual(compile_command("a = 1\n", "abc").co_filename,
293                         compile("a = 1\n", "abc", 'single').co_filename)
294        self.assertNotEqual(compile_command("a = 1\n", "abc").co_filename,
295                            compile("a = 1\n", "def", 'single').co_filename)
296
297
298if __name__ == "__main__":
299    unittest.main()
300