From 523fed1d2faafa6610f27dad9bbb7d7c4e122ea5 Mon Sep 17 00:00:00 2001 From: Ben Cail Date: Fri, 27 Oct 2023 09:23:07 -0400 Subject: [PATCH] Fixed #32106 -- Preserved HTTP_HOST in test Client when following redirects. Co-authored-by: David Sanders --- django/test/client.py | 1 + tests/test_client/tests.py | 7 +++++++ tests/test_client/urls.py | 6 ++++++ tests/test_client/views.py | 8 ++++++++ 4 files changed, 22 insertions(+) diff --git a/django/test/client.py b/django/test/client.py index d44e30ff56..766b60863f 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -901,6 +901,7 @@ class ClientMixin: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname + extra["HTTP_HOST"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index 402f282588..15f5cbe44e 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -856,6 +856,13 @@ class ClientTest(TestCase): response, "https://www.djangoproject.com/", fetch_redirect_response=False ) + @override_settings(ALLOWED_HOSTS=["hostname1", "hostname2"]) + def test_redirect_with_http_host(self): + response = self.client.get( + "/redirect_to_different_hostname/", follow=True, HTTP_HOST="hostname1" + ) + self.assertEqual(response.content, b"hostname2") + def test_external_redirect_without_trailing_slash(self): """ Client._handle_redirects() with an empty path. diff --git a/tests/test_client/urls.py b/tests/test_client/urls.py index 228e6c6a78..96b9dc6587 100644 --- a/tests/test_client/urls.py +++ b/tests/test_client/urls.py @@ -25,6 +25,12 @@ urlpatterns = [ "redirect_view_308_query_string/", views.method_saving_308_redirect_query_string_view, ), + path( + "redirect_to_different_hostname/", + views.redirect_to_different_hostname, + name="redirect_to_different_hostname", + ), + path("get_host_view/", views.get_host_view, name="get_host_view"), path("secure_view/", views.view_with_secure), path( "permanent_redirect_view/", diff --git a/tests/test_client/views.py b/tests/test_client/views.py index 494844009d..96e0142dd3 100644 --- a/tests/test_client/views.py +++ b/tests/test_client/views.py @@ -179,6 +179,14 @@ def method_saving_308_redirect_view(request): return _post_view_redirect(request, 308) +def redirect_to_different_hostname(request): + return HttpResponseRedirect("https://hostname2/get_host_view/") + + +def get_host_view(request): + return HttpResponse(request.get_host()) + + def view_with_secure(request): "A view that indicates if the request was secure" response = HttpResponse()