Best Python code snippet using localstack_python
sns.py
Source:sns.py
...17 logger.info("extracting sns message ... DONE")18 message_namespace = message["Trigger"]["Namespace"]19 logger.debug(f"message_namespace={message_namespace}")20 if message_namespace == "AWS/Lambda":21 logger.debug("calling get_lambda_logs() ...")22 function_logs = get_lambda_logs(alarm_event=message)23 if function_logs:24 logs_text = "\n".join(function_logs)25 logger.debug("calling get_lambda_logs() ... DONE")26 except json.JSONDecodeError:27 logger.error("JSONDecodeError - unable to decode 'message' as JSON, returning raw message!")28 message = record["Sns"]["Message"]29 json_encoded_alarm = json.dumps(message, indent=4)30 return json_encoded_alarm, logs_text31def post_to_slack(event, context) -> List[int]:32 """Lambda handler for incoming SNS events. SNS event 'Message' is posted to the configured SLACK_WEBHOOK_URL"""33 logger.debug(f"event={event}")34 logger.debug(f"context={context}")35 processed_record_status_codes = []36 if settings.ENABLE_POSTTOSLACK:37 logger.info(f"SLACK_WEBHOOK_URL={settings.SLACK_WEBHOOK_URL}")38 if "Records" in event:39 logger.debug(f"len(event['Records']={len(event['Records'])}")...
test_handlers_functions.py
Source:test_handlers_functions.py
...40 response = LOGS_CLIENT.put_log_events(logGroupName=self.log_group_name, logStreamName=self.log_stream_name, logEvents=events)41 except ClientError as e:42 if e.__class__.__name__ != "ResourceAlreadyExistsException":43 raise44 def test_get_lambda_logs(self):45 state_change_time = datetime.datetime.now(datetime.timezone.utc)46 alarm_event = {47 "AlarmName": "MyLambdaFunctionErrorsAlarm-stage",48 "AlarmDescription": "",49 "AWSAccountId": "xxx",50 "NewStateValue": "ALARM",51 "NewStateReason": "Threshold Crossed: 1 datapoint [1.0 (23/08/21 11:22:00)] was greater than or equal to the threshold (1.0).",52 "StateChangeTime": state_change_time.isoformat(),53 "Region": "Asia Pacific (Tokyo)",54 "AlarmArn": "arn:aws:cloudwatch:ap-northeast-1:xxx:alarm:MyLambdaFunctionErrorsAlarm-stage",55 "OldStateValue": "OK",56 "Trigger": {57 "MetricName": "Errors",58 "Namespace": "AWS/Lambda",59 "StatisticType": "Statistic",60 "Statistic": "MAXIMUM",61 "Unit": "",62 "Dimensions": [{"value": "LAMBDA-FUNCTION-NAME", "name": "FunctionName"}],63 "Period": 60,64 "EvaluationPeriods": 1,65 "ComparisonOperator": "GreaterThanOrEqualToThreshold",66 "Threshold": 1.0,67 "TreatMissingData": "- TreatMissingData: notBreaching",68 "EvaluateLowSampleCountPercentile": "",69 },70 }71 events = get_lambda_logs(alarm_event=alarm_event)...
util.py
Source:util.py
1import os2from localstack.utils.aws import aws_stack3def is_aws_cloud() -> bool:4 return os.environ.get("TEST_TARGET", "") == "AWS_CLOUD"5def get_lambda_logs(func_name, logs_client=None):6 logs_client = logs_client or aws_stack.create_external_boto_client("logs")7 log_group_name = f"/aws/lambda/{func_name}"8 streams = logs_client.describe_log_streams(logGroupName=log_group_name)["logStreams"]9 streams = sorted(streams, key=lambda x: x["creationTime"], reverse=True)10 log_events = logs_client.get_log_events(11 logGroupName=log_group_name, logStreamName=streams[0]["logStreamName"]12 )["events"]...
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!!