Debian Codegraph @

tests/asyncio_test.py

raw
1 """Tests for asyncio integration."""
2
3 import pytest
4
5 import eventlet
6 from eventlet.hubs import get_hub
7 from eventlet.hubs.asyncio import Hub as AsyncioHub
8 if not isinstance(get_hub(), AsyncioHub):
9 pytest.skip("Only works on asyncio hub", allow_module_level=True)
10
11 import asyncio
12 from time import time
13 import socket
14 import sys
15
16 from greenlet import GreenletExit
17
18 from eventlet.asyncio import spawn_for_awaitable
19 from eventlet.greenthread import getcurrent
20 from eventlet.support import greendns
21 from .wsgi_test import _TestBase, Site
22
23 import tests
24
25
26 class CallingAsyncFunctionsFromGreenletsHighLevelTests(_TestBase):
27 """
28 High-level tests for using ``asyncio``-based code inside greenlets.
29
30 For this functionality to be useful, users need to be able to use 3rd party
31 libraries that use sockets etc.. Merely hooking up futures to greenlets
32 doesn't help if you can't use the asyncio library ecosystem. So this set
33 of tests does more integration-y tests showing that functionality works.
34 """
35
36 def set_site(self):
37 self.site = Site()
38
39 def test_aiohttp_client(self):
40 """
41 The ``aiohttp`` HTTP client works correctly on top of eventlet.
42 """
43 import aiohttp
44
45 async def request():
46 host, port = self.server_addr
47 async with aiohttp.ClientSession() as session:
48 url = "http://{}:{}/".format(host, port)
49 async with session.get(url) as response:
50 html = await response.text()
51 return html
52
53 gthread = spawn_for_awaitable(request())
54 assert gthread.wait() == "hello world"
55
56
57 def test_result():
58 """
59 The result of the coroutine is returned by the ``GreenThread`` created by
60 ``spawn_for_awaitable``.
61 """
62
63 async def go():
64 await asyncio.sleep(0.0001)
65 return 13
66
67 assert spawn_for_awaitable(go()).wait() == 13
68
69
70 def test_exception():
71 """
72 An exception raised by the coroutine is raised by ``GreenThread.wait()``
73 for the green thread created by ``spawn_for_awaitable()``.
74 """
75
76 async def go():
77 await asyncio.sleep(0.0001)
78 raise ZeroDivisionError()
79
80 with pytest.raises(ZeroDivisionError):
81 assert spawn_for_awaitable(go()).wait()
82
83
84 def test_future_and_task():
85 """
86 ``spawn_for_awaitable()`` can take an ``asyncio.Future`` or an
87 ``asyncio.Task``.
88 """
89
90 async def go(value):
91 return value * 2
92
93 assert spawn_for_awaitable(asyncio.ensure_future(go(8))).wait() == 16
94 assert spawn_for_awaitable(asyncio.create_task(go(6))).wait() == 12
95
96
97 def test_asyncio_sleep():
98 """
99 ``asyncio`` scheduled events work on eventlet.
100 """
101
102 async def go():
103 start = time()
104 await asyncio.sleep(0.07)
105 return time() - start
106
107 elapsed = spawn_for_awaitable(go()).wait()
108 assert 0.05 < elapsed < 0.09
109
110
111 def test_kill_greenthread():
112 """
113 If a ``GreenThread`` wrapping an ``asyncio.Future``/coroutine is killed,
114 the ``asyncio.Future`` is cancelled.
115 """
116
117 the_greenthread = []
118 progress = []
119
120 async def go():
121 await asyncio.sleep(0.1)
122 progress.append(1)
123 while not the_greenthread:
124 await asyncio.sleep(0.001)
125 # Kill the green thread.
126 progress.append(2)
127 the_greenthread[0].kill()
128 progress.append(3)
129 await asyncio.sleep(1)
130 # This should never be reached:
131 progress.append(4)
132
133 future = asyncio.ensure_future(go())
134 the_greenthread.append(spawn_for_awaitable(future))
135 with pytest.raises(GreenletExit):
136 the_greenthread[0].wait()
137 assert progress == [1, 2, 3]
138 # Cancellation may not be immediate.
139 eventlet.sleep(0.01)
140 assert future.cancelled()
141 assert progress == [1, 2, 3]
142
143
144 def test_await_greenthread_success():
145 """
146 ``await`` on a ``GreenThread`` returns its eventual result.
147 """
148
149 def greenlet():
150 eventlet.sleep(0.001)
151 return 23
152
153 async def go():
154 result = await eventlet.spawn(greenlet)
155 return result
156
157 assert spawn_for_awaitable(go()).wait() == 23
158
159
160 def test_await_greenthread_exception():
161 """
162 ``await`` on a ``GreenThread`` raises its eventual exception.
163 """
164
165 def greenlet():
166 eventlet.sleep(0.001)
167 return 1 / 0
168
169 async def go():
170 try:
171 await eventlet.spawn(greenlet)
172 except ZeroDivisionError as e:
173 return e
174
175 result = spawn_for_awaitable(go()).wait()
176 assert isinstance(result, ZeroDivisionError)
177
178
179 def test_await_greenthread_success_immediate():
180 """
181 ``await`` on a ``GreenThread`` returns its immediate result.
182 """
183
184 def greenlet():
185 return 23
186
187 async def go():
188 result = await eventlet.spawn(greenlet)
189 return result
190
191 assert spawn_for_awaitable(go()).wait() == 23
192
193
194 def test_await_greenthread_exception_immediate():
195 """
196 ``await`` on a ``GreenThread`` raises its immediate exception.
197 """
198
199 def greenlet():
200 return 1 / 0
201
202 async def go():
203 try:
204 await eventlet.spawn(greenlet)
205 except ZeroDivisionError as e:
206 return e
207
208 result = spawn_for_awaitable(go()).wait()
209 assert isinstance(result, ZeroDivisionError)
210
211
212 def test_ensure_future():
213 """
214 ``asyncio.ensure_future()`` works correctly on a ``GreenThread``.
215 """
216
217 def greenlet():
218 eventlet.sleep(0.001)
219 return 27
220
221 async def go():
222 future = asyncio.ensure_future(eventlet.spawn(greenlet))
223 result = await future
224 return result
225
226 assert spawn_for_awaitable(go()).wait() == 27
227
228
229 def test_cancelling_future_kills_greenthread():
230 """
231 If the ``Future`` created by ``asyncio.ensure_future(a_green_thread)`` is
232 cancelled, the ``a_green_thread`` ``GreenThread`` is killed.
233 """
234
235 phases = []
236
237 def green():
238 phases.append(1)
239 future.cancel()
240 eventlet.sleep(1)
241 # This should never be reached:
242 phases.append(2)
243
244 gthread = eventlet.spawn(green)
245
246 async def go():
247 try:
248 await gthread
249 except asyncio.CancelledError:
250 return "good"
251 else:
252 return "bad"
253
254 future = asyncio.ensure_future(go())
255 assert spawn_for_awaitable(future).wait() == "good"
256
257 with pytest.raises(GreenletExit):
258 gthread.wait()
259 assert phases == [1]
260
261
262 def test_greenthread_killed_while_awaited():
263 """
264 If a ``GreenThread`` is killed, the ``async`` function ``await``ing it sees
265 it as cancellation.
266 """
267 phases = []
268
269 def green():
270 phases.append(1)
271 eventlet.sleep(0.001)
272 phases.append(2)
273 getcurrent().kill()
274 eventlet.sleep(1)
275 # Should never be reached:
276 phases.append(3)
277
278 gthread = eventlet.spawn(green)
279
280 async def go():
281 try:
282 await gthread
283 return "where is my cancellation?"
284 except asyncio.CancelledError:
285 return "canceled!"
286
287 assert spawn_for_awaitable(go()).wait() == "canceled!"
288 assert phases == [1, 2]
289
290
291 @pytest.mark.skipif(
292 sys.version_info[:2] < (3, 9), reason="to_thread() is new Python 3.9"
293 )
294 def test_asyncio_to_thread():
295 """
296 ``asyncio.to_thread()`` works with Eventlet.
297 """
298 tests.run_isolated("asyncio_to_thread.py")
299
300
301 def test_asyncio_does_not_use_greendns():
302 """
303 ``asyncio`` loops' ``getaddrinfo()`` and ``getnameinfo()`` do not use green
304 DNS.
305 """
306 tests.run_isolated("asyncio_dns.py")
307
308
309 def test_make_sure_monkey_patching_asyncio_is_restricted():
310 """
311 ``asyncio`` continues to have original, unpatched ``socket`` etc classes.
312 """
313 tests.run_isolated("asyncio_correct_patching.py")