How to use describe_severity_levels method in localstack

Best Python code snippet using localstack_python

ENTERPRISE_SUPPORT_PLAN_ENABLED_test.py

Source:ENTERPRISE_SUPPORT_PLAN_ENABLED_test.py Github

copy

Full Screen

1# Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"). You may4# not use this file except in compliance with the License. A copy of the License is located at5#6# http://aws.amazon.com/apache2.0/7#8# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for10# the specific language governing permissions and limitations under the License.11import sys12import unittest13try:14 from unittest.mock import MagicMock15except ImportError:16 from mock import MagicMock17import botocore18##############19# Parameters #20##############21# Define the default resource to report to Config Rules22DEFAULT_RESOURCE_TYPE = 'AWS::::Account'23#############24# Main Code #25#############26CONFIG_CLIENT_MOCK = MagicMock()27STS_CLIENT_MOCK = MagicMock()28SUPPORT_CLIENT_MOCK = MagicMock()29class Boto3Mock():30 @staticmethod31 def client(client_name, *args, **kwargs):32 if client_name == 'config':33 return CONFIG_CLIENT_MOCK34 if client_name == 'sts':35 return STS_CLIENT_MOCK36 if client_name == 'support':37 return SUPPORT_CLIENT_MOCK38 raise Exception("Attempting to create an unknown client")39sys.modules['boto3'] = Boto3Mock()40RULE = __import__('ENTERPRISE_SUPPORT_PLAN_ENABLED')41class NonCompliantResourceTest(unittest.TestCase):42 def test_scenario_1_basic_support_non_compliant(self):43 SUPPORT_CLIENT_MOCK.describe_severity_levels = MagicMock(44 side_effect=botocore.exceptions.ClientError(45 {'Error': {'Code': 'SubscriptionRequiredException', 'Message': 'unknown-message'}},46 'operation'47 )48 )49 lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(), {})50 assert_successful_evaluation(51 self,52 lambda_result,53 [build_expected_response(54 'NON_COMPLIANT',55 '123456789012',56 annotation='The AWS Enterprise Support Plan is not enabled for this AWS Account.'57 )]58 )59 def test_scenario_2_bussiness_support_non_compliant(self):60 SUPPORT_CLIENT_MOCK.describe_severity_levels = MagicMock(61 return_value={'severityLevels': [{'code': 'urgent', 'name': 'Urgent'}]}62 )63 lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(), {})64 assert_successful_evaluation(65 self,66 lambda_result,67 [build_expected_response(68 'NON_COMPLIANT',69 '123456789012',70 annotation='The AWS Enterprise Support Plan is not enabled for this AWS Account.'71 )]72 )73class CompliantResourceTest(unittest.TestCase):74 def test_scenario_3_enterprice_support_compliant(self):75 SUPPORT_CLIENT_MOCK.describe_severity_levels = MagicMock(76 return_value={'severityLevels': [{'code': 'critical', 'name': 'Critical'}]}77 )78 lambda_result = RULE.lambda_handler(build_lambda_scheduled_event(), {})79 assert_successful_evaluation(80 self,81 lambda_result,82 [build_expected_response(83 'COMPLIANT',84 '123456789012'85 )]86 )87####################88# Helper Functions #89####################90def build_lambda_configurationchange_event(invoking_event, rule_parameters=None):91 event_to_return = {92 'configRuleName':'myrule',93 'executionRoleArn':'roleArn',94 'eventLeftScope': False,95 'invokingEvent': invoking_event,96 'accountId': '123456789012',97 'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',98 'resultToken':'token'99 }100 if rule_parameters:101 event_to_return['ruleParameters'] = rule_parameters102 return event_to_return103def build_lambda_scheduled_event(rule_parameters=None):104 invoking_event = '{"messageType":"ScheduledNotification","notificationCreationTime":"2017-12-23T22:11:18.158Z"}'105 event_to_return = {106 'configRuleName':'myrule',107 'executionRoleArn':'roleArn',108 'eventLeftScope': False,109 'invokingEvent': invoking_event,110 'accountId': '123456789012',111 'configRuleArn': 'arn:aws:config:us-east-1:123456789012:config-rule/config-rule-8fngan',112 'resultToken':'token'113 }114 if rule_parameters:115 event_to_return['ruleParameters'] = rule_parameters116 return event_to_return117def build_expected_response(compliance_type, compliance_resource_id, compliance_resource_type=DEFAULT_RESOURCE_TYPE, annotation=None):118 if not annotation:119 return {120 'ComplianceType': compliance_type,121 'ComplianceResourceId': compliance_resource_id,122 'ComplianceResourceType': compliance_resource_type123 }124 return {125 'ComplianceType': compliance_type,126 'ComplianceResourceId': compliance_resource_id,127 'ComplianceResourceType': compliance_resource_type,128 'Annotation': annotation129 }130def assert_successful_evaluation(test_class, response, resp_expected, evaluations_count=1):131 if isinstance(response, dict):132 test_class.assertEquals(resp_expected['ComplianceResourceType'], response['ComplianceResourceType'])133 test_class.assertEquals(resp_expected['ComplianceResourceId'], response['ComplianceResourceId'])134 test_class.assertEquals(resp_expected['ComplianceType'], response['ComplianceType'])135 test_class.assertTrue(response['OrderingTimestamp'])136 if 'Annotation' in resp_expected or 'Annotation' in response:137 test_class.assertEquals(resp_expected['Annotation'], response['Annotation'])138 elif isinstance(response, list):139 test_class.assertEquals(evaluations_count, len(response))140 for i, response_expected in enumerate(resp_expected):141 test_class.assertEquals(response_expected['ComplianceResourceType'], response[i]['ComplianceResourceType'])142 test_class.assertEquals(response_expected['ComplianceResourceId'], response[i]['ComplianceResourceId'])143 test_class.assertEquals(response_expected['ComplianceType'], response[i]['ComplianceType'])144 test_class.assertTrue(response[i]['OrderingTimestamp'])145 if 'Annotation' in response_expected or 'Annotation' in response[i]:146 test_class.assertEquals(response_expected['Annotation'], response[i]['Annotation'])147def assert_customer_error_response(test_class, response, customer_error_code=None, customer_error_message=None):148 if customer_error_code:149 test_class.assertEqual(customer_error_code, response['customerErrorCode'])150 if customer_error_message:151 test_class.assertEqual(customer_error_message, response['customerErrorMessage'])152 test_class.assertTrue(response['customerErrorCode'])153 test_class.assertTrue(response['customerErrorMessage'])154 if "internalErrorMessage" in response:155 test_class.assertTrue(response['internalErrorMessage'])156 if "internalErrorDetails" in response:157 test_class.assertTrue(response['internalErrorDetails'])158def sts_mock():159 assume_role_response = {160 "Credentials": {161 "AccessKeyId": "string",162 "SecretAccessKey": "string",163 "SessionToken": "string"}}164 STS_CLIENT_MOCK.reset_mock(return_value=True)165 STS_CLIENT_MOCK.assume_role = MagicMock(return_value=assume_role_response)166##################167# Common Testing #168##################169class TestStsErrors(unittest.TestCase):170 def test_sts_unknown_error(self):171 RULE.ASSUME_ROLE_MODE = True172 STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(173 {'Error': {'Code': 'unknown-code', 'Message': 'unknown-message'}}, 'operation'))174 response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})175 assert_customer_error_response(176 self, response, 'InternalError', 'InternalError')177 def test_sts_access_denied(self):178 RULE.ASSUME_ROLE_MODE = True179 STS_CLIENT_MOCK.assume_role = MagicMock(side_effect=botocore.exceptions.ClientError(180 {'Error': {'Code': 'AccessDenied', 'Message': 'access-denied'}}, 'operation'))181 response = RULE.lambda_handler(build_lambda_configurationchange_event('{}'), {})182 assert_customer_error_response(...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful