[OpenStack UT] 单元测试之Monkey Patch

本文探讨了Python中的Test Double概念,包括Stub、Mock Object和Fake Object的使用,并重点介绍了Monkey Patch技术。Monkey Patch是一种在运行时通过替换名空间进行测试的方法,尤其适用于动态语言如Python。文章提到了依赖注入和Monkey Patch作为Test Double的实现方式,并链接到OpenStack的SmallTestingGuide了解更多详情。

再说monkey patch之前先说下, python中的Test Double, Test Double就是在测试case中给某个对象做替身的意思. 用一个假对象替换.

用Test Double时, 可以有三种实现的形式, Stub,Mock object, Fake Object, Mock object 在我的另一博文中http://blog.youkuaiyun.com/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的名空间。达到测试时的狸猫换太子。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值