Python mock patch a function within another function

前端 未结 2 1059
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 09:06
def f1():
    return 10, True

def f2():
    num, stat = f1()
    return 2*num, stat

How do I use python\'s mock library to patch f1()

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 09:14

    Assuming that you're using this mock libary:

    def f1():
        return 10, True
    
    def f2():
        num, stat = f1()
        return 2*num, stat
    
    import mock
    
    print f2()   # Unchanged f1 -> prints (20, True)
    
    with mock.patch('__main__.f1') as MockClass:       # replace f1 with MockClass 
        MockClass.return_value = (30, True)     # Change the return value
    
        print f2()     # f2 with changed f1 -> prints (60, True)
    

    If your code is divided into modules you would probably need to replace __main__.f1 with the path to your module/function.

提交回复
热议问题