之前的代码还没有为表单指定action=属性,因此提交表单默认返回之前渲染的页面,即“/”,这个由视图函数home_page处理。下面修改这个视图函数,让它能处理POST请求。

这意味着要为视图函数home_page编写一个新的单元测试,打开文件 lists/tests.py

在HomePageTest类中添加一个新方法,在其中添加post请求,在检查返回的HTML中是否有新添加的待办事项文本。

"""向浏览器返回真正的HTML响应,添加一个新的测试方法"""
from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from lists.views import home_page

class HomePageTest(TestCase): [……] def Test_home_page_can_save_a_post_request(self):
request = HttpRequest()
request.method = 'POST'
request.POST['item_text'] = 'A new list item' response = home_page(request)
self.assertIn('A new list item', response.content.decode())
设置配置——执行代码——编写断言是单元测试的典型结构(前三行作用是设置测试的背景;然后在中间添加一行调用要测试的函数;最后编写断言)

可以看出,用到了HttpRequest的几个特殊属性:.methed和.post.(更多内容查看https://docs.djangoproject.com/en/1.7/ref/request-response/)

 
post我们调用self.client.post,正如您所看到的,它需要一个数据参数,其中包含我们要发送的表单数据。
然后我们检查post请求以呈现的html结束。这给了我们预期的失败:
# python manage.py test

为了让测试通过,在view.py文件中添加一个if语句,为POST请求提供一个不同的代码执行路劲。按照典型的TDD方式,先故意编写一个愚蠢的返回值。

from django.shortcuts import render
from django.http import HttpResponse # Create your views here.在这儿编写视图
def home_page(request):
if request.method == 'POST':
return HttpResponse(request.POST['item_text'])
return render(request, 'home.html')

这样单元测试是通过了,但不是我们想要的,我们希望把POST请求提交的数据添加到首页模板的表格里。

最新文章

  1. P/Invoke:C#调用C++
  2. tomcat之Session的管理
  3. C#获取网页内容的三种方式
  4. Windows Azure支持七层负载均衡--Application Gateway
  5. [工作bug]一个weblogic跨应用导致session丢失的bug之旅
  6. Android Studio解决unspecified on project app resolves to an APK archive which is not supported
  7. jenkis编译报错:需要class,interface或enum
  8. linux cache swap 以及 虚拟内存等
  9. HTTP协议的8种请求类型介绍
  10. JavaScript 题目(作用域)
  11. windows部署MongoDB
  12. HTML页面全屏/退出全屏
  13. Java8 Lambda和Stream的用法
  14. applicationContext.xml配置Spring样板
  15. python编码问题在此终结
  16. c# 软件绑定网卡mac的实用
  17. 使用php的curl根据关键词爬取百度搜索结果页
  18. spring---aop(2)---Spring AOP的JDK动态代理
  19. 【转】VueJS中学习使用Vuex详解
  20. 解决Eclipse下启动tomcat报错:/bin/bootstrap.jar which is referenced by the classpath, does not exist.

热门文章

  1. vue2-org-tree 基于VUE的部门组织架构组件,增删节点实现
  2. 大觅网03Day
  3. OpenStack组件——Glance镜像服务
  4. 【C/C++】什么是类型安全
  5. 小米手机Toast带app名称
  6. 图解DMZ
  7. sqlalchemy映射数据库
  8. 修改state(react)中的某一个对象中的单个参数
  9. 2019牛客暑期多校训练营(第二场)-F artition problem
  10. [转帖](整理)GNU Hurd项目详解