From 09b3e46635da8048ac94ddbf058e37ec9ef31400 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 18 Aug 2017 21:18:24 +0200 Subject: [PATCH] Fixed #27796 -- Prevented middleware being loaded twice with runserver Thanks Tim Graham for the review. --- django/contrib/staticfiles/handlers.py | 5 +++++ tests/staticfiles_tests/test_management.py | 13 ++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py index 13453c9ac52..2ec6d07d712 100644 --- a/django/contrib/staticfiles/handlers.py +++ b/django/contrib/staticfiles/handlers.py @@ -21,6 +21,11 @@ class StaticFilesHandler(WSGIHandler): self.base_url = urlparse(self.get_base_url()) super().__init__() + def load_middleware(self): + # Middleware are already loaded for self.application; no need to reload + # them for self. + pass + def get_base_url(self): utils.check_settings() return settings.STATIC_URL diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py index 4a5963417ea..54c271b7939 100644 --- a/tests/staticfiles_tests/test_management.py +++ b/tests/staticfiles_tests/test_management.py @@ -11,7 +11,9 @@ from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.contrib.staticfiles import storage -from django.contrib.staticfiles.management.commands import collectstatic +from django.contrib.staticfiles.management.commands import ( + collectstatic, runserver, +) from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.test import override_settings @@ -34,6 +36,15 @@ class TestNoFilesCreated: self.assertEqual(os.listdir(settings.STATIC_ROOT), []) +class TestRunserver(StaticFilesTestCase): + @override_settings(MIDDLEWARE=['django.middleware.common.CommonMiddleware']) + def test_middleware_loaded_only_once(self): + command = runserver.Command() + with mock.patch('django.middleware.common.CommonMiddleware') as mocked: + command.get_handler(use_static_handler=True, insecure_serving=True) + self.assertEqual(mocked.call_count, 1) + + class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command.