I have 100s of HTML Templates that I have to test and don't know how to test each individual one to make sure that they load properly. I assume i would use a for loop through my project urls.py but when I do this i get the following error:
AttributeError: 'URLResolver' object has no attribute 'name'
from django.test import SimpleTestCase, TestCase, Client
from django.test.utils import setup_test_environment
from django.urls import reverse, URLPattern
from django.conf import settings
import importlib
from foo.urls import urlpatterns
# Create your tests here.
class LoginTest(SimpleTestCase):
def login_view_test(self):
client = Client()
for url in urlpatterns:
response = client.get(reverse(url.name))
self.assertEqual(response.status_code, 200)
print(str(reverse(url.name)) + " Status Code:" + str(response.status_code))
For some reason the code says that the URLResolver has no name attribute, I feel this error is it telling me I need to look in a different location for the name to reverse I just don't know where to look.
when removing the .name in the reverse tag, I got this error:
<URLResolver <module 'account.urls' from '/home/company/company_project/account/urls.py'> (None:None) 'account/'>
You don't have to give a urlpattern
a name.
For example:
...
path('someurl/', generic.RedirectView.as_view(url='/anyurl/')),
...
results in a URLPattern
without a name
<URLPattern 'someurl/'> # no name
In your case you could probably directly use the stored route:
from django.test import SimpleTestCase, TestCase, Client
from django.test.utils import setup_test_environment
from django.urls import reverse, URLPattern
from django.conf import settings
import importlib
from foo.urls import urlpatterns
# Create your tests here.
class LoginTest(SimpleTestCase):
def login_view_test(self):
client = Client()
for urlpattern in urlpatterns:
if urlpattern.name is None:
continue
response = client.get(urlpattern.pattern._route))
self.assertEqual(response.status_code, 200)
print(str(reverse(url.name)) + " Status Code:" + str(response.status_code))
Be aware that, that this does not work if you have pass some parameters, like primary keys.
Probably not yet the best solutions, since we are using a internal attribute, but it solves your issue :-)