How to test url in django

13,871

Solution 1

As @Selcuk said, you are missing the trailing slash in the URL. In order to avoid those typos and in case your URL will change some time, you should use django's reverse function to get URLs:

# django 1.x
from django.core.urlresolvers import reverse
# django 2.x
from django.urls import reverse

def test_create(self):
    response = self.client.get(reverse('create', args=[self.userName]))
    self.assertEqual(response.status_code, 200)

Solution 2

Your URL configuration requires a trailing slash (/) after userName. Since you did not include it in your test URL, Django first returns a redirect (301) to the correct URL.

Change the line

response = self.client.get('/mission/create/' + str(self.userName))

to

response = self.client.get('/mission/create/' + str(self.userName) + '/')

or better

response = self.client.get('/mission/create/{0}/'.format(self.userName))
Share:
13,871
James Reid
Author by

James Reid

Updated on June 04, 2022

Comments

  • James Reid
    James Reid almost 2 years

    I would like to test my url in django but I got error message.

    here are my codes:

    urls.py

    url(r'^create/(?P<userName>[0-9a-zA-Z-]+)/$', views.create, name='create'),
    

    test.py

    from django.test import TestCase, Client
    
    client = Client()
    
    
    def test_create(self):
        """Test the url for "create"
        """
    
        response = self.client.get('/mission/create/' + str(self.userName))
        self.assertEqual(response.status_code, 200)
    

    and i would get this result:

    FAIL: test_create (mission.tests.MissionUrlTests)
    Test the url for "create"
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/actinbox/mission/tests.py", line 122, in test_create
        self.assertEqual(response.status_code, 200)
    AssertionError: 301 != 200
    

    Please help me with my codes here. Thank you in advance.

  • Aipi
    Aipi over 6 years
    The reverse is the most advisable option like @ilse2005 said.
  • Walter Schweitzer
    Walter Schweitzer almost 5 years
    In Django 2.0: from django.urls import reverse