【问题标题】:Python Mock dependenciesPython 模拟依赖项
【发布时间】:2021-04-21 14:39:35
【问题描述】:

您好,我正在寻找一种方法来模拟由函数调用的函数。 目前我只找到类似这样的例子:

def f1():
    a = 'do not make this when f1() is mocked'
    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() # prints now 60, 

这样做的问题是方法的返回值被覆盖了,但函数的实际逻辑仍然被执行。 函数中发生的事情应该被忽略。 换句话说,我想为测试重载函数。 这是个好主意,还是有其他解决问题的方法?

【问题讨论】:

    标签: python mocking python-unittest patch


    【解决方案1】:

    函数的实际逻辑没有被执行。它将用新的模拟对象替换目标函数,该对象在调用时返回您的值

    def f1():
        a = 'do not make this when f1() is mocked'
        print("should be printed once")
        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() # prints now 60,
    

    输出:

    should be printed once
    (20, True)
    (60, True)
    
    

    sohuld be printed once 只打印一次,因此在打补丁时不会执行第二次内部逻辑。

    在这里查看执行https://ideone.com/jRpObT

    【讨论】:

    • 感谢您的回答,它有效。我将多个文件作为一个文件处理,问题是导入。我更改了我的导入: from package.file import method # not work import package.file # work 并设置了 method() 使用 file.method() 两边都改一下就行了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2014-09-23
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多