Django:为什么这个测试失败了?

Django: Why does this test fail?

我是 Django 的新手,也是测试驱动开发的新手。

完成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

这个 link 在浏览器中没有问题:

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'),   
]

client.get('/') 失败是因为您没有在根 url 配置中为 ^$ 定义 URL 模式(与您的 settings.py).

您已将 url 包含在:

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

在那个 url 中你有

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

因此在你的测试中你应该使用response = client.get('/wos_2017_2/')