python mox使用方法
来源:互联网 发布:mac如何airdrop 编辑:程序博客网 时间:2024/03/29 12:56
pymox是一套用于python代码unit test的框架. 官方链接如下:
https://code.google.com/p/pymox/
但是从官方的wiki上看到pymox的使用案例较少,而且比较简略.
这里按照通常使用情况整理下.
首先从最基本的框架说起.
创建一个unit test的test case, 在这里需要先import两个包
import moximport unittest
然后创建一个对应的测试类.
class TestZoo(unittest.TestCase): def setUp(self): self.m = mox.Mox() def tearDown(self): self.m.UnsetStubs()
现在设定被测程序存放于zoo.py, 提供函数如下:
from datetime import datedef get_most_popular_animal(): month = get_month() if month in [11,12,1]: return 'penguin' elif month in [6,7,8]: return 'swan' else: return 'tiger'def get_month(): today = date.today() return today.monthdef get_day(): today = date.today() return today.day
要测试函数get_most_popular_animal,需要先处理函数get_month,确保每次返回固定的数值。这里可以使用mox中的函数 StubOutWithMock.
def test_get_most_popular_animal(self): self.m.StubOutWithMock(zoo, 'get_month') zoo.get_month().AndReturn(1) self.m.ReplayAll() self.assertEqual('penguin', zoo.get_most_popular_animal()) self.m.VerifyAll()
StubOutWithMock 用来指明哪个模块中的哪个函数需要被mock,后面通过AndReturn就可以指定函数的行为了。在调用被测函数之前,运行ReplayAll函数来生效这些mock。
对于VerifyAll函数,其实在这里即使去掉这句话测试case也是可以通过的。
如果我们对case稍加修改:
def test_get_most_popular_animal(self): self.m.StubOutWithMock(zoo, 'get_month') zoo.get_month().AndReturn(1) self.m.StubOutWithMock(zoo, 'get_day') zoo.get_day().AndReturn(2) self.m.ReplayAll() self.assertEqual('penguin', zoo.get_most_popular_animal()) self.m.VerifyAll()mock一个新的函数get_day,get_most_popular_animal其实并未调用此函数,于是运行时会得到下面的错误:
ExpectedMethodCallsError: Verify: Expected methods never called: 0. get_day.__call__() -> 2
所以可以通过VerifyAll()函数来检测哪些函数应该被执行到。
0 0
- python mox使用方法
- python mox使用方法(2)
- python mox使用方法(3)
- 分析OpenStack中单元测试之mock & mox
- python异常简单使用方法
- Python搭配MongoDB使用方法
- boost.python使用方法
- python struct使用方法
- Python yield 使用方法简介
- Python搭配MongoDB使用方法
- Python基本使用方法记录
- [python]-mysqldb 使用方法
- Python yield 使用方法
- Python set模块使用方法
- Python的set使用方法
- Python yield使用方法
- Python set模块使用方法
- python subprocess 模块使用方法
- linux input 子系统分析 二
- std:string跨模块出错的问题
- 如何利用google原生包在android平台上实现语音识别
- linux input 子系统分析 三
- java 做多线程通讯
- python mox使用方法
- 网络数据包发送接收全过程简介
- 0长度数组
- iOS7滑动返回
- 收集书名
- linux------虚拟机的桥接模式和NAT模式的区别
- 动态批量上传文件的实现
- 20140103孤独者之旅19
- graphviz画图之张柏芝前夫是谢霆锋