如何使用模拟的@patch模拟在单独的Python模块中定义的函数 [英] How to mock a function defined in a separate Python module using mock's @patch

查看:169
本文介绍了如何使用模拟的@patch模拟在单独的Python模块中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用模拟和@patch装饰器为Python应用程序构建测试.

I am attempting to build a test for a Python application using mock and the @patch decorator.

给出以下目录结构:

  |-- mypackage
  |   |-- mymodule
  |   |   |-- __init__.py
  |   |   \-- somefile.py
  |   \-- myothermodule
  |       |-- tests
  |       |   |-- __init__.py
  |       |   \-- test_func_to_test.py
  |       \-- __init__.py
  \-- __init__.py

文件内容在哪里:

#mypackage/mymodule/somefile.py

def some_function():
    return 'A'


#mypackage/myothermodule/__init__.py

from mypackage.mymodule.somefile import some_function

def func_to_test():
    return some_function()


#mypackage/myothermodule/tests/test_func_to_test.py

from unittest import TestCase
from mock import patch

class TestFunc_to_test(TestCase):
    def test_func_to_test(self):
        from mypackage.myothermodule import func_to_test
        self.assertEqual('A', func_to_test())

    @patch('mypackage.mymodule.somefile.some_function')
    def test_func_to_test_mocked(self, some_mock_function):
        from mypackage.myothermodule import func_to_test
        some_mock_function.return_value = 'B'
        self.assertEqual('B', func_to_test())


我的问题是,尽管第一个测试通过(test_func_to_test),而第二个测试(test_func_to_test_mocked)没有(由于AssertionError).


The problem I have is that, while the first test passes (test_func_to_test), the second test (test_func_to_test_mocked) does not (due to an AssertionError).

我已经能够使用相同的方法来模拟内置"模块(例如,requests.get)中的函数,但是当尝试从中修补函数时,我似乎无法使@patch起作用我的模块之一...

I have been able to mock function from "built-in" modules (like requests.get, for example) using the same approach, however I can't seem to get the @patch working when trying to patch a function from one of my modules...

任何帮助将不胜感激:)

Any help would be appreciated :)

推荐答案

mypackage.myothermodule已被导入,因此名称some_function已绑定在该模块中.您需要在从以下位置调用它的模块中模拟该名称的用法:

mypackage.myothermodule has already been imported, so the name some_function is already bound within that module. You need to mock the usage of that name within the module it is being called from:

@patch('mypackage.myothermodule.some_function')

您也可以重新加载mypackage.myothermodule:

import mypackage.myothermodule
reload(mypackage.myothermodule)

这篇关于如何使用模拟的@patch模拟在单独的Python模块中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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