Best Python code snippet using localstack_python
test_awslambdamanager.py
Source:test_awslambdamanager.py
1from copy import deepcopy2import yaml3from os import path4import os5from shutil import copytree, rmtree6from tempfile import mkdtemp7import boto38from git import Repo9from moto import mock_lambda, mock_s310import pytest11from lambdamanager.awslambda import AwsLambdaManager12boto3.setup_default_session(region_name='us-west-1')13FUNCTION_EXAMPLE = {14 'Runtime': 'python2.7',15 'Role': 'a-iam-role',16 'Handler': 'module_name.lambda_handler',17 'Description': 'A function description', # optional18 'Code': {19 'S3Bucket': 'the-bucket-name-to-upload-releases',20 'S3KeyPath': 'route/to/releases/directory',21 'Directory': 'path/to/code/directory',22 },23 'MemorySize': 128,24 'Timeout': 120, # optional25 'VpcConfig': { # optional26 'SubnetIds': [27 'string',28 ],29 'SecurityGroupIds': [30 'string',31 ],32 },33 'Environment': { # optional34 'Variables': {35 'KEY1': 'VALUE1',36 'KEY2': 'VALUE2',37 'KEY3': 'VALUE3',38 }39 },40}41AWS_LAMBDA_CONFIG_ONE_FUNCTION = {42 'function-one': FUNCTION_EXAMPLE,43}44AWS_LAMBDA_CONFIG_FUNCTIONS = {45 'function-one': FUNCTION_EXAMPLE,46 'function-two': FUNCTION_EXAMPLE,47}48FUNCTION_ONE_PATH = path.join(path.dirname(path.dirname(__file__)),49 'assets/function_sample')50with open(path.join(FUNCTION_ONE_PATH, 'functions.yml'), 'r') as config_file:51 FUNCTION_ONE_CONFIG = yaml.load(config_file)52@mock_lambda53def test_awslambda_init():54 config = {}55 alm = AwsLambdaManager(config)56 assert alm.config == config57@mock_lambda58def test_awslambda_init_config():59 alm = AwsLambdaManager(AWS_LAMBDA_CONFIG_ONE_FUNCTION)60 assert alm.config == AWS_LAMBDA_CONFIG_ONE_FUNCTION61@mock_lambda62def test_awslambda_available_functions():63 alm = AwsLambdaManager(AWS_LAMBDA_CONFIG_ONE_FUNCTION)64 assert 'function-one' in alm.available_functions()65@mock_lambda66def test_awslambda_select_function_default():67 alm = AwsLambdaManager(AWS_LAMBDA_CONFIG_ONE_FUNCTION)68 alm.select_function()69 assert alm.function_selected == 'function-one'70@mock_lambda71def test_awslambda_select_function_from_multiple():72 alm = AwsLambdaManager(AWS_LAMBDA_CONFIG_FUNCTIONS)73 with pytest.raises(AwsLambdaManager.MultipleFunctionsFoundError):74 alm.select_function()75 alm.select_function('function-two')76 assert alm.function_selected == 'function-two'77 with pytest.raises(AwsLambdaManager.FunctionNotFoundError):78 alm.select_function('not-valid-function')79@mock_lambda80def test_awslambda_get_function_configuration_ok():81 alm = AwsLambdaManager(AWS_LAMBDA_CONFIG_ONE_FUNCTION)82 alm.select_function()83 function_config = alm.get_function_configuration()84 # Check required keys are present:85 for key in ('FunctionName', 'Runtime', 'Role', 'Handler', 'MemorySize'):86 assert key in function_config87 # Check not required keys are present:88 for key in ('Environment', 'Description', 'Timeout', 'VpcConfig'):89 assert key in function_config90@mock_lambda91def test_awslambda_get_function_configuration_mininal():92 config = deepcopy(FUNCTION_EXAMPLE)93 for key in ('Environment', 'Description', 'Timeout', 'VpcConfig'):94 del config[key]95 alm = AwsLambdaManager({'function-one': config})96 alm.select_function()97 function_config = alm.get_function_configuration()98 # Check required keys are present:99 for key in ('FunctionName', 'Runtime', 'Role', 'Handler', 'MemorySize'):100 assert key in function_config101 # Check not required keys are not present:102 for key in ('Environment', 'Description', 'Timeout', 'VpcConfig'):103 assert key not in function_config104@mock_lambda105def test_awslambda_create_package_config_ok():106 # Temporary asset creation107 tmpdir = mkdtemp(prefix='lambdamanagertest')108 function_basename = path.basename(FUNCTION_ONE_PATH)109 copytree(FUNCTION_ONE_PATH, path.join(tmpdir, function_basename))110 oldpwd = os.getcwd()111 os.chdir(path.join(tmpdir, function_basename))112 # Create a repo structure113 tmprepo = Repo.init('.')114 open('GIT_FILE', 'w').close()115 tmprepo.index.add(['GIT_FILE'])116 tmprepo.index.commit('sad initial commit')117 alm = AwsLambdaManager(FUNCTION_ONE_CONFIG)118 alm.select_function('function-one')119 alm.create_package(release_tag='test')120 assert path.getsize(alm.local_filename) > 128121 assert path.isfile(alm.local_filename)122 # test extra tearDown ...123 os.chdir(oldpwd)124 rmtree(tmpdir)125# TODO: Implement a helper to create more tests about packaging.126# Including something about Runtime selection.127@mock_lambda128@mock_s3129def test_awslambda_upload_package_ok():130 # Temporary asset creation131 tmpdir = mkdtemp(prefix='lambdamanagertest')132 function_basename = path.basename(FUNCTION_ONE_PATH)133 copytree(FUNCTION_ONE_PATH, path.join(tmpdir, function_basename))134 oldpwd = os.getcwd()135 os.chdir(path.join(tmpdir, function_basename))136 # Create a repo structure137 tmprepo = Repo.init('.')138 open('GIT_FILE', 'w').close()139 tmprepo.index.add(['GIT_FILE'])140 tmprepo.index.commit('sad initial commit')141 alm = AwsLambdaManager(FUNCTION_ONE_CONFIG)142 alm.select_function('function-one')143 alm.create_package(release_tag='test')144 alm.upload_package()145 s3 = boto3.resource('s3')146 mocked_obj = s3.Object(147 FUNCTION_ONE_CONFIG['function-one']['Code']['S3Bucket'],148 path.join(FUNCTION_ONE_CONFIG['function-one']['Code']['S3KeyPath'],149 alm.local_filename)150 ).get()151 assert path.getsize(alm.local_filename) > 0152 assert mocked_obj['ContentLength'] == path.getsize(alm.local_filename)153 # test extra tearDown ...154 os.chdir(oldpwd)155 rmtree(tmpdir)156@mock_lambda157@mock_s3158def test_awslambda_create_function_ok():159 # TODO: To be implemented160 assert True161@mock_lambda162def test_awslambda_function_exists_exists():163 # TODO: To be implemented164 assert True165@mock_lambda166def test_awslambda_function_exists_not_exists():167 # TODO: To be implemented168 assert True169@mock_lambda170@mock_s3171def test_awslambda_create_release():172 # TODO: To be implemented173 assert True174@mock_lambda175def test_awslambda_update_or_create_alias_update():176 # TODO: To be implemented177 assert True178@mock_lambda179def test_awslambda_update_or_create_alias_create():180 # TODO: To be implemented181 assert True182@mock_lambda183def test_awslambda_update_or_create_alias_failed():184 # TODO: To be implemented185 assert True186@mock_lambda187def test_awslambda_update_function_configuration_ok():188 # TODO: To be implemented189 assert True190@mock_lambda191def test_awslambda_update_function_configuration_failed():192 # TODO: To be implemented193 assert True194@mock_lambda195def test_awslambda_list_aliases_ok():196 # TODO: To be implemented197 assert True198@mock_lambda199def test_awslambda_list_aliases_failed():200 # TODO: To be implemented201 assert True202@mock_lambda203def test_awslambda_promote_release_ok():204 # TODO: To be implemented205 assert True206@mock_lambda207def test_awslambda_promote_release_failed():208 # TODO: To be implemented209 assert True210@mock_lambda211def test_awslambda_invoke_sync_ok():212 # TODO: To be implemented213 assert True214@mock_lambda215def test_awslambda_invoke_sync_failed():216 # TODO: To be implemented217 assert True218@mock_lambda219def test_awslambda_invoke_async_ok():220 # TODO: To be implemented221 assert True222@mock_lambda223def test_awslambda_invoke_async_failed():224 # TODO: To be implemented...
test_aws_lambda.py
Source:test_aws_lambda.py
1import pytest2from test.pytestutils import before3from unittest.mock import Mock4from datetime import timedelta5from codeguru_profiler_agent.agent_metadata.aws_lambda import AWSLambda6from codeguru_profiler_agent.aws_lambda.lambda_context import LambdaContext7class TestAWSLambda:8 class TestLookUpMetadata:9 class TestWhenContextIsAvailable:10 class TestWhenEnvIsAvailable:11 @before12 def before(self):13 self.context = Mock()14 self.context.invoked_function_arn = "the_lambda_function_arn"15 self.env = {"AWS_EXECUTION_ENV": "AWS_Lambda_python3.6", "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "2048"}16 def test_it_finds_the_arn(self):17 subject = AWSLambda.look_up_metadata(self.context, self.env)18 assert subject.function_arn == "the_lambda_function_arn"19 def test_it_finds_memory_limit(self):20 subject = AWSLambda.look_up_metadata(self.context, self.env)21 assert subject.memory_limit_mb == 204822 def test_it_finds_the_execution_env(self):23 subject = AWSLambda.look_up_metadata(self.context, self.env)24 assert subject.execution_env == "AWS_Lambda_python3.6"25 def test_when_env_is_not_available_it_still_returns_at_least_the_arn(self):26 subject = AWSLambda.look_up_metadata(self.context, {})27 assert subject.function_arn == "the_lambda_function_arn"28 def test_when_env_is_not_available_other_values_are_set_to_none(self):29 subject = AWSLambda.look_up_metadata(self.context, {})30 assert subject.execution_env is None31 assert subject.memory_limit_mb is None32 class TestWhenMemoryEnvIsNotValidInt:33 @before34 def before(self):35 self.context = Mock()36 self.context.invoked_function_arn = "the_lambda_function_arn"37 self.env = {"AWS_EXECUTION_ENV": "AWS_Lambda_python3.6",38 "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "not_a_valid_integer"}39 def test_it_still_returns_the_arn(self):40 subject = AWSLambda.look_up_metadata(self.context, {})41 assert subject.function_arn == "the_lambda_function_arn"42 def test_it_finds_the_execution_env(self):43 subject = AWSLambda.look_up_metadata(self.context, self.env)44 assert subject.execution_env == "AWS_Lambda_python3.6"45 def test_memory_limit_is_set_to_none(self):46 subject = AWSLambda.look_up_metadata(self.context, self.env)47 assert subject.memory_limit_mb is None48 class TestWhenContextIsNotAvailable:49 def test_it_returns_none(self):50 subject = AWSLambda.look_up_metadata(context=None, env={})51 assert subject is None52 class TestSerializeToMap:53 def test_it_returns_a_map(self):54 subject = AWSLambda(function_arn="the_arn", memory_limit_mb=512, execution_env="AWS_Lambda_python3.8")55 assert subject.serialize_to_map() == {56 "computeType": "aws_lambda",57 "functionArn": "the_arn",58 "memoryLimitInMB": 512,59 "executionEnv": "AWS_Lambda_python3.8"60 }61 def test_it_ignores_memory_limit_if_none(self):62 subject = AWSLambda(function_arn="the_arn", memory_limit_mb=None, execution_env="AWS_Lambda_python3.8")63 assert subject.serialize_to_map() == {64 "computeType": "aws_lambda",65 "functionArn": "the_arn",66 "executionEnv": "AWS_Lambda_python3.8"67 }68 def test_it_ignores_execution_env_if_none(self):69 subject = AWSLambda(function_arn="the_arn", memory_limit_mb=512, execution_env=None)70 assert subject.serialize_to_map() == {71 "computeType": "aws_lambda",72 "functionArn": "the_arn",73 "memoryLimitInMB": 51274 }75 class TestGetMetadataForConfigureAgentCall:76 @before77 def before(self):78 self.context = Mock()79 self.context.invoked_function_arn = "the_lambda_function_arn"80 self.context.aws_request_id = "the_aws_request_id"81 self.context.get_remaining_time_in_millis = Mock(return_value=30125)82 self.subject = AWSLambda(function_arn="the_lambda_function_arn", memory_limit_mb=512,83 execution_env="AWS_Lambda_python3.8",84 agent_id="a509707f-12db-462d-b5c9-18bc19c69bf0")85 self.lambda_context = LambdaContext()86 self.lambda_context.context = self.context87 self.lambda_context.last_execution_duration = timedelta(seconds=1, milliseconds=234, microseconds=987)88 def test_it_returns_the_metadata_needed_for_configure_agent_call(self):89 assert self.subject.get_metadata_for_configure_agent_call(lambda_context=self.lambda_context) == {90 "ComputePlatform": "AWSLambda",91 "AgentId": "a509707f-12db-462d-b5c9-18bc19c69bf0",92 "AwsRequestId": "the_aws_request_id",93 "ExecutionEnvironment": "AWS_Lambda_python3.8",94 "LambdaFunctionArn": "the_lambda_function_arn",95 "LambdaMemoryLimitInMB": "512",96 "LambdaRemainingTimeInMilliseconds": "30125",97 "LambdaPreviousExecutionTimeInMilliseconds": "1234"98 }99 class TestWhenSomeFieldsAreMissing:100 @pytest.fixture(autouse=True)101 def around(self):102 self.subject = AWSLambda(function_arn="the_lambda_function_arn",103 memory_limit_mb=None,104 execution_env=None,105 agent_id="a509707f-12db-462d-b5c9-18bc19c69bf0")106 LambdaContext.get()107 yield108 LambdaContext._singleton = None109 def test_it_returns_at_least_the_compute_platform(self):110 metadata = self.subject.get_metadata_for_configure_agent_call()111 assert metadata["ComputePlatform"] == "AWSLambda"112 def test_it_can_return_last_execution_duration_independently(self):113 LambdaContext.get().last_execution_duration = timedelta(seconds=1, milliseconds=234, microseconds=987)114 metadata = self.subject.get_metadata_for_configure_agent_call()...
__init__.py
Source:__init__.py
1# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved2#3# Permission is hereby granted, free of charge, to any person obtaining a4# copy of this software and associated documentation files (the5# "Software"), to deal in the Software without restriction, including6# without limitation the rights to use, copy, modify, merge, publish, dis-7# tribute, sublicense, and/or sell copies of the Software, and to permit8# persons to whom the Software is furnished to do so, subject to the fol-9# lowing conditions:10#11# The above copyright notice and this permission notice shall be included12# in all copies or substantial portions of the Software.13#14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS15# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-16# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT17# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,18# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20# IN THE SOFTWARE.21#22from boto.regioninfo import RegionInfo, get_regions23from boto.regioninfo import connect24def regions():25 """26 Get all available regions for the AWS Lambda service.27 :rtype: list28 :return: A list of :class:`boto.regioninfo.RegionInfo`29 """30 from boto.awslambda.layer1 import AWSLambdaConnection31 return get_regions('awslambda',32 connection_cls=AWSLambdaConnection)33def connect_to_region(region_name, **kw_params):34 from boto.awslambda.layer1 import AWSLambdaConnection35 return connect('awslambda', region_name,...
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!!