Best Python code snippet using localstack_python
conftest.py
Source:conftest.py
1import datetime2import os3import pytest4AWS_REGION = os.getenv("AWS_REGION")5SQS_QUEUE_ARN = os.getenv("SQS_QUEUE_ARN")6TABLE_NAME = os.getenv("TABLE_NAME")7date_time = datetime.date8@pytest.fixture(scope="module")9def post_event():10 """ Generates SQS event containing POST"""11 post_body = "{\"TableName\":\"" + TABLE_NAME + "\",\"Item\":{\"date\": " + \12 "{\"S\": \"2001-01-01\"}, \"time\": {\"S\": \"01:01:07\"},\"location\": {\"S\": \"location-03\"}, " + \13 "\"source\": {\"S\":\"wireless\"}, \"local_dest\": {\"S\": \"router-1\"}, \"local_avg\": " + \14 "{\"N\": \"5.32\"}, \"remote_dest\": {\"S\": \"device-1\"}, \"remote_avg\": {\"N\": \"11.01\"}}}"15 return {16 "Records": [17 {18 "body": post_body,19 "messageAttributes": {20 "Method": {21 "stringValue": "POST",22 "stringListValues": [],23 "binaryListValues": [],24 "dataType": "String"25 },26 "eventSource": "aws:sqs",27 "eventSourceARN": SQS_QUEUE_ARN,28 "awsRegion": AWS_REGION29 }30 }31 ]32 }33@pytest.fixture(scope="module")34def put_event():35 """ Generates SQS event containing PUT"""36 put_body = "{\"TableName\": \"" + TABLE_NAME + "\", " + \37 "\"Key\": {\"date\": {\"S\": \"2001-01-01\"},\"time\": {\"S\": \"01:01:07\"}}, " + \38 "\"UpdateExpression\": \"set remote_avg = :val1\", " + \39 "\"ExpressionAttributeValues\": {\":val1\": {\"N\": \"9.00\"}}}"40 return {41 "Records": [42 {43 "body": put_body,44 "messageAttributes": {45 "Method": {46 "stringValue": "PUT",47 "stringListValues": [],48 "binaryListValues": [],49 "dataType": "String"50 },51 "eventSource": "aws:sqs",52 "eventSourceARN": SQS_QUEUE_ARN,53 "awsRegion": AWS_REGION54 }55 }56 ]57 }58@pytest.fixture(scope="module")59def delete_event():60 """ Generates SQS event containing DELETE"""61 delete_body = "{\"TableName\": \"" + TABLE_NAME + "\", " + \62 "\"Key\": {\"date\": {\"S\": \"2001-01-01\"}, \"time\": {\"S\": \"01:01:07\"}}}"63 return {64 "Records": [65 {66 "body": delete_body,67 "messageAttributes": {68 "Method": {69 "stringValue": "DELETE",70 "stringListValues": [],71 "binaryListValues": [],72 "dataType": "String"73 },74 "eventSource": "aws:sqs",75 "eventSourceARN": SQS_QUEUE_ARN,76 "awsRegion": AWS_REGION77 }78 }79 ]80 }81@pytest.fixture(scope="module")82def get_event():83 """ Generates SQS event containing GET"""84 get_body = "{\"TableName\": \"" + TABLE_NAME + "\", " + \85 "\"Key\": {\"date\": {\"S\": \"2001-01-01\"}, \"time\": {\"S\": \"01:01:07\"}}}"86 return {87 "Records": [88 {89 "body": get_body,90 "messageAttributes": {91 "Method": {92 "stringValue": "GET",93 "stringListValues": [],94 "binaryListValues": [],95 "dataType": "String"96 },97 "eventSource": "aws:sqs",98 "eventSourceARN": SQS_QUEUE_ARN,99 "awsRegion": AWS_REGION100 }101 }102 ]103 }104@pytest.fixture(scope="module")105def get_all_event():106 """ Generates SQS event containing GET_ALL (SCAN)"""107 get_all_body = "{\"TableName\": \"" + TABLE_NAME + "\"}"108 return {109 "Records": [110 {111 "body": get_all_body,112 "messageAttributes": {113 "Method": {114 "stringValue": "GET_ALL",115 "stringListValues": [],116 "binaryListValues": [],117 "dataType": "String"118 },119 "eventSource": "aws:sqs",120 "eventSourceARN": SQS_QUEUE_ARN,121 "awsRegion": AWS_REGION122 }123 }124 ]...
pipeline.py
Source:pipeline.py
1import os2import boto3, json3from datastore import PipelineOpsStore4from helper import AwsHelper, SQSHelper 5PIPELINE_OPS_TABLE = os.environ.get("PIPELINE_OPS_TABLE", None)6SQS_QUEUE_ARN = os.environ.get("SQS_QUEUE_ARN", None)7if not PIPELINE_OPS_TABLE or not SQS_QUEUE_ARN:8 raise ValueError("Missing arguments.")9 10def startDocumentTracking(documentPayload, receipt):11 print("Started tracking document {}".format(documentPayload['documentId']))12 client = PipelineOpsStore(PIPELINE_OPS_TABLE)13 14 res = client.startDocumentTracking(**documentPayload)15 print(res)16 if res['Status'] == 200:17 SQSHelper().deleteMessage(SQS_QUEUE_ARN, receipt)18 else:19 raise Exception("Unable to post document {}: {}".format(documentPayload['documentId'], res['Error']))20 return res21def updateDocumentStatus(documentPayload, receipt, messageNote=None):22 print("Putting pipeline document status update")23 client = PipelineOpsStore(PIPELINE_OPS_TABLE)24 if messageNote:25 statusPayload = {26 "documentId": documentPayload['documentId'],27 "status": documentPayload['status'],28 "stage": documentPayload['stage'],29 "timestamp": documentPayload['timestamp'],30 "message": messageNote31 }32 else:33 statusPayload = {34 "documentId": documentPayload['documentId'],35 "status": documentPayload['status'],36 "stage": documentPayload['stage'],37 "timestamp": documentPayload['timestamp']38 }39 res = client.updateDocumentStatus(**statusPayload)40 print(res)41 if res['Status'] == 200:42 SQSHelper().deleteMessage(SQS_QUEUE_ARN, receipt)43 else:44 raise Exception("Unable to update status of document {}: {}".format(statusPayload['documentId'], res['Error']))45 return res46def lambda_handler(event, context):47 for record in event['Records']:48 print(event)49 assert record['eventSourceARN'] == SQS_QUEUE_ARN, "Unexpected Lambda event source ARN. Expected {}, got {}".format(SQS_QUEUE_ARN, record['eventSourceARN'])50 payload = json.loads(record["body"])51 message = json.loads(payload['Message'])52 receipt = record['receiptHandle']53 print(message)54 try:55 documentPayload = {56 "documentId": message['documentId'],57 "bucketName": message['bucketName'],58 "objectName": message['objectName'],59 "status": message['status'],60 "stage": message['stage'],61 "timestamp": message['timestamp'],62 }63 except Exception as e:64 print("Missing " + str(e))65 raise ValueError("Missing parameters in payload to pipeline metadata lambda")66 if 'initDoc' in message and message.get('initDoc') == "True":67 startDocumentTracking(documentPayload, receipt)68 else:69 messageNote = message.get('message')70 updateDocumentStatus(documentPayload, receipt, messageNote)...
registry.py
Source:registry.py
1import os2import boto3, json3from datastore import DocumentRegistryStore4from helper import AwsHelper, SQSHelper5REGISTRY_TABLE = os.environ.get("REGISTRY_TABLE", None)6SQS_QUEUE_ARN = os.environ.get("SQS_QUEUE_ARN", None)7if not REGISTRY_TABLE or not SQS_QUEUE_ARN:8 raise ValueError("Missing arguments.")9def postRegistration(documentInfoPayload, receipt):10 print("posting Registration")11 client = DocumentRegistryStore(REGISTRY_TABLE)12 13 res = client.registerDocument(**documentInfoPayload)14 if res['Status'] == 200:15 SQSHelper().deleteMessage(SQS_QUEUE_ARN, receipt)16 else:17 raise Exception("Unable to update progress of document {}: {}".format(documentInfoPayload['documentId'], res['Error']))18 return res19def lambda_handler(event, context):20 for record in event['Records']:21 print(event)22 assert record['eventSourceARN'] == SQS_QUEUE_ARN, "Unexpected Lambda event source ARN. Expected {}, got {}".format(SQS_QUEUE_ARN, record['eventSourceARN'])23 payload = json.loads(record["body"])24 message = json.loads(payload['Message'])25 print(message)26 receipt = record['receiptHandle']27 registryPayload = {}28 try:29 registryPayload = {30 "documentId": message['documentId'],31 "bucketName": message['bucketName'],32 "documentName": message['documentName'],33 "documentMetadata": message.get('documentMetadata', dict()),34 "documentLink": message['documentLink'],35 "principalIAMWriter": message['principalIAMWriter'],36 "timestamp": message['timestamp'],37 }38 if 'documentVersion' in message:39 registryPayload['documentVersion'] = message['documentVersion']40 except Exception as e:41 print(e)42 raise ValueError("Missing parameters in payload to document registry lambda")43 44 postRegistration(registryPayload, receipt)...
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!!