Best Python code snippet using localstack_python
test_secretsmanager_basics.py
Source:test_secretsmanager_basics.py
1# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.2# SPDX-License-Identifier: Apache-2.03"""4Unit tests for secretsmanager_basics.py5"""6import uuid7import boto38from botocore.exceptions import ClientError9import pytest10from secretsmanager_basics import SecretsManagerSecret11@pytest.mark.parametrize('secret_value,error_code', [12 ('test-secret', None),13 (b'test-secret', None),14 ('test-secret', 'TestException')])15def test_create(make_stubber, secret_value, error_code):16 secretsmanager_client = boto3.client('secretsmanager')17 secretsmanager_stubber = make_stubber(secretsmanager_client)18 secret = SecretsManagerSecret(secretsmanager_client)19 name = 'test-name'20 secretsmanager_stubber.stub_create_secret(21 name, secret_value, error_code=error_code)22 if error_code is None:23 secret.create(name, secret_value)24 assert secret.name == name25 else:26 with pytest.raises(ClientError) as exc_info:27 secret.create(name, secret_value)28 assert exc_info.value.response['Error']['Code'] == error_code29@pytest.mark.parametrize('name,error_code', [30 ('test-name', None),31 (None, None),32 ('test-name', 'TestException')])33def test_describe(make_stubber, name, error_code):34 secretsmanager_client = boto3.client('secretsmanager')35 secretsmanager_stubber = make_stubber(secretsmanager_client)36 secret = SecretsManagerSecret(secretsmanager_client)37 existing_name = 'secret-name'38 if name is None:39 secret.name = existing_name40 secretsmanager_stubber.stub_describe_secret(41 name if name is not None else existing_name, error_code=error_code)42 if error_code is None:43 secret.describe(name)44 if name is None:45 assert secret.name == existing_name46 else:47 assert secret.name == name48 else:49 with pytest.raises(ClientError) as exc_info:50 secret.describe(name)51 assert exc_info.value.response['Error']['Code'] == error_code52@pytest.mark.parametrize('stage,secret_value,error_code', [53 ('test-stage', 'test-value', None),54 ('test-stage', b'test-value', None),55 (None, 'test-value', None),56 ('test-stage', 'test-value', 'TestException')])57def test_get_value(make_stubber, stage, secret_value, error_code):58 secretsmanager_client = boto3.client('secretsmanager')59 secretsmanager_stubber = make_stubber(secretsmanager_client)60 secret = SecretsManagerSecret(secretsmanager_client)61 secret.name = 'test-name'62 secretsmanager_stubber.stub_get_secret_value(63 secret.name, stage, secret_value, error_code=error_code)64 if error_code is None:65 got_response = secret.get_value(stage)66 if isinstance(secret_value, str):67 assert got_response['SecretString'] == secret_value68 elif isinstance(secret_value, bytes):69 assert got_response['SecretBinary'] == secret_value70 else:71 with pytest.raises(ClientError) as exc_info:72 secret.get_value(stage)73 assert exc_info.value.response['Error']['Code'] == error_code74@pytest.mark.parametrize('error_code', [None, 'TestException'])75def test_get_random_password(make_stubber, error_code):76 secretsmanager_client = boto3.client('secretsmanager')77 secretsmanager_stubber = make_stubber(secretsmanager_client)78 secret = SecretsManagerSecret(secretsmanager_client)79 pw_length = 2080 password = 'test-password'81 secretsmanager_stubber.stub_get_random_password(82 pw_length, password, error_code=error_code)83 if error_code is None:84 got_password = secret.get_random_password(pw_length)85 assert got_password == password86 else:87 with pytest.raises(ClientError) as exc_info:88 secret.get_random_password(pw_length)89 assert exc_info.value.response['Error']['Code'] == error_code90@pytest.mark.parametrize('secret_value,stages,error_code', [91 ('test-value', ['test-stage'], None),92 (b'test-value', None, None),93 ('test-value', ['test-stage'], 'TestException')])94def test_put_value(make_stubber, secret_value, stages, error_code):95 secretsmanager_client = boto3.client('secretsmanager')96 secretsmanager_stubber = make_stubber(secretsmanager_client)97 secret = SecretsManagerSecret(secretsmanager_client)98 secret.name = 'test-name'99 secretsmanager_stubber.stub_put_secret_value(100 secret.name, secret_value, stages, error_code=error_code)101 if error_code is None:102 secret.put_value(secret_value, stages)103 else:104 with pytest.raises(ClientError) as exc_info:105 secret.put_value(secret_value, stages)106 assert exc_info.value.response['Error']['Code'] == error_code107@pytest.mark.parametrize('error_code', [None, 'TestException'])108def test_update_version_stage(make_stubber, error_code):109 secretsmanager_client = boto3.client('secretsmanager')110 secretsmanager_stubber = make_stubber(secretsmanager_client)111 secret = SecretsManagerSecret(secretsmanager_client)112 secret.name = 'test-name'113 stage = 'test-stage'114 remove_from = str(uuid.uuid4())115 move_to = str(uuid.uuid4())116 secretsmanager_stubber.stub_update_secret_version_stage(117 secret.name, stage, remove_from, move_to, error_code=error_code)118 if error_code is None:119 secret.update_version_stage(stage, remove_from, move_to)120 else:121 with pytest.raises(ClientError) as exc_info:122 secret.update_version_stage(stage, remove_from, move_to)123 assert exc_info.value.response['Error']['Code'] == error_code124@pytest.mark.parametrize('error_code', [None, 'TestException'])125def test_delete(make_stubber, error_code):126 secretsmanager_client = boto3.client('secretsmanager')127 secretsmanager_stubber = make_stubber(secretsmanager_client)128 secret = SecretsManagerSecret(secretsmanager_client)129 secret.name = 'test-name'130 secretsmanager_stubber.stub_delete_secret(secret.name, error_code=error_code)131 if error_code is None:132 secret.delete(True)133 else:134 with pytest.raises(ClientError) as exc_info:135 secret.delete(True)136 assert exc_info.value.response['Error']['Code'] == error_code137@pytest.mark.parametrize('error_code', [None, 'TestException'])138def test_list(make_stubber, error_code):139 secretsmanager_client = boto3.client('secretsmanager')140 secretsmanager_stubber = make_stubber(secretsmanager_client)141 secret = SecretsManagerSecret(secretsmanager_client)142 secrets = [{'Name': f'test-name-{secid}'} for secid in range(5)]143 secretsmanager_stubber.stub_list_secrets(secrets, error_code=error_code)144 if error_code is None:145 assert secrets == list(secret.list(10))146 else:147 with pytest.raises(ClientError) as exc_info:148 list(secret.list(10))...
secretsmanager.py
Source:secretsmanager.py
1"""2Provider for AWS SecretsManager3"""4import json5import boto36import botocore.exceptions7from ftl_python_lib.core.context.environment import EnvironmentContext8from ftl_python_lib.core.log import LOGGER9from ftl_python_lib.decorators.exponential_backoff import DecoratorExponentialBackoff10# pylint: disable=R090311class ProviderSecretsManager:12 """13 Provider for AWS SecretsManager14 :param __secretsmanager_resource: SecretsManager boto3 resource15 :type __secretsmanager_resource16 """17 __secretsmanager_resource = boto3.client("secretsmanager", region_name="us-east-1")18 def __init__(self, environ_context: EnvironmentContext) -> None:19 """20 Constructor21 :param secretsmanager_name: Name of the SecretManager22 :type secretsmanager_name: str23 """24 LOGGER.logger.debug("Creating SecretManager provider")25 self.__environ_context = environ_context26 self.__secretsmanager_resource = boto3.client(27 "secretsmanager", region_name=self.__environ_context.active_region28 )29 self.__secretsmanager_name: str = self.__environ_context.runtime_secretsmanager30 @DecoratorExponentialBackoff.retry(Exception)31 def get_value(self, secretsmanager_name: str = None):32 """33 Get object value34 """35 try:36 if secretsmanager_name is not None:37 self.__secretsmanager_name: str = secretsmanager_name38 LOGGER.logger.debug(39 f"Retrieving value: secretsmanager: {self.__secretsmanager_name}"40 )41 response = self.__secretsmanager_resource.get_secret_value(42 SecretId=self.__secretsmanager_name43 )44 LOGGER.logger.debug(45 f"Retrieved value: secretsmanager: {self.__secretsmanager_name}"46 )47 return json.loads(response["SecretString"])48 except botocore.exceptions.ClientError as exc:49 if exc.response.get("Error").get("Code") == "NoSuchKey":50 LOGGER.logger.error(51 f"NoSuchKey! Could not retrieve value: secretsmanager: {self.__secretsmanager_name}"52 )53 LOGGER.logger.error(54 f"Returning empty body for value: secretsmanager: {self.__secretsmanager_name}"55 )56 return b""57 raise exc58 @DecoratorExponentialBackoff.retry(Exception)59 def put_value(self, database_secrets, secretsmanager_name: str = None):60 """61 Get object value62 """63 try:64 if secretsmanager_name is not None:65 self.__secretsmanager_name: str = secretsmanager_name66 LOGGER.logger.debug(67 f"Save value: secretsmanager: {self.__secretsmanager_name}"68 )69 response = self.__secretsmanager_resource.put_secret_value(70 SecretId=self.__secretsmanager_name,71 SecretString=json.dumps(database_secrets),72 )73 LOGGER.logger.debug(74 f"Save value: secretsmanager: {self.__secretsmanager_name}"75 )76 return response77 except botocore.exceptions.ClientError as exc:78 if exc.response.get("Error").get("Code") == "NoSuchKey":79 LOGGER.logger.error(80 f"NoSuchKey! Could not retrieve value: secretsmanager: {self.__secretsmanager_name}"81 )82 LOGGER.logger.error(83 f"Returning empty body for value: secretsmanager: {self.__secretsmanager_name}"84 )85 return b""...
secretsmanager_environ.py
Source:secretsmanager_environ.py
1"""2Provider for AWS SecretsManager3"""4import json5from typing import Dict6from typing import List7import boto38import botocore.exceptions9from ftl_python_lib.core.log import LOGGER10from ftl_python_lib.decorators.exponential_backoff import DecoratorExponentialBackoff11# pylint: disable=R090312class ProviderSecretsManagerEnviron:13 """14 Provider for AWS SecretsManager & Environment Congext15 :param __secretsmanager_resource: SecretsManager boto3 resource16 :type __secretsmanager_resource17 """18 def __init__(self, environ_context) -> None:19 """20 Constructor21 :param secretsmanager_name: Name of the SecretManager22 :type secretsmanager_name: str23 """24 LOGGER.logger.debug("Creating SecretManager provider")25 self.__secretsmanager_resource = boto3.client(26 "secretsmanager", region_name=environ_context.active_region27 )28 self.__environment_context_secret_name: str = (29 environ_context.environment_context_secret_name30 )31 @DecoratorExponentialBackoff.retry(Exception)32 def get_value(self):33 """34 Get object value35 """36 try:37 secretsmanager_names: str = self.__environment_context_secret_name38 LOGGER.logger.debug(39 f"Retrieving value: secretsmanager: {secretsmanager_names}"40 )41 if secretsmanager_names is None:42 return []43 res: Dict[str, str] = {}44 secretsmanager_names_: List[str] = secretsmanager_names.split(",")45 for secretsmanager_name_ in secretsmanager_names_:46 response = self.__secretsmanager_resource.get_secret_value(47 SecretId=secretsmanager_name_48 )49 LOGGER.logger.debug(50 f"Retrieved value: secretsmanager: {secretsmanager_name_}"51 )52 res = res | json.loads(response["SecretString"])53 return res54 except botocore.exceptions.ClientError as exc:55 if exc.response.get("Error").get("Code") == "NoSuchKey":56 LOGGER.logger.error(57 f"NoSuchKey! Could not retrieve value: secretsmanager: {secretsmanager_names}"58 )59 LOGGER.logger.error(60 f"Returning empty body for value: secretsmanager: {secretsmanager_names}"61 )62 return b""...
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!!