再说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 = FakePersonGateway # ... tree = FamilyTree()
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的名空间。达到测试时的狸猫换太子。