我想在django中测试我的网址,但是我收到了错误消息。
这是我的代码:
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)
我会得到这个结果:
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
请在这里帮我处理我的代码。提前谢谢。
答案 0 :(得分:7)
正如@Selcuk所说,你错过了URL中的尾部斜杠。为了避免这些拼写错误,如果您的网址会更改一段时间,您应该使用django's reverse函数来获取网址:
# 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)
答案 1 :(得分:6)
您的网址配置在userName
之后需要一个斜杠(/)。由于您没有将其包含在测试URL中,因此Django首先将重定向(301)返回到正确的URL。
更改行
response = self.client.get('/mission/create/' + str(self.userName))
到
response = self.client.get('/mission/create/' + str(self.userName) + '/')
或更好
response = self.client.get('/mission/create/{0}/'.format(self.userName))