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 閱讀(306) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2014年3月>
          2324252627281
          2345678
          9101112131415
          16171819202122
          23242526272829
          303112345

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 扎鲁特旗| 保山市| 盘锦市| 屯昌县| 宜黄县| 阳泉市| 德昌县| 察哈| 安吉县| 青岛市| 晋城| 固安县| 文山县| 万山特区| 敦煌市| 五原县| 香河县| 泽普县| 高尔夫| 云南省| 措勤县| 靖西县| 南阳市| 铜鼓县| 怀仁县| 丰都县| 广水市| 河东区| 定结县| 闻喜县| 通江县| 冷水江市| 会昌县| 奇台县| 沭阳县| 五华县| 江达县| 新平| 柏乡县| 长汀县| 宁国市|