From 383dff3a9eb4b61d9cc82b1483faed2a0c431e07 Mon Sep 17 00:00:00 2001 From: James Thorniley Date: Fri, 15 Sep 2023 11:39:31 +0100 Subject: [PATCH] Use contextvars API compatible down to python 3.7 --- asgiref/testing.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/asgiref/testing.py b/asgiref/testing.py index 45028fce..aa7cff1c 100644 --- a/asgiref/testing.py +++ b/asgiref/testing.py @@ -17,12 +17,13 @@ def __init__(self, application, scope): self.scope = scope self.input_queue = asyncio.Queue() self.output_queue = asyncio.Queue() - self.future = asyncio.create_task( + # Clear context - this ensures that context vars set in the testing scope + # are not "leaked" into the application which would normally begin with + # an empty context. In Python >= 3.11 this could also be written as: + # asyncio.create_task(..., context=contextvars.Context()) + self.future = contextvars.Context().run( + asyncio.create_task, self.application(scope, self.input_queue.get, self.output_queue.put), - # Clear context - this ensure that context vars set in the testing scope - # are not "leaked" into the application which would normally begin with - # an empty context. - context=contextvars.Context(), ) async def wait(self, timeout=1):