Skip to content

Commit f3067b8

Browse files
committed
unitest enterClassContext compatibility shim for python<3.11/django<5.1
1 parent ea19bec commit f3067b8

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

channels/testing/live.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,27 @@
77
from django.test.testcases import TransactionTestCase
88
from django.test.utils import modify_settings
99
from django.utils.functional import classproperty
10+
from django.utils.version import PY311
1011

1112
from channels.routing import get_default_application
1213

14+
if not PY311:
15+
# Backport of unittest.case._enter_context() from Python 3.11.
16+
def _enter_context(cm, addcleanup):
17+
# Look up the special methods on the type to match the with statement.
18+
cls = type(cm)
19+
try:
20+
enter = cls.__enter__
21+
exit = cls.__exit__
22+
except AttributeError:
23+
raise TypeError(
24+
f"'{cls.__module__}.{cls.__qualname__}' object does not support the "
25+
f"context manager protocol"
26+
) from None
27+
result = enter(cm)
28+
addcleanup(exit, cm, None, None, None)
29+
return result
30+
1331

1432
def make_application(*, static_wrapper):
1533
# Module-level function for pickle-ability
@@ -124,6 +142,12 @@ class ChannelsLiveServerTestCase(TransactionTestCase):
124142
static_handler = ASGIStaticFilesHandler
125143
serve_static = True
126144

145+
if not PY311:
146+
# Backport of unittest.TestCase.enterClassContext() from Python 3.11.
147+
@classmethod
148+
def enterClassContext(cls, cm):
149+
return _enter_context(cm, cls.addClassCleanup)
150+
127151
@classproperty
128152
def live_server_url(cls):
129153
return "http://%s:%s" % (cls.host, cls.server_thread.port)
@@ -193,11 +217,6 @@ def _terminate_thread(cls):
193217
for conn in cls.server_thread.connections_override.values():
194218
conn.dec_thread_sharing()
195219

196-
@classmethod
197-
def tearDownClass(cls):
198-
# The cleanup is now handled by addClassCleanup in _start_server_thread
199-
super().tearDownClass()
200-
201220
@classmethod
202221
def _is_in_memory_db(cls, connection):
203222
"""

0 commit comments

Comments
 (0)