Best Python code snippet using localstack_python
test_lifecyleconfiguration.py
Source: test_lifecyleconfiguration.py
1# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You4# may not use this file except in compliance with the License. A copy of5# the License is located at6#7# http://aws.amazon.com/apache2.0/8#9# or in the "license" file accompanying this file. This file is10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF11# ANY KIND, either express or implied. See the License for the specific12# language governing permissions and limitations under the License.13import unittest14import copy15from datetime import datetime16import mock17from dateutil.tz import tzutc18from ebcli.objects.exceptions import InvalidOptionsError, NotFoundError19from ebcli.objects import lifecycleconfiguration20from ebcli.objects.lifecycleconfiguration import LifecycleConfiguration21class TestLifecycleConfiguration(unittest.TestCase):22 current_time = datetime.now()23 region = 'us-foo-1'24 app_name = 'foo_app'25 file_location = 'local/app/'26 service_role = 'arn:aws:iam::123123123123:role/aws-elasticbeanstalk-service-role'27 get_role_response = {u'Arn': service_role}28 api_model = {u'ApplicationName': app_name, u'Description': 'Application created from the EB CLI using "eb init"',29 u'Versions': ['Sample Application'],30 u'DateCreated': datetime(2016, 12, 20, 2, 48, 7, 938000, tzinfo=tzutc()),31 u'ConfigurationTemplates': [],32 u'DateUpdated': datetime(2016, 12, 20, 2, 48, 7, 938000, tzinfo=tzutc()),33 u'ResourceLifecycleConfig': {u'VersionLifecycleConfig':34 {u'MaxCountRule': {u'DeleteSourceFromS3': False, u'Enabled': False,35 u'MaxCount': 200},36 u'MaxAgeRule': {u'DeleteSourceFromS3': False, u'Enabled': False,37 u'MaxAgeInDays': 180}},38 u'ServiceRole': service_role}}39 usr_model = {'ApplicationName': app_name,40 'DateUpdated': datetime(2016, 12, 20, 2, 48, 7, 938000, tzinfo=tzutc()),41 'Configurations': {u'VersionLifecycleConfig':42 {u'MaxCountRule': {u'DeleteSourceFromS3': False, u'Enabled': False,43 u'MaxCount': 200},44 u'MaxAgeRule': {u'DeleteSourceFromS3': False, u'Enabled': False,45 u'MaxAgeInDays': 180}},46 u'ServiceRole': service_role}}47 def setUp(self):48 self.patcher_get_role = mock.patch('ebcli.objects.lifecycleconfiguration.get_role')49 self.mock_get_role = self.patcher_get_role.start()50 def tearDown(self):51 self.patcher_get_role.stop()52 '''53 Testing collect_changes54 '''55 def test_collect_changes_no_service_role(self):56 no_service_role_model = copy.deepcopy(self.usr_model)57 del no_service_role_model['Configurations']['ServiceRole']58 expected_changes = no_service_role_model['Configurations']59 lifecycle_config = LifecycleConfiguration(self.api_model)60 changes = lifecycle_config.collect_changes(no_service_role_model)61 self.assertEqual(expected_changes, changes,62 "Expected changes to be: {0}\n But was: {1}".format(expected_changes, changes))63 self.mock_get_role.assert_not_called()64 def test_collect_changes_with_service_role(self):65 lifecycle_config = LifecycleConfiguration(self.api_model)66 changes = lifecycle_config.collect_changes(self.usr_model)67 expected_changed = self.usr_model['Configurations']68 self.assertEqual(expected_changed, changes,69 "Expected changes to be: {0}\n But was: {1}".format(expected_changed, changes))70 self.mock_get_role.assert_called_with(self.service_role.split('/')[-1])71 def test_collect_changes_service_role_not_found(self):72 self.mock_get_role.side_effect = NotFoundError("Could not find role")73 lifecycle_config = LifecycleConfiguration(self.api_model)74 self.assertRaises(InvalidOptionsError, lifecycle_config.collect_changes, self.usr_model)75 self.mock_get_role.assert_called_with(self.service_role.split('/')[-1])76 '''77 Testing convert_api_to_usr_model78 '''79 def test_convert_api_to_usr_model_no_service_role(self):80 self.mock_get_role.return_value = self.get_role_response81 no_service_role_model = copy.deepcopy(self.api_model)82 del no_service_role_model['ResourceLifecycleConfig']['ServiceRole']83 lifecycle_config = LifecycleConfiguration(no_service_role_model)84 actual_usr_model = lifecycle_config.convert_api_to_usr_model()85 self.assertEqual(self.usr_model, actual_usr_model,86 "Expected changes to be: {0}\n But was: {1}".format(self.usr_model, actual_usr_model))87 self.mock_get_role.assert_called_with(lifecycleconfiguration.DEFAULT_LIFECYCLE_SERVICE_ROLE)88 def test_convert_api_to_usr_model_default_role_does_not_exist(self):89 self.mock_get_role.side_effect = NotFoundError("Could not find role")90 no_service_role_model = copy.deepcopy(self.api_model)91 del no_service_role_model['ResourceLifecycleConfig']['ServiceRole']92 lifecycle_config = LifecycleConfiguration(no_service_role_model)93 actual_usr_model = lifecycle_config.convert_api_to_usr_model()94 expected_usr_model = copy.deepcopy(self.usr_model)95 expected_usr_model['Configurations'][u'ServiceRole'] = lifecycleconfiguration.DEFAULT_ARN_STRING96 self.assertEqual(expected_usr_model, actual_usr_model,97 "Expected changes to be: {0}\n But was: {1}".format(expected_usr_model, actual_usr_model))98 self.mock_get_role.assert_called_with(lifecycleconfiguration.DEFAULT_LIFECYCLE_SERVICE_ROLE)99 def test_convert_api_to_usr_model_with_service_role(self):100 lifecycle_config = LifecycleConfiguration(self.api_model)101 actual_usr_model = lifecycle_config.convert_api_to_usr_model()102 self.assertEqual(self.usr_model, actual_usr_model,103 "Expected changes to be: {0}\n But was: {1}".format(self.usr_model, actual_usr_model))...
test_notebook.py
Source: test_notebook.py
...22@pytest.fixture(autouse=True)23def default_region():24 os.environ["AWS_DEFAULT_REGION"] = "us-east-1"25@pytest.fixture()26def lifecycle_config():27 os.environ["AWS_DEFAULT_REGION"] = "us-east-1"28 import infrastructure.forecast.sagemaker.lifecycle_config as lifecycle_config29 yield lifecycle_config30 os.environ.pop("AWS_DEFAULT_REGION", None)31@pytest.fixture32def forecast_stub():33 client = boto3.client("sagemaker", region_name="us-east-1")34 with Stubber(client) as stubber:35 yield stubber36@pytest.fixture(scope="function")37def s3_valid_config():38 with mock_s3():39 client = boto3.client("s3", region_name=os.environ.get("AWS_REGION"))40 client.create_bucket(Bucket="testbucket")...
set_s3_lifecycle.py
Source: set_s3_lifecycle.py
1#!/usr/bin/env python32# Copyright (c) 2019 - Brian J. Smith3# Version 0.44import boto35import argparse6import logging7from botocore.exceptions import ClientError8#9# Vaild s3 types STANDARD, STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING, GLACIER, DEEP_ARCHIVE10#11#12lifecycle_config = {13 "Rules": [14 {15 "ID": "S3 30day StandardIA 90day Glacier Transition Rule",16 "Filter": {17 "Prefix": ""18 },19 "Status": "Enabled",20 "Transitions": [21 {22 "Days": 300,23 "StorageClass": "STANDARD_IA"24 },25 {26 "Days": 900,27 "StorageClass": "GLACIER"28 }29 ],30 "NoncurrentVersionTransitions": [31 {32 "NoncurrentDays": 400,33 "StorageClass": "STANDARD_IA"34 },35 {36 "NoncurrentDays": 1000,37 "StorageClass": "GLACIER"38 }39 ]40 }41 ]42}43# lifecycle_config = {44# 'Rules': [45# {'ID': 'S3 30day StandardIA 90day Glacier Transition Rule',46# 'Filter': {'Prefix': ''},47# 'Status': 'Enabled',48# 'Transitions': [49# {'Days': 300,50# 'StorageClass': 'STANDARD_IA'},51# {'Days': 900,52# 'StorageClass': 'GLACIER'}53# ]}54# ]}55def Main():56 my_parser = argparse.ArgumentParser(57 prog='set_s3_lifecycle', description='Attempt to set the lifecycle of a S3 bucket')58 my_parser.add_argument('bucket', type=str,59 help='specify AWS S3 bucket to modify')60 my_parser.add_argument('-v', '--verbose', help='verbose output, show lifecycle after modifying',61 action="store_true")62 args = my_parser.parse_args()63 logging.basicConfig(level=logging.INFO,64 format='%(levelname)s: %(asctime)s: %(message)s')65 #66 # Vaild s3 types STANDARD, STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING, GLACIER, REDUCED_REDUNDANCY67 #68 #69 if (get_bucket_lifecycle(args.bucket) != ''):70 set_lifecycle(args.bucket, lifecycle_config)71 if (args.verbose):72 print_lifecycle(args.bucket)73 else:74 logging.info('Unable to update the lifecyle policy for', args.bucket)75def set_lifecycle(bucket, lifecycle):76 # aws s3api put-bucket-lifecycle-configuration --bucket <bucket> --lifecycle-configuration file://<file.json>77 s3 = boto3.client('s3')78 try:79 s3.put_bucket_lifecycle_configuration(Bucket=bucket,80 LifecycleConfiguration=lifecycle)81 except ClientError as e:82 # print(e.response)83 return False84 return True85def get_bucket_lifecycle(bucket):86 s3_client = boto3.client('s3')87 # aws s3api get-bucket-lifecycle-configuration --bucket <bucket>88 try:89 response = s3_client.get_bucket_lifecycle_configuration(Bucket=bucket)90 except ClientError as e:91 if e.response['Error']['Code'] == 'NoSuchLifecycleConfiguration':92 return response['Rules']93 else:94 e.response['Error']['Code'] == 'NoSuchBucket'95 logging.error(bucket, 'bucket does not exist')96 return None97 return response['Rules']98def print_lifecycle(bucket):99 lifecycle_config = get_bucket_lifecycle(bucket)100 if lifecycle_config is not None:101 if not lifecycle_config:102 logging.error(bucket, 'does not have a lifecycle configuration.')103 else:104 for rule in lifecycle_config:105 print(lifecycle_config)106if __name__ == '__main__':...
Check out the latest blogs from LambdaTest on this topic:
The fact is not alien to us anymore that cross browser testing is imperative to enhance your application’s user experience. Enhanced knowledge of popular and highly acclaimed testing frameworks goes a long way in developing a new app. It holds more significance if you are a full-stack developer or expert programmer.
QA testers have a unique role and responsibility to serve the customer. Serving the customer in software testing means protecting customers from application defects, failures, and perceived failures from missing or misunderstood requirements. Testing for known requirements based on documentation or discussion is the core of the testing profession. One unique way QA testers can both differentiate themselves and be innovative occurs when senseshaping is used to improve the application user experience.
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.
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!!