创建第一个应用:
python manage.py startapp lists
第一个测试:测试网站根路径返回homepage
在《lists/test.py》中写入:
from django.test import TestCase
from django.core.urlresolvers import resolve
from .views import home_page
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolve_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
上述代码中,resolve用来解析URL,将其映射到相应的视图函数上。
在《lists》目录下新建一个《urls.py》在其写入:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home_page, name='home')
]
使解析的URL指向《lists.views.home_page》
在主urls.py文件中写入:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('lists.urls'))
]
使其能包含刚刚新建的《lists.urls.py》文件。
最后,在调用views中的home_page时,需要有一个home_page函数,因此,在《views》中写入:
def home_page():
pass
即可通过第一次测试。
下面为视图编写真正的测试,在《lists.test.py》文件中,写入:
from django.test import TestCase
from django.core.urlresolvers import resolve
from .views import home_page
from django.http import HttpRequest
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolve_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
self.assertTrue(response.content.startswith(b'<html>'))
self.assertIn(b'<title>To-Do lists</title>',response.content)
self.assertTrue(response.content.endswith(b'</html>'))
这里为home_page()函数传入了一个参数,因此需要更改《views》中的home_page函数
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.shortcuts import render
def home_page(request):
return HttpResponse('<html><title>To-Do lists</title></html>')
至此,单元测试通过,打开开发服务器,运行功能测试functional_tests.py,提示‘finish the test’信息,测试通过,手动打开“http://127.0.0.1:8000/”会出现一个空白网页,检查源码便是自己输入的'<html><title>To-Do lists</title></html>'