如何在python单元测试中模拟未在本地安装的库?

如何在python单元测试中模拟未在本地安装的库?,python,unit-testing,python-mock,Python,Unit Testing,Python Mock,我正在尝试使用unittest一个以(my_app.py)开头的python 3.6脚本进行测试: 所以在我的测试中,我做了一些类似的事情: import unittest import datetime from mock import patch import my_app class TestMyApp(unittest.TestCase): @patch('awsglue.utils.getResolvedOptions') def test_mock_stubs(s

我正在尝试使用
unittest
一个以(
my_app.py
)开头的python 3.6脚本进行测试:

所以在我的测试中,我做了一些类似的事情:

import unittest
import datetime
from mock import patch
import my_app

class TestMyApp(unittest.TestCase):

    @patch('awsglue.utils.getResolvedOptions')
    def test_mock_stubs(self, patch_opts):
        patch_opts.return_value = {}
        ....
但在导入my_应用程序时,测试很快失败,原因是:

ModuleNotFoundError:没有名为“awsglue”的模块


因为没有本地安装的
awsglue
。如何测试导入非本地安装库的模块,并在测试中对其进行模拟?

在导入my_app之前,您需要模拟导入的模块<代码>修补程序在此处不起作用,因为
修补程序
导入模块以对其进行修补。在这种情况下,导入本身会导致错误

要做到这一点,最简单的方法是欺骗python,使其认为
awsglue
已经导入。您可以通过将模拟直接放在
sys.modules
字典中来实现这一点。之后,您可以执行
myu应用程序
导入

import unittest
import sys
from unittest import mock


class TestMyApp(unittest.TestCase):

    def test_mock_stubs(self):
        # mock the module
        mocked_awsglue = mock.MagicMock()
        # mock the import by hacking sys.modules
        sys.modules['awsglue.utils'] = mocked_awsglue
        mocked_awsglue.getResolvedOptions.return_value = {}

        # move the import here to make sure that the mocks are setup before it's imported
        import my_app

您可以将导入hack零件移动到
设置
夹具方法


但是我建议只安装软件包。导入黑客可能很难维护

在导入
my_app
之前,您需要模拟导入的模块<代码>修补程序在此处不起作用,因为
修补程序
导入模块以对其进行修补。在这种情况下,导入本身会导致错误

要做到这一点,最简单的方法是欺骗python,使其认为
awsglue
已经导入。您可以通过将模拟直接放在
sys.modules
字典中来实现这一点。之后,您可以执行
myu应用程序
导入

import unittest
import sys
from unittest import mock


class TestMyApp(unittest.TestCase):

    def test_mock_stubs(self):
        # mock the module
        mocked_awsglue = mock.MagicMock()
        # mock the import by hacking sys.modules
        sys.modules['awsglue.utils'] = mocked_awsglue
        mocked_awsglue.getResolvedOptions.return_value = {}

        # move the import here to make sure that the mocks are setup before it's imported
        import my_app

您可以将导入hack零件移动到
设置
夹具方法

但是我建议只安装软件包。导入黑客可能很难维护