Best Python code snippet using localstack_python
test_lambda.py
Source:test_lambda.py  
1#2# (c) 2017 Michael De La Rue3#4# This file is part of Ansible5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)6# Make coding more python3-ish7from __future__ import (absolute_import, division, print_function)8__metaclass__ = type9import copy10import pytest11from ansible_collections.community.amazon.tests.unit.compat.mock import MagicMock, Mock, patch12from ansible.module_utils import basic13from ansible_collections.community.amazon.tests.unit.modules.utils import set_module_args14boto3 = pytest.importorskip("boto3")15# lambda is a keyword so we have to hack this.16_temp = __import__('ansible_collections.community.amazon.plugins.modules.lambda')17lda = getattr(_temp.modules.cloud.amazon, "lambda")18base_lambda_config = {19    'FunctionName': 'lambda_name',20    'Role': 'arn:aws:iam::987654321012:role/lambda_basic_execution',21    'Handler': 'lambda_python.my_handler',22    'Description': 'this that the other',23    'Timeout': 3,24    'MemorySize': 128,25    'Runtime': 'python2.7',26    'CodeSha256': 'AqMZ+xptM7aC9VXu+5jyp1sqO+Nj4WFMNzQxtPMP2n8=',27}28one_change_lambda_config = copy.copy(base_lambda_config)29one_change_lambda_config['Timeout'] = 430two_change_lambda_config = copy.copy(one_change_lambda_config)31two_change_lambda_config['Role'] = 'arn:aws:iam::987654321012:role/lambda_advanced_execution'32code_change_lambda_config = copy.copy(base_lambda_config)33code_change_lambda_config['CodeSha256'] = 'P+Zy8U4T4RiiHWElhL10VBKj9jw4rSJ5bm/TiW+4Rts='34base_module_args = {35    "region": "us-west-1",36    "name": "lambda_name",37    "state": "present",38    "zip_file": "test/units/modules/cloud/amazon/fixtures/thezip.zip",39    "runtime": 'python2.7',40    "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution',41    "memory_size": 128,42    "timeout": 3,43    "handler": 'lambda_python.my_handler'44}45module_args_with_environment = dict(base_module_args, environment_variables={46    "variable_name": "variable_value"47})48def make_mock_no_connection_connection(config):49    """return a mock of ansible's boto3_conn ready to return a mock AWS API client"""50    lambda_client_double = MagicMock()51    lambda_client_double.get_function.configure_mock(52        return_value=False53    )54    lambda_client_double.update_function_configuration.configure_mock(55        return_value={56            'Version': 157        }58    )59    fake_boto3_conn = Mock(return_value=lambda_client_double)60    return (fake_boto3_conn, lambda_client_double)61def make_mock_connection(config):62    """return a mock of ansible's boto3_conn ready to return a mock AWS API client"""63    lambda_client_double = MagicMock()64    lambda_client_double.get_function.configure_mock(65        return_value={66            'Configuration': config67        }68    )69    lambda_client_double.update_function_configuration.configure_mock(70        return_value={71            'Version': 172        }73    )74    fake_boto3_conn = Mock(return_value=lambda_client_double)75    return (fake_boto3_conn, lambda_client_double)76class AnsibleFailJson(Exception):77    pass78def fail_json_double(*args, **kwargs):79    """works like fail_json but returns module results inside exception instead of stdout"""80    kwargs['failed'] = True81    raise AnsibleFailJson(kwargs)82# TODO: def test_handle_different_types_in_config_params():83def test_create_lambda_if_not_exist():84    set_module_args(base_module_args)85    (boto3_conn_double, lambda_client_double) = make_mock_no_connection_connection(code_change_lambda_config)86    with patch.object(lda, 'boto3_conn', boto3_conn_double):87        try:88            lda.main()89        except SystemExit:90            pass91    # guard against calling other than for a lambda connection (e.g. IAM)92    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"93    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"94    assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \95        "unexpectedly updated lambda configuration when should have only created"96    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \97        "update lambda function code when function should have been created only"98    assert(len(lambda_client_double.create_function.mock_calls) > 0), \99        "failed to call create_function "100    (create_args, create_kwargs) = lambda_client_double.create_function.call_args101    assert (len(create_kwargs) > 0), "expected create called with keyword args, none found"102    try:103        # For now I assume that we should NOT send an empty environment.  It might104        # be okay / better to explicitly send an empty environment.  However `None'105        # is not acceptable - mikedlr106        create_kwargs["Environment"]107        raise(Exception("Environment sent to boto when none expected"))108    except KeyError:109        pass  # We are happy, no environment is fine110def test_update_lambda_if_code_changed():111    set_module_args(base_module_args)112    (boto3_conn_double, lambda_client_double) = make_mock_connection(code_change_lambda_config)113    with patch.object(lda, 'boto3_conn', boto3_conn_double):114        try:115            lda.main()116        except SystemExit:117            pass118    # guard against calling other than for a lambda connection (e.g. IAM)119    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"120    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"121    assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \122        "unexpectedly updatede lambda configuration when only code changed"123    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \124        "lambda function update called multiple times when only one time should be needed"125    assert(len(lambda_client_double.update_function_code.mock_calls) > 1), \126        "failed to update lambda function when code changed"127    # 3 because after uploading we call into the return from mock to try to find what function version128    # was returned so the MagicMock actually sees two calls for one update.129    assert(len(lambda_client_double.update_function_code.mock_calls) < 3), \130        "lambda function code update called multiple times when only one time should be needed"131def test_update_lambda_if_config_changed():132    set_module_args(base_module_args)133    (boto3_conn_double, lambda_client_double) = make_mock_connection(two_change_lambda_config)134    with patch.object(lda, 'boto3_conn', boto3_conn_double):135        try:136            lda.main()137        except SystemExit:138            pass139    # guard against calling other than for a lambda connection (e.g. IAM)140    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"141    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"142    assert(len(lambda_client_double.update_function_configuration.mock_calls) > 0), \143        "failed to update lambda function when configuration changed"144    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \145        "lambda function update called multiple times when only one time should be needed"146    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \147        "updated lambda code when no change should have happened"148def test_update_lambda_if_only_one_config_item_changed():149    set_module_args(base_module_args)150    (boto3_conn_double, lambda_client_double) = make_mock_connection(one_change_lambda_config)151    with patch.object(lda, 'boto3_conn', boto3_conn_double):152        try:153            lda.main()154        except SystemExit:155            pass156    # guard against calling other than for a lambda connection (e.g. IAM)157    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"158    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"159    assert(len(lambda_client_double.update_function_configuration.mock_calls) > 0), \160        "failed to update lambda function when configuration changed"161    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \162        "lambda function update called multiple times when only one time should be needed"163    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \164        "updated lambda code when no change should have happened"165def test_update_lambda_if_added_environment_variable():166    set_module_args(module_args_with_environment)167    (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config)168    with patch.object(lda, 'boto3_conn', boto3_conn_double):169        try:170            lda.main()171        except SystemExit:172            pass173    # guard against calling other than for a lambda connection (e.g. IAM)174    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"175    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"176    assert(len(lambda_client_double.update_function_configuration.mock_calls) > 0), \177        "failed to update lambda function when configuration changed"178    assert(len(lambda_client_double.update_function_configuration.mock_calls) < 2), \179        "lambda function update called multiple times when only one time should be needed"180    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \181        "updated lambda code when no change should have happened"182    (update_args, update_kwargs) = lambda_client_double.update_function_configuration.call_args183    assert (len(update_kwargs) > 0), "expected update configuration called with keyword args, none found"184    assert update_kwargs['Environment']['Variables'] == module_args_with_environment['environment_variables']185def test_dont_update_lambda_if_nothing_changed():186    set_module_args(base_module_args)187    (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config)188    with patch.object(lda, 'boto3_conn', boto3_conn_double):189        try:190            lda.main()191        except SystemExit:192            pass193    # guard against calling other than for a lambda connection (e.g. IAM)194    assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used"195    assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly"196    assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \197        "updated lambda function when no configuration changed"198    assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \199        "updated lambda code when no change should have happened"200def test_warn_region_not_specified():201    set_module_args({202        "name": "lambda_name",203        "state": "present",204        # Module is called without a region causing error205        # "region": "us-east-1",206        "zip_file": "test/units/modules/cloud/amazon/fixtures/thezip.zip",207        "runtime": 'python2.7',208        "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution',209        "handler": 'lambda_python.my_handler'})210    get_aws_connection_info_double = Mock(return_value=(None, None, None))211    with patch.object(lda, 'get_aws_connection_info', get_aws_connection_info_double):212        with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double):213            try:214                lda.main()215            except AnsibleFailJson as e:216                result = e.args[0]...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
