模拟一个用户去访问views 先是创建了一个httprequest对象 然后把httprequest对象传给home_page视图,得到的是httpresponse返回 提取相应是content字节,decode转换成html字符串
tests.py
'''from django.test import TestCase
# Create your tests here.
class Smokeclass(TestCase):
def test_bad_maths(self):
self.assertEquals(1+1,3)'''''
from django.urls import resolve
from django.test import TestCase
from lists.views import home_page
from django.http import HttpRequest
class HomePageTest(TestCase):
def test_root_url_resolve_to_home_page_view(self):
found=resolve('/')
# resolve函数是django内部使用的函数,用于解析url,
# 并且将其映射到相应的视图函数上,检查网站根路径时"/",
# 是否能找到home_page函数
self.assertEquals(found.func,home_page)
def test_home_page_returns_correct_html(self):
request=HttpRequest()
# 创建httprequest对象,用户在浏览器中请求网页时
# django看到的就是httprequest对象
response=home_page(request)
# 把对象传给home_page视图
html=response.content.decode('utf8')
# 提取content,得到结果是原始的字节,即发个用户
# 浏览器的0和1,随后调用.decode(),把原始字节
# 转换成发给用户的html字符串
self.assertTrue(html.startswith('<html>'))
self.assertIn('<title>To-Do lists</title>',html)
self.assertTrue(html.endswith('</html>'))
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_page(request):
return HttpResponse('<html><title>To-Do lists</title></html>')
需要注意的点:
1)html.startswith和html.endswith单词的编写
2) html=response.content.decode('utf8')
编码格式是utf8
3)请求是HttpRequest,返回是HttpResponse