Skip to content

Commit

Permalink
Refs #35059 -- Made asgi tests' SignalHandler helper class re-usable …
Browse files Browse the repository at this point in the history
…by other tests.
  • Loading branch information
nessita committed Jan 31, 2024
1 parent b3dc806 commit a43d75e
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions tests/asgi/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@
TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static"


class SignalHandler:
"""Helper class to track threads and kwargs when signals are dispatched."""

def __init__(self):
super().__init__()
self.calls = []

def __call__(self, signal, **kwargs):
self.calls.append({"thread": threading.current_thread(), "kwargs": kwargs})


@override_settings(ROOT_URLCONF="asgi.urls")
class ASGITest(SimpleTestCase):
async_request_factory = AsyncRequestFactory()
Expand Down Expand Up @@ -310,17 +321,12 @@ async def test_non_unicode_query_string(self):
self.assertEqual(response_body["body"], b"")

async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self):
class SignalHandler:
"""Track threads handler is dispatched on."""

threads = []

def __call__(self, **kwargs):
self.threads.append(threading.current_thread())

# Track request_started and request_finished signals.
signal_handler = SignalHandler()
request_started.connect(signal_handler)
self.addCleanup(request_started.disconnect, signal_handler)
request_finished.connect(signal_handler)
self.addCleanup(request_finished.disconnect, signal_handler)

# Perform a basic request.
application = get_asgi_application()
Expand All @@ -337,10 +343,9 @@ def __call__(self, **kwargs):
await communicator.wait()

# AsyncToSync should have executed the signals in the same thread.
request_started_thread, request_finished_thread = signal_handler.threads
self.assertEqual(request_started_thread, request_finished_thread)
request_started.disconnect(signal_handler)
request_finished.disconnect(signal_handler)
self.assertEqual(len(signal_handler.calls), 2)
request_started_call, request_finished_call = signal_handler.calls
self.assertEqual(request_started_call["thread"], request_finished_call["thread"])

async def test_concurrent_async_uses_multiple_thread_pools(self):
sync_waiter.active_threads.clear()
Expand Down

0 comments on commit a43d75e

Please sign in to comment.