From be138f32ed32a4bf3e62305145423285e462c853 Mon Sep 17 00:00:00 2001 From: Clifford Gama Date: Thu, 17 Oct 2024 17:59:58 +0200 Subject: [PATCH] Refs #28999 -- Added tests for reversing a class-based view by instance. --- tests/urlpatterns_reverse/tests.py | 9 +++++++++ tests/urlpatterns_reverse/urls.py | 3 +++ tests/urlpatterns_reverse/views.py | 9 ++++++++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index 5843382a8c..216545b5f5 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -522,6 +522,15 @@ class URLPatternReverse(SimpleTestCase): with self.assertRaisesMessage(NoReverseMatch, msg): reverse("places", kwargs={"arg1": 2}) + def test_func_view_from_cbv(self): + expected = "/hello/world/" + url = reverse(views.view_func_from_cbv, kwargs={"name": "world"}) + self.assertEqual(url, expected) + + def test_func_view_from_cbv_no_expected_kwarg(self): + with self.assertRaises(NoReverseMatch): + reverse(views.view_func_from_cbv) + class ResolverTests(SimpleTestCase): def test_resolver_repr(self): diff --git a/tests/urlpatterns_reverse/urls.py b/tests/urlpatterns_reverse/urls.py index c745331483..5bf20a3f63 100644 --- a/tests/urlpatterns_reverse/urls.py +++ b/tests/urlpatterns_reverse/urls.py @@ -8,6 +8,7 @@ from .views import ( empty_view_partial, empty_view_wrapped, nested_view, + view_func_from_cbv, ) other_patterns = [ @@ -136,4 +137,6 @@ urlpatterns = [ path("includes/", include(other_patterns)), # Security tests re_path("(.+)/security/$", empty_view, name="security"), + # View function from cbv + path("hello//", view_func_from_cbv), ] diff --git a/tests/urlpatterns_reverse/views.py b/tests/urlpatterns_reverse/views.py index 17c7fe1c3d..aa55917ec0 100644 --- a/tests/urlpatterns_reverse/views.py +++ b/tests/urlpatterns_reverse/views.py @@ -3,7 +3,7 @@ from functools import partial, update_wrapper from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponse from django.urls import reverse_lazy -from django.views.generic import RedirectView +from django.views.generic import RedirectView, View def empty_view(request, *args, **kwargs): @@ -58,6 +58,13 @@ def bad_view(request, *args, **kwargs): raise ValueError("I don't think I'm getting good value for this view") +class _HelloView(View): + def get(self, request, *args, **kwargs): + return HttpResponse(f"Hello {self.kwargs['name']}") + + +view_func_from_cbv = _HelloView.as_view() + empty_view_partial = partial(empty_view, template_name="template.html") empty_view_nested_partial = partial( empty_view_partial, template_name="nested_partial.html"