I have a generic template I’m trying to test that is used by a superclass view that is intended to be derived. It’s not technically an abstract class, so I was shortcutting the testing and rendering its template like this:
class BSTListViewTests(BaseTemplateTests):
list_view_template = "models/bst/list_view.html"
def render_list_view_template(self, view: BSTListView):
view.object_list = view.get_queryset()[:]
context = view.get_context_data()
return render_to_string(self.list_view_template, context)
def test_cookie_resets(self):
request = HttpRequest()
slv = StudyLV(request=request)
slv.cookie_resets.append("test")
template_str = self.render_list_view_template(slv)
It was all working ok until I added some code to the template that included this simple tag call:
{% url request.resolver_match.url_name %}
. I started getting errors in the test saying:
django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name.
that come from that line in the template (which go away if I comment out that 1 line). I tried to hack my way around having to create a real page with a url, but had no success. I also tried a google AI suggestion for temporary testing URLs, like this:
# tests/urls.py (temporary URLconf)
from django.urls import path
urlpatterns = [
path('test-view/', your_test_view, name='test_view'),
]
# tests/test_views.py (test case)
from django.test import TestCase
from . import urls # Import the temporary URLconf
from django.urls import reverse
class TestView(TestCase):
urls = 'tests.urls' # Set the urls attribute to the temporary URLconf
but I still got the same error. Clearly, I don’t know what I’m doing. Is there a simple way to fake the URL resolver match or set up a url just for testing that will work with {% url request.resolver_match.url_name %}
?