如何验证是否使用mock在python中从另一个方法调用了一个方法?

时间:2016-04-04 12:30:51

标签: python unit-testing mocking

我的主要目的是测试是否从session方法调用commit_proto_zk

我已阅读 Assert that a method was called in a Python unit test ,但无法理解:

zooKeeper.py:

def session(self, flag = ''):
    if flag == 1:
        return True
    return False 

esx.py

from zooKeeper import session
import sys

class EsxCollector():

    def collectHW(self):
        a1 = self.a()
        b1 = self.b()
        c1 = self.c()
        hwInfo = self.writeProto(a1, b1, c1)
        return hwInfo

    def a(self):
        return 'a'

    def b(self):
        return 'b'

    def c(self):
        return 'c'

    def writeProto(self, a1, b1, c1):
        return '{0} {1} {2}'.format(a1, b1, c1)


    def commit_proto_zk(self, hwInfo):  

        flag = 1
        zkSession = session(flag)

        if not zkSession:
            print "**no session**"
            sys.exit(1)
        else:
            return zkSession
        if isinstance(hwInfo,str):
            print "*****", hwInfo
            return True
        else:
            return False



    def ab(self, l):
        return l*2

def __main__():
    esxCollector = EsxCollector()
    hwInfo = esxCollector.collectHW()
    print esxCollector.commit_proto_zk(hwInfo)

if __name__=='__main__':
    __main__()

1 个答案:

答案 0 :(得分:0)

您可以使用inspect模块来获取函数的调用堆栈。

import inspect
def getCallingFunc():
    fnName = inspect.stack()[1][3]
    return fnName 
def func():
    return getCallingFunc()

print func()

输出:

func

在你的情况下,

def session(self, flag = ''):
    import inspect
    print "The calling function is ", inspect.stack()[1][3]
    if flag == 1:
        return True
    return False 
相关问题