Python模拟导入模块中的函数

2024-04-16 05:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了解如何从导入的模块中创建函数

到目前为止,我就在这里

app/mocking.py:

from app.my_module import get_user_name

def test_method():
  return get_user_name()

if __name__ == "__main__":
  print "Starting Program..."
  test_method()

app/my\u module/\uuu init\uuu.py:

def get_user_name():
  return "Unmocked User"

测试/模拟测试。py:

import unittest
from app.mocking import test_method 

def mock_get_user():
  return "Mocked This Silly"

@patch('app.my_module.get_user_name')
class MockingTestTestCase(unittest.TestCase):

  def test_mock_stubs(self, mock_method):
    mock_method.return_value = 'Mocked This Silly')
    ret = test_method()
    self.assertEqual(ret, 'Mocked This Silly')

if __name__ == '__main__':
  unittest.main()

这并不像我预期的那样有效。“patched”模块只返回未修改的值get_user_name。如何模拟其他包中的方法,将这些方法导入测试中的命名空间


Tags: namepytestimportappgetreturnmain
2条回答

虽然Matti John的回答解决了您的问题(也帮助了我,谢谢!),但是,我建议将原来的“get_user_name”函数替换为模拟函数。这将允许您控制何时替换该函数以及何时不替换该函数。此外,这将允许您在同一测试中进行多次替换。为此,请以非常相似的方式使用“with”语句:

from mock import patch

class MockingTestTestCase(unittest.TestCase):

    def test_mock_stubs(self):
        with patch('app.mocking.get_user_name', return_value = 'Mocked This Silly'):
            ret = test_method()
            self.assertEqual(ret, 'Mocked This Silly')

当您使用来自unittest.mock包的patch装饰器时,您不是在修补模块从中导入的命名空间(在本例中为app.my_module.get_user_name),而是在测试app.mocking.get_user_name下的命名空间中修补它

要使用Mock执行上述操作,请尝试以下操作:

from mock import patch
from app.mocking import test_method 

class MockingTestTestCase(unittest.TestCase):

    @patch('app.mocking.get_user_name')
    def test_mock_stubs(self, test_patch):
        test_patch.return_value = 'Mocked This Silly'
        ret = test_method()
        self.assertEqual(ret, 'Mocked This Silly')

标准库文档包括一个有用的section来描述这一点

相关问题 更多 >