首页视图编写
lists/tests.py
from django.test import TestCase
from django.urls import resolve
from lists.views import home_page
class HomePageTest(TestCase):
def test_root_url_to_home_page(self):
found = resolve('/') # resolve是Django内部函数,用于解析URL,并将其映射到相应的视图函数上
self.assertEqual(found.func, home_page) # 检查解析网站根路径/时,是否能找到home_page
终端运行
$ python manage.py test ImportError: cannot import name 'home_page'
编写应用代码,解决上面的问题 lists/views.py
from django.shortcuts import render home_page = None
再次运行测试
$ python manage.py test
依旧有报错信息。
接下来在urls.py文件中定义如何把URL映射到视图函数上,在文件夹superlists/superlists中有个主urls.py文件,这个文件应用于整个网站。
from django.contrib import admin from django.conf.urls import url from lists import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^$', views.home_page, name='home') ]
python manage.py test
[...]
TypeError: view must be a callable or a list/tuple in the case of include().
That’s progress! We’re no longer getting a 404
修正 lists/views.py
from django.shortcuts import render
# Create your views here.
def home_page():
pass
现在
$ python manage.py test
(django) root@ranxf-TEST:/studydisk/Python_web_TDD/superlists# python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Destroying test database for alias 'default'..
第一个测试通过,版本有比较提交一次。
$ git diff $ git commit -am "First unit test and url mapping, dummy view —— 第一个单元测试和url映射,虚拟视图”