Python模拟如何编辑模拟函数的返回值

Ash*_*mar 4 python unit-testing mocking mongodb flask

我在一个单独的文件中有一个函数,在另一个文件中有一个单元测试,我的目标是获取该函数的实际返回值并对其进行编辑。

my_module.py

def function_to_test(a,b,c)(arg1,arg2,arg3):
    data_to_send = Mongoclient.find({_id:'arg1'})
    return data_to_send

def another_function():
    """Do something."""
    value_to_be_used = function_to_test(a,b,c)
    another_function_call_in_another_module(value_to_be_used)
Run Code Online (Sandbox Code Playgroud)

test_file.py

class Mytest(unittest.TestCase):
    def test_one(self):
        # return_value is based on the original return value, 
        # and should vary based on the original returned value
        with patch(my_module.function_to_test, return_value='new data'):  
            my_module.another_function()
Run Code Online (Sandbox Code Playgroud)

新数据是原始数据+对原始数据的一些编辑。

我该如何实现这一目标?

Jos*_*ilo 6

  • 您可以保留对原始函数的引用。
  • 然后您可以定义修补后的函数,该函数调用原始函数并添加一些数据。
  • 然后你可以使用你的修补函数作为side_effect你的模拟。
class Mytest(unittest.TestCase):
    def test_one(self):
        # the return_value is based on the original return value and
        # should vary based on the original returned value

        original = my_module.function_to_test

        def patched(arg1, arg2, arg3):
            original_result = original(arg1, arg2, arg3)
            return original_result + ' @ new data'

        with patch("my_module.function_to_test", side_effect=patched):
            result = my_module.another_function()

        assert result == 'old data @ new data', result
Run Code Online (Sandbox Code Playgroud)
def function_to_test(arg1, arg2, arg3):
    return 'old data'


def another_function_call_in_another_module(value_to_be_used):
    return value_to_be_used


def another_function():
    # Do something
    a, b, c = 1, 2, 3
    value_to_be_used = function_to_test(a, b, c)
    return another_function_call_in_another_module(value_to_be_used)
Run Code Online (Sandbox Code Playgroud)

一些参考: