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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...