查了很多资料,很多资料都是把mock跟unittest结合在一起讲的,unittest本身是有一定难度的,其实我们完全可以单独使用mock的。参考文献1中把mock讲的很详细,只要静下心来看,必定收获很多,感谢译者的辛勤付出!参考文献2中有个pdf文档,是最详细的官方文档,大概100页,也很不错,没有深入读了,以后用到了再在这篇博客里更新。
我现在主要是在nose框架下使用的mock,mock主要有name,return_value,side_effect,和spec四个函数,其中的意义都看下面的文档吧。
四个主要的assert方法:
assert_called_with 是否调用了这个函数
assert_called_once_with 是否只调用了一次这个函数
assert_has_calls 查看方法调用的顺序
assert_any_calls 是否调用了这个函数,前两个函数只能判断离它们最近的一次调用,这个是全局的。
参见代码:
from mock import Mock, call
class Order(object):
# instance properties
_orderItem = "None"
_orderAmount = 0
_orderFilled = -1
# Constructor
def __init__(self, argItem, argAmount):
print "Order:__init__"
# set the order item
if (isinstance(argItem, str)):
if (len(argItem) > 0):
self._orderItem = argItem
# set the order amount
if (argAmount > 0):
self._orderAmount = argAmount
# Magic methods
def __repr__(self):
# assemble the dictionary
locOrder = {'item':self._orderItem, 'amount':self._orderAmount}
return repr(locOrder)
# Instance methods
# attempt to fill the order
def fill(self, argSrc):
print "Order:fill_"
try:
# does the warehouse has the item in stock?
if (argSrc is not None):
if (argSrc.hasInventory(self._orderItem)):
# get the item
locCount = argSrc.getInventory(self._orderItem, self._orderAmount)
# update the following property
self._orderFilled = locCount
else:
print "Inventory item not available"
else:
print "Warehouse not available"
except TypeError:
print "Invalid warehouse"
# check if the order has been filled
def isFilled(self):
print "Order:isFilled_"
return (self._orderAmount == self._orderFilled)
class Warehouse(object):
# private properties
_houseName = None
_houseList = None
# accessors
def warehouseName(self):
return (self._houseName)
def inventory(self):
return (self._houseList)
# -- INVENTORY ACTIONS
# set up the warehouse
def setup(self, argName, argList):
pass
# check for an inventory item
def hasInventory(self, argItem):
pass
# retrieve an inventory item
def getInventory(self, argItem, argCount):
pass
# add an inventory item
def addInventory(self, argItem, argCount):
pass
class Test_Order(object):
# preparing to test
# objective: creating an order
def test_orderCheck(self):
"""Test routine C"""
# creating a test order
testOrder = Order("mushrooms", 10)
print repr(testOrder)
fooSource = Mock(spec = Warehouse)
fooSource.hasInventory.return_value = True
fooSource.getInventory.return_value = 0
# perform the test
assert fooSource != None
testOrder.fill(fooSource)
# perform the checks
assert testOrder.isFilled() == False
assert testOrder._orderFilled == 0
fooSource.hasInventory.assert_called_once_with("mushrooms")
print fooSource.mock_calls
2.https://pypi.python.org/pypi/mock