【脚本语言系列】关于Python测试工具mock, 你需要知道的事
来源:互联网 发布:手机降温软件 编辑:程序博客网 时间:2024/05/17 08:05
如何使用mock
假设求阶乘会引起一系列的反应,导致发生核灾难的后果;使用mock包,用一个模拟对象来模拟阶乘计算。
1. 安装mock
easy_install mockpip install mock
- 编写阶乘函数
class NuclearReactor(): def __init__(self, n): self.n = n def do_work(self, msg): print "Working" return self.factorial(self.n, msg) def factorial(self, n, msg): print msg if n == 0: return 1 if n < 0: raise ValueError, "Core meltdown" return numpy.arange(1, n+1).cumprod()
- 创建一个模拟对象
核反应堆类有一个do_work方法,该方法会调用危险的factorial方法;
这将确保模拟对象被调用后,其返回值是6.
reactor.factorial = MagicMock(return_value=6)
class NuclearReactorTest(unittest.TestCase): def test_called(self): reactor = NuclearReactor(3) reactor.factorial = MagicMock(return_value= 6) result = reactor.do_work("mocked") self.assertEqual(6, result) reactor.factorial.assert_called_with(3, "mocked") def test_unmocked(self): reactor = NuclearReactor(3) reactor.factorial(3, "unmocked") numpy.testing.assert_raises(ValueError)
- 断言行为
可以用若干种方法,检查模拟对象的行为,进而测试真实对象的行为。
可以断言,用正确的参数调用了潜在的有爆炸危险的factorial方法。
self.assertEqual(6, result)reactor.factorial.assert_called_with(3, "mocked")
运行结果
测试代码
测试结果
什么是mock
模拟对象(mock)是真实对象的替代物,用来测试真实对象的部分行为。
一般来说,只有在不方便创建真实对象(例如数据库连接)时,或者对真实对象的测试会产生不希望有的副作用时,才需要用到模拟对象。
例如,我们可能不希望在测试过程中,把数据写入到文件系统或数据库中。
0 0
- 【脚本语言系列】关于Python测试工具mock, 你需要知道的事
- 【脚本语言系列】关于Python测试工具lettuce, 你需要知道的事
- 【脚本语言系列】关于Python测试工具unittest, 你需要知道的事
- 【脚本语言系列】关于Python测试工具docstrings, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pyflakes, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pylint, 你需要知道的事
- 【脚本语言系列】关于Python系统管理,你需要知道的事
- 【脚本语言系列】关于Python容器,你需要知道的事
- 【脚本语言系列】关于Python性能分析工具timeit, 你需要知道的事
- 【脚本语言系列】关于Python代码分析工具line_profiler,你需要知道的事
- 【脚本语言系列】关于Python游戏工具Pygame,你需要知道的事
- 【脚本语言系列】关于Python调试报错,你需要知道的事
- 【脚本语言系列】关于Python开发环境搭建,你需要知道的事
- 【脚本语言系列】关于Python数值计算NumPy, 你需要知道的事
- 【脚本语言系列】关于Python机器学习scikits-learn,你需要知道的事
- 【脚本语言系列】关于Python数值计算Pandas,你需要知道的事
- 【脚本语言系列】关于Python统计分析statsmodel,你需要知道的事
- 【脚本语言系列】关于Python邮件服务smtplib,你需要知道的事
- git fatal: cannot create directory at XXX中文 No such file or directory
- MapReduce实现两表的Join--原理及python和java代码实现
- Mysql引擎 Innodb和MyISAM的区别
- 腾讯课堂——IMWeb训练营: Day5 作业
- vector
- 【脚本语言系列】关于Python测试工具mock, 你需要知道的事
- 关于485串口通信
- 解决Execution failed for task ':app:clean'. > Unable to delete directory问题
- vue2 router 动态传参,多个参数
- IMWeb训练营 todo list作业
- Android实现地图照片墙原理
- 2017.4.19 数列 思考记录
- python程序的加密和打包
- C++常用排序总结