2014-04-17 25 views
0

请帮助修复测试。 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

抛出的错误非常清楚:'IndexError'。您想在'models.py'的某个位置检索空的查询集的第一个元素。这就是我没有你的模型文件的实际代码所能说的。 – linkyndy

回答

0

每个试验从空白开始数据库。如果你没有在你自己的测试中创建任何数据,例如在setUp方法或者通过灯具,那么你正在测试的视图将找不到任何数据。在这种情况下,您的get_main_page方法预计在Page模型中至少有一个条目,并且您没有任何条目。

当然,这实际上暴露了您的代码本身的错误:当没有数据时它崩溃。如果这是一个用例,你需要处理,那么你应该检查这种情况并显示一个合适的错误页面。