Django - TestCase - response.status code failing

1k views Asked by At

Hello everyone out there,

I'm starting my journey trough django test-code. The start is not great.

I'm starting some very basic testing ( tough important) as follows:

from django.test import TestCase, SimpleTestCase
from django.urls import reverse

# Create your tests here.

class RegistryTest(SimpleTestCase):

    def test_homepage_status(self):
        response = self.client.get('Registry/search/')
        self.assertEqual(response.status_code, 200)

    def test_homepage_url_name(self):
        response = self.client.get(reverse('search'))
        self.assertEqual(response.status_code, 200)

    def test_homepage_template(self):
        response = self.client.get('Registry/search/')
        self.assertTemplateUsed(response, 'registry/search_registry.html')

here is my urls.py:

from django.contrib import admin
from django.urls import include
from django.urls import path
from django.conf.urls import url
from .views import *

app_name = 'registry'

urlpatterns = [
    path('search/', search, name='search'),

    #customerSupplier
    path('customerSupplier/detail/<int:idCS>/', detail_customerSupplier, name='detail_customerSupplier'),
    path('customerSupplier/new/', new_customerSupplier, name='new_customerSupplier'),
]

this is my search view from views.py:

def search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            azienda = form.cleaned_data['Company']
            testo   = form.cleaned_data['RagSociale']
            tipo    = form.cleaned_data['Tipologia']

            result = CustomerSupplier.search(azienda, testo, tipo)
            return render(request, 'registry/search_registry.html', {'form': form, 'CustomerSupplierList':result })

    else:
        form = SearchForm()
        return render(request, 'registry/search_registry.html', {'form': form })

this is the mail urls.py of the project forlder:

from django.contrib import admin
from django.urls import include
from django.urls import path
from django.conf.urls import url
from .views import *

app_name = 'registry'

urlpatterns = [
    path('search/', search, name='search'),

    #customerSupplier
    path('customerSupplier/detail/<int:idCS>/', detail_customerSupplier, name='detail_customerSupplier'),
    path('customerSupplier/new/', new_customerSupplier, name='new_customerSupplier'),
]

when I run the test i get back this error:

python manage.py test Registry System check identified no issues (0 silenced). FFE ====================================================================== ERROR: test_homepage_url_name (tests.RegistryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carloc/Projects/100_CogniSpa/gestionale-cogni/src/Registry/tests.py", line 13, in test_homepage_url_name response = self.client.get(reverse('search')) File "/home/carloc/.local/lib/python3.7/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/carloc/.local/lib/python3.7/site-packages/django/urls/resolvers.py", line 660, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'search' not found. 'search' is not a valid view function or pattern name.

====================================================================== FAIL: test_homepage_status (tests.RegistryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carloc/Projects/100_CogniSpa/gestionale-cogni/src/Registry/tests.py", line 10, in test_homepage_status self.assertEqual(response.status_code, 200) AssertionError: 404 != 200

====================================================================== FAIL: test_homepage_template (tests.RegistryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carloc/Projects/100_CogniSpa/gestionale-cogni/src/Registry/tests.py", line 18, in test_homepage_template self.assertTemplateUsed(response, 'registry/search_registry.html') File "/home/carloc/.local/lib/python3.7/site-packages/django/test/testcases.py", line 639, in assertTemplateUsed self.fail(msg_prefix + "No templates used to render the response") AssertionError: No templates used to render the response

---------------------------------------------------------------------- Ran 3 tests in 0.008s

FAILED (failures=2, errors=1)

I'm kind of lost... the template is located at templates/registry/search_registry.html in the app, but still it says no template as been used for the response.

Any help?

thank you very much.

Carlo

1

There are 1 answers

0
Carlo Cogni On

OK solved.

2 issues worth pointing out:

first: the client.get() method should be:

response = self.client.get('/your/path/')

and not:

response = self.client.get('your/path/')

that first leading slash is important.

Second: In my case I was testing with 'SimpleTestCase' which does not allow for connections to the database, which my view required in order to process the test correctly. Therefore I switched to class RegistryTest(TestCase): .....

By making this corrections, the third and final test ('assertTemplateUsed') passed the test as well.

Thank you guys very much for the hint. It really helped