Best Python code snippet using localstack_python
test_s3_notifications_sns.py
Source: test_s3_notifications_sns.py
...9 from mypy_boto3_s3.literals import EventType10 from mypy_boto3_sns import SNSClient11 from mypy_boto3_sqs import SQSClient12LOG = logging.getLogger(__name__)13def create_sns_bucket_notification(14 s3_client: "S3Client",15 sns_client: "SNSClient",16 bucket_name: str,17 topic_arn: str,18 events: List["EventType"],19):20 """A NotificationFactory."""21 bucket_arn = aws_stack.s3_bucket_arn(bucket_name)22 policy = {23 "Version": "2012-10-17",24 "Statement": [25 {26 "Effect": "Allow",27 "Principal": "*",28 "Action": "sns:Publish",29 "Resource": topic_arn,30 "Condition": {"ArnEquals": {"aws:SourceArn": bucket_arn}},31 }32 ],33 }34 sns_client.set_topic_attributes(35 TopicArn=topic_arn, AttributeName="Policy", AttributeValue=json.dumps(policy)36 )37 s3_client.put_bucket_notification_configuration(38 Bucket=bucket_name,39 NotificationConfiguration=dict(40 TopicConfigurations=[41 dict(42 TopicArn=topic_arn,43 Events=events,44 )45 ]46 ),47 )48def sqs_collect_sns_messages(49 sqs_client: "SQSClient", queue_url: str, min_messages: int, timeout: int = 1050) -> List[Dict]:51 """52 Polls the given queue for the given amount of time and extracts the received SQS messages all SNS messages (messages that have a "TopicArn" field).53 :param sqs_client: the boto3 client to use54 :param queue_url: the queue URL connected to the topic55 :param min_messages: the minimum number of messages to wait for56 :param timeout: the number of seconds to wait before raising an assert error57 :return: a list with the deserialized SNS messages58 """59 collected_messages = []60 def collect_events() -> int:61 _response = sqs_client.receive_message(62 QueueUrl=queue_url, WaitTimeSeconds=timeout, MaxNumberOfMessages=163 )64 messages = _response.get("Messages", [])65 if not messages:66 LOG.info("no messages received from %s after %d seconds", queue_url, timeout)67 for m in messages:68 body = m["Body"]69 # see https://www.mikulskibartosz.name/what-is-s3-test-event/70 if "s3:TestEvent" in body:71 continue72 doc = json.loads(body)73 assert "TopicArn" in doc, f"unexpected event in message {m}"74 collected_messages.append(doc)75 return len(collected_messages)76 assert poll_condition(lambda: collect_events() >= min_messages, timeout=timeout)77 return collected_messages78class TestS3NotificationsToSns:79 @pytest.mark.aws_validated80 def test_object_created_put(81 self,82 s3_client,83 sqs_client,84 sns_client,85 s3_create_bucket,86 sqs_create_queue,87 sns_create_topic,88 sns_create_sqs_subscription,89 ):90 bucket_name = s3_create_bucket()91 topic_arn = sns_create_topic()["TopicArn"]92 queue_url = sqs_create_queue()93 key_name = "bucket-key"94 # connect topic to queue95 sns_create_sqs_subscription(topic_arn, queue_url)96 create_sns_bucket_notification(97 s3_client, sns_client, bucket_name, topic_arn, ["s3:ObjectCreated:*"]98 )99 # trigger the events100 s3_client.put_object(Bucket=bucket_name, Key=key_name, Body="first event")101 s3_client.put_object(Bucket=bucket_name, Key=key_name, Body="second event")102 # collect messages103 messages = sqs_collect_sns_messages(sqs_client, queue_url, 2)104 # asserts105 # first event106 message = messages[0]107 assert message["Type"] == "Notification"108 assert message["TopicArn"] == topic_arn109 assert message["Subject"] == "Amazon S3 Notification"110 event = json.loads(message["Message"])["Records"][0]...
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!!