Skip to content

Commit 2f4c471

Browse files
VeldaKiaratim-schillingmatthiask
authored
'djdt' is not a registered namespace #1405 (#1889)
* updated the change to the changes.rst file * solution to djdt registered namespace,update docs, system checks and tests * removing test in the if statements * Add basic test to example app and example_test to make commands. * Update check for toolbar and tests. * update check using with, combine the four tests to one, update default config * update installation files and remove patch from namespace check * Clean-up the changelog * Add docs for the IS_RUNNING_TESTS setting Co-authored-by: Matthias Kestenholz <mk@feinheit.ch> * Change the code for the toolbar testing error to E001 * Reduce number of .settings calls and document config update. --------- Co-authored-by: Tim Schilling <schillingt@better-simple.com> Co-authored-by: Matthias Kestenholz <mk@feinheit.ch>
1 parent a36bbba commit 2f4c471

File tree

11 files changed

+138
-11
lines changed

11 files changed

+138
-11
lines changed

Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ example:
66
--noinput --username="$(USER)" --email="$(USER)@mailinator.com"
77
python example/manage.py runserver
88

9+
example_test:
10+
python example/manage.py test example
11+
912
test:
1013
DJANGO_SETTINGS_MODULE=tests.settings \
1114
python -m django test $${TEST_ARGS:-tests}

debug_toolbar/apps.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from django.apps import AppConfig
55
from django.conf import settings
6-
from django.core.checks import Warning, register
6+
from django.core.checks import Error, Warning, register
77
from django.middleware.gzip import GZipMiddleware
88
from django.utils.module_loading import import_string
99
from django.utils.translation import gettext_lazy as _
@@ -177,7 +177,7 @@ def check_panels(app_configs, **kwargs):
177177
return errors
178178

179179

180-
@register()
180+
@register
181181
def js_mimetype_check(app_configs, **kwargs):
182182
"""
183183
Check that JavaScript files are resolving to the correct content type.
@@ -208,7 +208,29 @@ def js_mimetype_check(app_configs, **kwargs):
208208
return []
209209

210210

211-
@register()
211+
@register
212+
def debug_toolbar_installed_when_running_tests_check(app_configs, **kwargs):
213+
"""
214+
Check that the toolbar is not being used when tests are running
215+
"""
216+
if not settings.DEBUG and dt_settings.get_config()["IS_RUNNING_TESTS"]:
217+
return [
218+
Error(
219+
"The Django Debug Toolbar can't be used with tests",
220+
hint="Django changes the DEBUG setting to False when running "
221+
"tests. By default the Django Debug Toolbar is installed because "
222+
"DEBUG is set to True. For most cases, you need to avoid installing "
223+
"the toolbar when running tests. If you feel this check is in error, "
224+
"you can set `DEBUG_TOOLBAR_CONFIG['IS_RUNNING_TESTS'] = False` to "
225+
"bypass this check.",
226+
id="debug_toolbar.E001",
227+
)
228+
]
229+
else:
230+
return []
231+
232+
233+
@register
212234
def check_settings(app_configs, **kwargs):
213235
errors = []
214236
USER_CONFIG = getattr(settings, "DEBUG_TOOLBAR_CONFIG", {})

debug_toolbar/settings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import sys
12
import warnings
23
from functools import lru_cache
34

@@ -42,6 +43,7 @@
4243
"SQL_WARNING_THRESHOLD": 500, # milliseconds
4344
"OBSERVE_REQUEST_CALLBACK": "debug_toolbar.toolbar.observe_request",
4445
"TOOLBAR_LANGUAGE": None,
46+
"IS_RUNNING_TESTS": "test" in sys.argv,
4547
"UPDATE_ON_FETCH": False,
4648
}
4749

docs/changes.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@ Pending
2222
``DEBUG_TOOLBAR_SETTINGS``.
2323
* Add a note on the profiling panel about using Python 3.12 and later
2424
about needing ``--nothreading``
25+
* Added ``IS_RUNNING_TESTS`` setting to allow overriding the
26+
``debug_toolbar.E001`` check to avoid including the toolbar when running
27+
tests.
28+
* Fixed the bug causing ``'djdt' is not a registered namespace`` and updated
29+
docs to help in initial configuration while running tests.
30+
* Added a link in the installation docs to a more complete installation
31+
example in the example app.
32+
* Added check to prevent the toolbar from being installed when tests
33+
are running.
34+
* Added test to example app and command to run the example app's tests.
2535

2636
4.3.0 (2024-02-01)
2737
------------------

docs/configuration.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ Toolbar options
7272
The toolbar searches for this string in the HTML and inserts itself just
7373
before.
7474

75+
* ``IS_RUNNING_TESTS``
76+
77+
Default: ``"test" in sys.argv``
78+
79+
This setting whether the application is running tests. If this resolves to
80+
``True``, the toolbar will prevent you from running tests. This should only
81+
be changed if your test command doesn't include ``test`` or if you wish to
82+
test your application with the toolbar configured. If you do wish to test
83+
your application with the toolbar configured, set this setting to
84+
``False``.
85+
7586
.. _RENDER_PANELS:
7687

7788
* ``RENDER_PANELS``

docs/installation.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,11 @@ Add ``"debug_toolbar"`` to your ``INSTALLED_APPS`` setting:
8181
"debug_toolbar",
8282
# ...
8383
]
84+
.. note:: Check out the configuration example in the
85+
`example app
86+
<https://github.com/jazzband/django-debug-toolbar/tree/main/example>`_
87+
to learn how to set up the toolbar to function smoothly while running
88+
your tests.
8489

8590
4. Add the URLs
8691
^^^^^^^^^^^^^^^
@@ -99,6 +104,7 @@ Add django-debug-toolbar's URLs to your project's URLconf:
99104
This example uses the ``__debug__`` prefix, but you can use any prefix that
100105
doesn't clash with your application's URLs.
101106

107+
102108
5. Add the Middleware
103109
^^^^^^^^^^^^^^^^^^^^^
104110

example/settings.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""Django settings for example project."""
22

33
import os
4+
import sys
45

56
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
67

78

89
# Quick-start development settings - unsuitable for production
910

11+
1012
SECRET_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
1113

1214
DEBUG = True
@@ -22,11 +24,9 @@
2224
"django.contrib.sessions",
2325
"django.contrib.messages",
2426
"django.contrib.staticfiles",
25-
"debug_toolbar",
2627
]
2728

2829
MIDDLEWARE = [
29-
"debug_toolbar.middleware.DebugToolbarMiddleware",
3030
"django.middleware.security.SecurityMiddleware",
3131
"django.contrib.sessions.middleware.SessionMiddleware",
3232
"django.middleware.common.CommonMiddleware",
@@ -61,7 +61,6 @@
6161

6262
WSGI_APPLICATION = "example.wsgi.application"
6363

64-
DEBUG_TOOLBAR_CONFIG = {"ROOT_TAG_EXTRA_ATTRS": "data-turbo-permanent hx-preserve"}
6564

6665
# Cache and database
6766

@@ -97,3 +96,18 @@
9796
}
9897

9998
STATICFILES_DIRS = [os.path.join(BASE_DIR, "example", "static")]
99+
100+
101+
# Only enable the toolbar when we're in debug mode and we're
102+
# not running tests. Django will change DEBUG to be False for
103+
# tests, so we can't rely on DEBUG alone.
104+
ENABLE_DEBUG_TOOLBAR = DEBUG and "test" not in sys.argv
105+
if ENABLE_DEBUG_TOOLBAR:
106+
INSTALLED_APPS += [
107+
"debug_toolbar",
108+
]
109+
MIDDLEWARE += [
110+
"debug_toolbar.middleware.DebugToolbarMiddleware",
111+
]
112+
# Customize the config to support turbo and htmx boosting.
113+
DEBUG_TOOLBAR_CONFIG = {"ROOT_TAG_EXTRA_ATTRS": "data-turbo-permanent hx-preserve"}

example/test_views.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Add tests to example app to check how the toolbar is used
2+
# when running tests for a project.
3+
# See https://github.com/jazzband/django-debug-toolbar/issues/1405
4+
5+
from django.test import TestCase
6+
from django.urls import reverse
7+
8+
9+
class ViewTestCase(TestCase):
10+
def test_index(self):
11+
response = self.client.get(reverse("home"))
12+
assert response.status_code == 200

example/urls.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django.conf import settings
12
from django.contrib import admin
23
from django.urls import include, path
34
from django.views.generic import TemplateView
@@ -33,5 +34,9 @@
3334
),
3435
path("admin/", admin.site.urls),
3536
path("ajax/increment", increment, name="ajax_increment"),
36-
path("__debug__/", include("debug_toolbar.urls")),
3737
]
38+
39+
if settings.ENABLE_DEBUG_TOOLBAR:
40+
urlpatterns += [
41+
path("__debug__/", include("debug_toolbar.urls")),
42+
]

tests/settings.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,7 @@
126126

127127
DEBUG_TOOLBAR_CONFIG = {
128128
# Django's test client sets wsgi.multiprocess to True inappropriately
129-
"RENDER_PANELS": False
129+
"RENDER_PANELS": False,
130+
# IS_RUNNING_TESTS must be False even though we're running tests because we're running the toolbar's own tests.
131+
"IS_RUNNING_TESTS": False,
130132
}

tests/test_checks.py

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
from unittest.mock import patch
22

3-
from django.core.checks import Warning, run_checks
3+
from django.core.checks import Error, Warning, run_checks
44
from django.test import SimpleTestCase, override_settings
55

6+
from debug_toolbar import settings as dt_settings
7+
from debug_toolbar.apps import debug_toolbar_installed_when_running_tests_check
8+
69

710
class ChecksTestCase(SimpleTestCase):
811
@override_settings(
@@ -97,7 +100,7 @@ def test_panels_is_empty(self):
97100
hint="Set DEBUG_TOOLBAR_PANELS to a non-empty list in your "
98101
"settings.py.",
99102
id="debug_toolbar.W005",
100-
)
103+
),
101104
],
102105
)
103106

@@ -236,8 +239,45 @@ def test_check_w007_invalid(self, mocked_guess_type):
236239
],
237240
)
238241

242+
def test_debug_toolbar_installed_when_running_tests(self):
243+
with self.settings(DEBUG=True):
244+
# Update the config options because self.settings()
245+
# would require redefining DEBUG_TOOLBAR_CONFIG entirely.
246+
dt_settings.get_config()["IS_RUNNING_TESTS"] = True
247+
errors = debug_toolbar_installed_when_running_tests_check(None)
248+
self.assertEqual(len(errors), 0)
249+
250+
dt_settings.get_config()["IS_RUNNING_TESTS"] = False
251+
errors = debug_toolbar_installed_when_running_tests_check(None)
252+
self.assertEqual(len(errors), 0)
253+
with self.settings(DEBUG=False):
254+
dt_settings.get_config()["IS_RUNNING_TESTS"] = False
255+
errors = debug_toolbar_installed_when_running_tests_check(None)
256+
self.assertEqual(len(errors), 0)
257+
258+
dt_settings.get_config()["IS_RUNNING_TESTS"] = True
259+
errors = debug_toolbar_installed_when_running_tests_check(None)
260+
self.assertEqual(
261+
errors,
262+
[
263+
Error(
264+
"The Django Debug Toolbar can't be used with tests",
265+
hint="Django changes the DEBUG setting to False when running "
266+
"tests. By default the Django Debug Toolbar is installed because "
267+
"DEBUG is set to True. For most cases, you need to avoid installing "
268+
"the toolbar when running tests. If you feel this check is in error, "
269+
"you can set `DEBUG_TOOLBAR_CONFIG['IS_RUNNING_TESTS'] = False` to "
270+
"bypass this check.",
271+
id="debug_toolbar.E001",
272+
)
273+
],
274+
)
275+
239276
@override_settings(
240-
DEBUG_TOOLBAR_CONFIG={"OBSERVE_REQUEST_CALLBACK": lambda request: False}
277+
DEBUG_TOOLBAR_CONFIG={
278+
"OBSERVE_REQUEST_CALLBACK": lambda request: False,
279+
"IS_RUNNING_TESTS": False,
280+
}
241281
)
242282
def test_observe_request_callback_specified(self):
243283
errors = run_checks()

0 commit comments

Comments
 (0)