我是Django和Test Driven Devolopment的新手。
完成1.11官方文档中的教程后 我正在开始我的第一个应用程序:wos_2017_2
此测试失败,我无法弄清楚原因:
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
浏览器中的此链接无问题:
http://localhost:8000/wos_2017_2/
在shell中(从项目根目录运行):
>>> 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
在wos_2017_1.urls.py中:
from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^$', views.index, name='index'),
]
答案 0 :(得分:2)
client.get('/')
失败,因为您尚未在根网址配置中定义^$
的网址格式(与settings.py
位于同一目录中的网址格式)。
您已将自己的网址包含在:
url(r'^wos_2017_2/', include('wos_2017_2.urls')),
并在那个网址中
url(r'^$', views.index, name='index'),
因此,在测试中,您应该使用response = client.get('/wos_2017_2/')