简体   繁体   English

Python 模拟修补另一个函数调用的函数

[英]Python mock patch a function called by another function

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() and return a custom result so I could test f2() ?如何使用 python 的模拟库来修补f1()并返回自定义结果以便我可以测试f2()

Edited: Is there something wrong with my test?编辑:我的测试有问题吗? This doesn't seem to be working, all the tests failed with AssertionError这似乎不起作用,所有测试都因 AssertionError 而失败

from foo.bar import f2
from mock import patch

class MyTest(TestCase):

    def test_f2_1(self):
        with patch('project.module.f1') as some_func:
            some_func.return_value = (20, False)
            num, stat = f2()
            self.assertEqual((num, stat), (40, False))

   @patch('project.module.f1')
   def test_f2_2(self, some_func):
       some_func.return_value = (20, False)
       num, stat = f2()
       self.assertEqual((num, stat), (40, False))

First example suggests that f1() and f2() defined in the same module.第一个示例表明 f1() 和 f2() 定义在同一模块中。 Hence the following should work:因此,以下应该工作:

from foo.bar import f2
from mock import patch

class MyTest(TestCase):

    @patch('foo.bar.f1')
    def test_f2_2(self, some_func):
        some_func.return_value = (20, False)
        num, stat = f2()
        self.assertEqual((num, stat), (40, False))

Patch is on the same as import: @patch('foo.bar.f1')补丁与导入相同: @patch('foo.bar.f1')

Here is a good answer on the issue:关于这个问题,这里有一个很好的答案:

http://bhfsteve.blogspot.nl/2012/06/patching-tip-using-mocks-in-python-unit.html http://bhfsteve.blogspot.nl/2012/06/patching-tip-using-mocks-in-python-unit.html

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.如果您的代码分为多个模块,您可能需要将__main__.f1替换为您的模块/函数的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM