Skip to content

Commit 7366d2b

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 84c624d commit 7366d2b

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

debug_toolbar/toolbar.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from django.apps import apps
1010
from django.core.exceptions import ImproperlyConfigured
11+
from django.dispatch import Signal
1112
from django.template import TemplateSyntaxError
1213
from django.template.loader import render_to_string
1314
from django.urls import path, resolve
@@ -18,6 +19,9 @@
1819

1920

2021
class DebugToolbar:
22+
# for internal testing use only
23+
_created = Signal()
24+
2125
def __init__(self, request, get_response):
2226
self.request = request
2327
self.config = dt_settings.get_config().copy()
@@ -38,6 +42,7 @@ def __init__(self, request, get_response):
3842
self.stats = {}
3943
self.server_timing_stats = {}
4044
self.store_id = None
45+
self._created.send(request, toolbar=self)
4146

4247
# Manage panels
4348

tests/base.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,37 @@
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

56
from debug_toolbar.toolbar import DebugToolbar
67

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

931

1032
class BaseTestCase(TestCase):
33+
client_class = ToolbarTestClient
34+
1135
panel_id = None
1236

1337
def setUp(self):

0 commit comments

Comments
 (0)