Johann Spies
Johann Spies

Reputation: 33

Django: Why does this test fail?

I an new to Django and to Test Driven Devolopment as well.

After working through the tutorials in the 1.11 official documentation I am starting my first app: wos_2017_2

This test fails and I cannot figure out why:

import unittest
from django.test import TestCase
from django.test import Client
from .models import *
from .views import *
class SimpleTest(unittest.TestCase):
    def test_index(self):
        client = Client()
        response = client.get('/')
        self.assertEqual(response.status_code, 200)

FAIL: test_index (wos_2017_2.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/js/django/wos/wos_2017_2/tests.py", line 16, in test_index
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

This link in the browser works without a problem:

http://localhost:8000/wos_2017_2/

In the shell (run from the project root):

>>> from django.test import Client
>>> client = Client()
>>> response = client.get('/')
>>> response = client.get('wos_2017_2/index')
Not Found: /wos_2017_2index
>>> response = client.get('wos_2017_2/')
Not Found: /wos_2017_2
>>> response = client.get('/wos_2017_2/')
>>> response = client.get('/wos_2017_2/index/')
Not Found: /wos_2017_2/index/
>>> response = client.get('/wos_2017_2/')
>>> response.status_code
200

in wos_2017_1.urls.py:

from . import views
from django.conf.urls import url    
urlpatterns = [
    url(r'^$', views.index, name='index'),   
]

Upvotes: 0

Views: 625

Answers (1)

Alasdair
Alasdair

Reputation: 309089

client.get('/') is failing because you haven't defined a URL pattern for ^$ in your root url config (the one in the same directory as your settings.py).

You have included your urls with:

url(r'^wos_2017_2/', include('wos_2017_2.urls')),

and in that urls you have

url(r'^$', views.index, name='index'),   

Therefore in your test you should use response = client.get('/wos_2017_2/')

Upvotes: 2

Related Questions