##// END OF EJS Templates
Fix async_helpers tests...
Paul Ganssle -
Show More
@@ -1,237 +1,234 b''
1 """
1 """
2 Test for async helpers.
2 Test for async helpers.
3
3
4 Should only trigger on python 3.5+ or will have syntax errors.
4 Should only trigger on python 3.5+ or will have syntax errors.
5 """
5 """
6
6
7 import sys
7 import sys
8 import nose.tools as nt
8 import nose.tools as nt
9 from textwrap import dedent, indent
9 from textwrap import dedent, indent
10 from unittest import TestCase
10 from unittest import TestCase
11
11
12 ip = get_ipython()
12 ip = get_ipython()
13 iprc = lambda x: ip.run_cell(dedent(x))
13 iprc = lambda x: ip.run_cell(dedent(x)).raise_error()
14 iprc_err = lambda x: iprc(x).raise_error()
15
14
16 if sys.version_info > (3, 5):
15 if sys.version_info > (3, 5):
17 from IPython.core.async_helpers import _should_be_async
16 from IPython.core.async_helpers import _should_be_async
18
17
19 class AsyncTest(TestCase):
18 class AsyncTest(TestCase):
20 def test_should_be_async(self):
19 def test_should_be_async(self):
21 nt.assert_false(_should_be_async("False"))
20 nt.assert_false(_should_be_async("False"))
22 nt.assert_true(_should_be_async("await bar()"))
21 nt.assert_true(_should_be_async("await bar()"))
23 nt.assert_true(_should_be_async("x = await bar()"))
22 nt.assert_true(_should_be_async("x = await bar()"))
24 nt.assert_false(
23 nt.assert_false(
25 _should_be_async(
24 _should_be_async(
26 dedent(
25 dedent(
27 """
26 """
28 async def awaitable():
27 async def awaitable():
29 pass
28 pass
30 """
29 """
31 )
30 )
32 )
31 )
33 )
32 )
34
33
35 def _get_top_level_cases(self):
34 def _get_top_level_cases(self):
36 # These are test cases that should be valid in a function
35 # These are test cases that should be valid in a function
37 # but invalid outside of a function.
36 # but invalid outside of a function.
38 test_cases = []
37 test_cases = []
39 test_cases.append(('basic', "{val}"))
38 test_cases.append(('basic', "{val}"))
40
39
41 # Note, in all conditional cases, I use True instead of
40 # Note, in all conditional cases, I use True instead of
42 # False so that the peephole optimizer won't optimize away
41 # False so that the peephole optimizer won't optimize away
43 # the return, so CPython will see this as a syntax error:
42 # the return, so CPython will see this as a syntax error:
44 #
43 #
45 # while True:
44 # while True:
46 # break
45 # break
47 # return
46 # return
48 #
47 #
49 # But not this:
48 # But not this:
50 #
49 #
51 # while False:
50 # while False:
52 # return
51 # return
53 #
52 #
54 # See https://bugs.python.org/issue1875
53 # See https://bugs.python.org/issue1875
55
54
56 test_cases.append(('if', dedent("""
55 test_cases.append(('if', dedent("""
57 if True:
56 if True:
58 {val}
57 {val}
59 """)))
58 """)))
60
59
61 test_cases.append(('while', dedent("""
60 test_cases.append(('while', dedent("""
62 while True:
61 while True:
63 {val}
62 {val}
64 break
63 break
65 """)))
64 """)))
66
65
67 test_cases.append(('try', dedent("""
66 test_cases.append(('try', dedent("""
68 try:
67 try:
69 {val}
68 {val}
70 except:
69 except:
71 pass
70 pass
72 """)))
71 """)))
73
72
74 test_cases.append(('except', dedent("""
73 test_cases.append(('except', dedent("""
75 try:
74 try:
76 pass
75 pass
77 except:
76 except:
78 {val}
77 {val}
79 """)))
78 """)))
80
79
81 test_cases.append(('finally', dedent("""
80 test_cases.append(('finally', dedent("""
82 try:
81 try:
83 pass
82 pass
84 except:
83 except:
85 pass
84 pass
86 finally:
85 finally:
87 {val}
86 {val}
88 """)))
87 """)))
89
88
90 test_cases.append(('for', dedent("""
89 test_cases.append(('for', dedent("""
91 for _ in range(4):
90 for _ in range(4):
92 {val}
91 {val}
93 """)))
92 """)))
94
93
95
94
96 test_cases.append(('nested', dedent("""
95 test_cases.append(('nested', dedent("""
97 if True:
96 if True:
98 while True:
97 while True:
99 {val}
98 {val}
100 break
99 break
101 """)))
100 """)))
102
101
103 test_cases.append(('deep-nested', dedent("""
102 test_cases.append(('deep-nested', dedent("""
104 if True:
103 if True:
105 while True:
104 while True:
106 break
105 break
107 for x in range(3):
106 for x in range(3):
108 if True:
107 if True:
109 while True:
108 while True:
110 for x in range(3):
109 for x in range(3):
111 {val}
110 {val}
112 """)))
111 """)))
113
112
114 return test_cases
113 return test_cases
115
114
116 def _get_ry_syntax_errors(self):
115 def _get_ry_syntax_errors(self):
117 # This is a mix of tests that should be a syntax error if
116 # This is a mix of tests that should be a syntax error if
118 # return or yield whether or not they are in a function
117 # return or yield whether or not they are in a function
119
118
120 test_cases = []
119 test_cases = []
121
120
122 test_cases.append(('class', dedent("""
121 test_cases.append(('class', dedent("""
123 class V:
122 class V:
124 {val}
123 {val}
125 """)))
124 """)))
126
125
127 test_cases.append(('nested-class', dedent("""
126 test_cases.append(('nested-class', dedent("""
128 class V:
127 class V:
129 class C:
128 class C:
130 {val}
129 {val}
131 """)))
130 """)))
132
131
133 return test_cases
132 return test_cases
134
133
135
134
136 def test_top_level_return_error(self):
135 def test_top_level_return_error(self):
137 tl_err_test_cases = self._get_top_level_cases()
136 tl_err_test_cases = self._get_top_level_cases()
138 tl_err_test_cases.extend(self._get_ry_syntax_errors())
137 tl_err_test_cases.extend(self._get_ry_syntax_errors())
139
138
140 vals = ('return', 'yield', 'yield from (_ for _ in range(3))')
139 vals = ('return', 'yield', 'yield from (_ for _ in range(3))')
141
140
142 for test_name, test_case in tl_err_test_cases:
141 for test_name, test_case in tl_err_test_cases:
143 # This example should work if 'pass' is used as the value
142 # This example should work if 'pass' is used as the value
144 with self.subTest((test_name, 'pass')):
143 with self.subTest((test_name, 'pass')):
145 iprc_err(test_case.format(val='pass'))
144 iprc(test_case.format(val='pass'))
146
145
147 # It should fail with all the values
146 # It should fail with all the values
148 for val in vals:
147 for val in vals:
149 with self.subTest((test_name, val)):
148 with self.subTest((test_name, val)):
150 msg = "Syntax error not raised for %s, %s" % (test_name, val)
149 msg = "Syntax error not raised for %s, %s" % (test_name, val)
151 with self.assertRaises(SyntaxError, msg=msg):
150 with self.assertRaises(SyntaxError, msg=msg):
152 iprc_err(test_case.format(val=val))
151 iprc(test_case.format(val=val))
153
152
154 def test_in_func_no_error(self):
153 def test_in_func_no_error(self):
155 # Test that the implementation of top-level return/yield
154 # Test that the implementation of top-level return/yield
156 # detection isn't *too* aggressive, and works inside a function
155 # detection isn't *too* aggressive, and works inside a function
157 func_contexts = []
156 func_contexts = []
158
157
159 func_contexts.append(('func', dedent("""
158 func_contexts.append(('func', dedent("""
160 def f():""")))
159 def f():""")))
161
160
162 func_contexts.append(('method', dedent("""
161 func_contexts.append(('method', dedent("""
163 class MyClass:
162 class MyClass:
164 def __init__(self):
163 def __init__(self):
165 """)))
164 """)))
166
165
167 func_contexts.append(('async-func', dedent("""
166 func_contexts.append(('async-func', dedent("""
168 async def f():""")))
167 async def f():""")))
169
168
170 func_contexts.append(('closure', dedent("""
169 func_contexts.append(('closure', dedent("""
171 def f():
170 def f():
172 def g():
171 def g():
173 """)))
172 """)))
174
173
175 def nest_case(context, case):
174 def nest_case(context, case):
176 # Detect indentation
175 # Detect indentation
177 lines = context.strip().splitlines()
176 lines = context.strip().splitlines()
178 prefix_len = 0
177 prefix_len = 0
179 for c in lines[-1]:
178 for c in lines[-1]:
180 if c != ' ':
179 if c != ' ':
181 break
180 break
182 prefix_len += 1
181 prefix_len += 1
183
182
184 indented_case = indent(case, ' ' * (prefix_len + 4))
183 indented_case = indent(case, ' ' * (prefix_len + 4))
185 return context + '\n' + indented_case
184 return context + '\n' + indented_case
186
185
187 # Gather and run the tests
186 # Gather and run the tests
188 vals = ('return', 'yield')
187 vals = ('return', 'yield')
189
188
190 success_tests = self._get_top_level_cases()
189 success_tests = self._get_top_level_cases()
191 failure_tests = self._get_ry_syntax_errors()
190 failure_tests = self._get_ry_syntax_errors()
192
191
193 for context_name, context in func_contexts:
192 for context_name, context in func_contexts:
194 # These tests should now successfully run
193 # These tests should now successfully run
195 for test_name, test_case in success_tests:
194 for test_name, test_case in success_tests:
196 nested_case = nest_case(context, test_case)
195 nested_case = nest_case(context, test_case)
197
196
198 for val in vals:
197 for val in vals:
199 with self.subTest((test_name, context_name, val)):
198 with self.subTest((test_name, context_name, val)):
200 iprc_err(nested_case.format(val=val))
199 iprc(nested_case.format(val=val))
201
200
202 # These tests should still raise a SyntaxError
201 # These tests should still raise a SyntaxError
203 for test_name, test_case in failure_tests:
202 for test_name, test_case in failure_tests:
204 nested_case = nest_case(context, test_case)
203 nested_case = nest_case(context, test_case)
205
204
206 for val in vals:
205 for val in vals:
207 with self.subTest((test_name, context_name, val)):
206 with self.subTest((test_name, context_name, val)):
208 with self.assertRaises(SyntaxError):
207 with self.assertRaises(SyntaxError):
209 iprc_err(nested_case.format(val=val))
208 iprc(nested_case.format(val=val))
210
209
211
210
212 def test_execute(self):
211 def test_execute(self):
213 iprc(
212 iprc("""
214 """
215 import asyncio
213 import asyncio
216 await asyncio.sleep(0.001)
214 await asyncio.sleep(0.001)
217 """
215 """
218 )
216 )
219
217
220 def test_autoawait(self):
218 def test_autoawait(self):
221 ip.run_cell("%autoawait False")
219 iprc("%autoawait False")
222 ip.run_cell("%autoawait True")
220 iprc("%autoawait True")
223 iprc(
221 iprc("""
224 """
222 from asyncio import sleep
225 from asyncio import sleep
223 await sleep(0.1)
226 await.sleep(0.1)
227 """
224 """
228 )
225 )
229
226
230 def test_autoawait_curio(self):
227 def test_autoawait_curio(self):
231 ip.run_cell("%autoawait curio")
228 iprc("%autoawait curio")
232
229
233 def test_autoawait_trio(self):
230 def test_autoawait_trio(self):
234 ip.run_cell("%autoawait trio")
231 iprc("%autoawait trio")
235
232
236 def tearDown(self):
233 def tearDown(self):
237 ip.loop_runner = "asyncio"
234 ip.loop_runner = "asyncio"
General Comments 0
You need to be logged in to leave comments. Login now