如何在python单元测试中模拟未安装在本地的库? [英] How to mock in a python unittest a library not installed locally?

查看:26
本文介绍了如何在python单元测试中模拟未安装在本地的库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test using unittest a python 3.6 script that starts with (my_app.py):

import sys
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv, ['opt1', 'opt2', 'opt3'])
opt1 = args['opt1']
opt2 = args['opt2']
opt3 = args['opt3']
....

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

so in my test I did something like:

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 = {}
        ....

但测试很快在 import my_app 处失败:

but the test soon fails at import my_app with:

ModuleNotFoundError: 没有名为awsglue"的模块

因为本地没有安装 awsglue.如何测试导入未本地安装的库的模块并在我的测试中模拟它?

as there is not awsglue locally installed. How can I test a module that import a not locally installed library and also mock it in my test?

推荐答案

您需要在导入 my_app 之前模拟导入的模块.patch 在这里不起作用,因为 patch 导入模块以对其进行修补.在这种情况下,导入本身会导致错误.

You'll need to mock the imported module before the import for my_app happens. patch won't work here, because patch imports the module in order to patch it. And in this case, that import itself would cause an error.

要做到这一点,最简单的方法是让 python 认为 awsglue 已经导入.你可以通过将你的模拟直接放在 sys.modules 字典中来做到这一点.在此之后,您可以执行 my_app 导入.

To do this the simplest way is to trick python into thinking that awsglue is already imported. You can do that by putting your mock directly in the sys.modules dictionary. After this you can do the my_app import.

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 部分移动到 setup 夹具方法.

You can move the import hack part to a setup fixture method.

但是我建议只安装软件包.导入 hack 可能很难维护.

However I would suggest just installing the package. The import hack can be very difficult to maintain.

这篇关于如何在python单元测试中模拟未安装在本地的库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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