ยปCore Development>Code coverage>Lib/test/test_asyncgen.py

Python code coverage for Lib/test/test_asyncgen.py

#countcontent
1n/aimport inspect
2n/aimport types
3n/aimport unittest
4n/a
5n/afrom unittest import mock
6n/a
7n/afrom test.support import import_module
8n/aasyncio = import_module("asyncio")
9n/a
10n/a
11n/aclass AwaitException(Exception):
12n/a pass
13n/a
14n/a
15n/a@types.coroutine
16n/adef awaitable(*, throw=False):
17n/a if throw:
18n/a yield ('throw',)
19n/a else:
20n/a yield ('result',)
21n/a
22n/a
23n/adef run_until_complete(coro):
24n/a exc = False
25n/a while True:
26n/a try:
27n/a if exc:
28n/a exc = False
29n/a fut = coro.throw(AwaitException)
30n/a else:
31n/a fut = coro.send(None)
32n/a except StopIteration as ex:
33n/a return ex.args[0]
34n/a
35n/a if fut == ('throw',):
36n/a exc = True
37n/a
38n/a
39n/adef to_list(gen):
40n/a async def iterate():
41n/a res = []
42n/a async for i in gen:
43n/a res.append(i)
44n/a return res
45n/a
46n/a return run_until_complete(iterate())
47n/a
48n/a
49n/aclass AsyncGenSyntaxTest(unittest.TestCase):
50n/a
51n/a def test_async_gen_syntax_01(self):
52n/a code = '''async def foo():
53n/a await abc
54n/a yield from 123
55n/a '''
56n/a
57n/a with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
58n/a exec(code, {}, {})
59n/a
60n/a def test_async_gen_syntax_02(self):
61n/a code = '''async def foo():
62n/a yield from 123
63n/a '''
64n/a
65n/a with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
66n/a exec(code, {}, {})
67n/a
68n/a def test_async_gen_syntax_03(self):
69n/a code = '''async def foo():
70n/a await abc
71n/a yield
72n/a return 123
73n/a '''
74n/a
75n/a with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
76n/a exec(code, {}, {})
77n/a
78n/a def test_async_gen_syntax_04(self):
79n/a code = '''async def foo():
80n/a yield
81n/a return 123
82n/a '''
83n/a
84n/a with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
85n/a exec(code, {}, {})
86n/a
87n/a def test_async_gen_syntax_05(self):
88n/a code = '''async def foo():
89n/a if 0:
90n/a yield
91n/a return 12
92n/a '''
93n/a
94n/a with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
95n/a exec(code, {}, {})
96n/a
97n/a
98n/aclass AsyncGenTest(unittest.TestCase):
99n/a
100n/a def compare_generators(self, sync_gen, async_gen):
101n/a def sync_iterate(g):
102n/a res = []
103n/a while True:
104n/a try:
105n/a res.append(g.__next__())
106n/a except StopIteration:
107n/a res.append('STOP')
108n/a break
109n/a except Exception as ex:
110n/a res.append(str(type(ex)))
111n/a return res
112n/a
113n/a def async_iterate(g):
114n/a res = []
115n/a while True:
116n/a try:
117n/a g.__anext__().__next__()
118n/a except StopAsyncIteration:
119n/a res.append('STOP')
120n/a break
121n/a except StopIteration as ex:
122n/a if ex.args:
123n/a res.append(ex.args[0])
124n/a else:
125n/a res.append('EMPTY StopIteration')
126n/a break
127n/a except Exception as ex:
128n/a res.append(str(type(ex)))
129n/a return res
130n/a
131n/a sync_gen_result = sync_iterate(sync_gen)
132n/a async_gen_result = async_iterate(async_gen)
133n/a self.assertEqual(sync_gen_result, async_gen_result)
134n/a return async_gen_result
135n/a
136n/a def test_async_gen_iteration_01(self):
137n/a async def gen():
138n/a await awaitable()
139n/a a = yield 123
140n/a self.assertIs(a, None)
141n/a await awaitable()
142n/a yield 456
143n/a await awaitable()
144n/a yield 789
145n/a
146n/a self.assertEqual(to_list(gen()), [123, 456, 789])
147n/a
148n/a def test_async_gen_iteration_02(self):
149n/a async def gen():
150n/a await awaitable()
151n/a yield 123
152n/a await awaitable()
153n/a
154n/a g = gen()
155n/a ai = g.__aiter__()
156n/a self.assertEqual(ai.__anext__().__next__(), ('result',))
157n/a
158n/a try:
159n/a ai.__anext__().__next__()
160n/a except StopIteration as ex:
161n/a self.assertEqual(ex.args[0], 123)
162n/a else:
163n/a self.fail('StopIteration was not raised')
164n/a
165n/a self.assertEqual(ai.__anext__().__next__(), ('result',))
166n/a
167n/a try:
168n/a ai.__anext__().__next__()
169n/a except StopAsyncIteration as ex:
170n/a self.assertFalse(ex.args)
171n/a else:
172n/a self.fail('StopAsyncIteration was not raised')
173n/a
174n/a def test_async_gen_exception_03(self):
175n/a async def gen():
176n/a await awaitable()
177n/a yield 123
178n/a await awaitable(throw=True)
179n/a yield 456
180n/a
181n/a with self.assertRaises(AwaitException):
182n/a to_list(gen())
183n/a
184n/a def test_async_gen_exception_04(self):
185n/a async def gen():
186n/a await awaitable()
187n/a yield 123
188n/a 1 / 0
189n/a
190n/a g = gen()
191n/a ai = g.__aiter__()
192n/a self.assertEqual(ai.__anext__().__next__(), ('result',))
193n/a
194n/a try:
195n/a ai.__anext__().__next__()
196n/a except StopIteration as ex:
197n/a self.assertEqual(ex.args[0], 123)
198n/a else:
199n/a self.fail('StopIteration was not raised')
200n/a
201n/a with self.assertRaises(ZeroDivisionError):
202n/a ai.__anext__().__next__()
203n/a
204n/a def test_async_gen_exception_05(self):
205n/a async def gen():
206n/a yield 123
207n/a raise StopAsyncIteration
208n/a
209n/a with self.assertRaisesRegex(RuntimeError,
210n/a 'async generator.*StopAsyncIteration'):
211n/a to_list(gen())
212n/a
213n/a def test_async_gen_exception_06(self):
214n/a async def gen():
215n/a yield 123
216n/a raise StopIteration
217n/a
218n/a with self.assertRaisesRegex(RuntimeError,
219n/a 'async generator.*StopIteration'):
220n/a to_list(gen())
221n/a
222n/a def test_async_gen_exception_07(self):
223n/a def sync_gen():
224n/a try:
225n/a yield 1
226n/a 1 / 0
227n/a finally:
228n/a yield 2
229n/a yield 3
230n/a
231n/a yield 100
232n/a
233n/a async def async_gen():
234n/a try:
235n/a yield 1
236n/a 1 / 0
237n/a finally:
238n/a yield 2
239n/a yield 3
240n/a
241n/a yield 100
242n/a
243n/a self.compare_generators(sync_gen(), async_gen())
244n/a
245n/a def test_async_gen_exception_08(self):
246n/a def sync_gen():
247n/a try:
248n/a yield 1
249n/a finally:
250n/a yield 2
251n/a 1 / 0
252n/a yield 3
253n/a
254n/a yield 100
255n/a
256n/a async def async_gen():
257n/a try:
258n/a yield 1
259n/a await awaitable()
260n/a finally:
261n/a await awaitable()
262n/a yield 2
263n/a 1 / 0
264n/a yield 3
265n/a
266n/a yield 100
267n/a
268n/a self.compare_generators(sync_gen(), async_gen())
269n/a
270n/a def test_async_gen_exception_09(self):
271n/a def sync_gen():
272n/a try:
273n/a yield 1
274n/a 1 / 0
275n/a finally:
276n/a yield 2
277n/a yield 3
278n/a
279n/a yield 100
280n/a
281n/a async def async_gen():
282n/a try:
283n/a await awaitable()
284n/a yield 1
285n/a 1 / 0
286n/a finally:
287n/a yield 2
288n/a await awaitable()
289n/a yield 3
290n/a
291n/a yield 100
292n/a
293n/a self.compare_generators(sync_gen(), async_gen())
294n/a
295n/a def test_async_gen_exception_10(self):
296n/a async def gen():
297n/a yield 123
298n/a with self.assertRaisesRegex(TypeError,
299n/a "non-None value .* async generator"):
300n/a gen().__anext__().send(100)
301n/a
302n/a def test_async_gen_api_01(self):
303n/a async def gen():
304n/a yield 123
305n/a
306n/a g = gen()
307n/a
308n/a self.assertEqual(g.__name__, 'gen')
309n/a g.__name__ = '123'
310n/a self.assertEqual(g.__name__, '123')
311n/a
312n/a self.assertIn('.gen', g.__qualname__)
313n/a g.__qualname__ = '123'
314n/a self.assertEqual(g.__qualname__, '123')
315n/a
316n/a self.assertIsNone(g.ag_await)
317n/a self.assertIsInstance(g.ag_frame, types.FrameType)
318n/a self.assertFalse(g.ag_running)
319n/a self.assertIsInstance(g.ag_code, types.CodeType)
320n/a
321n/a self.assertTrue(inspect.isawaitable(g.aclose()))
322n/a
323n/a
324n/aclass AsyncGenAsyncioTest(unittest.TestCase):
325n/a
326n/a def setUp(self):
327n/a self.loop = asyncio.new_event_loop()
328n/a asyncio.set_event_loop(None)
329n/a
330n/a def tearDown(self):
331n/a self.loop.close()
332n/a self.loop = None
333n/a
334n/a async def to_list(self, gen):
335n/a res = []
336n/a async for i in gen:
337n/a res.append(i)
338n/a return res
339n/a
340n/a def test_async_gen_asyncio_01(self):
341n/a async def gen():
342n/a yield 1
343n/a await asyncio.sleep(0.01, loop=self.loop)
344n/a yield 2
345n/a await asyncio.sleep(0.01, loop=self.loop)
346n/a return
347n/a yield 3
348n/a
349n/a res = self.loop.run_until_complete(self.to_list(gen()))
350n/a self.assertEqual(res, [1, 2])
351n/a
352n/a def test_async_gen_asyncio_02(self):
353n/a async def gen():
354n/a yield 1
355n/a await asyncio.sleep(0.01, loop=self.loop)
356n/a yield 2
357n/a 1 / 0
358n/a yield 3
359n/a
360n/a with self.assertRaises(ZeroDivisionError):
361n/a self.loop.run_until_complete(self.to_list(gen()))
362n/a
363n/a def test_async_gen_asyncio_03(self):
364n/a loop = self.loop
365n/a
366n/a class Gen:
367n/a async def __aiter__(self):
368n/a yield 1
369n/a await asyncio.sleep(0.01, loop=loop)
370n/a yield 2
371n/a
372n/a res = loop.run_until_complete(self.to_list(Gen()))
373n/a self.assertEqual(res, [1, 2])
374n/a
375n/a def test_async_gen_asyncio_anext_04(self):
376n/a async def foo():
377n/a yield 1
378n/a await asyncio.sleep(0.01, loop=self.loop)
379n/a try:
380n/a yield 2
381n/a yield 3
382n/a except ZeroDivisionError:
383n/a yield 1000
384n/a await asyncio.sleep(0.01, loop=self.loop)
385n/a yield 4
386n/a
387n/a async def run1():
388n/a it = foo().__aiter__()
389n/a
390n/a self.assertEqual(await it.__anext__(), 1)
391n/a self.assertEqual(await it.__anext__(), 2)
392n/a self.assertEqual(await it.__anext__(), 3)
393n/a self.assertEqual(await it.__anext__(), 4)
394n/a with self.assertRaises(StopAsyncIteration):
395n/a await it.__anext__()
396n/a with self.assertRaises(StopAsyncIteration):
397n/a await it.__anext__()
398n/a
399n/a async def run2():
400n/a it = foo().__aiter__()
401n/a
402n/a self.assertEqual(await it.__anext__(), 1)
403n/a self.assertEqual(await it.__anext__(), 2)
404n/a try:
405n/a it.__anext__().throw(ZeroDivisionError)
406n/a except StopIteration as ex:
407n/a self.assertEqual(ex.args[0], 1000)
408n/a else:
409n/a self.fail('StopIteration was not raised')
410n/a self.assertEqual(await it.__anext__(), 4)
411n/a with self.assertRaises(StopAsyncIteration):
412n/a await it.__anext__()
413n/a
414n/a self.loop.run_until_complete(run1())
415n/a self.loop.run_until_complete(run2())
416n/a
417n/a def test_async_gen_asyncio_anext_05(self):
418n/a async def foo():
419n/a v = yield 1
420n/a v = yield v
421n/a yield v * 100
422n/a
423n/a async def run():
424n/a it = foo().__aiter__()
425n/a
426n/a try:
427n/a it.__anext__().send(None)
428n/a except StopIteration as ex:
429n/a self.assertEqual(ex.args[0], 1)
430n/a else:
431n/a self.fail('StopIteration was not raised')
432n/a
433n/a try:
434n/a it.__anext__().send(10)
435n/a except StopIteration as ex:
436n/a self.assertEqual(ex.args[0], 10)
437n/a else:
438n/a self.fail('StopIteration was not raised')
439n/a
440n/a try:
441n/a it.__anext__().send(12)
442n/a except StopIteration as ex:
443n/a self.assertEqual(ex.args[0], 1200)
444n/a else:
445n/a self.fail('StopIteration was not raised')
446n/a
447n/a with self.assertRaises(StopAsyncIteration):
448n/a await it.__anext__()
449n/a
450n/a self.loop.run_until_complete(run())
451n/a
452n/a def test_async_gen_asyncio_anext_06(self):
453n/a DONE = 0
454n/a
455n/a # test synchronous generators
456n/a def foo():
457n/a try:
458n/a yield
459n/a except:
460n/a pass
461n/a g = foo()
462n/a g.send(None)
463n/a with self.assertRaises(StopIteration):
464n/a g.send(None)
465n/a
466n/a # now with asynchronous generators
467n/a
468n/a async def gen():
469n/a nonlocal DONE
470n/a try:
471n/a yield
472n/a except:
473n/a pass
474n/a DONE = 1
475n/a
476n/a async def run():
477n/a nonlocal DONE
478n/a g = gen()
479n/a await g.asend(None)
480n/a with self.assertRaises(StopAsyncIteration):
481n/a await g.asend(None)
482n/a DONE += 10
483n/a
484n/a self.loop.run_until_complete(run())
485n/a self.assertEqual(DONE, 11)
486n/a
487n/a def test_async_gen_asyncio_anext_tuple(self):
488n/a async def foo():
489n/a try:
490n/a yield (1,)
491n/a except ZeroDivisionError:
492n/a yield (2,)
493n/a
494n/a async def run():
495n/a it = foo().__aiter__()
496n/a
497n/a self.assertEqual(await it.__anext__(), (1,))
498n/a with self.assertRaises(StopIteration) as cm:
499n/a it.__anext__().throw(ZeroDivisionError)
500n/a self.assertEqual(cm.exception.args[0], (2,))
501n/a with self.assertRaises(StopAsyncIteration):
502n/a await it.__anext__()
503n/a
504n/a self.loop.run_until_complete(run())
505n/a
506n/a def test_async_gen_asyncio_anext_stopiteration(self):
507n/a async def foo():
508n/a try:
509n/a yield StopIteration(1)
510n/a except ZeroDivisionError:
511n/a yield StopIteration(3)
512n/a
513n/a async def run():
514n/a it = foo().__aiter__()
515n/a
516n/a v = await it.__anext__()
517n/a self.assertIsInstance(v, StopIteration)
518n/a self.assertEqual(v.value, 1)
519n/a with self.assertRaises(StopIteration) as cm:
520n/a it.__anext__().throw(ZeroDivisionError)
521n/a v = cm.exception.args[0]
522n/a self.assertIsInstance(v, StopIteration)
523n/a self.assertEqual(v.value, 3)
524n/a with self.assertRaises(StopAsyncIteration):
525n/a await it.__anext__()
526n/a
527n/a self.loop.run_until_complete(run())
528n/a
529n/a def test_async_gen_asyncio_aclose_06(self):
530n/a async def foo():
531n/a try:
532n/a yield 1
533n/a 1 / 0
534n/a finally:
535n/a await asyncio.sleep(0.01, loop=self.loop)
536n/a yield 12
537n/a
538n/a async def run():
539n/a gen = foo()
540n/a it = gen.__aiter__()
541n/a await it.__anext__()
542n/a await gen.aclose()
543n/a
544n/a with self.assertRaisesRegex(
545n/a RuntimeError,
546n/a "async generator ignored GeneratorExit"):
547n/a self.loop.run_until_complete(run())
548n/a
549n/a def test_async_gen_asyncio_aclose_07(self):
550n/a DONE = 0
551n/a
552n/a async def foo():
553n/a nonlocal DONE
554n/a try:
555n/a yield 1
556n/a 1 / 0
557n/a finally:
558n/a await asyncio.sleep(0.01, loop=self.loop)
559n/a await asyncio.sleep(0.01, loop=self.loop)
560n/a DONE += 1
561n/a DONE += 1000
562n/a
563n/a async def run():
564n/a gen = foo()
565n/a it = gen.__aiter__()
566n/a await it.__anext__()
567n/a await gen.aclose()
568n/a
569n/a self.loop.run_until_complete(run())
570n/a self.assertEqual(DONE, 1)
571n/a
572n/a def test_async_gen_asyncio_aclose_08(self):
573n/a DONE = 0
574n/a
575n/a fut = asyncio.Future(loop=self.loop)
576n/a
577n/a async def foo():
578n/a nonlocal DONE
579n/a try:
580n/a yield 1
581n/a await fut
582n/a DONE += 1000
583n/a yield 2
584n/a finally:
585n/a await asyncio.sleep(0.01, loop=self.loop)
586n/a await asyncio.sleep(0.01, loop=self.loop)
587n/a DONE += 1
588n/a DONE += 1000
589n/a
590n/a async def run():
591n/a gen = foo()
592n/a it = gen.__aiter__()
593n/a self.assertEqual(await it.__anext__(), 1)
594n/a t = self.loop.create_task(it.__anext__())
595n/a await asyncio.sleep(0.01, loop=self.loop)
596n/a await gen.aclose()
597n/a return t
598n/a
599n/a t = self.loop.run_until_complete(run())
600n/a self.assertEqual(DONE, 1)
601n/a
602n/a # Silence ResourceWarnings
603n/a fut.cancel()
604n/a t.cancel()
605n/a self.loop.run_until_complete(asyncio.sleep(0.01, loop=self.loop))
606n/a
607n/a def test_async_gen_asyncio_gc_aclose_09(self):
608n/a DONE = 0
609n/a
610n/a async def gen():
611n/a nonlocal DONE
612n/a try:
613n/a while True:
614n/a yield 1
615n/a finally:
616n/a await asyncio.sleep(0.01, loop=self.loop)
617n/a await asyncio.sleep(0.01, loop=self.loop)
618n/a DONE = 1
619n/a
620n/a async def run():
621n/a g = gen()
622n/a await g.__anext__()
623n/a await g.__anext__()
624n/a del g
625n/a
626n/a await asyncio.sleep(0.1, loop=self.loop)
627n/a
628n/a self.loop.run_until_complete(run())
629n/a self.assertEqual(DONE, 1)
630n/a
631n/a def test_async_gen_asyncio_aclose_10(self):
632n/a DONE = 0
633n/a
634n/a # test synchronous generators
635n/a def foo():
636n/a try:
637n/a yield
638n/a except:
639n/a pass
640n/a g = foo()
641n/a g.send(None)
642n/a g.close()
643n/a
644n/a # now with asynchronous generators
645n/a
646n/a async def gen():
647n/a nonlocal DONE
648n/a try:
649n/a yield
650n/a except:
651n/a pass
652n/a DONE = 1
653n/a
654n/a async def run():
655n/a nonlocal DONE
656n/a g = gen()
657n/a await g.asend(None)
658n/a await g.aclose()
659n/a DONE += 10
660n/a
661n/a self.loop.run_until_complete(run())
662n/a self.assertEqual(DONE, 11)
663n/a
664n/a def test_async_gen_asyncio_aclose_11(self):
665n/a DONE = 0
666n/a
667n/a # test synchronous generators
668n/a def foo():
669n/a try:
670n/a yield
671n/a except:
672n/a pass
673n/a yield
674n/a g = foo()
675n/a g.send(None)
676n/a with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
677n/a g.close()
678n/a
679n/a # now with asynchronous generators
680n/a
681n/a async def gen():
682n/a nonlocal DONE
683n/a try:
684n/a yield
685n/a except:
686n/a pass
687n/a yield
688n/a DONE += 1
689n/a
690n/a async def run():
691n/a nonlocal DONE
692n/a g = gen()
693n/a await g.asend(None)
694n/a with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
695n/a await g.aclose()
696n/a DONE += 10
697n/a
698n/a self.loop.run_until_complete(run())
699n/a self.assertEqual(DONE, 10)
700n/a
701n/a def test_async_gen_asyncio_asend_01(self):
702n/a DONE = 0
703n/a
704n/a # Sanity check:
705n/a def sgen():
706n/a v = yield 1
707n/a yield v * 2
708n/a sg = sgen()
709n/a v = sg.send(None)
710n/a self.assertEqual(v, 1)
711n/a v = sg.send(100)
712n/a self.assertEqual(v, 200)
713n/a
714n/a async def gen():
715n/a nonlocal DONE
716n/a try:
717n/a await asyncio.sleep(0.01, loop=self.loop)
718n/a v = yield 1
719n/a await asyncio.sleep(0.01, loop=self.loop)
720n/a yield v * 2
721n/a await asyncio.sleep(0.01, loop=self.loop)
722n/a return
723n/a finally:
724n/a await asyncio.sleep(0.01, loop=self.loop)
725n/a await asyncio.sleep(0.01, loop=self.loop)
726n/a DONE = 1
727n/a
728n/a async def run():
729n/a g = gen()
730n/a
731n/a v = await g.asend(None)
732n/a self.assertEqual(v, 1)
733n/a
734n/a v = await g.asend(100)
735n/a self.assertEqual(v, 200)
736n/a
737n/a with self.assertRaises(StopAsyncIteration):
738n/a await g.asend(None)
739n/a
740n/a self.loop.run_until_complete(run())
741n/a self.assertEqual(DONE, 1)
742n/a
743n/a def test_async_gen_asyncio_asend_02(self):
744n/a DONE = 0
745n/a
746n/a async def sleep_n_crash(delay):
747n/a await asyncio.sleep(delay, loop=self.loop)
748n/a 1 / 0
749n/a
750n/a async def gen():
751n/a nonlocal DONE
752n/a try:
753n/a await asyncio.sleep(0.01, loop=self.loop)
754n/a v = yield 1
755n/a await sleep_n_crash(0.01)
756n/a DONE += 1000
757n/a yield v * 2
758n/a finally:
759n/a await asyncio.sleep(0.01, loop=self.loop)
760n/a await asyncio.sleep(0.01, loop=self.loop)
761n/a DONE = 1
762n/a
763n/a async def run():
764n/a g = gen()
765n/a
766n/a v = await g.asend(None)
767n/a self.assertEqual(v, 1)
768n/a
769n/a await g.asend(100)
770n/a
771n/a with self.assertRaises(ZeroDivisionError):
772n/a self.loop.run_until_complete(run())
773n/a self.assertEqual(DONE, 1)
774n/a
775n/a def test_async_gen_asyncio_asend_03(self):
776n/a DONE = 0
777n/a
778n/a async def sleep_n_crash(delay):
779n/a fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),
780n/a loop=self.loop)
781n/a self.loop.call_later(delay / 2, lambda: fut.cancel())
782n/a return await fut
783n/a
784n/a async def gen():
785n/a nonlocal DONE
786n/a try:
787n/a await asyncio.sleep(0.01, loop=self.loop)
788n/a v = yield 1
789n/a await sleep_n_crash(0.01)
790n/a DONE += 1000
791n/a yield v * 2
792n/a finally:
793n/a await asyncio.sleep(0.01, loop=self.loop)
794n/a await asyncio.sleep(0.01, loop=self.loop)
795n/a DONE = 1
796n/a
797n/a async def run():
798n/a g = gen()
799n/a
800n/a v = await g.asend(None)
801n/a self.assertEqual(v, 1)
802n/a
803n/a await g.asend(100)
804n/a
805n/a with self.assertRaises(asyncio.CancelledError):
806n/a self.loop.run_until_complete(run())
807n/a self.assertEqual(DONE, 1)
808n/a
809n/a def test_async_gen_asyncio_athrow_01(self):
810n/a DONE = 0
811n/a
812n/a class FooEr(Exception):
813n/a pass
814n/a
815n/a # Sanity check:
816n/a def sgen():
817n/a try:
818n/a v = yield 1
819n/a except FooEr:
820n/a v = 1000
821n/a yield v * 2
822n/a sg = sgen()
823n/a v = sg.send(None)
824n/a self.assertEqual(v, 1)
825n/a v = sg.throw(FooEr)
826n/a self.assertEqual(v, 2000)
827n/a with self.assertRaises(StopIteration):
828n/a sg.send(None)
829n/a
830n/a async def gen():
831n/a nonlocal DONE
832n/a try:
833n/a await asyncio.sleep(0.01, loop=self.loop)
834n/a try:
835n/a v = yield 1
836n/a except FooEr:
837n/a v = 1000
838n/a await asyncio.sleep(0.01, loop=self.loop)
839n/a yield v * 2
840n/a await asyncio.sleep(0.01, loop=self.loop)
841n/a # return
842n/a finally:
843n/a await asyncio.sleep(0.01, loop=self.loop)
844n/a await asyncio.sleep(0.01, loop=self.loop)
845n/a DONE = 1
846n/a
847n/a async def run():
848n/a g = gen()
849n/a
850n/a v = await g.asend(None)
851n/a self.assertEqual(v, 1)
852n/a
853n/a v = await g.athrow(FooEr)
854n/a self.assertEqual(v, 2000)
855n/a
856n/a with self.assertRaises(StopAsyncIteration):
857n/a await g.asend(None)
858n/a
859n/a self.loop.run_until_complete(run())
860n/a self.assertEqual(DONE, 1)
861n/a
862n/a def test_async_gen_asyncio_athrow_02(self):
863n/a DONE = 0
864n/a
865n/a class FooEr(Exception):
866n/a pass
867n/a
868n/a async def sleep_n_crash(delay):
869n/a fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),
870n/a loop=self.loop)
871n/a self.loop.call_later(delay / 2, lambda: fut.cancel())
872n/a return await fut
873n/a
874n/a async def gen():
875n/a nonlocal DONE
876n/a try:
877n/a await asyncio.sleep(0.01, loop=self.loop)
878n/a try:
879n/a v = yield 1
880n/a except FooEr:
881n/a await sleep_n_crash(0.01)
882n/a yield v * 2
883n/a await asyncio.sleep(0.01, loop=self.loop)
884n/a # return
885n/a finally:
886n/a await asyncio.sleep(0.01, loop=self.loop)
887n/a await asyncio.sleep(0.01, loop=self.loop)
888n/a DONE = 1
889n/a
890n/a async def run():
891n/a g = gen()
892n/a
893n/a v = await g.asend(None)
894n/a self.assertEqual(v, 1)
895n/a
896n/a try:
897n/a await g.athrow(FooEr)
898n/a except asyncio.CancelledError:
899n/a self.assertEqual(DONE, 1)
900n/a raise
901n/a else:
902n/a self.fail('CancelledError was not raised')
903n/a
904n/a with self.assertRaises(asyncio.CancelledError):
905n/a self.loop.run_until_complete(run())
906n/a self.assertEqual(DONE, 1)
907n/a
908n/a def test_async_gen_asyncio_athrow_03(self):
909n/a DONE = 0
910n/a
911n/a # test synchronous generators
912n/a def foo():
913n/a try:
914n/a yield
915n/a except:
916n/a pass
917n/a g = foo()
918n/a g.send(None)
919n/a with self.assertRaises(StopIteration):
920n/a g.throw(ValueError)
921n/a
922n/a # now with asynchronous generators
923n/a
924n/a async def gen():
925n/a nonlocal DONE
926n/a try:
927n/a yield
928n/a except:
929n/a pass
930n/a DONE = 1
931n/a
932n/a async def run():
933n/a nonlocal DONE
934n/a g = gen()
935n/a await g.asend(None)
936n/a with self.assertRaises(StopAsyncIteration):
937n/a await g.athrow(ValueError)
938n/a DONE += 10
939n/a
940n/a self.loop.run_until_complete(run())
941n/a self.assertEqual(DONE, 11)
942n/a
943n/a def test_async_gen_asyncio_athrow_tuple(self):
944n/a async def gen():
945n/a try:
946n/a yield 1
947n/a except ZeroDivisionError:
948n/a yield (2,)
949n/a
950n/a async def run():
951n/a g = gen()
952n/a v = await g.asend(None)
953n/a self.assertEqual(v, 1)
954n/a v = await g.athrow(ZeroDivisionError)
955n/a self.assertEqual(v, (2,))
956n/a with self.assertRaises(StopAsyncIteration):
957n/a await g.asend(None)
958n/a
959n/a self.loop.run_until_complete(run())
960n/a
961n/a def test_async_gen_asyncio_athrow_stopiteration(self):
962n/a async def gen():
963n/a try:
964n/a yield 1
965n/a except ZeroDivisionError:
966n/a yield StopIteration(2)
967n/a
968n/a async def run():
969n/a g = gen()
970n/a v = await g.asend(None)
971n/a self.assertEqual(v, 1)
972n/a v = await g.athrow(ZeroDivisionError)
973n/a self.assertIsInstance(v, StopIteration)
974n/a self.assertEqual(v.value, 2)
975n/a with self.assertRaises(StopAsyncIteration):
976n/a await g.asend(None)
977n/a
978n/a self.loop.run_until_complete(run())
979n/a
980n/a def test_async_gen_asyncio_shutdown_01(self):
981n/a finalized = 0
982n/a
983n/a async def waiter(timeout):
984n/a nonlocal finalized
985n/a try:
986n/a await asyncio.sleep(timeout, loop=self.loop)
987n/a yield 1
988n/a finally:
989n/a await asyncio.sleep(0, loop=self.loop)
990n/a finalized += 1
991n/a
992n/a async def wait():
993n/a async for _ in waiter(1):
994n/a pass
995n/a
996n/a t1 = self.loop.create_task(wait())
997n/a t2 = self.loop.create_task(wait())
998n/a
999n/a self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))
1000n/a
1001n/a self.loop.run_until_complete(self.loop.shutdown_asyncgens())
1002n/a self.assertEqual(finalized, 2)
1003n/a
1004n/a # Silence warnings
1005n/a t1.cancel()
1006n/a t2.cancel()
1007n/a self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))
1008n/a
1009n/a def test_async_gen_asyncio_shutdown_02(self):
1010n/a logged = 0
1011n/a
1012n/a def logger(loop, context):
1013n/a nonlocal logged
1014n/a self.assertIn('asyncgen', context)
1015n/a expected = 'an error occurred during closing of asynchronous'
1016n/a if expected in context['message']:
1017n/a logged += 1
1018n/a
1019n/a async def waiter(timeout):
1020n/a try:
1021n/a await asyncio.sleep(timeout, loop=self.loop)
1022n/a yield 1
1023n/a finally:
1024n/a 1 / 0
1025n/a
1026n/a async def wait():
1027n/a async for _ in waiter(1):
1028n/a pass
1029n/a
1030n/a t = self.loop.create_task(wait())
1031n/a self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))
1032n/a
1033n/a self.loop.set_exception_handler(logger)
1034n/a self.loop.run_until_complete(self.loop.shutdown_asyncgens())
1035n/a
1036n/a self.assertEqual(logged, 1)
1037n/a
1038n/a # Silence warnings
1039n/a t.cancel()
1040n/a self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))
1041n/a
1042n/aif __name__ == "__main__":
1043n/a unittest.main()