Python模拟补丁另一个函数中的一个函数 [英] Python mock patch a function within another function

查看:99
本文介绍了Python模拟补丁另一个函数中的一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def f1():
    return 10, True

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

如何使用python的模拟库修补f1()并返回自定义结果,以便我可以测试f2()?

How do I use python's mock library to patch f1() and return a custom result so I could test f2()?

我的考试有问题吗?这似乎不起作用,所有测试均因AssertionError失败

Edited: Is there something wrong with my test? This doesn't seem to be working, all the tests failed with 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))

推荐答案

第一个示例建议f1()和f2()在同一模块中定义. 因此,以下方法应该起作用:

First example suggests that f1() and f2() defined in the same module. 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('foo.bar.f1')

这是一个很好的答案:

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

这篇关于Python模拟补丁另一个函数中的一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆