如何在 python 中为测试用例模拟对象

How to mock an object for test cases in python

我在为下面提到的 ZabbixAPILayer class 编写测试用例时遇到困难。我不确定如何在那里模拟 'zabbix_conn_obj'。任何帮助将不胜感激。谢谢!

文件:externalapi/apilayer.py

from zabbix.api import ZabbixAPI

import json
import time
class ZabbixAPILayer(object):

    def uptime(self,arg,zabbix_conn_obj):
        try:
            getUpdateItem =  zabbix_conn_obj.do_request("item.get", {"host":arg})

            lastclock=getUpdateItem['result'][37].get('lastclock')
            lastclock=int(lastclock)

            curclock=int(time.time())

            check_val=curclock-lastclock
            limit=60*1000
            if check_val<limit:
                lastval=getUpdateItem['result'][37].get('lastvalue')
                return time.strftime("%H:%M:%S", time.gmtime(float(getUpdateItem['result'][37].get('lastvalue'))))

            else:
                return "-"

        except:
            return "NOT AVAILABLE"
    .....

class APILayer(ZabbixAPILayer):
    def __init__(self):
        self.zabbix_conn_obj=ZabbixAPI(url=settings.ZABBIX_URL, user=settings.ZABBIX_USER, password=settings.ZABBIX_PWD)

    def uptime(self,arg):
        return super(APILayer,self).uptime(arg,self.zabbix_conn_obj)
.....

文件:base/admin.py

......
from ..externalapis.apilayer import APILayer
......
gen_obj= APILayer()

gen_obj.uptime()
......

感谢您的评论。得到这个工作!这是我这样做的方式

import mock

...

def test_uptime(self):
    zabbix_conn_obj = mock.Mock()
    json_blob = {} # This is the json blob i'm using as return value from do request
    zabbix_conn_obj.do_request = mock.Mock(return_value=json_blob)
    obj = ZabbixAPILayer()
    value = obj.uptime("TestHOST",zabbix_conn_obj)
    desired_result = '' #whatever my desired value is
    self.assertEqual(value, desired_result)