Skip to content

Commit 22df64a

Browse files
committed
Allow integration tests to access the toolbar
Add a mechanism for integration tests to access the toolbar used for a particular request: Update DebugToolbar to emit a signal on creation referencing itself. Then create and use a custom Django test client that connects to this signal to capture the toolbar that was created while the request was being processed, and to store the toolbar on the response for use by tests.
1 parent 323251d commit 22df64a

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

debug_toolbar/signals.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from django.dispatch import Signal
2+
3+
# Signal used internally for testing
4+
toolbar_created = Signal()

debug_toolbar/toolbar.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from django.utils.module_loading import import_string
1616

1717
from debug_toolbar import APP_NAME, settings as dt_settings
18+
from debug_toolbar.signals import toolbar_created
1819

1920

2021
class DebugToolbar:
@@ -38,6 +39,7 @@ def __init__(self, request, get_response):
3839
self.stats = {}
3940
self.server_timing_stats = {}
4041
self.store_id = None
42+
toolbar_created.send(request, toolbar=self)
4143

4244
# Manage panels
4345

tests/base.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,38 @@
11
import html5lib
2+
from asgiref.local import Local
23
from django.http import HttpResponse
3-
from django.test import RequestFactory, TestCase
4+
from django.test import Client, RequestFactory, TestCase
45

6+
from debug_toolbar.signals import toolbar_created
57
from debug_toolbar.toolbar import DebugToolbar
68

9+
10+
class ToolbarTestClient(Client):
11+
def request(self, **request):
12+
# Use a thread/async task context-local variable to guard against a
13+
# concurrent toolbar_created signal from a different thread/task.
14+
data = Local()
15+
data.toolbar = None
16+
17+
def handle_toolbar_created(sender, toolbar=None, **kwargs):
18+
data.toolbar = toolbar
19+
20+
toolbar_created.connect(handle_toolbar_created)
21+
try:
22+
response = super().request(**request)
23+
finally:
24+
toolbar_created.disconnect(handle_toolbar_created)
25+
response.toolbar = data.toolbar
26+
27+
return response
28+
29+
730
rf = RequestFactory()
831

932

1033
class BaseTestCase(TestCase):
34+
client_class = ToolbarTestClient
35+
1136
panel_id = None
1237

1338
def setUp(self):

0 commit comments

Comments
 (0)