请帮助修复测试。 tests.py:
from django.test import TestCase
from django.test.client import Client
import os
from django.conf import settings
class HomePageTest(TestCase):
def test_homepage_available(self):
c = Client()
response = c.get('/')
self.assertEquals(response.status_code, 200)
urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
#from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'mutants.views.inner_page', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
由于在控制台中进行测试,显示以下错误消息:
c:\Python33\django_projects\mutants>python manage.py test
Creating test database for alias 'default'... E
======================================================================
ERROR: test_homepage_available (accounts.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Python33\django_projects\mutants\accounts\tests.py", line 11, in test_homepage_available
response = c.get('/') File "C:\Python33\lib\site-packages\django\test\client.py", line 473, in get
response = super(Client, self).get(path, data=data, **extra)
File "C:\Python33\lib\site-packages\django\test\client.py", line 280, in get
return self.request(**r)
File "C:\Python33\lib\site-packages\django\test\client.py", line 444, in request
six.reraise(*exc_info)
File "C:\Python33\lib\site-packages\django\utils\six.py", line 536, in reraise
raise value
File "C:\Python33\lib\site-packages\django\core\handlers\base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "c:\Python33\django_projects\mutants\mutants\views.py", line 13, in inner_page
obj = Page.get_main_page()
File "c:\Python33\django_projects\mutants\mutants\models.py", line 39, in get_main_page
return self.objects.filter(main_page=True)[0]
File "C:\Python33\lib\site-packages\django\db\models\query.py", line 132, in __getitem__
return list(qs)[0] IndexError: list index out of range
----------------------------------------------------------------------
Ran 1 test in 0.030s
FAILED (errors=1) Destroying test database for alias 'default'...
c:\Python33\django_projects\mutants>
答案 0 :(得分:0)
每个测试都从空白数据库开始。如果您不在自己的测试中创建任何数据,例如在setUp方法中或通过fixture,那么您正在测试的视图将无法找到任何数据。在这种情况下,您的get_main_page
方法预计Page
模式中至少有一个条目,并且您没有任何条目。
当然,这实际上暴露了代码本身的一个错误:它在没有数据时崩溃。如果这是您需要处理的用例,那么您应该检查该情况并显示正确的错误页面。