qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

单元测试之Monkey Patch

  再说monkey patch之前先说下, python中的Test Double, Test Double就是在测试case中给某个对象做替身的意思. 用一个假对象替换.
  用Test Double时, 可以有三种实现的形式, Stub,Mock object, Fake Object, Mock object 在我的另一博文中http://blog.csdn.net/juvxiao/article/details/21562325分析了下, 其他两种比较简单, 可看https://wiki.openstack.org/wiki/SmallTestingGuide了解 ,这个link中还提到Test Double的两种实现方式: 依赖注入 和 monkey patching.
  依赖注入
class FamilyTree(object):
def __init__(self, person_gateway):
self._person_gateway = person_gateway
  可以把person_gateway用一个假对象替换, 从而让测试专注在FamilyTree本身,
person_gateway = FakePersonGateway()
# ...
tree = FamilyTree(person_gateway)
monkey patching
  这种测试只能运行在像python这样的动态语言中, 它通过在运行时替换名空间的方式实现测试。如下例
class FamilyTree(object):
def __init__(self):
self._person_gateway = mylibrary.dataaccess.PersonGateway()
  那我们就可以在测试时把mylibrary.dataaccess.PersonGateway名空间替换为FakeGataway名空间.
mylibrary.dataaccess.PersonGateway = FakePersonGateway
# ...
tree = FamilyTree()
通过一个OpenStack中使用monkey patch的例子来说说, 这个代码片断摘自nova的单元测试test_virt_driver.py,用于讲述monkey patch用法
import nova.tests.virt.libvirt.fake_imagebackend as fake_imagebackend
import nova.tests.virt.libvirt.fake_libvirt_utils as fake_libvirt_utils
import nova.tests.virt.libvirt.fakelibvirt as fakelibvirt
sys.modules['libvirt'] = fakelibvirt
import nova.virt.libvirt.driver
import nova.virt.libvirt.firewall
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.imagebackend',
fake_imagebackend))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt',
fakelibvirt))
self.useFixture(fixtures.MonkeyPatch(
'nova.virt.libvirt.driver.libvirt_utils',
fake_libvirt_utils))
  这个例子中使用了fixtures module(fixtures就是一个testcase助手, 把一些不依赖具体测试的过程提取出来放到fixtures module中, 可以使得测试代码干净)来实现monkey patch, 就是用前几行的fake object 这个名空间替换真正driver object的名空间。达到测试时的狸猫换太子。

posted on 2014-03-31 11:35 顺其自然EVO 阅读(290) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2014年3月>
2324252627281
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜