bpo-46994: Accept explicit contextvars.Context in asyncio create_task() API (GH-31837)

This commit is contained in:
Andrew Svetlov 2022-03-14 13:54:13 +02:00 committed by GitHub
parent 2153daf0a0
commit 9523c0d84f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 209 additions and 65 deletions

View file

@ -2,6 +2,7 @@
import asyncio
import contextvars
from asyncio import taskgroups
import unittest
@ -708,6 +709,23 @@ class TestTaskGroup(unittest.IsolatedAsyncioTestCase):
t = g.create_task(coro(), name="yolo")
self.assertEqual(t.get_name(), "yolo")
async def test_taskgroup_task_context(self):
cvar = contextvars.ContextVar('cvar')
async def coro(val):
await asyncio.sleep(0)
cvar.set(val)
async with taskgroups.TaskGroup() as g:
ctx = contextvars.copy_context()
self.assertIsNone(ctx.get(cvar))
t1 = g.create_task(coro(1), context=ctx)
await t1
self.assertEqual(1, ctx.get(cvar))
t2 = g.create_task(coro(2), context=ctx)
await t2
self.assertEqual(2, ctx.get(cvar))
if __name__ == "__main__":
unittest.main()