Python 3 unittest 补丁没有返回所需的值 [英] Python 3 unittest patch doesn't return desired value

查看:66
本文介绍了Python 3 unittest 补丁没有返回所需的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 unitttest mock 框架 (python 3.4.9) 来模拟我的测试用例中的方法之一.它失败了,因为它没有返回模拟值.

I am trying to use the unitttest mock framework (python 3.4.9) to mock one of the method in my test case. And it's failing as it doesn't return the mocked value.

这是最简单的例子.就我而言,我无法更改调用方法的方式.

This is the simplest example. In my case I can't change the way method being invoked.

模拟方法

def patch_this_method():
    return 100

测试用例

import unittest
from unittest.mock import patch
from libs.util import patch_this_method
import libs

class TestLibs(unittest.TestCase):
    @patch('libs.util.patch_this_method', return_value="200")
    def test_1(self, *mock):
        # return 200
        print(libs.util.patch_this_method())

        # this returns 100, original value
        print(patch_this_method())

推荐答案

此行

from libs.util import patch_this_method

导入一个对象,该对象是原始函数的副本,该函数尚未修补.

imports an object that is a copy of the original function, and the function has not been patched yet.

然后在mock参数前有一个奇怪的*字符;它实际上不会影响代码,因为它没有被使用,然后您会获得预期的结果.第一个调用链接到修补过的函数.另一个没有.

Then there is a strange * char before the mock parameter; it actually doesn't affect the code because it is not used and then you obtain the expected results. The first call links to the patched function. The other one doesn't.

关于您在评论中的问题,您不能不使用补丁装饰器,使用某个包中未包含的简单名称是行不通的.来自补丁装饰器的文档(目标是要补丁的字符串):

About your question in the comment, you can't not with the patch decorator, using a simple name not contained in some package won't do. From the documentation of patch decorator (target is the string to patch):

target 应该是package.module.ClassName"形式的字符串.目标被导入并且指定的对象被新对象替换,因此目标必须可以从您调用 patch() 的环境中导入.目标是在执行装饰函数时导入的,而不是在装饰时导入.

target should be a string in the form 'package.module.ClassName'. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch() from. The target is imported when the decorated function is executed, not at decoration time.

但你可以简单地写:

from unittest.mock import Mock # or MagickMock if you need it
...
patch_this_method = Mock(return_value=200) 

现在您的函数将使用模拟函数.

And now your functions will use the mocked function.

这篇关于Python 3 unittest 补丁没有返回所需的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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