前面介绍了moco的详细的使用,它主要是基于moco-runner-0.11.0-standalone.jar,通过编写json的文件来实现,mock翻译过来就是模拟的意思,也就是说,它是将测试对象所依存的对象替换为虚构对象的库,该虚构对象的调用允许事后查看。Python中有几个库是可以模拟请求和响应的.

1. mock

在python的2.x版本中,mock是属于第三方的库,需要单独的按钮,在python3.3的版本以后,不需要单独的安装,从unitest里直接导入就可以了

接下来我们来看mock库的经常使用的方法以及它的详细的帮助信息,见以下的代码:

class Count:
def add(self):
pass from unittest import mock
import unittest class test_add(unittest.TestCase):
def test_add(self):
count = Count()
#找到要替换的对象,这个对象可以是一个类,或者是一个函数,或者是一个类实例
#实例化Mock类得到一个mock对象,并且设置这个mock对象的行为,比如被调用的时候返回什么值,被访问成员的时候返回什么值等
count.add = mock.Mock(return_value=)
result = count.add(,)
self.assertEqual(result,) if __name__ == '__main__':
unittest.main()

2. responses库

安装: pip install responses

接下来看看responses的使用方法:

import responses
import requests, unittest class responsesTest(unittest.TestCase):
def setUp(self):
pass def tearDown(self):
pass @responses.activate
def test_simple1(self):
responses.add(responses.GET, 'http://twitter.com/api/1/foobar',
json={'error': 'not found'}, status=)
url = 'http://twitter.com/api/1/foobar'
r = requests.get(url)
# print(r.json())
self.assertEqual(r.json()['error'], 'not found') if __name__ == '__main__':
unittest.main()
import json,responses, requests, unittest

class responseTest(unittest.TestCase):
def setUp(self):
pass def tearDown(self):
pass @responses.activate
def test_case1(self):
def request_callback(request):
payload = json.loads(request.body)
resp_body = {'value': sum(payload['numbers'])}
headers = {'request-id': '728d329e-0e86-11e4-a748-0c84dc037c13'}
return (, headers, json.dumps(resp_body)) responses.add_callback(
responses.POST, 'http://calc.com/sum',
callback=request_callback,
content_type='application/json',
) resp = requests.post(
'http://calc.com/sum',
json.dumps({'numbers': [, , ]}),
headers={'content-type': 'application/json'},
) self.assertEqual(resp.json()['value'], )
self.assertEqual(resp.status_code,)
self.assertEqual(resp.headers['request-id'], '728d329e-0e86-11e4-a748-0c84dc037c13') if __name__ == '__main__':
unittest.main()

最新文章

  1. 【Java 新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件
  2. 通过统计用户DNS解析记录,实现监控用户上网行为
  3. ArcGIS Server 增加缓存路径
  4. 第四课 Activity
  5. HttpClient + ASP.NET Web API, WCF之外的另一个选择
  6. go lang学习笔记——channel机理及调度理解
  7. Hibernate的检索策略
  8. Solution for "De-serialization exception: Unable to find assembly xxxxx"
  9. html table 知识点
  10. UVA 1600 Patrol Robot(机器人穿越障碍最短路线BFS)
  11. 解决SQL Server 占用80端口
  12. python基础:测量python代码的运行时间
  13. 如何直接在github上预览html网页效果
  14. php年会抽奖
  15. UEditor单个图片上传遇到的问题记录
  16. ssh登陆被拒?(云:使用云的网页版远程登陆) 不好用。
  17. android studio - Indexing paused due to batch updated
  18. as和is,但is也有as所没有的功能[C#] --转载 甘木
  19. JavaScript编写简单的增加与减少元素
  20. systemd-udevd

热门文章

  1. ffmpeg函数05__vcodec_decode_video2()
  2. C#基础进阶
  3. CVE漏洞分析
  4. 第二章 Vue快速入门-- 18 v-for中key的使用注意事项
  5. Scale-up and Scale-out(转载)
  6. Github首次使用,上传代码
  7. php的异步非阻塞swoole模块使用(一)实现简易tcp服务器--服务端
  8. 前端js之BOM和DOM操作
  9. 对React的研究-------------引用
  10. layui 批量上传