微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python-模拟模块和方法

如何解决python-模拟模块和方法

我正在使用lambda层为无服务器AWS编写单元测试。 我需要在CI / CD中运行测试。这意味着-utils.py层模块在测试期间不可用。 我需要:

  1. 模拟模块
  2. 模拟方法在模块级别调用
  3. 模拟方法方法级别调用
  4. 模拟装饰器

我该怎么做?谢谢。

我已经成功运行了单元测试,但是该模块必须在单元测试期间可用。

#functional module func_module.py
from app.lib_common import utils
log_level = utils.get_logging_level()

@utils.log_performance
def lambda_handler()
   utils.get_code('abc')

在单元测试期间不可用的模块:

# utils.py

# regular function
def get_code(input)
    return input + 'def'

# method called from class level
def get_logging_level():
    return 1

# wrapper function
def log_performance(func):
'''Decorator to log the amount of time it takes for a function to execute.'''
if not callable(func):
    raise ValueError('This method is to be used as a decorator only.')
    def wrapper_func(*func_args,**func_kwargs):
        start_time = time.time()
        result = func(*func_args,**func_kwargs)
        elapsed_time = time.time() - start_time
        logger.info(f'Elapsed time: {time.strftime("%H:%M:%s",time.gmtime(elapsed_time))}')
        return result
    return wrapper_func

单元测试:

# test.py
import func_module
from unittest.mock import patch
from unittest.mock import Mock
sys.modules['utils'] = Mock()

class Test_Get_By_Entity(unittest.TestCase):
    @patch('app.lib_common.utils',autospec=True,spec_set=True)
    def test_cam_get_by_entity_event_none_return_400(self,mock_utils):
        mock_utils.get_code = {}
        mock_utils.get_loggging_level.return_value = 3
        response = func_module.lambda_handler()
        self.assertEqual(response['statusCode'],200)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。