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

Python code coverage for Lib/test/test_coroutines.py

#countcontent
1n/aimport contextlib
2n/aimport copy
3n/aimport inspect
4n/aimport pickle
5n/aimport sys
6n/aimport types
7n/aimport unittest
8n/aimport warnings
9n/afrom test import support
10n/a
11n/a
12n/aclass AsyncYieldFrom:
13n/a def __init__(self, obj):
14n/a self.obj = obj
15n/a
16n/a def __await__(self):
17n/a yield from self.obj
18n/a
19n/a
20n/aclass AsyncYield:
21n/a def __init__(self, value):
22n/a self.value = value
23n/a
24n/a def __await__(self):
25n/a yield self.value
26n/a
27n/a
28n/adef run_async(coro):
29n/a assert coro.__class__ in {types.GeneratorType, types.CoroutineType}
30n/a
31n/a buffer = []
32n/a result = None
33n/a while True:
34n/a try:
35n/a buffer.append(coro.send(None))
36n/a except StopIteration as ex:
37n/a result = ex.args[0] if ex.args else None
38n/a break
39n/a return buffer, result
40n/a
41n/a
42n/adef run_async__await__(coro):
43n/a assert coro.__class__ is types.CoroutineType
44n/a aw = coro.__await__()
45n/a buffer = []
46n/a result = None
47n/a i = 0
48n/a while True:
49n/a try:
50n/a if i % 2:
51n/a buffer.append(next(aw))
52n/a else:
53n/a buffer.append(aw.send(None))
54n/a i += 1
55n/a except StopIteration as ex:
56n/a result = ex.args[0] if ex.args else None
57n/a break
58n/a return buffer, result
59n/a
60n/a
61n/a@contextlib.contextmanager
62n/adef silence_coro_gc():
63n/a with warnings.catch_warnings():
64n/a warnings.simplefilter("ignore")
65n/a yield
66n/a support.gc_collect()
67n/a
68n/a
69n/aclass AsyncBadSyntaxTest(unittest.TestCase):
70n/a
71n/a def test_badsyntax_1(self):
72n/a samples = [
73n/a """def foo():
74n/a await something()
75n/a """,
76n/a
77n/a """await something()""",
78n/a
79n/a """async def foo():
80n/a yield from []
81n/a """,
82n/a
83n/a """async def foo():
84n/a await await fut
85n/a """,
86n/a
87n/a """async def foo(a=await something()):
88n/a pass
89n/a """,
90n/a
91n/a """async def foo(a:await something()):
92n/a pass
93n/a """,
94n/a
95n/a """async def foo():
96n/a def bar():
97n/a [i async for i in els]
98n/a """,
99n/a
100n/a """async def foo():
101n/a def bar():
102n/a [await i for i in els]
103n/a """,
104n/a
105n/a """async def foo():
106n/a def bar():
107n/a [i for i in els
108n/a async for b in els]
109n/a """,
110n/a
111n/a """async def foo():
112n/a def bar():
113n/a [i for i in els
114n/a for c in b
115n/a async for b in els]
116n/a """,
117n/a
118n/a """async def foo():
119n/a def bar():
120n/a [i for i in els
121n/a async for b in els
122n/a for c in b]
123n/a """,
124n/a
125n/a """async def foo():
126n/a def bar():
127n/a [i for i in els
128n/a for b in await els]
129n/a """,
130n/a
131n/a """async def foo():
132n/a def bar():
133n/a [i for i in els
134n/a for b in els
135n/a if await b]
136n/a """,
137n/a
138n/a """async def foo():
139n/a def bar():
140n/a [i for i in await els]
141n/a """,
142n/a
143n/a """async def foo():
144n/a def bar():
145n/a [i for i in els if await i]
146n/a """,
147n/a
148n/a """def bar():
149n/a [i async for i in els]
150n/a """,
151n/a
152n/a """def bar():
153n/a [await i for i in els]
154n/a """,
155n/a
156n/a """def bar():
157n/a [i for i in els
158n/a async for b in els]
159n/a """,
160n/a
161n/a """def bar():
162n/a [i for i in els
163n/a for c in b
164n/a async for b in els]
165n/a """,
166n/a
167n/a """def bar():
168n/a [i for i in els
169n/a async for b in els
170n/a for c in b]
171n/a """,
172n/a
173n/a """def bar():
174n/a [i for i in els
175n/a for b in await els]
176n/a """,
177n/a
178n/a """def bar():
179n/a [i for i in els
180n/a for b in els
181n/a if await b]
182n/a """,
183n/a
184n/a """def bar():
185n/a [i for i in await els]
186n/a """,
187n/a
188n/a """def bar():
189n/a [i for i in els if await i]
190n/a """,
191n/a
192n/a """async def foo():
193n/a await
194n/a """,
195n/a
196n/a """async def foo():
197n/a def bar(): pass
198n/a await = 1
199n/a """,
200n/a
201n/a """async def foo():
202n/a
203n/a def bar(): pass
204n/a await = 1
205n/a """,
206n/a
207n/a """async def foo():
208n/a def bar(): pass
209n/a if 1:
210n/a await = 1
211n/a """,
212n/a
213n/a """def foo():
214n/a async def bar(): pass
215n/a if 1:
216n/a await a
217n/a """,
218n/a
219n/a """def foo():
220n/a async def bar(): pass
221n/a await a
222n/a """,
223n/a
224n/a """def foo():
225n/a def baz(): pass
226n/a async def bar(): pass
227n/a await a
228n/a """,
229n/a
230n/a """def foo():
231n/a def baz(): pass
232n/a # 456
233n/a async def bar(): pass
234n/a # 123
235n/a await a
236n/a """,
237n/a
238n/a """async def foo():
239n/a def baz(): pass
240n/a # 456
241n/a async def bar(): pass
242n/a # 123
243n/a await = 2
244n/a """,
245n/a
246n/a """def foo():
247n/a
248n/a def baz(): pass
249n/a
250n/a async def bar(): pass
251n/a
252n/a await a
253n/a """,
254n/a
255n/a """async def foo():
256n/a
257n/a def baz(): pass
258n/a
259n/a async def bar(): pass
260n/a
261n/a await = 2
262n/a """,
263n/a
264n/a """async def foo():
265n/a def async(): pass
266n/a """,
267n/a
268n/a """async def foo():
269n/a def await(): pass
270n/a """,
271n/a
272n/a """async def foo():
273n/a def bar():
274n/a await
275n/a """,
276n/a
277n/a """async def foo():
278n/a return lambda async: await
279n/a """,
280n/a
281n/a """async def foo():
282n/a return lambda a: await
283n/a """,
284n/a
285n/a """await a()""",
286n/a
287n/a """async def foo(a=await b):
288n/a pass
289n/a """,
290n/a
291n/a """async def foo(a:await b):
292n/a pass
293n/a """,
294n/a
295n/a """def baz():
296n/a async def foo(a=await b):
297n/a pass
298n/a """,
299n/a
300n/a """async def foo(async):
301n/a pass
302n/a """,
303n/a
304n/a """async def foo():
305n/a def bar():
306n/a def baz():
307n/a async = 1
308n/a """,
309n/a
310n/a """async def foo():
311n/a def bar():
312n/a def baz():
313n/a pass
314n/a async = 1
315n/a """,
316n/a
317n/a """def foo():
318n/a async def bar():
319n/a
320n/a async def baz():
321n/a pass
322n/a
323n/a def baz():
324n/a 42
325n/a
326n/a async = 1
327n/a """,
328n/a
329n/a """async def foo():
330n/a def bar():
331n/a def baz():
332n/a pass\nawait foo()
333n/a """,
334n/a
335n/a """def foo():
336n/a def bar():
337n/a async def baz():
338n/a pass\nawait foo()
339n/a """,
340n/a
341n/a """async def foo(await):
342n/a pass
343n/a """,
344n/a
345n/a """def foo():
346n/a
347n/a async def bar(): pass
348n/a
349n/a await a
350n/a """,
351n/a
352n/a """def foo():
353n/a async def bar():
354n/a pass\nawait a
355n/a """]
356n/a
357n/a for code in samples:
358n/a with self.subTest(code=code), self.assertRaises(SyntaxError):
359n/a compile(code, "<test>", "exec")
360n/a
361n/a def test_badsyntax_2(self):
362n/a samples = [
363n/a """def foo():
364n/a await = 1
365n/a """,
366n/a
367n/a """class Bar:
368n/a def async(): pass
369n/a """,
370n/a
371n/a """class Bar:
372n/a async = 1
373n/a """,
374n/a
375n/a """class async:
376n/a pass
377n/a """,
378n/a
379n/a """class await:
380n/a pass
381n/a """,
382n/a
383n/a """import math as await""",
384n/a
385n/a """def async():
386n/a pass""",
387n/a
388n/a """def foo(*, await=1):
389n/a pass"""
390n/a
391n/a """async = 1""",
392n/a
393n/a """print(await=1)"""
394n/a ]
395n/a
396n/a for code in samples:
397n/a with self.subTest(code=code), self.assertWarnsRegex(
398n/a DeprecationWarning,
399n/a "'await' will become reserved keywords"):
400n/a compile(code, "<test>", "exec")
401n/a
402n/a def test_badsyntax_3(self):
403n/a with self.assertRaises(DeprecationWarning):
404n/a with warnings.catch_warnings():
405n/a warnings.simplefilter("error")
406n/a compile("async = 1", "<test>", "exec")
407n/a
408n/a def test_goodsyntax_1(self):
409n/a # Tests for issue 24619
410n/a
411n/a samples = [
412n/a '''def foo(await):
413n/a async def foo(): pass
414n/a async def foo():
415n/a pass
416n/a return await + 1
417n/a ''',
418n/a
419n/a '''def foo(await):
420n/a async def foo(): pass
421n/a async def foo(): pass
422n/a return await + 1
423n/a ''',
424n/a
425n/a '''def foo(await):
426n/a
427n/a async def foo(): pass
428n/a
429n/a async def foo(): pass
430n/a
431n/a return await + 1
432n/a ''',
433n/a
434n/a '''def foo(await):
435n/a """spam"""
436n/a async def foo(): \
437n/a pass
438n/a # 123
439n/a async def foo(): pass
440n/a # 456
441n/a return await + 1
442n/a ''',
443n/a
444n/a '''def foo(await):
445n/a def foo(): pass
446n/a def foo(): pass
447n/a async def bar(): return await_
448n/a await_ = await
449n/a try:
450n/a bar().send(None)
451n/a except StopIteration as ex:
452n/a return ex.args[0] + 1
453n/a '''
454n/a ]
455n/a
456n/a for code in samples:
457n/a with self.subTest(code=code):
458n/a loc = {}
459n/a
460n/a with warnings.catch_warnings():
461n/a warnings.simplefilter("ignore")
462n/a exec(code, loc, loc)
463n/a
464n/a self.assertEqual(loc['foo'](10), 11)
465n/a
466n/a
467n/aclass TokenizerRegrTest(unittest.TestCase):
468n/a
469n/a def test_oneline_defs(self):
470n/a buf = []
471n/a for i in range(500):
472n/a buf.append('def i{i}(): return {i}'.format(i=i))
473n/a buf = '\n'.join(buf)
474n/a
475n/a # Test that 500 consequent, one-line defs is OK
476n/a ns = {}
477n/a exec(buf, ns, ns)
478n/a self.assertEqual(ns['i499'](), 499)
479n/a
480n/a # Test that 500 consequent, one-line defs *and*
481n/a # one 'async def' following them is OK
482n/a buf += '\nasync def foo():\n return'
483n/a ns = {}
484n/a exec(buf, ns, ns)
485n/a self.assertEqual(ns['i499'](), 499)
486n/a self.assertTrue(inspect.iscoroutinefunction(ns['foo']))
487n/a
488n/a
489n/aclass CoroutineTest(unittest.TestCase):
490n/a
491n/a def test_gen_1(self):
492n/a def gen(): yield
493n/a self.assertFalse(hasattr(gen, '__await__'))
494n/a
495n/a def test_func_1(self):
496n/a async def foo():
497n/a return 10
498n/a
499n/a f = foo()
500n/a self.assertIsInstance(f, types.CoroutineType)
501n/a self.assertTrue(bool(foo.__code__.co_flags & inspect.CO_COROUTINE))
502n/a self.assertFalse(bool(foo.__code__.co_flags & inspect.CO_GENERATOR))
503n/a self.assertTrue(bool(f.cr_code.co_flags & inspect.CO_COROUTINE))
504n/a self.assertFalse(bool(f.cr_code.co_flags & inspect.CO_GENERATOR))
505n/a self.assertEqual(run_async(f), ([], 10))
506n/a
507n/a self.assertEqual(run_async__await__(foo()), ([], 10))
508n/a
509n/a def bar(): pass
510n/a self.assertFalse(bool(bar.__code__.co_flags & inspect.CO_COROUTINE))
511n/a
512n/a def test_func_2(self):
513n/a async def foo():
514n/a raise StopIteration
515n/a
516n/a with self.assertRaisesRegex(
517n/a RuntimeError, "coroutine raised StopIteration"):
518n/a
519n/a run_async(foo())
520n/a
521n/a def test_func_3(self):
522n/a async def foo():
523n/a raise StopIteration
524n/a
525n/a with silence_coro_gc():
526n/a self.assertRegex(repr(foo()), '^<coroutine object.* at 0x.*>$')
527n/a
528n/a def test_func_4(self):
529n/a async def foo():
530n/a raise StopIteration
531n/a
532n/a check = lambda: self.assertRaisesRegex(
533n/a TypeError, "'coroutine' object is not iterable")
534n/a
535n/a with check():
536n/a list(foo())
537n/a
538n/a with check():
539n/a tuple(foo())
540n/a
541n/a with check():
542n/a sum(foo())
543n/a
544n/a with check():
545n/a iter(foo())
546n/a
547n/a with silence_coro_gc(), check():
548n/a for i in foo():
549n/a pass
550n/a
551n/a with silence_coro_gc(), check():
552n/a [i for i in foo()]
553n/a
554n/a def test_func_5(self):
555n/a @types.coroutine
556n/a def bar():
557n/a yield 1
558n/a
559n/a async def foo():
560n/a await bar()
561n/a
562n/a check = lambda: self.assertRaisesRegex(
563n/a TypeError, "'coroutine' object is not iterable")
564n/a
565n/a with check():
566n/a for el in foo(): pass
567n/a
568n/a # the following should pass without an error
569n/a for el in bar():
570n/a self.assertEqual(el, 1)
571n/a self.assertEqual([el for el in bar()], [1])
572n/a self.assertEqual(tuple(bar()), (1,))
573n/a self.assertEqual(next(iter(bar())), 1)
574n/a
575n/a def test_func_6(self):
576n/a @types.coroutine
577n/a def bar():
578n/a yield 1
579n/a yield 2
580n/a
581n/a async def foo():
582n/a await bar()
583n/a
584n/a f = foo()
585n/a self.assertEqual(f.send(None), 1)
586n/a self.assertEqual(f.send(None), 2)
587n/a with self.assertRaises(StopIteration):
588n/a f.send(None)
589n/a
590n/a def test_func_7(self):
591n/a async def bar():
592n/a return 10
593n/a
594n/a def foo():
595n/a yield from bar()
596n/a
597n/a with silence_coro_gc(), self.assertRaisesRegex(
598n/a TypeError,
599n/a "cannot 'yield from' a coroutine object in a non-coroutine generator"):
600n/a
601n/a list(foo())
602n/a
603n/a def test_func_8(self):
604n/a @types.coroutine
605n/a def bar():
606n/a return (yield from foo())
607n/a
608n/a async def foo():
609n/a return 'spam'
610n/a
611n/a self.assertEqual(run_async(bar()), ([], 'spam') )
612n/a
613n/a def test_func_9(self):
614n/a async def foo(): pass
615n/a
616n/a with self.assertWarnsRegex(
617n/a RuntimeWarning, "coroutine '.*test_func_9.*foo' was never awaited"):
618n/a
619n/a foo()
620n/a support.gc_collect()
621n/a
622n/a def test_func_10(self):
623n/a N = 0
624n/a
625n/a @types.coroutine
626n/a def gen():
627n/a nonlocal N
628n/a try:
629n/a a = yield
630n/a yield (a ** 2)
631n/a except ZeroDivisionError:
632n/a N += 100
633n/a raise
634n/a finally:
635n/a N += 1
636n/a
637n/a async def foo():
638n/a await gen()
639n/a
640n/a coro = foo()
641n/a aw = coro.__await__()
642n/a self.assertIs(aw, iter(aw))
643n/a next(aw)
644n/a self.assertEqual(aw.send(10), 100)
645n/a
646n/a self.assertEqual(N, 0)
647n/a aw.close()
648n/a self.assertEqual(N, 1)
649n/a
650n/a coro = foo()
651n/a aw = coro.__await__()
652n/a next(aw)
653n/a with self.assertRaises(ZeroDivisionError):
654n/a aw.throw(ZeroDivisionError, None, None)
655n/a self.assertEqual(N, 102)
656n/a
657n/a def test_func_11(self):
658n/a async def func(): pass
659n/a coro = func()
660n/a # Test that PyCoro_Type and _PyCoroWrapper_Type types were properly
661n/a # initialized
662n/a self.assertIn('__await__', dir(coro))
663n/a self.assertIn('__iter__', dir(coro.__await__()))
664n/a self.assertIn('coroutine_wrapper', repr(coro.__await__()))
665n/a coro.close() # avoid RuntimeWarning
666n/a
667n/a def test_func_12(self):
668n/a async def g():
669n/a i = me.send(None)
670n/a await foo
671n/a me = g()
672n/a with self.assertRaisesRegex(ValueError,
673n/a "coroutine already executing"):
674n/a me.send(None)
675n/a
676n/a def test_func_13(self):
677n/a async def g():
678n/a pass
679n/a with self.assertRaisesRegex(
680n/a TypeError,
681n/a "can't send non-None value to a just-started coroutine"):
682n/a
683n/a g().send('spam')
684n/a
685n/a def test_func_14(self):
686n/a @types.coroutine
687n/a def gen():
688n/a yield
689n/a async def coro():
690n/a try:
691n/a await gen()
692n/a except GeneratorExit:
693n/a await gen()
694n/a c = coro()
695n/a c.send(None)
696n/a with self.assertRaisesRegex(RuntimeError,
697n/a "coroutine ignored GeneratorExit"):
698n/a c.close()
699n/a
700n/a def test_func_15(self):
701n/a # See http://bugs.python.org/issue25887 for details
702n/a
703n/a async def spammer():
704n/a return 'spam'
705n/a async def reader(coro):
706n/a return await coro
707n/a
708n/a spammer_coro = spammer()
709n/a
710n/a with self.assertRaisesRegex(StopIteration, 'spam'):
711n/a reader(spammer_coro).send(None)
712n/a
713n/a with self.assertRaisesRegex(RuntimeError,
714n/a 'cannot reuse already awaited coroutine'):
715n/a reader(spammer_coro).send(None)
716n/a
717n/a def test_func_16(self):
718n/a # See http://bugs.python.org/issue25887 for details
719n/a
720n/a @types.coroutine
721n/a def nop():
722n/a yield
723n/a async def send():
724n/a await nop()
725n/a return 'spam'
726n/a async def read(coro):
727n/a await nop()
728n/a return await coro
729n/a
730n/a spammer = send()
731n/a
732n/a reader = read(spammer)
733n/a reader.send(None)
734n/a reader.send(None)
735n/a with self.assertRaisesRegex(Exception, 'ham'):
736n/a reader.throw(Exception('ham'))
737n/a
738n/a reader = read(spammer)
739n/a reader.send(None)
740n/a with self.assertRaisesRegex(RuntimeError,
741n/a 'cannot reuse already awaited coroutine'):
742n/a reader.send(None)
743n/a
744n/a with self.assertRaisesRegex(RuntimeError,
745n/a 'cannot reuse already awaited coroutine'):
746n/a reader.throw(Exception('wat'))
747n/a
748n/a def test_func_17(self):
749n/a # See http://bugs.python.org/issue25887 for details
750n/a
751n/a async def coroutine():
752n/a return 'spam'
753n/a
754n/a coro = coroutine()
755n/a with self.assertRaisesRegex(StopIteration, 'spam'):
756n/a coro.send(None)
757n/a
758n/a with self.assertRaisesRegex(RuntimeError,
759n/a 'cannot reuse already awaited coroutine'):
760n/a coro.send(None)
761n/a
762n/a with self.assertRaisesRegex(RuntimeError,
763n/a 'cannot reuse already awaited coroutine'):
764n/a coro.throw(Exception('wat'))
765n/a
766n/a # Closing a coroutine shouldn't raise any exception even if it's
767n/a # already closed/exhausted (similar to generators)
768n/a coro.close()
769n/a coro.close()
770n/a
771n/a def test_func_18(self):
772n/a # See http://bugs.python.org/issue25887 for details
773n/a
774n/a async def coroutine():
775n/a return 'spam'
776n/a
777n/a coro = coroutine()
778n/a await_iter = coro.__await__()
779n/a it = iter(await_iter)
780n/a
781n/a with self.assertRaisesRegex(StopIteration, 'spam'):
782n/a it.send(None)
783n/a
784n/a with self.assertRaisesRegex(RuntimeError,
785n/a 'cannot reuse already awaited coroutine'):
786n/a it.send(None)
787n/a
788n/a with self.assertRaisesRegex(RuntimeError,
789n/a 'cannot reuse already awaited coroutine'):
790n/a # Although the iterator protocol requires iterators to
791n/a # raise another StopIteration here, we don't want to do
792n/a # that. In this particular case, the iterator will raise
793n/a # a RuntimeError, so that 'yield from' and 'await'
794n/a # expressions will trigger the error, instead of silently
795n/a # ignoring the call.
796n/a next(it)
797n/a
798n/a with self.assertRaisesRegex(RuntimeError,
799n/a 'cannot reuse already awaited coroutine'):
800n/a it.throw(Exception('wat'))
801n/a
802n/a with self.assertRaisesRegex(RuntimeError,
803n/a 'cannot reuse already awaited coroutine'):
804n/a it.throw(Exception('wat'))
805n/a
806n/a # Closing a coroutine shouldn't raise any exception even if it's
807n/a # already closed/exhausted (similar to generators)
808n/a it.close()
809n/a it.close()
810n/a
811n/a def test_func_19(self):
812n/a CHK = 0
813n/a
814n/a @types.coroutine
815n/a def foo():
816n/a nonlocal CHK
817n/a yield
818n/a try:
819n/a yield
820n/a except GeneratorExit:
821n/a CHK += 1
822n/a
823n/a async def coroutine():
824n/a await foo()
825n/a
826n/a coro = coroutine()
827n/a
828n/a coro.send(None)
829n/a coro.send(None)
830n/a
831n/a self.assertEqual(CHK, 0)
832n/a coro.close()
833n/a self.assertEqual(CHK, 1)
834n/a
835n/a for _ in range(3):
836n/a # Closing a coroutine shouldn't raise any exception even if it's
837n/a # already closed/exhausted (similar to generators)
838n/a coro.close()
839n/a self.assertEqual(CHK, 1)
840n/a
841n/a def test_coro_wrapper_send_tuple(self):
842n/a async def foo():
843n/a return (10,)
844n/a
845n/a result = run_async__await__(foo())
846n/a self.assertEqual(result, ([], (10,)))
847n/a
848n/a def test_coro_wrapper_send_stop_iterator(self):
849n/a async def foo():
850n/a return StopIteration(10)
851n/a
852n/a result = run_async__await__(foo())
853n/a self.assertIsInstance(result[1], StopIteration)
854n/a self.assertEqual(result[1].value, 10)
855n/a
856n/a def test_cr_await(self):
857n/a @types.coroutine
858n/a def a():
859n/a self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING)
860n/a self.assertIsNone(coro_b.cr_await)
861n/a yield
862n/a self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING)
863n/a self.assertIsNone(coro_b.cr_await)
864n/a
865n/a async def c():
866n/a await a()
867n/a
868n/a async def b():
869n/a self.assertIsNone(coro_b.cr_await)
870n/a await c()
871n/a self.assertIsNone(coro_b.cr_await)
872n/a
873n/a coro_b = b()
874n/a self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CREATED)
875n/a self.assertIsNone(coro_b.cr_await)
876n/a
877n/a coro_b.send(None)
878n/a self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_SUSPENDED)
879n/a self.assertEqual(coro_b.cr_await.cr_await.gi_code.co_name, 'a')
880n/a
881n/a with self.assertRaises(StopIteration):
882n/a coro_b.send(None) # complete coroutine
883n/a self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CLOSED)
884n/a self.assertIsNone(coro_b.cr_await)
885n/a
886n/a def test_corotype_1(self):
887n/a ct = types.CoroutineType
888n/a self.assertIn('into coroutine', ct.send.__doc__)
889n/a self.assertIn('inside coroutine', ct.close.__doc__)
890n/a self.assertIn('in coroutine', ct.throw.__doc__)
891n/a self.assertIn('of the coroutine', ct.__dict__['__name__'].__doc__)
892n/a self.assertIn('of the coroutine', ct.__dict__['__qualname__'].__doc__)
893n/a self.assertEqual(ct.__name__, 'coroutine')
894n/a
895n/a async def f(): pass
896n/a c = f()
897n/a self.assertIn('coroutine object', repr(c))
898n/a c.close()
899n/a
900n/a def test_await_1(self):
901n/a
902n/a async def foo():
903n/a await 1
904n/a with self.assertRaisesRegex(TypeError, "object int can.t.*await"):
905n/a run_async(foo())
906n/a
907n/a def test_await_2(self):
908n/a async def foo():
909n/a await []
910n/a with self.assertRaisesRegex(TypeError, "object list can.t.*await"):
911n/a run_async(foo())
912n/a
913n/a def test_await_3(self):
914n/a async def foo():
915n/a await AsyncYieldFrom([1, 2, 3])
916n/a
917n/a self.assertEqual(run_async(foo()), ([1, 2, 3], None))
918n/a self.assertEqual(run_async__await__(foo()), ([1, 2, 3], None))
919n/a
920n/a def test_await_4(self):
921n/a async def bar():
922n/a return 42
923n/a
924n/a async def foo():
925n/a return await bar()
926n/a
927n/a self.assertEqual(run_async(foo()), ([], 42))
928n/a
929n/a def test_await_5(self):
930n/a class Awaitable:
931n/a def __await__(self):
932n/a return
933n/a
934n/a async def foo():
935n/a return (await Awaitable())
936n/a
937n/a with self.assertRaisesRegex(
938n/a TypeError, "__await__.*returned non-iterator of type"):
939n/a
940n/a run_async(foo())
941n/a
942n/a def test_await_6(self):
943n/a class Awaitable:
944n/a def __await__(self):
945n/a return iter([52])
946n/a
947n/a async def foo():
948n/a return (await Awaitable())
949n/a
950n/a self.assertEqual(run_async(foo()), ([52], None))
951n/a
952n/a def test_await_7(self):
953n/a class Awaitable:
954n/a def __await__(self):
955n/a yield 42
956n/a return 100
957n/a
958n/a async def foo():
959n/a return (await Awaitable())
960n/a
961n/a self.assertEqual(run_async(foo()), ([42], 100))
962n/a
963n/a def test_await_8(self):
964n/a class Awaitable:
965n/a pass
966n/a
967n/a async def foo(): return await Awaitable()
968n/a
969n/a with self.assertRaisesRegex(
970n/a TypeError, "object Awaitable can't be used in 'await' expression"):
971n/a
972n/a run_async(foo())
973n/a
974n/a def test_await_9(self):
975n/a def wrap():
976n/a return bar
977n/a
978n/a async def bar():
979n/a return 42
980n/a
981n/a async def foo():
982n/a b = bar()
983n/a
984n/a db = {'b': lambda: wrap}
985n/a
986n/a class DB:
987n/a b = wrap
988n/a
989n/a return (await bar() + await wrap()() + await db['b']()()() +
990n/a await bar() * 1000 + await DB.b()())
991n/a
992n/a async def foo2():
993n/a return -await bar()
994n/a
995n/a self.assertEqual(run_async(foo()), ([], 42168))
996n/a self.assertEqual(run_async(foo2()), ([], -42))
997n/a
998n/a def test_await_10(self):
999n/a async def baz():
1000n/a return 42
1001n/a
1002n/a async def bar():
1003n/a return baz()
1004n/a
1005n/a async def foo():
1006n/a return await (await bar())
1007n/a
1008n/a self.assertEqual(run_async(foo()), ([], 42))
1009n/a
1010n/a def test_await_11(self):
1011n/a def ident(val):
1012n/a return val
1013n/a
1014n/a async def bar():
1015n/a return 'spam'
1016n/a
1017n/a async def foo():
1018n/a return ident(val=await bar())
1019n/a
1020n/a async def foo2():
1021n/a return await bar(), 'ham'
1022n/a
1023n/a self.assertEqual(run_async(foo2()), ([], ('spam', 'ham')))
1024n/a
1025n/a def test_await_12(self):
1026n/a async def coro():
1027n/a return 'spam'
1028n/a
1029n/a class Awaitable:
1030n/a def __await__(self):
1031n/a return coro()
1032n/a
1033n/a async def foo():
1034n/a return await Awaitable()
1035n/a
1036n/a with self.assertRaisesRegex(
1037n/a TypeError, r"__await__\(\) returned a coroutine"):
1038n/a
1039n/a run_async(foo())
1040n/a
1041n/a def test_await_13(self):
1042n/a class Awaitable:
1043n/a def __await__(self):
1044n/a return self
1045n/a
1046n/a async def foo():
1047n/a return await Awaitable()
1048n/a
1049n/a with self.assertRaisesRegex(
1050n/a TypeError, "__await__.*returned non-iterator of type"):
1051n/a
1052n/a run_async(foo())
1053n/a
1054n/a def test_await_14(self):
1055n/a class Wrapper:
1056n/a # Forces the interpreter to use CoroutineType.__await__
1057n/a def __init__(self, coro):
1058n/a assert coro.__class__ is types.CoroutineType
1059n/a self.coro = coro
1060n/a def __await__(self):
1061n/a return self.coro.__await__()
1062n/a
1063n/a class FutureLike:
1064n/a def __await__(self):
1065n/a return (yield)
1066n/a
1067n/a class Marker(Exception):
1068n/a pass
1069n/a
1070n/a async def coro1():
1071n/a try:
1072n/a return await FutureLike()
1073n/a except ZeroDivisionError:
1074n/a raise Marker
1075n/a async def coro2():
1076n/a return await Wrapper(coro1())
1077n/a
1078n/a c = coro2()
1079n/a c.send(None)
1080n/a with self.assertRaisesRegex(StopIteration, 'spam'):
1081n/a c.send('spam')
1082n/a
1083n/a c = coro2()
1084n/a c.send(None)
1085n/a with self.assertRaises(Marker):
1086n/a c.throw(ZeroDivisionError)
1087n/a
1088n/a def test_await_15(self):
1089n/a @types.coroutine
1090n/a def nop():
1091n/a yield
1092n/a
1093n/a async def coroutine():
1094n/a await nop()
1095n/a
1096n/a async def waiter(coro):
1097n/a await coro
1098n/a
1099n/a coro = coroutine()
1100n/a coro.send(None)
1101n/a
1102n/a with self.assertRaisesRegex(RuntimeError,
1103n/a "coroutine is being awaited already"):
1104n/a waiter(coro).send(None)
1105n/a
1106n/a def test_with_1(self):
1107n/a class Manager:
1108n/a def __init__(self, name):
1109n/a self.name = name
1110n/a
1111n/a async def __aenter__(self):
1112n/a await AsyncYieldFrom(['enter-1-' + self.name,
1113n/a 'enter-2-' + self.name])
1114n/a return self
1115n/a
1116n/a async def __aexit__(self, *args):
1117n/a await AsyncYieldFrom(['exit-1-' + self.name,
1118n/a 'exit-2-' + self.name])
1119n/a
1120n/a if self.name == 'B':
1121n/a return True
1122n/a
1123n/a
1124n/a async def foo():
1125n/a async with Manager("A") as a, Manager("B") as b:
1126n/a await AsyncYieldFrom([('managers', a.name, b.name)])
1127n/a 1/0
1128n/a
1129n/a f = foo()
1130n/a result, _ = run_async(f)
1131n/a
1132n/a self.assertEqual(
1133n/a result, ['enter-1-A', 'enter-2-A', 'enter-1-B', 'enter-2-B',
1134n/a ('managers', 'A', 'B'),
1135n/a 'exit-1-B', 'exit-2-B', 'exit-1-A', 'exit-2-A']
1136n/a )
1137n/a
1138n/a async def foo():
1139n/a async with Manager("A") as a, Manager("C") as c:
1140n/a await AsyncYieldFrom([('managers', a.name, c.name)])
1141n/a 1/0
1142n/a
1143n/a with self.assertRaises(ZeroDivisionError):
1144n/a run_async(foo())
1145n/a
1146n/a def test_with_2(self):
1147n/a class CM:
1148n/a def __aenter__(self):
1149n/a pass
1150n/a
1151n/a async def foo():
1152n/a async with CM():
1153n/a pass
1154n/a
1155n/a with self.assertRaisesRegex(AttributeError, '__aexit__'):
1156n/a run_async(foo())
1157n/a
1158n/a def test_with_3(self):
1159n/a class CM:
1160n/a def __aexit__(self):
1161n/a pass
1162n/a
1163n/a async def foo():
1164n/a async with CM():
1165n/a pass
1166n/a
1167n/a with self.assertRaisesRegex(AttributeError, '__aenter__'):
1168n/a run_async(foo())
1169n/a
1170n/a def test_with_4(self):
1171n/a class CM:
1172n/a def __enter__(self):
1173n/a pass
1174n/a
1175n/a def __exit__(self):
1176n/a pass
1177n/a
1178n/a async def foo():
1179n/a async with CM():
1180n/a pass
1181n/a
1182n/a with self.assertRaisesRegex(AttributeError, '__aexit__'):
1183n/a run_async(foo())
1184n/a
1185n/a def test_with_5(self):
1186n/a # While this test doesn't make a lot of sense,
1187n/a # it's a regression test for an early bug with opcodes
1188n/a # generation
1189n/a
1190n/a class CM:
1191n/a async def __aenter__(self):
1192n/a return self
1193n/a
1194n/a async def __aexit__(self, *exc):
1195n/a pass
1196n/a
1197n/a async def func():
1198n/a async with CM():
1199n/a assert (1, ) == 1
1200n/a
1201n/a with self.assertRaises(AssertionError):
1202n/a run_async(func())
1203n/a
1204n/a def test_with_6(self):
1205n/a class CM:
1206n/a def __aenter__(self):
1207n/a return 123
1208n/a
1209n/a def __aexit__(self, *e):
1210n/a return 456
1211n/a
1212n/a async def foo():
1213n/a async with CM():
1214n/a pass
1215n/a
1216n/a with self.assertRaisesRegex(
1217n/a TypeError, "object int can't be used in 'await' expression"):
1218n/a # it's important that __aexit__ wasn't called
1219n/a run_async(foo())
1220n/a
1221n/a def test_with_7(self):
1222n/a class CM:
1223n/a async def __aenter__(self):
1224n/a return self
1225n/a
1226n/a def __aexit__(self, *e):
1227n/a return 444
1228n/a
1229n/a async def foo():
1230n/a async with CM():
1231n/a 1/0
1232n/a
1233n/a try:
1234n/a run_async(foo())
1235n/a except TypeError as exc:
1236n/a self.assertRegex(
1237n/a exc.args[0], "object int can't be used in 'await' expression")
1238n/a self.assertTrue(exc.__context__ is not None)
1239n/a self.assertTrue(isinstance(exc.__context__, ZeroDivisionError))
1240n/a else:
1241n/a self.fail('invalid asynchronous context manager did not fail')
1242n/a
1243n/a
1244n/a def test_with_8(self):
1245n/a CNT = 0
1246n/a
1247n/a class CM:
1248n/a async def __aenter__(self):
1249n/a return self
1250n/a
1251n/a def __aexit__(self, *e):
1252n/a return 456
1253n/a
1254n/a async def foo():
1255n/a nonlocal CNT
1256n/a async with CM():
1257n/a CNT += 1
1258n/a
1259n/a
1260n/a with self.assertRaisesRegex(
1261n/a TypeError, "object int can't be used in 'await' expression"):
1262n/a
1263n/a run_async(foo())
1264n/a
1265n/a self.assertEqual(CNT, 1)
1266n/a
1267n/a
1268n/a def test_with_9(self):
1269n/a CNT = 0
1270n/a
1271n/a class CM:
1272n/a async def __aenter__(self):
1273n/a return self
1274n/a
1275n/a async def __aexit__(self, *e):
1276n/a 1/0
1277n/a
1278n/a async def foo():
1279n/a nonlocal CNT
1280n/a async with CM():
1281n/a CNT += 1
1282n/a
1283n/a with self.assertRaises(ZeroDivisionError):
1284n/a run_async(foo())
1285n/a
1286n/a self.assertEqual(CNT, 1)
1287n/a
1288n/a def test_with_10(self):
1289n/a CNT = 0
1290n/a
1291n/a class CM:
1292n/a async def __aenter__(self):
1293n/a return self
1294n/a
1295n/a async def __aexit__(self, *e):
1296n/a 1/0
1297n/a
1298n/a async def foo():
1299n/a nonlocal CNT
1300n/a async with CM():
1301n/a async with CM():
1302n/a raise RuntimeError
1303n/a
1304n/a try:
1305n/a run_async(foo())
1306n/a except ZeroDivisionError as exc:
1307n/a self.assertTrue(exc.__context__ is not None)
1308n/a self.assertTrue(isinstance(exc.__context__, ZeroDivisionError))
1309n/a self.assertTrue(isinstance(exc.__context__.__context__,
1310n/a RuntimeError))
1311n/a else:
1312n/a self.fail('exception from __aexit__ did not propagate')
1313n/a
1314n/a def test_with_11(self):
1315n/a CNT = 0
1316n/a
1317n/a class CM:
1318n/a async def __aenter__(self):
1319n/a raise NotImplementedError
1320n/a
1321n/a async def __aexit__(self, *e):
1322n/a 1/0
1323n/a
1324n/a async def foo():
1325n/a nonlocal CNT
1326n/a async with CM():
1327n/a raise RuntimeError
1328n/a
1329n/a try:
1330n/a run_async(foo())
1331n/a except NotImplementedError as exc:
1332n/a self.assertTrue(exc.__context__ is None)
1333n/a else:
1334n/a self.fail('exception from __aenter__ did not propagate')
1335n/a
1336n/a def test_with_12(self):
1337n/a CNT = 0
1338n/a
1339n/a class CM:
1340n/a async def __aenter__(self):
1341n/a return self
1342n/a
1343n/a async def __aexit__(self, *e):
1344n/a return True
1345n/a
1346n/a async def foo():
1347n/a nonlocal CNT
1348n/a async with CM() as cm:
1349n/a self.assertIs(cm.__class__, CM)
1350n/a raise RuntimeError
1351n/a
1352n/a run_async(foo())
1353n/a
1354n/a def test_with_13(self):
1355n/a CNT = 0
1356n/a
1357n/a class CM:
1358n/a async def __aenter__(self):
1359n/a 1/0
1360n/a
1361n/a async def __aexit__(self, *e):
1362n/a return True
1363n/a
1364n/a async def foo():
1365n/a nonlocal CNT
1366n/a CNT += 1
1367n/a async with CM():
1368n/a CNT += 1000
1369n/a CNT += 10000
1370n/a
1371n/a with self.assertRaises(ZeroDivisionError):
1372n/a run_async(foo())
1373n/a self.assertEqual(CNT, 1)
1374n/a
1375n/a def test_for_1(self):
1376n/a aiter_calls = 0
1377n/a
1378n/a class AsyncIter:
1379n/a def __init__(self):
1380n/a self.i = 0
1381n/a
1382n/a async def __aiter__(self):
1383n/a nonlocal aiter_calls
1384n/a aiter_calls += 1
1385n/a return self
1386n/a
1387n/a async def __anext__(self):
1388n/a self.i += 1
1389n/a
1390n/a if not (self.i % 10):
1391n/a await AsyncYield(self.i * 10)
1392n/a
1393n/a if self.i > 100:
1394n/a raise StopAsyncIteration
1395n/a
1396n/a return self.i, self.i
1397n/a
1398n/a
1399n/a buffer = []
1400n/a async def test1():
1401n/a with self.assertWarnsRegex(DeprecationWarning, "legacy"):
1402n/a async for i1, i2 in AsyncIter():
1403n/a buffer.append(i1 + i2)
1404n/a
1405n/a yielded, _ = run_async(test1())
1406n/a # Make sure that __aiter__ was called only once
1407n/a self.assertEqual(aiter_calls, 1)
1408n/a self.assertEqual(yielded, [i * 100 for i in range(1, 11)])
1409n/a self.assertEqual(buffer, [i*2 for i in range(1, 101)])
1410n/a
1411n/a
1412n/a buffer = []
1413n/a async def test2():
1414n/a nonlocal buffer
1415n/a with self.assertWarnsRegex(DeprecationWarning, "legacy"):
1416n/a async for i in AsyncIter():
1417n/a buffer.append(i[0])
1418n/a if i[0] == 20:
1419n/a break
1420n/a else:
1421n/a buffer.append('what?')
1422n/a buffer.append('end')
1423n/a
1424n/a yielded, _ = run_async(test2())
1425n/a # Make sure that __aiter__ was called only once
1426n/a self.assertEqual(aiter_calls, 2)
1427n/a self.assertEqual(yielded, [100, 200])
1428n/a self.assertEqual(buffer, [i for i in range(1, 21)] + ['end'])
1429n/a
1430n/a
1431n/a buffer = []
1432n/a async def test3():
1433n/a nonlocal buffer
1434n/a with self.assertWarnsRegex(DeprecationWarning, "legacy"):
1435n/a async for i in AsyncIter():
1436n/a if i[0] > 20:
1437n/a continue
1438n/a buffer.append(i[0])
1439n/a else:
1440n/a buffer.append('what?')
1441n/a buffer.append('end')
1442n/a
1443n/a yielded, _ = run_async(test3())
1444n/a # Make sure that __aiter__ was called only once
1445n/a self.assertEqual(aiter_calls, 3)
1446n/a self.assertEqual(yielded, [i * 100 for i in range(1, 11)])
1447n/a self.assertEqual(buffer, [i for i in range(1, 21)] +
1448n/a ['what?', 'end'])
1449n/a
1450n/a def test_for_2(self):
1451n/a tup = (1, 2, 3)
1452n/a refs_before = sys.getrefcount(tup)
1453n/a
1454n/a async def foo():
1455n/a async for i in tup:
1456n/a print('never going to happen')
1457n/a
1458n/a with self.assertRaisesRegex(
1459n/a TypeError, "async for' requires an object.*__aiter__.*tuple"):
1460n/a
1461n/a run_async(foo())
1462n/a
1463n/a self.assertEqual(sys.getrefcount(tup), refs_before)
1464n/a
1465n/a def test_for_3(self):
1466n/a class I:
1467n/a def __aiter__(self):
1468n/a return self
1469n/a
1470n/a aiter = I()
1471n/a refs_before = sys.getrefcount(aiter)
1472n/a
1473n/a async def foo():
1474n/a async for i in aiter:
1475n/a print('never going to happen')
1476n/a
1477n/a with self.assertRaisesRegex(
1478n/a TypeError,
1479n/a r"async for' received an invalid object.*__aiter.*\: I"):
1480n/a
1481n/a run_async(foo())
1482n/a
1483n/a self.assertEqual(sys.getrefcount(aiter), refs_before)
1484n/a
1485n/a def test_for_4(self):
1486n/a class I:
1487n/a def __aiter__(self):
1488n/a return self
1489n/a
1490n/a def __anext__(self):
1491n/a return ()
1492n/a
1493n/a aiter = I()
1494n/a refs_before = sys.getrefcount(aiter)
1495n/a
1496n/a async def foo():
1497n/a async for i in aiter:
1498n/a print('never going to happen')
1499n/a
1500n/a with self.assertRaisesRegex(
1501n/a TypeError,
1502n/a "async for' received an invalid object.*__anext__.*tuple"):
1503n/a
1504n/a run_async(foo())
1505n/a
1506n/a self.assertEqual(sys.getrefcount(aiter), refs_before)
1507n/a
1508n/a def test_for_5(self):
1509n/a class I:
1510n/a async def __aiter__(self):
1511n/a return self
1512n/a
1513n/a def __anext__(self):
1514n/a return 123
1515n/a
1516n/a async def foo():
1517n/a with self.assertWarnsRegex(DeprecationWarning, "legacy"):
1518n/a async for i in I():
1519n/a print('never going to happen')
1520n/a
1521n/a with self.assertRaisesRegex(
1522n/a TypeError,
1523n/a "async for' received an invalid object.*__anext.*int"):
1524n/a
1525n/a run_async(foo())
1526n/a
1527n/a def test_for_6(self):
1528n/a I = 0
1529n/a
1530n/a class Manager:
1531n/a async def __aenter__(self):
1532n/a nonlocal I
1533n/a I += 10000
1534n/a
1535n/a async def __aexit__(self, *args):
1536n/a nonlocal I
1537n/a I += 100000
1538n/a
1539n/a class Iterable:
1540n/a def __init__(self):
1541n/a self.i = 0
1542n/a
1543n/a def __aiter__(self):
1544n/a return self
1545n/a
1546n/a async def __anext__(self):
1547n/a if self.i > 10:
1548n/a raise StopAsyncIteration
1549n/a self.i += 1
1550n/a return self.i
1551n/a
1552n/a ##############
1553n/a
1554n/a manager = Manager()
1555n/a iterable = Iterable()
1556n/a mrefs_before = sys.getrefcount(manager)
1557n/a irefs_before = sys.getrefcount(iterable)
1558n/a
1559n/a async def main():
1560n/a nonlocal I
1561n/a
1562n/a async with manager:
1563n/a async for i in iterable:
1564n/a I += 1
1565n/a I += 1000
1566n/a
1567n/a with warnings.catch_warnings():
1568n/a warnings.simplefilter("error")
1569n/a # Test that __aiter__ that returns an asynchronous iterator
1570n/a # directly does not throw any warnings.
1571n/a run_async(main())
1572n/a self.assertEqual(I, 111011)
1573n/a
1574n/a self.assertEqual(sys.getrefcount(manager), mrefs_before)
1575n/a self.assertEqual(sys.getrefcount(iterable), irefs_before)
1576n/a
1577n/a ##############
1578n/a
1579n/a async def main():
1580n/a nonlocal I
1581n/a
1582n/a async with Manager():
1583n/a async for i in Iterable():
1584n/a I += 1
1585n/a I += 1000
1586n/a
1587n/a async with Manager():
1588n/a async for i in Iterable():
1589n/a I += 1
1590n/a I += 1000
1591n/a
1592n/a run_async(main())
1593n/a self.assertEqual(I, 333033)
1594n/a
1595n/a ##############
1596n/a
1597n/a async def main():
1598n/a nonlocal I
1599n/a
1600n/a async with Manager():
1601n/a I += 100
1602n/a async for i in Iterable():
1603n/a I += 1
1604n/a else:
1605n/a I += 10000000
1606n/a I += 1000
1607n/a
1608n/a async with Manager():
1609n/a I += 100
1610n/a async for i in Iterable():
1611n/a I += 1
1612n/a else:
1613n/a I += 10000000
1614n/a I += 1000
1615n/a
1616n/a run_async(main())
1617n/a self.assertEqual(I, 20555255)
1618n/a
1619n/a def test_for_7(self):
1620n/a CNT = 0
1621n/a class AI:
1622n/a async def __aiter__(self):
1623n/a 1/0
1624n/a async def foo():
1625n/a nonlocal CNT
1626n/a with self.assertWarnsRegex(DeprecationWarning, "legacy"):
1627n/a async for i in AI():
1628n/a CNT += 1
1629n/a CNT += 10
1630n/a with self.assertRaises(ZeroDivisionError):
1631n/a run_async(foo())
1632n/a self.assertEqual(CNT, 0)
1633n/a
1634n/a def test_for_8(self):
1635n/a CNT = 0
1636n/a class AI:
1637n/a def __aiter__(self):
1638n/a 1/0
1639n/a async def foo():
1640n/a nonlocal CNT
1641n/a async for i in AI():
1642n/a CNT += 1
1643n/a CNT += 10
1644n/a with self.assertRaises(ZeroDivisionError):
1645n/a with warnings.catch_warnings():
1646n/a warnings.simplefilter("error")
1647n/a # Test that if __aiter__ raises an exception it propagates
1648n/a # without any kind of warning.
1649n/a run_async(foo())
1650n/a self.assertEqual(CNT, 0)
1651n/a
1652n/a def test_for_9(self):
1653n/a # Test that DeprecationWarning can safely be converted into
1654n/a # an exception (__aiter__ should not have a chance to raise
1655n/a # a ZeroDivisionError.)
1656n/a class AI:
1657n/a async def __aiter__(self):
1658n/a 1/0
1659n/a async def foo():
1660n/a async for i in AI():
1661n/a pass
1662n/a
1663n/a with self.assertRaises(DeprecationWarning):
1664n/a with warnings.catch_warnings():
1665n/a warnings.simplefilter("error")
1666n/a run_async(foo())
1667n/a
1668n/a def test_for_10(self):
1669n/a # Test that DeprecationWarning can safely be converted into
1670n/a # an exception.
1671n/a class AI:
1672n/a async def __aiter__(self):
1673n/a pass
1674n/a async def foo():
1675n/a async for i in AI():
1676n/a pass
1677n/a
1678n/a with self.assertRaises(DeprecationWarning):
1679n/a with warnings.catch_warnings():
1680n/a warnings.simplefilter("error")
1681n/a run_async(foo())
1682n/a
1683n/a def test_for_tuple(self):
1684n/a class Done(Exception): pass
1685n/a
1686n/a class AIter(tuple):
1687n/a i = 0
1688n/a def __aiter__(self):
1689n/a return self
1690n/a async def __anext__(self):
1691n/a if self.i >= len(self):
1692n/a raise StopAsyncIteration
1693n/a self.i += 1
1694n/a return self[self.i - 1]
1695n/a
1696n/a result = []
1697n/a async def foo():
1698n/a async for i in AIter([42]):
1699n/a result.append(i)
1700n/a raise Done
1701n/a
1702n/a with self.assertRaises(Done):
1703n/a foo().send(None)
1704n/a self.assertEqual(result, [42])
1705n/a
1706n/a def test_for_stop_iteration(self):
1707n/a class Done(Exception): pass
1708n/a
1709n/a class AIter(StopIteration):
1710n/a i = 0
1711n/a def __aiter__(self):
1712n/a return self
1713n/a async def __anext__(self):
1714n/a if self.i:
1715n/a raise StopAsyncIteration
1716n/a self.i += 1
1717n/a return self.value
1718n/a
1719n/a result = []
1720n/a async def foo():
1721n/a async for i in AIter(42):
1722n/a result.append(i)
1723n/a raise Done
1724n/a
1725n/a with self.assertRaises(Done):
1726n/a foo().send(None)
1727n/a self.assertEqual(result, [42])
1728n/a
1729n/a def test_comp_1(self):
1730n/a async def f(i):
1731n/a return i
1732n/a
1733n/a async def run_list():
1734n/a return [await c for c in [f(1), f(41)]]
1735n/a
1736n/a async def run_set():
1737n/a return {await c for c in [f(1), f(41)]}
1738n/a
1739n/a async def run_dict1():
1740n/a return {await c: 'a' for c in [f(1), f(41)]}
1741n/a
1742n/a async def run_dict2():
1743n/a return {i: await c for i, c in enumerate([f(1), f(41)])}
1744n/a
1745n/a self.assertEqual(run_async(run_list()), ([], [1, 41]))
1746n/a self.assertEqual(run_async(run_set()), ([], {1, 41}))
1747n/a self.assertEqual(run_async(run_dict1()), ([], {1: 'a', 41: 'a'}))
1748n/a self.assertEqual(run_async(run_dict2()), ([], {0: 1, 1: 41}))
1749n/a
1750n/a def test_comp_2(self):
1751n/a async def f(i):
1752n/a return i
1753n/a
1754n/a async def run_list():
1755n/a return [s for c in [f(''), f('abc'), f(''), f(['de', 'fg'])]
1756n/a for s in await c]
1757n/a
1758n/a self.assertEqual(
1759n/a run_async(run_list()),
1760n/a ([], ['a', 'b', 'c', 'de', 'fg']))
1761n/a
1762n/a async def run_set():
1763n/a return {d
1764n/a for c in [f([f([10, 30]),
1765n/a f([20])])]
1766n/a for s in await c
1767n/a for d in await s}
1768n/a
1769n/a self.assertEqual(
1770n/a run_async(run_set()),
1771n/a ([], {10, 20, 30}))
1772n/a
1773n/a async def run_set2():
1774n/a return {await s
1775n/a for c in [f([f(10), f(20)])]
1776n/a for s in await c}
1777n/a
1778n/a self.assertEqual(
1779n/a run_async(run_set2()),
1780n/a ([], {10, 20}))
1781n/a
1782n/a def test_comp_3(self):
1783n/a async def f(it):
1784n/a for i in it:
1785n/a yield i
1786n/a
1787n/a async def run_list():
1788n/a return [i + 1 async for i in f([10, 20])]
1789n/a self.assertEqual(
1790n/a run_async(run_list()),
1791n/a ([], [11, 21]))
1792n/a
1793n/a async def run_set():
1794n/a return {i + 1 async for i in f([10, 20])}
1795n/a self.assertEqual(
1796n/a run_async(run_set()),
1797n/a ([], {11, 21}))
1798n/a
1799n/a async def run_dict():
1800n/a return {i + 1: i + 2 async for i in f([10, 20])}
1801n/a self.assertEqual(
1802n/a run_async(run_dict()),
1803n/a ([], {11: 12, 21: 22}))
1804n/a
1805n/a async def run_gen():
1806n/a gen = (i + 1 async for i in f([10, 20]))
1807n/a return [g + 100 async for g in gen]
1808n/a self.assertEqual(
1809n/a run_async(run_gen()),
1810n/a ([], [111, 121]))
1811n/a
1812n/a def test_comp_4(self):
1813n/a async def f(it):
1814n/a for i in it:
1815n/a yield i
1816n/a
1817n/a async def run_list():
1818n/a return [i + 1 async for i in f([10, 20]) if i > 10]
1819n/a self.assertEqual(
1820n/a run_async(run_list()),
1821n/a ([], [21]))
1822n/a
1823n/a async def run_set():
1824n/a return {i + 1 async for i in f([10, 20]) if i > 10}
1825n/a self.assertEqual(
1826n/a run_async(run_set()),
1827n/a ([], {21}))
1828n/a
1829n/a async def run_dict():
1830n/a return {i + 1: i + 2 async for i in f([10, 20]) if i > 10}
1831n/a self.assertEqual(
1832n/a run_async(run_dict()),
1833n/a ([], {21: 22}))
1834n/a
1835n/a async def run_gen():
1836n/a gen = (i + 1 async for i in f([10, 20]) if i > 10)
1837n/a return [g + 100 async for g in gen]
1838n/a self.assertEqual(
1839n/a run_async(run_gen()),
1840n/a ([], [121]))
1841n/a
1842n/a def test_comp_5(self):
1843n/a async def f(it):
1844n/a for i in it:
1845n/a yield i
1846n/a
1847n/a async def run_list():
1848n/a return [i + 1 for pair in ([10, 20], [30, 40]) if pair[0] > 10
1849n/a async for i in f(pair) if i > 30]
1850n/a self.assertEqual(
1851n/a run_async(run_list()),
1852n/a ([], [41]))
1853n/a
1854n/a def test_comp_6(self):
1855n/a async def f(it):
1856n/a for i in it:
1857n/a yield i
1858n/a
1859n/a async def run_list():
1860n/a return [i + 1 async for seq in f([(10, 20), (30,)])
1861n/a for i in seq]
1862n/a
1863n/a self.assertEqual(
1864n/a run_async(run_list()),
1865n/a ([], [11, 21, 31]))
1866n/a
1867n/a def test_comp_7(self):
1868n/a async def f():
1869n/a yield 1
1870n/a yield 2
1871n/a raise Exception('aaa')
1872n/a
1873n/a async def run_list():
1874n/a return [i async for i in f()]
1875n/a
1876n/a with self.assertRaisesRegex(Exception, 'aaa'):
1877n/a run_async(run_list())
1878n/a
1879n/a def test_comp_8(self):
1880n/a async def f():
1881n/a return [i for i in [1, 2, 3]]
1882n/a
1883n/a self.assertEqual(
1884n/a run_async(f()),
1885n/a ([], [1, 2, 3]))
1886n/a
1887n/a def test_comp_9(self):
1888n/a async def gen():
1889n/a yield 1
1890n/a yield 2
1891n/a async def f():
1892n/a l = [i async for i in gen()]
1893n/a return [i for i in l]
1894n/a
1895n/a self.assertEqual(
1896n/a run_async(f()),
1897n/a ([], [1, 2]))
1898n/a
1899n/a def test_comp_10(self):
1900n/a async def f():
1901n/a xx = {i for i in [1, 2, 3]}
1902n/a return {x: x for x in xx}
1903n/a
1904n/a self.assertEqual(
1905n/a run_async(f()),
1906n/a ([], {1: 1, 2: 2, 3: 3}))
1907n/a
1908n/a def test_copy(self):
1909n/a async def func(): pass
1910n/a coro = func()
1911n/a with self.assertRaises(TypeError):
1912n/a copy.copy(coro)
1913n/a
1914n/a aw = coro.__await__()
1915n/a try:
1916n/a with self.assertRaises(TypeError):
1917n/a copy.copy(aw)
1918n/a finally:
1919n/a aw.close()
1920n/a
1921n/a def test_pickle(self):
1922n/a async def func(): pass
1923n/a coro = func()
1924n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1925n/a with self.assertRaises((TypeError, pickle.PicklingError)):
1926n/a pickle.dumps(coro, proto)
1927n/a
1928n/a aw = coro.__await__()
1929n/a try:
1930n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1931n/a with self.assertRaises((TypeError, pickle.PicklingError)):
1932n/a pickle.dumps(aw, proto)
1933n/a finally:
1934n/a aw.close()
1935n/a
1936n/a def test_fatal_coro_warning(self):
1937n/a # Issue 27811
1938n/a async def func(): pass
1939n/a with warnings.catch_warnings(), support.captured_stderr() as stderr:
1940n/a warnings.filterwarnings("error")
1941n/a func()
1942n/a support.gc_collect()
1943n/a self.assertIn("was never awaited", stderr.getvalue())
1944n/a
1945n/a
1946n/aclass CoroAsyncIOCompatTest(unittest.TestCase):
1947n/a
1948n/a def test_asyncio_1(self):
1949n/a # asyncio cannot be imported when Python is compiled without thread
1950n/a # support
1951n/a asyncio = support.import_module('asyncio')
1952n/a
1953n/a class MyException(Exception):
1954n/a pass
1955n/a
1956n/a buffer = []
1957n/a
1958n/a class CM:
1959n/a async def __aenter__(self):
1960n/a buffer.append(1)
1961n/a await asyncio.sleep(0.01)
1962n/a buffer.append(2)
1963n/a return self
1964n/a
1965n/a async def __aexit__(self, exc_type, exc_val, exc_tb):
1966n/a await asyncio.sleep(0.01)
1967n/a buffer.append(exc_type.__name__)
1968n/a
1969n/a async def f():
1970n/a async with CM() as c:
1971n/a await asyncio.sleep(0.01)
1972n/a raise MyException
1973n/a buffer.append('unreachable')
1974n/a
1975n/a loop = asyncio.new_event_loop()
1976n/a asyncio.set_event_loop(loop)
1977n/a try:
1978n/a loop.run_until_complete(f())
1979n/a except MyException:
1980n/a pass
1981n/a finally:
1982n/a loop.close()
1983n/a asyncio.set_event_loop(None)
1984n/a
1985n/a self.assertEqual(buffer, [1, 2, 'MyException'])
1986n/a
1987n/a
1988n/aclass SysSetCoroWrapperTest(unittest.TestCase):
1989n/a
1990n/a def test_set_wrapper_1(self):
1991n/a async def foo():
1992n/a return 'spam'
1993n/a
1994n/a wrapped = None
1995n/a def wrap(gen):
1996n/a nonlocal wrapped
1997n/a wrapped = gen
1998n/a return gen
1999n/a
2000n/a self.assertIsNone(sys.get_coroutine_wrapper())
2001n/a
2002n/a sys.set_coroutine_wrapper(wrap)
2003n/a self.assertIs(sys.get_coroutine_wrapper(), wrap)
2004n/a try:
2005n/a f = foo()
2006n/a self.assertTrue(wrapped)
2007n/a
2008n/a self.assertEqual(run_async(f), ([], 'spam'))
2009n/a finally:
2010n/a sys.set_coroutine_wrapper(None)
2011n/a
2012n/a self.assertIsNone(sys.get_coroutine_wrapper())
2013n/a
2014n/a wrapped = None
2015n/a with silence_coro_gc():
2016n/a foo()
2017n/a self.assertFalse(wrapped)
2018n/a
2019n/a def test_set_wrapper_2(self):
2020n/a self.assertIsNone(sys.get_coroutine_wrapper())
2021n/a with self.assertRaisesRegex(TypeError, "callable expected, got int"):
2022n/a sys.set_coroutine_wrapper(1)
2023n/a self.assertIsNone(sys.get_coroutine_wrapper())
2024n/a
2025n/a def test_set_wrapper_3(self):
2026n/a async def foo():
2027n/a return 'spam'
2028n/a
2029n/a def wrapper(coro):
2030n/a async def wrap(coro):
2031n/a return await coro
2032n/a return wrap(coro)
2033n/a
2034n/a sys.set_coroutine_wrapper(wrapper)
2035n/a try:
2036n/a with silence_coro_gc(), self.assertRaisesRegex(
2037n/a RuntimeError,
2038n/a r"coroutine wrapper.*\.wrapper at 0x.*attempted to "
2039n/a r"recursively wrap .* wrap .*"):
2040n/a
2041n/a foo()
2042n/a finally:
2043n/a sys.set_coroutine_wrapper(None)
2044n/a
2045n/a def test_set_wrapper_4(self):
2046n/a @types.coroutine
2047n/a def foo():
2048n/a return 'spam'
2049n/a
2050n/a wrapped = None
2051n/a def wrap(gen):
2052n/a nonlocal wrapped
2053n/a wrapped = gen
2054n/a return gen
2055n/a
2056n/a sys.set_coroutine_wrapper(wrap)
2057n/a try:
2058n/a foo()
2059n/a self.assertIs(
2060n/a wrapped, None,
2061n/a "generator-based coroutine was wrapped via "
2062n/a "sys.set_coroutine_wrapper")
2063n/a finally:
2064n/a sys.set_coroutine_wrapper(None)
2065n/a
2066n/a
2067n/aclass CAPITest(unittest.TestCase):
2068n/a
2069n/a def test_tp_await_1(self):
2070n/a from _testcapi import awaitType as at
2071n/a
2072n/a async def foo():
2073n/a future = at(iter([1]))
2074n/a return (await future)
2075n/a
2076n/a self.assertEqual(foo().send(None), 1)
2077n/a
2078n/a def test_tp_await_2(self):
2079n/a # Test tp_await to __await__ mapping
2080n/a from _testcapi import awaitType as at
2081n/a future = at(iter([1]))
2082n/a self.assertEqual(next(future.__await__()), 1)
2083n/a
2084n/a def test_tp_await_3(self):
2085n/a from _testcapi import awaitType as at
2086n/a
2087n/a async def foo():
2088n/a future = at(1)
2089n/a return (await future)
2090n/a
2091n/a with self.assertRaisesRegex(
2092n/a TypeError, "__await__.*returned non-iterator of type 'int'"):
2093n/a self.assertEqual(foo().send(None), 1)
2094n/a
2095n/a
2096n/aif __name__=="__main__":
2097n/a unittest.main()