test_asyncgen.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. import inspect
  2. import types
  3. import unittest
  4. import contextlib
  5. from test.support.import_helper import import_module
  6. from test.support import gc_collect, requires_working_socket
  7. asyncio = import_module("asyncio")
  8. requires_working_socket(module=True)
  9. _no_default = object()
  10. class AwaitException(Exception):
  11. pass
  12. @types.coroutine
  13. def awaitable(*, throw=False):
  14. if throw:
  15. yield ('throw',)
  16. else:
  17. yield ('result',)
  18. def run_until_complete(coro):
  19. exc = False
  20. while True:
  21. try:
  22. if exc:
  23. exc = False
  24. fut = coro.throw(AwaitException)
  25. else:
  26. fut = coro.send(None)
  27. except StopIteration as ex:
  28. return ex.args[0]
  29. if fut == ('throw',):
  30. exc = True
  31. def to_list(gen):
  32. async def iterate():
  33. res = []
  34. async for i in gen:
  35. res.append(i)
  36. return res
  37. return run_until_complete(iterate())
  38. def py_anext(iterator, default=_no_default):
  39. """Pure-Python implementation of anext() for testing purposes.
  40. Closely matches the builtin anext() C implementation.
  41. Can be used to compare the built-in implementation of the inner
  42. coroutines machinery to C-implementation of __anext__() and send()
  43. or throw() on the returned generator.
  44. """
  45. try:
  46. __anext__ = type(iterator).__anext__
  47. except AttributeError:
  48. raise TypeError(f'{iterator!r} is not an async iterator')
  49. if default is _no_default:
  50. return __anext__(iterator)
  51. async def anext_impl():
  52. try:
  53. # The C code is way more low-level than this, as it implements
  54. # all methods of the iterator protocol. In this implementation
  55. # we're relying on higher-level coroutine concepts, but that's
  56. # exactly what we want -- crosstest pure-Python high-level
  57. # implementation and low-level C anext() iterators.
  58. return await __anext__(iterator)
  59. except StopAsyncIteration:
  60. return default
  61. return anext_impl()
  62. class AsyncGenSyntaxTest(unittest.TestCase):
  63. def test_async_gen_syntax_01(self):
  64. code = '''async def foo():
  65. await abc
  66. yield from 123
  67. '''
  68. with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
  69. exec(code, {}, {})
  70. def test_async_gen_syntax_02(self):
  71. code = '''async def foo():
  72. yield from 123
  73. '''
  74. with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):
  75. exec(code, {}, {})
  76. def test_async_gen_syntax_03(self):
  77. code = '''async def foo():
  78. await abc
  79. yield
  80. return 123
  81. '''
  82. with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
  83. exec(code, {}, {})
  84. def test_async_gen_syntax_04(self):
  85. code = '''async def foo():
  86. yield
  87. return 123
  88. '''
  89. with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
  90. exec(code, {}, {})
  91. def test_async_gen_syntax_05(self):
  92. code = '''async def foo():
  93. if 0:
  94. yield
  95. return 12
  96. '''
  97. with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):
  98. exec(code, {}, {})
  99. class AsyncGenTest(unittest.TestCase):
  100. def compare_generators(self, sync_gen, async_gen):
  101. def sync_iterate(g):
  102. res = []
  103. while True:
  104. try:
  105. res.append(g.__next__())
  106. except StopIteration:
  107. res.append('STOP')
  108. break
  109. except Exception as ex:
  110. res.append(str(type(ex)))
  111. return res
  112. def async_iterate(g):
  113. res = []
  114. while True:
  115. an = g.__anext__()
  116. try:
  117. while True:
  118. try:
  119. an.__next__()
  120. except StopIteration as ex:
  121. if ex.args:
  122. res.append(ex.args[0])
  123. break
  124. else:
  125. res.append('EMPTY StopIteration')
  126. break
  127. except StopAsyncIteration:
  128. raise
  129. except Exception as ex:
  130. res.append(str(type(ex)))
  131. break
  132. except StopAsyncIteration:
  133. res.append('STOP')
  134. break
  135. return res
  136. sync_gen_result = sync_iterate(sync_gen)
  137. async_gen_result = async_iterate(async_gen)
  138. self.assertEqual(sync_gen_result, async_gen_result)
  139. return async_gen_result
  140. def test_async_gen_iteration_01(self):
  141. async def gen():
  142. await awaitable()
  143. a = yield 123
  144. self.assertIs(a, None)
  145. await awaitable()
  146. yield 456
  147. await awaitable()
  148. yield 789
  149. self.assertEqual(to_list(gen()), [123, 456, 789])
  150. def test_async_gen_iteration_02(self):
  151. async def gen():
  152. await awaitable()
  153. yield 123
  154. await awaitable()
  155. g = gen()
  156. ai = g.__aiter__()
  157. an = ai.__anext__()
  158. self.assertEqual(an.__next__(), ('result',))
  159. try:
  160. an.__next__()
  161. except StopIteration as ex:
  162. self.assertEqual(ex.args[0], 123)
  163. else:
  164. self.fail('StopIteration was not raised')
  165. an = ai.__anext__()
  166. self.assertEqual(an.__next__(), ('result',))
  167. try:
  168. an.__next__()
  169. except StopAsyncIteration as ex:
  170. self.assertFalse(ex.args)
  171. else:
  172. self.fail('StopAsyncIteration was not raised')
  173. def test_async_gen_exception_03(self):
  174. async def gen():
  175. await awaitable()
  176. yield 123
  177. await awaitable(throw=True)
  178. yield 456
  179. with self.assertRaises(AwaitException):
  180. to_list(gen())
  181. def test_async_gen_exception_04(self):
  182. async def gen():
  183. await awaitable()
  184. yield 123
  185. 1 / 0
  186. g = gen()
  187. ai = g.__aiter__()
  188. an = ai.__anext__()
  189. self.assertEqual(an.__next__(), ('result',))
  190. try:
  191. an.__next__()
  192. except StopIteration as ex:
  193. self.assertEqual(ex.args[0], 123)
  194. else:
  195. self.fail('StopIteration was not raised')
  196. with self.assertRaises(ZeroDivisionError):
  197. ai.__anext__().__next__()
  198. def test_async_gen_exception_05(self):
  199. async def gen():
  200. yield 123
  201. raise StopAsyncIteration
  202. with self.assertRaisesRegex(RuntimeError,
  203. 'async generator.*StopAsyncIteration'):
  204. to_list(gen())
  205. def test_async_gen_exception_06(self):
  206. async def gen():
  207. yield 123
  208. raise StopIteration
  209. with self.assertRaisesRegex(RuntimeError,
  210. 'async generator.*StopIteration'):
  211. to_list(gen())
  212. def test_async_gen_exception_07(self):
  213. def sync_gen():
  214. try:
  215. yield 1
  216. 1 / 0
  217. finally:
  218. yield 2
  219. yield 3
  220. yield 100
  221. async def async_gen():
  222. try:
  223. yield 1
  224. 1 / 0
  225. finally:
  226. yield 2
  227. yield 3
  228. yield 100
  229. self.compare_generators(sync_gen(), async_gen())
  230. def test_async_gen_exception_08(self):
  231. def sync_gen():
  232. try:
  233. yield 1
  234. finally:
  235. yield 2
  236. 1 / 0
  237. yield 3
  238. yield 100
  239. async def async_gen():
  240. try:
  241. yield 1
  242. await awaitable()
  243. finally:
  244. await awaitable()
  245. yield 2
  246. 1 / 0
  247. yield 3
  248. yield 100
  249. self.compare_generators(sync_gen(), async_gen())
  250. def test_async_gen_exception_09(self):
  251. def sync_gen():
  252. try:
  253. yield 1
  254. 1 / 0
  255. finally:
  256. yield 2
  257. yield 3
  258. yield 100
  259. async def async_gen():
  260. try:
  261. await awaitable()
  262. yield 1
  263. 1 / 0
  264. finally:
  265. yield 2
  266. await awaitable()
  267. yield 3
  268. yield 100
  269. self.compare_generators(sync_gen(), async_gen())
  270. def test_async_gen_exception_10(self):
  271. async def gen():
  272. yield 123
  273. with self.assertRaisesRegex(TypeError,
  274. "non-None value .* async generator"):
  275. gen().__anext__().send(100)
  276. def test_async_gen_exception_11(self):
  277. def sync_gen():
  278. yield 10
  279. yield 20
  280. def sync_gen_wrapper():
  281. yield 1
  282. sg = sync_gen()
  283. sg.send(None)
  284. try:
  285. sg.throw(GeneratorExit())
  286. except GeneratorExit:
  287. yield 2
  288. yield 3
  289. async def async_gen():
  290. yield 10
  291. yield 20
  292. async def async_gen_wrapper():
  293. yield 1
  294. asg = async_gen()
  295. await asg.asend(None)
  296. try:
  297. await asg.athrow(GeneratorExit())
  298. except GeneratorExit:
  299. yield 2
  300. yield 3
  301. self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())
  302. def test_async_gen_api_01(self):
  303. async def gen():
  304. yield 123
  305. g = gen()
  306. self.assertEqual(g.__name__, 'gen')
  307. g.__name__ = '123'
  308. self.assertEqual(g.__name__, '123')
  309. self.assertIn('.gen', g.__qualname__)
  310. g.__qualname__ = '123'
  311. self.assertEqual(g.__qualname__, '123')
  312. self.assertIsNone(g.ag_await)
  313. self.assertIsInstance(g.ag_frame, types.FrameType)
  314. self.assertFalse(g.ag_running)
  315. self.assertIsInstance(g.ag_code, types.CodeType)
  316. self.assertTrue(inspect.isawaitable(g.aclose()))
  317. class AsyncGenAsyncioTest(unittest.TestCase):
  318. def setUp(self):
  319. self.loop = asyncio.new_event_loop()
  320. asyncio.set_event_loop(None)
  321. def tearDown(self):
  322. self.loop.close()
  323. self.loop = None
  324. asyncio.set_event_loop_policy(None)
  325. def check_async_iterator_anext(self, ait_class):
  326. with self.subTest(anext="pure-Python"):
  327. self._check_async_iterator_anext(ait_class, py_anext)
  328. with self.subTest(anext="builtin"):
  329. self._check_async_iterator_anext(ait_class, anext)
  330. def _check_async_iterator_anext(self, ait_class, anext):
  331. g = ait_class()
  332. async def consume():
  333. results = []
  334. results.append(await anext(g))
  335. results.append(await anext(g))
  336. results.append(await anext(g, 'buckle my shoe'))
  337. return results
  338. res = self.loop.run_until_complete(consume())
  339. self.assertEqual(res, [1, 2, 'buckle my shoe'])
  340. with self.assertRaises(StopAsyncIteration):
  341. self.loop.run_until_complete(consume())
  342. async def test_2():
  343. g1 = ait_class()
  344. self.assertEqual(await anext(g1), 1)
  345. self.assertEqual(await anext(g1), 2)
  346. with self.assertRaises(StopAsyncIteration):
  347. await anext(g1)
  348. with self.assertRaises(StopAsyncIteration):
  349. await anext(g1)
  350. g2 = ait_class()
  351. self.assertEqual(await anext(g2, "default"), 1)
  352. self.assertEqual(await anext(g2, "default"), 2)
  353. self.assertEqual(await anext(g2, "default"), "default")
  354. self.assertEqual(await anext(g2, "default"), "default")
  355. return "completed"
  356. result = self.loop.run_until_complete(test_2())
  357. self.assertEqual(result, "completed")
  358. def test_send():
  359. p = ait_class()
  360. obj = anext(p, "completed")
  361. with self.assertRaises(StopIteration):
  362. with contextlib.closing(obj.__await__()) as g:
  363. g.send(None)
  364. test_send()
  365. async def test_throw():
  366. p = ait_class()
  367. obj = anext(p, "completed")
  368. self.assertRaises(SyntaxError, obj.throw, SyntaxError)
  369. return "completed"
  370. result = self.loop.run_until_complete(test_throw())
  371. self.assertEqual(result, "completed")
  372. def test_async_generator_anext(self):
  373. async def agen():
  374. yield 1
  375. yield 2
  376. self.check_async_iterator_anext(agen)
  377. def test_python_async_iterator_anext(self):
  378. class MyAsyncIter:
  379. """Asynchronously yield 1, then 2."""
  380. def __init__(self):
  381. self.yielded = 0
  382. def __aiter__(self):
  383. return self
  384. async def __anext__(self):
  385. if self.yielded >= 2:
  386. raise StopAsyncIteration()
  387. else:
  388. self.yielded += 1
  389. return self.yielded
  390. self.check_async_iterator_anext(MyAsyncIter)
  391. def test_python_async_iterator_types_coroutine_anext(self):
  392. import types
  393. class MyAsyncIterWithTypesCoro:
  394. """Asynchronously yield 1, then 2."""
  395. def __init__(self):
  396. self.yielded = 0
  397. def __aiter__(self):
  398. return self
  399. @types.coroutine
  400. def __anext__(self):
  401. if False:
  402. yield "this is a generator-based coroutine"
  403. if self.yielded >= 2:
  404. raise StopAsyncIteration()
  405. else:
  406. self.yielded += 1
  407. return self.yielded
  408. self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)
  409. def test_async_gen_aiter(self):
  410. async def gen():
  411. yield 1
  412. yield 2
  413. g = gen()
  414. async def consume():
  415. return [i async for i in aiter(g)]
  416. res = self.loop.run_until_complete(consume())
  417. self.assertEqual(res, [1, 2])
  418. def test_async_gen_aiter_class(self):
  419. results = []
  420. class Gen:
  421. async def __aiter__(self):
  422. yield 1
  423. yield 2
  424. g = Gen()
  425. async def consume():
  426. ait = aiter(g)
  427. while True:
  428. try:
  429. results.append(await anext(ait))
  430. except StopAsyncIteration:
  431. break
  432. self.loop.run_until_complete(consume())
  433. self.assertEqual(results, [1, 2])
  434. def test_aiter_idempotent(self):
  435. async def gen():
  436. yield 1
  437. applied_once = aiter(gen())
  438. applied_twice = aiter(applied_once)
  439. self.assertIs(applied_once, applied_twice)
  440. def test_anext_bad_args(self):
  441. async def gen():
  442. yield 1
  443. async def call_with_too_few_args():
  444. await anext()
  445. async def call_with_too_many_args():
  446. await anext(gen(), 1, 3)
  447. async def call_with_wrong_type_args():
  448. await anext(1, gen())
  449. async def call_with_kwarg():
  450. await anext(aiterator=gen())
  451. with self.assertRaises(TypeError):
  452. self.loop.run_until_complete(call_with_too_few_args())
  453. with self.assertRaises(TypeError):
  454. self.loop.run_until_complete(call_with_too_many_args())
  455. with self.assertRaises(TypeError):
  456. self.loop.run_until_complete(call_with_wrong_type_args())
  457. with self.assertRaises(TypeError):
  458. self.loop.run_until_complete(call_with_kwarg())
  459. def test_anext_bad_await(self):
  460. async def bad_awaitable():
  461. class BadAwaitable:
  462. def __await__(self):
  463. return 42
  464. class MyAsyncIter:
  465. def __aiter__(self):
  466. return self
  467. def __anext__(self):
  468. return BadAwaitable()
  469. regex = r"__await__.*iterator"
  470. awaitable = anext(MyAsyncIter(), "default")
  471. with self.assertRaisesRegex(TypeError, regex):
  472. await awaitable
  473. awaitable = anext(MyAsyncIter())
  474. with self.assertRaisesRegex(TypeError, regex):
  475. await awaitable
  476. return "completed"
  477. result = self.loop.run_until_complete(bad_awaitable())
  478. self.assertEqual(result, "completed")
  479. async def check_anext_returning_iterator(self, aiter_class):
  480. awaitable = anext(aiter_class(), "default")
  481. with self.assertRaises(TypeError):
  482. await awaitable
  483. awaitable = anext(aiter_class())
  484. with self.assertRaises(TypeError):
  485. await awaitable
  486. return "completed"
  487. def test_anext_return_iterator(self):
  488. class WithIterAnext:
  489. def __aiter__(self):
  490. return self
  491. def __anext__(self):
  492. return iter("abc")
  493. result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))
  494. self.assertEqual(result, "completed")
  495. def test_anext_return_generator(self):
  496. class WithGenAnext:
  497. def __aiter__(self):
  498. return self
  499. def __anext__(self):
  500. yield
  501. result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))
  502. self.assertEqual(result, "completed")
  503. def test_anext_await_raises(self):
  504. class RaisingAwaitable:
  505. def __await__(self):
  506. raise ZeroDivisionError()
  507. yield
  508. class WithRaisingAwaitableAnext:
  509. def __aiter__(self):
  510. return self
  511. def __anext__(self):
  512. return RaisingAwaitable()
  513. async def do_test():
  514. awaitable = anext(WithRaisingAwaitableAnext())
  515. with self.assertRaises(ZeroDivisionError):
  516. await awaitable
  517. awaitable = anext(WithRaisingAwaitableAnext(), "default")
  518. with self.assertRaises(ZeroDivisionError):
  519. await awaitable
  520. return "completed"
  521. result = self.loop.run_until_complete(do_test())
  522. self.assertEqual(result, "completed")
  523. def test_anext_iter(self):
  524. @types.coroutine
  525. def _async_yield(v):
  526. return (yield v)
  527. class MyError(Exception):
  528. pass
  529. async def agenfn():
  530. try:
  531. await _async_yield(1)
  532. except MyError:
  533. await _async_yield(2)
  534. return
  535. yield
  536. def test1(anext):
  537. agen = agenfn()
  538. with contextlib.closing(anext(agen, "default").__await__()) as g:
  539. self.assertEqual(g.send(None), 1)
  540. self.assertEqual(g.throw(MyError, MyError(), None), 2)
  541. try:
  542. g.send(None)
  543. except StopIteration as e:
  544. err = e
  545. else:
  546. self.fail('StopIteration was not raised')
  547. self.assertEqual(err.value, "default")
  548. def test2(anext):
  549. agen = agenfn()
  550. with contextlib.closing(anext(agen, "default").__await__()) as g:
  551. self.assertEqual(g.send(None), 1)
  552. self.assertEqual(g.throw(MyError, MyError(), None), 2)
  553. with self.assertRaises(MyError):
  554. g.throw(MyError, MyError(), None)
  555. def test3(anext):
  556. agen = agenfn()
  557. with contextlib.closing(anext(agen, "default").__await__()) as g:
  558. self.assertEqual(g.send(None), 1)
  559. g.close()
  560. with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):
  561. self.assertEqual(g.send(None), 1)
  562. def test4(anext):
  563. @types.coroutine
  564. def _async_yield(v):
  565. yield v * 10
  566. return (yield (v * 10 + 1))
  567. async def agenfn():
  568. try:
  569. await _async_yield(1)
  570. except MyError:
  571. await _async_yield(2)
  572. return
  573. yield
  574. agen = agenfn()
  575. with contextlib.closing(anext(agen, "default").__await__()) as g:
  576. self.assertEqual(g.send(None), 10)
  577. self.assertEqual(g.throw(MyError, MyError(), None), 20)
  578. with self.assertRaisesRegex(MyError, 'val'):
  579. g.throw(MyError, MyError('val'), None)
  580. def test5(anext):
  581. @types.coroutine
  582. def _async_yield(v):
  583. yield v * 10
  584. return (yield (v * 10 + 1))
  585. async def agenfn():
  586. try:
  587. await _async_yield(1)
  588. except MyError:
  589. return
  590. yield 'aaa'
  591. agen = agenfn()
  592. with contextlib.closing(anext(agen, "default").__await__()) as g:
  593. self.assertEqual(g.send(None), 10)
  594. with self.assertRaisesRegex(StopIteration, 'default'):
  595. g.throw(MyError, MyError(), None)
  596. def test6(anext):
  597. @types.coroutine
  598. def _async_yield(v):
  599. yield v * 10
  600. return (yield (v * 10 + 1))
  601. async def agenfn():
  602. await _async_yield(1)
  603. yield 'aaa'
  604. agen = agenfn()
  605. with contextlib.closing(anext(agen, "default").__await__()) as g:
  606. with self.assertRaises(MyError):
  607. g.throw(MyError, MyError(), None)
  608. def run_test(test):
  609. with self.subTest('pure-Python anext()'):
  610. test(py_anext)
  611. with self.subTest('builtin anext()'):
  612. test(anext)
  613. run_test(test1)
  614. run_test(test2)
  615. run_test(test3)
  616. run_test(test4)
  617. run_test(test5)
  618. run_test(test6)
  619. def test_aiter_bad_args(self):
  620. async def gen():
  621. yield 1
  622. async def call_with_too_few_args():
  623. await aiter()
  624. async def call_with_too_many_args():
  625. await aiter(gen(), 1)
  626. async def call_with_wrong_type_arg():
  627. await aiter(1)
  628. with self.assertRaises(TypeError):
  629. self.loop.run_until_complete(call_with_too_few_args())
  630. with self.assertRaises(TypeError):
  631. self.loop.run_until_complete(call_with_too_many_args())
  632. with self.assertRaises(TypeError):
  633. self.loop.run_until_complete(call_with_wrong_type_arg())
  634. async def to_list(self, gen):
  635. res = []
  636. async for i in gen:
  637. res.append(i)
  638. return res
  639. def test_async_gen_asyncio_01(self):
  640. async def gen():
  641. yield 1
  642. await asyncio.sleep(0.01)
  643. yield 2
  644. await asyncio.sleep(0.01)
  645. return
  646. yield 3
  647. res = self.loop.run_until_complete(self.to_list(gen()))
  648. self.assertEqual(res, [1, 2])
  649. def test_async_gen_asyncio_02(self):
  650. async def gen():
  651. yield 1
  652. await asyncio.sleep(0.01)
  653. yield 2
  654. 1 / 0
  655. yield 3
  656. with self.assertRaises(ZeroDivisionError):
  657. self.loop.run_until_complete(self.to_list(gen()))
  658. def test_async_gen_asyncio_03(self):
  659. loop = self.loop
  660. class Gen:
  661. async def __aiter__(self):
  662. yield 1
  663. await asyncio.sleep(0.01)
  664. yield 2
  665. res = loop.run_until_complete(self.to_list(Gen()))
  666. self.assertEqual(res, [1, 2])
  667. def test_async_gen_asyncio_anext_04(self):
  668. async def foo():
  669. yield 1
  670. await asyncio.sleep(0.01)
  671. try:
  672. yield 2
  673. yield 3
  674. except ZeroDivisionError:
  675. yield 1000
  676. await asyncio.sleep(0.01)
  677. yield 4
  678. async def run1():
  679. it = foo().__aiter__()
  680. self.assertEqual(await it.__anext__(), 1)
  681. self.assertEqual(await it.__anext__(), 2)
  682. self.assertEqual(await it.__anext__(), 3)
  683. self.assertEqual(await it.__anext__(), 4)
  684. with self.assertRaises(StopAsyncIteration):
  685. await it.__anext__()
  686. with self.assertRaises(StopAsyncIteration):
  687. await it.__anext__()
  688. async def run2():
  689. it = foo().__aiter__()
  690. self.assertEqual(await it.__anext__(), 1)
  691. self.assertEqual(await it.__anext__(), 2)
  692. try:
  693. it.__anext__().throw(ZeroDivisionError)
  694. except StopIteration as ex:
  695. self.assertEqual(ex.args[0], 1000)
  696. else:
  697. self.fail('StopIteration was not raised')
  698. self.assertEqual(await it.__anext__(), 4)
  699. with self.assertRaises(StopAsyncIteration):
  700. await it.__anext__()
  701. self.loop.run_until_complete(run1())
  702. self.loop.run_until_complete(run2())
  703. def test_async_gen_asyncio_anext_05(self):
  704. async def foo():
  705. v = yield 1
  706. v = yield v
  707. yield v * 100
  708. async def run():
  709. it = foo().__aiter__()
  710. try:
  711. it.__anext__().send(None)
  712. except StopIteration as ex:
  713. self.assertEqual(ex.args[0], 1)
  714. else:
  715. self.fail('StopIteration was not raised')
  716. try:
  717. it.__anext__().send(10)
  718. except StopIteration as ex:
  719. self.assertEqual(ex.args[0], 10)
  720. else:
  721. self.fail('StopIteration was not raised')
  722. try:
  723. it.__anext__().send(12)
  724. except StopIteration as ex:
  725. self.assertEqual(ex.args[0], 1200)
  726. else:
  727. self.fail('StopIteration was not raised')
  728. with self.assertRaises(StopAsyncIteration):
  729. await it.__anext__()
  730. self.loop.run_until_complete(run())
  731. def test_async_gen_asyncio_anext_06(self):
  732. DONE = 0
  733. # test synchronous generators
  734. def foo():
  735. try:
  736. yield
  737. except:
  738. pass
  739. g = foo()
  740. g.send(None)
  741. with self.assertRaises(StopIteration):
  742. g.send(None)
  743. # now with asynchronous generators
  744. async def gen():
  745. nonlocal DONE
  746. try:
  747. yield
  748. except:
  749. pass
  750. DONE = 1
  751. async def run():
  752. nonlocal DONE
  753. g = gen()
  754. await g.asend(None)
  755. with self.assertRaises(StopAsyncIteration):
  756. await g.asend(None)
  757. DONE += 10
  758. self.loop.run_until_complete(run())
  759. self.assertEqual(DONE, 11)
  760. def test_async_gen_asyncio_anext_tuple(self):
  761. async def foo():
  762. try:
  763. yield (1,)
  764. except ZeroDivisionError:
  765. yield (2,)
  766. async def run():
  767. it = foo().__aiter__()
  768. self.assertEqual(await it.__anext__(), (1,))
  769. with self.assertRaises(StopIteration) as cm:
  770. it.__anext__().throw(ZeroDivisionError)
  771. self.assertEqual(cm.exception.args[0], (2,))
  772. with self.assertRaises(StopAsyncIteration):
  773. await it.__anext__()
  774. self.loop.run_until_complete(run())
  775. def test_async_gen_asyncio_anext_stopiteration(self):
  776. async def foo():
  777. try:
  778. yield StopIteration(1)
  779. except ZeroDivisionError:
  780. yield StopIteration(3)
  781. async def run():
  782. it = foo().__aiter__()
  783. v = await it.__anext__()
  784. self.assertIsInstance(v, StopIteration)
  785. self.assertEqual(v.value, 1)
  786. with self.assertRaises(StopIteration) as cm:
  787. it.__anext__().throw(ZeroDivisionError)
  788. v = cm.exception.args[0]
  789. self.assertIsInstance(v, StopIteration)
  790. self.assertEqual(v.value, 3)
  791. with self.assertRaises(StopAsyncIteration):
  792. await it.__anext__()
  793. self.loop.run_until_complete(run())
  794. def test_async_gen_asyncio_aclose_06(self):
  795. async def foo():
  796. try:
  797. yield 1
  798. 1 / 0
  799. finally:
  800. await asyncio.sleep(0.01)
  801. yield 12
  802. async def run():
  803. gen = foo()
  804. it = gen.__aiter__()
  805. await it.__anext__()
  806. await gen.aclose()
  807. with self.assertRaisesRegex(
  808. RuntimeError,
  809. "async generator ignored GeneratorExit"):
  810. self.loop.run_until_complete(run())
  811. def test_async_gen_asyncio_aclose_07(self):
  812. DONE = 0
  813. async def foo():
  814. nonlocal DONE
  815. try:
  816. yield 1
  817. 1 / 0
  818. finally:
  819. await asyncio.sleep(0.01)
  820. await asyncio.sleep(0.01)
  821. DONE += 1
  822. DONE += 1000
  823. async def run():
  824. gen = foo()
  825. it = gen.__aiter__()
  826. await it.__anext__()
  827. await gen.aclose()
  828. self.loop.run_until_complete(run())
  829. self.assertEqual(DONE, 1)
  830. def test_async_gen_asyncio_aclose_08(self):
  831. DONE = 0
  832. fut = asyncio.Future(loop=self.loop)
  833. async def foo():
  834. nonlocal DONE
  835. try:
  836. yield 1
  837. await fut
  838. DONE += 1000
  839. yield 2
  840. finally:
  841. await asyncio.sleep(0.01)
  842. await asyncio.sleep(0.01)
  843. DONE += 1
  844. DONE += 1000
  845. async def run():
  846. gen = foo()
  847. it = gen.__aiter__()
  848. self.assertEqual(await it.__anext__(), 1)
  849. await gen.aclose()
  850. self.loop.run_until_complete(run())
  851. self.assertEqual(DONE, 1)
  852. # Silence ResourceWarnings
  853. fut.cancel()
  854. self.loop.run_until_complete(asyncio.sleep(0.01))
  855. def test_async_gen_asyncio_gc_aclose_09(self):
  856. DONE = 0
  857. async def gen():
  858. nonlocal DONE
  859. try:
  860. while True:
  861. yield 1
  862. finally:
  863. await asyncio.sleep(0.01)
  864. await asyncio.sleep(0.01)
  865. DONE = 1
  866. async def run():
  867. g = gen()
  868. await g.__anext__()
  869. await g.__anext__()
  870. del g
  871. gc_collect() # For PyPy or other GCs.
  872. await asyncio.sleep(0.1)
  873. self.loop.run_until_complete(run())
  874. self.assertEqual(DONE, 1)
  875. def test_async_gen_asyncio_aclose_10(self):
  876. DONE = 0
  877. # test synchronous generators
  878. def foo():
  879. try:
  880. yield
  881. except:
  882. pass
  883. g = foo()
  884. g.send(None)
  885. g.close()
  886. # now with asynchronous generators
  887. async def gen():
  888. nonlocal DONE
  889. try:
  890. yield
  891. except:
  892. pass
  893. DONE = 1
  894. async def run():
  895. nonlocal DONE
  896. g = gen()
  897. await g.asend(None)
  898. await g.aclose()
  899. DONE += 10
  900. self.loop.run_until_complete(run())
  901. self.assertEqual(DONE, 11)
  902. def test_async_gen_asyncio_aclose_11(self):
  903. DONE = 0
  904. # test synchronous generators
  905. def foo():
  906. try:
  907. yield
  908. except:
  909. pass
  910. yield
  911. g = foo()
  912. g.send(None)
  913. with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
  914. g.close()
  915. # now with asynchronous generators
  916. async def gen():
  917. nonlocal DONE
  918. try:
  919. yield
  920. except:
  921. pass
  922. yield
  923. DONE += 1
  924. async def run():
  925. nonlocal DONE
  926. g = gen()
  927. await g.asend(None)
  928. with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):
  929. await g.aclose()
  930. DONE += 10
  931. self.loop.run_until_complete(run())
  932. self.assertEqual(DONE, 10)
  933. def test_async_gen_asyncio_aclose_12(self):
  934. DONE = 0
  935. async def target():
  936. await asyncio.sleep(0.01)
  937. 1 / 0
  938. async def foo():
  939. nonlocal DONE
  940. task = asyncio.create_task(target())
  941. try:
  942. yield 1
  943. finally:
  944. try:
  945. await task
  946. except ZeroDivisionError:
  947. DONE = 1
  948. async def run():
  949. gen = foo()
  950. it = gen.__aiter__()
  951. await it.__anext__()
  952. await gen.aclose()
  953. self.loop.run_until_complete(run())
  954. self.assertEqual(DONE, 1)
  955. def test_async_gen_asyncio_asend_01(self):
  956. DONE = 0
  957. # Sanity check:
  958. def sgen():
  959. v = yield 1
  960. yield v * 2
  961. sg = sgen()
  962. v = sg.send(None)
  963. self.assertEqual(v, 1)
  964. v = sg.send(100)
  965. self.assertEqual(v, 200)
  966. async def gen():
  967. nonlocal DONE
  968. try:
  969. await asyncio.sleep(0.01)
  970. v = yield 1
  971. await asyncio.sleep(0.01)
  972. yield v * 2
  973. await asyncio.sleep(0.01)
  974. return
  975. finally:
  976. await asyncio.sleep(0.01)
  977. await asyncio.sleep(0.01)
  978. DONE = 1
  979. async def run():
  980. g = gen()
  981. v = await g.asend(None)
  982. self.assertEqual(v, 1)
  983. v = await g.asend(100)
  984. self.assertEqual(v, 200)
  985. with self.assertRaises(StopAsyncIteration):
  986. await g.asend(None)
  987. self.loop.run_until_complete(run())
  988. self.assertEqual(DONE, 1)
  989. def test_async_gen_asyncio_asend_02(self):
  990. DONE = 0
  991. async def sleep_n_crash(delay):
  992. await asyncio.sleep(delay)
  993. 1 / 0
  994. async def gen():
  995. nonlocal DONE
  996. try:
  997. await asyncio.sleep(0.01)
  998. v = yield 1
  999. await sleep_n_crash(0.01)
  1000. DONE += 1000
  1001. yield v * 2
  1002. finally:
  1003. await asyncio.sleep(0.01)
  1004. await asyncio.sleep(0.01)
  1005. DONE = 1
  1006. async def run():
  1007. g = gen()
  1008. v = await g.asend(None)
  1009. self.assertEqual(v, 1)
  1010. await g.asend(100)
  1011. with self.assertRaises(ZeroDivisionError):
  1012. self.loop.run_until_complete(run())
  1013. self.assertEqual(DONE, 1)
  1014. def test_async_gen_asyncio_asend_03(self):
  1015. DONE = 0
  1016. async def sleep_n_crash(delay):
  1017. fut = asyncio.ensure_future(asyncio.sleep(delay),
  1018. loop=self.loop)
  1019. self.loop.call_later(delay / 2, lambda: fut.cancel())
  1020. return await fut
  1021. async def gen():
  1022. nonlocal DONE
  1023. try:
  1024. await asyncio.sleep(0.01)
  1025. v = yield 1
  1026. await sleep_n_crash(0.01)
  1027. DONE += 1000
  1028. yield v * 2
  1029. finally:
  1030. await asyncio.sleep(0.01)
  1031. await asyncio.sleep(0.01)
  1032. DONE = 1
  1033. async def run():
  1034. g = gen()
  1035. v = await g.asend(None)
  1036. self.assertEqual(v, 1)
  1037. await g.asend(100)
  1038. with self.assertRaises(asyncio.CancelledError):
  1039. self.loop.run_until_complete(run())
  1040. self.assertEqual(DONE, 1)
  1041. def test_async_gen_asyncio_athrow_01(self):
  1042. DONE = 0
  1043. class FooEr(Exception):
  1044. pass
  1045. # Sanity check:
  1046. def sgen():
  1047. try:
  1048. v = yield 1
  1049. except FooEr:
  1050. v = 1000
  1051. yield v * 2
  1052. sg = sgen()
  1053. v = sg.send(None)
  1054. self.assertEqual(v, 1)
  1055. v = sg.throw(FooEr)
  1056. self.assertEqual(v, 2000)
  1057. with self.assertRaises(StopIteration):
  1058. sg.send(None)
  1059. async def gen():
  1060. nonlocal DONE
  1061. try:
  1062. await asyncio.sleep(0.01)
  1063. try:
  1064. v = yield 1
  1065. except FooEr:
  1066. v = 1000
  1067. await asyncio.sleep(0.01)
  1068. yield v * 2
  1069. await asyncio.sleep(0.01)
  1070. # return
  1071. finally:
  1072. await asyncio.sleep(0.01)
  1073. await asyncio.sleep(0.01)
  1074. DONE = 1
  1075. async def run():
  1076. g = gen()
  1077. v = await g.asend(None)
  1078. self.assertEqual(v, 1)
  1079. v = await g.athrow(FooEr)
  1080. self.assertEqual(v, 2000)
  1081. with self.assertRaises(StopAsyncIteration):
  1082. await g.asend(None)
  1083. self.loop.run_until_complete(run())
  1084. self.assertEqual(DONE, 1)
  1085. def test_async_gen_asyncio_athrow_02(self):
  1086. DONE = 0
  1087. class FooEr(Exception):
  1088. pass
  1089. async def sleep_n_crash(delay):
  1090. fut = asyncio.ensure_future(asyncio.sleep(delay),
  1091. loop=self.loop)
  1092. self.loop.call_later(delay / 2, lambda: fut.cancel())
  1093. return await fut
  1094. async def gen():
  1095. nonlocal DONE
  1096. try:
  1097. await asyncio.sleep(0.01)
  1098. try:
  1099. v = yield 1
  1100. except FooEr:
  1101. await sleep_n_crash(0.01)
  1102. yield v * 2
  1103. await asyncio.sleep(0.01)
  1104. # return
  1105. finally:
  1106. await asyncio.sleep(0.01)
  1107. await asyncio.sleep(0.01)
  1108. DONE = 1
  1109. async def run():
  1110. g = gen()
  1111. v = await g.asend(None)
  1112. self.assertEqual(v, 1)
  1113. try:
  1114. await g.athrow(FooEr)
  1115. except asyncio.CancelledError:
  1116. self.assertEqual(DONE, 1)
  1117. raise
  1118. else:
  1119. self.fail('CancelledError was not raised')
  1120. with self.assertRaises(asyncio.CancelledError):
  1121. self.loop.run_until_complete(run())
  1122. self.assertEqual(DONE, 1)
  1123. def test_async_gen_asyncio_athrow_03(self):
  1124. DONE = 0
  1125. # test synchronous generators
  1126. def foo():
  1127. try:
  1128. yield
  1129. except:
  1130. pass
  1131. g = foo()
  1132. g.send(None)
  1133. with self.assertRaises(StopIteration):
  1134. g.throw(ValueError)
  1135. # now with asynchronous generators
  1136. async def gen():
  1137. nonlocal DONE
  1138. try:
  1139. yield
  1140. except:
  1141. pass
  1142. DONE = 1
  1143. async def run():
  1144. nonlocal DONE
  1145. g = gen()
  1146. await g.asend(None)
  1147. with self.assertRaises(StopAsyncIteration):
  1148. await g.athrow(ValueError)
  1149. DONE += 10
  1150. self.loop.run_until_complete(run())
  1151. self.assertEqual(DONE, 11)
  1152. def test_async_gen_asyncio_athrow_tuple(self):
  1153. async def gen():
  1154. try:
  1155. yield 1
  1156. except ZeroDivisionError:
  1157. yield (2,)
  1158. async def run():
  1159. g = gen()
  1160. v = await g.asend(None)
  1161. self.assertEqual(v, 1)
  1162. v = await g.athrow(ZeroDivisionError)
  1163. self.assertEqual(v, (2,))
  1164. with self.assertRaises(StopAsyncIteration):
  1165. await g.asend(None)
  1166. self.loop.run_until_complete(run())
  1167. def test_async_gen_asyncio_athrow_stopiteration(self):
  1168. async def gen():
  1169. try:
  1170. yield 1
  1171. except ZeroDivisionError:
  1172. yield StopIteration(2)
  1173. async def run():
  1174. g = gen()
  1175. v = await g.asend(None)
  1176. self.assertEqual(v, 1)
  1177. v = await g.athrow(ZeroDivisionError)
  1178. self.assertIsInstance(v, StopIteration)
  1179. self.assertEqual(v.value, 2)
  1180. with self.assertRaises(StopAsyncIteration):
  1181. await g.asend(None)
  1182. self.loop.run_until_complete(run())
  1183. def test_async_gen_asyncio_shutdown_01(self):
  1184. finalized = 0
  1185. async def waiter(timeout):
  1186. nonlocal finalized
  1187. try:
  1188. await asyncio.sleep(timeout)
  1189. yield 1
  1190. finally:
  1191. await asyncio.sleep(0)
  1192. finalized += 1
  1193. async def wait():
  1194. async for _ in waiter(1):
  1195. pass
  1196. t1 = self.loop.create_task(wait())
  1197. t2 = self.loop.create_task(wait())
  1198. self.loop.run_until_complete(asyncio.sleep(0.1))
  1199. # Silence warnings
  1200. t1.cancel()
  1201. t2.cancel()
  1202. with self.assertRaises(asyncio.CancelledError):
  1203. self.loop.run_until_complete(t1)
  1204. with self.assertRaises(asyncio.CancelledError):
  1205. self.loop.run_until_complete(t2)
  1206. self.loop.run_until_complete(self.loop.shutdown_asyncgens())
  1207. self.assertEqual(finalized, 2)
  1208. def test_async_gen_asyncio_shutdown_02(self):
  1209. messages = []
  1210. def exception_handler(loop, context):
  1211. messages.append(context)
  1212. async def async_iterate():
  1213. yield 1
  1214. yield 2
  1215. it = async_iterate()
  1216. async def main():
  1217. loop = asyncio.get_running_loop()
  1218. loop.set_exception_handler(exception_handler)
  1219. async for i in it:
  1220. break
  1221. asyncio.run(main())
  1222. self.assertEqual(messages, [])
  1223. def test_async_gen_asyncio_shutdown_exception_01(self):
  1224. messages = []
  1225. def exception_handler(loop, context):
  1226. messages.append(context)
  1227. async def async_iterate():
  1228. try:
  1229. yield 1
  1230. yield 2
  1231. finally:
  1232. 1/0
  1233. it = async_iterate()
  1234. async def main():
  1235. loop = asyncio.get_running_loop()
  1236. loop.set_exception_handler(exception_handler)
  1237. async for i in it:
  1238. break
  1239. asyncio.run(main())
  1240. message, = messages
  1241. self.assertEqual(message['asyncgen'], it)
  1242. self.assertIsInstance(message['exception'], ZeroDivisionError)
  1243. self.assertIn('an error occurred during closing of asynchronous generator',
  1244. message['message'])
  1245. def test_async_gen_asyncio_shutdown_exception_02(self):
  1246. messages = []
  1247. def exception_handler(loop, context):
  1248. messages.append(context)
  1249. async def async_iterate():
  1250. try:
  1251. yield 1
  1252. yield 2
  1253. finally:
  1254. 1/0
  1255. async def main():
  1256. loop = asyncio.get_running_loop()
  1257. loop.set_exception_handler(exception_handler)
  1258. async for i in async_iterate():
  1259. break
  1260. gc_collect()
  1261. asyncio.run(main())
  1262. message, = messages
  1263. self.assertIsInstance(message['exception'], ZeroDivisionError)
  1264. self.assertIn('unhandled exception during asyncio.run() shutdown',
  1265. message['message'])
  1266. def test_async_gen_expression_01(self):
  1267. async def arange(n):
  1268. for i in range(n):
  1269. await asyncio.sleep(0.01)
  1270. yield i
  1271. def make_arange(n):
  1272. # This syntax is legal starting with Python 3.7
  1273. return (i * 2 async for i in arange(n))
  1274. async def run():
  1275. return [i async for i in make_arange(10)]
  1276. res = self.loop.run_until_complete(run())
  1277. self.assertEqual(res, [i * 2 for i in range(10)])
  1278. def test_async_gen_expression_02(self):
  1279. async def wrap(n):
  1280. await asyncio.sleep(0.01)
  1281. return n
  1282. def make_arange(n):
  1283. # This syntax is legal starting with Python 3.7
  1284. return (i * 2 for i in range(n) if await wrap(i))
  1285. async def run():
  1286. return [i async for i in make_arange(10)]
  1287. res = self.loop.run_until_complete(run())
  1288. self.assertEqual(res, [i * 2 for i in range(1, 10)])
  1289. def test_asyncgen_nonstarted_hooks_are_cancellable(self):
  1290. # See https://bugs.python.org/issue38013
  1291. messages = []
  1292. def exception_handler(loop, context):
  1293. messages.append(context)
  1294. async def async_iterate():
  1295. yield 1
  1296. yield 2
  1297. async def main():
  1298. loop = asyncio.get_running_loop()
  1299. loop.set_exception_handler(exception_handler)
  1300. async for i in async_iterate():
  1301. break
  1302. asyncio.run(main())
  1303. self.assertEqual([], messages)
  1304. def test_async_gen_await_same_anext_coro_twice(self):
  1305. async def async_iterate():
  1306. yield 1
  1307. yield 2
  1308. async def run():
  1309. it = async_iterate()
  1310. nxt = it.__anext__()
  1311. await nxt
  1312. with self.assertRaisesRegex(
  1313. RuntimeError,
  1314. r"cannot reuse already awaited __anext__\(\)/asend\(\)"
  1315. ):
  1316. await nxt
  1317. await it.aclose() # prevent unfinished iterator warning
  1318. self.loop.run_until_complete(run())
  1319. def test_async_gen_await_same_aclose_coro_twice(self):
  1320. async def async_iterate():
  1321. yield 1
  1322. yield 2
  1323. async def run():
  1324. it = async_iterate()
  1325. nxt = it.aclose()
  1326. await nxt
  1327. with self.assertRaisesRegex(
  1328. RuntimeError,
  1329. r"cannot reuse already awaited aclose\(\)/athrow\(\)"
  1330. ):
  1331. await nxt
  1332. self.loop.run_until_complete(run())
  1333. def test_async_gen_aclose_twice_with_different_coros(self):
  1334. # Regression test for https://bugs.python.org/issue39606
  1335. async def async_iterate():
  1336. yield 1
  1337. yield 2
  1338. async def run():
  1339. it = async_iterate()
  1340. await it.aclose()
  1341. await it.aclose()
  1342. self.loop.run_until_complete(run())
  1343. def test_async_gen_aclose_after_exhaustion(self):
  1344. # Regression test for https://bugs.python.org/issue39606
  1345. async def async_iterate():
  1346. yield 1
  1347. yield 2
  1348. async def run():
  1349. it = async_iterate()
  1350. async for _ in it:
  1351. pass
  1352. await it.aclose()
  1353. self.loop.run_until_complete(run())
  1354. def test_async_gen_aclose_compatible_with_get_stack(self):
  1355. async def async_generator():
  1356. yield object()
  1357. async def run():
  1358. ag = async_generator()
  1359. asyncio.create_task(ag.aclose())
  1360. tasks = asyncio.all_tasks()
  1361. for task in tasks:
  1362. # No AttributeError raised
  1363. task.get_stack()
  1364. self.loop.run_until_complete(run())
  1365. if __name__ == "__main__":
  1366. unittest.main()