python - mock module AND the method

163 views Asked by At

I'm writing a unit test for aws serverless using lambda layers. I need to run test in a CI/CD. This means, the layer - utils.py module is NOT available during the test. I need to:

  1. mock MODULE
  2. mock METHOD calls on module level
  3. mock METHOD calls on method level
  4. mock decorators

How do I do that? Thanks.

I've been running unit test successfully but the module has to be available during the unit testing.

#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')

Module that's NOT AVAILABLE during the unit testing:

# 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

And the unit test:

# 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)
0

There are 0 answers