3.1第一个Django应用,第一个单元测试
python3 manage.py startapp lists 创建一个应用
功能测试站在用户的角度从外部测试应用,而单元测试从程序员的角度从内部测试应用
3.2Django中的单元测试
打开新生成的的文件lists/tests.py
注:单元测试运行,会自动测试以test开头的函数
#tests.py # -*- coding: utf-8 -*- from django.test import TestCase class SimpleTest(TestCase): def test_bad_maths(self): self.assertEqual(1+1,3)
python3 manage.py test 运行单元测试,出现错误,good
3.3Django中的MVC,URL和视图函数
#tests.py # -*- coding: utf-8 -*- from django.test import TestCase from django.core.urlresolvers import resolve from lists.views import home_page
class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func,home_page) #resolve是Django的内部函数,用于解析URL,并映射到相应师视图函数,解析网站跟路径'/'时,是否能找到名为home_page函数,home_page函数保存在文件lists/views。py中
python3 manage.py test 运行单元测试,查看错误
3.4编写应用代码
视图函数views.py
#views from django.shortcuts import render,redirect #编写视图 def home_page(): pass
python3 manage.py test 运行单元测试,查看错误,抛出404错误,说明Django无法找找到 "/" 的url 映射
编写urls.py
from django.conf.urls import url,include from django.contrib import admin from lists import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^$',views.home_page) ] #r'^$'表示正则表达式,表示空字符串
python3 manage.py test 运行单元测试,测试通过。。。
3.5为视图编写单元测试
编写test.py
#tests.py # -*- coding: utf-8 -*- from django.test import TestCase from django.http import HttpRequest from django.core.urlresolvers import resolve from lists.views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func,home_page) def test_home_page_return_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>'))
编写views.py
#views from django.shortcuts import render,redirect from django.http import HttpResponse def home_page(request): return HttpResponse('<html><title>To-Do lists</title></html>')
python3 manage.py test 运行单元测试,测试应该通过。。。