Best Python code snippet using localstack_python
test_serializer.py
Source:test_serializer.py
...50 del parsed_response["ResponseMetadata"]51 if expected_response_content is None:52 expected_response_content = response53 assert parsed_response == expected_response_content54def _botocore_error_serializer_integration_test(55 service: str,56 action: str,57 exception: ServiceException,58 code: str,59 status_code: int,60 message: str,61):62 """63 Performs an integration test for the error serialization using botocore as parser.64 It executes the following steps:65 - Load the given service (f.e. "sqs")66 - Serialize the _error_ response with the appropriate serializer from the AWS Serivce Framework67 - Parse the serialized error response using the botocore parser68 - Checks the the metadata is correct (status code, requestID,...)69 - Checks if the parsed error response content is correct70 :param service: to load the correct service specification, serializer, and parser71 :param action: to load the correct service specification, serializer, and parser72 :param exception: which should be serialized and tested against73 :param code: expected "code" of the exception (i.e. the AWS specific exception ID, f.e.74 "CloudFrontOriginAccessIdentityAlreadyExists")75 :param status_code: expected HTTP response status code76 :param message: expected error message77 :return: None78 """79 # Load the appropriate service80 service = load_service(service)81 # Use our serializer to serialize the response82 response_serializer = create_serializer(service)83 serialized_response = response_serializer.serialize_error_to_response(84 exception, service.operation_model(action)85 )86 # Use the parser from botocore to parse the serialized response87 response_parser: ResponseParser = create_parser(service.protocol)88 parsed_response = response_parser.parse(89 serialized_response, service.operation_model(action).output_shape90 )91 # Check if the result is equal to the initial response params92 assert "Error" in parsed_response93 assert "Code" in parsed_response["Error"]94 assert "Message" in parsed_response["Error"]95 assert parsed_response["Error"]["Code"] == code96 assert parsed_response["Error"]["Message"] == message97 assert "ResponseMetadata" in parsed_response98 assert "RequestId" in parsed_response["ResponseMetadata"]99 assert len(parsed_response["ResponseMetadata"]["RequestId"]) == 52100 assert "HTTPStatusCode" in parsed_response["ResponseMetadata"]101 assert parsed_response["ResponseMetadata"]["HTTPStatusCode"] == status_code102def test_rest_xml_serializer_cloudfront_with_botocore():103 parameters = {104 "TestResult": {105 "FunctionSummary": {106 "Name": "string",107 "Status": "string",108 "FunctionConfig": {"Comment": "string", "Runtime": "cloudfront-js-1.0"},109 "FunctionMetadata": {110 "FunctionARN": "string",111 "Stage": "LIVE",112 "CreatedTime": datetime(2015, 1, 1, tzinfo=tzutc()),113 "LastModifiedTime": datetime(2015, 1, 1, tzinfo=tzutc()),114 },115 },116 "ComputeUtilization": "string",117 "FunctionExecutionLogs": [118 "string",119 ],120 "FunctionErrorMessage": "string",121 "FunctionOutput": "string",122 }123 }124 _botocore_serializer_integration_test("cloudfront", "TestFunction", parameters)125def test_rest_xml_serializer_route53_with_botocore():126 parameters = {127 "HostedZone": {128 "Id": "/hostedzone/9WXI4LV03NAZVS1",129 "Name": "fuu.",130 "Config": {"PrivateZone": False},131 "ResourceRecordSetCount": 0,132 },133 "DelegationSet": {"NameServers": ["dns.localhost.localstack.cloud"]},134 }135 _botocore_serializer_integration_test("route53", "CreateHostedZone", parameters, 201)136def test_rest_xml_serializer_s3_with_botocore():137 parameters = {138 "AnalyticsConfiguration": {139 "Id": "string",140 "Filter": {141 "Prefix": "string",142 "Tag": {"Key": "string", "Value": "string"},143 "And": {144 "Prefix": "string",145 "Tags": [146 {"Key": "string", "Value": "string"},147 ],148 },149 },150 "StorageClassAnalysis": {151 "DataExport": {152 "OutputSchemaVersion": "V_1",153 "Destination": {154 "S3BucketDestination": {155 "Format": "CSV",156 "BucketAccountId": "string",157 "Bucket": "string",158 "Prefix": "string",159 }160 },161 }162 },163 }164 }165 _botocore_serializer_integration_test("s3", "GetBucketAnalyticsConfiguration", parameters)166@pytest.mark.skip(reason="failing! 'Body' has 'streaming=True'!")167def test_rest_xml_serializer_s3_2_with_botocore():168 parameters = {169 # TODO170 # 'Body': StreamingBody(),171 "Body": "Fuu",172 "DeleteMarker": True,173 "AcceptRanges": "string",174 "Expiration": "string",175 "Restore": "string",176 "LastModified": datetime(2015, 1, 1),177 "ContentLength": 123,178 "ETag": "string",179 "MissingMeta": 123,180 "VersionId": "string",181 "CacheControl": "string",182 "ContentDisposition": "string",183 "ContentEncoding": "string",184 "ContentLanguage": "string",185 "ContentRange": "string",186 "ContentType": "string",187 "Expires": datetime(2015, 1, 1),188 "WebsiteRedirectLocation": "string",189 "ServerSideEncryption": "AES256",190 "Metadata": {"string": "string"},191 "SSECustomerAlgorithm": "string",192 "SSECustomerKeyMD5": "string",193 "SSEKMSKeyId": "string",194 "BucketKeyEnabled": True | False,195 "StorageClass": "STANDARD",196 "RequestCharged": "requester",197 "ReplicationStatus": "COMPLETE",198 "PartsCount": 123,199 "TagCount": 123,200 "ObjectLockMode": "GOVERNANCE",201 "ObjectLockRetainUntilDate": datetime(2015, 1, 1),202 "ObjectLockLegalHoldStatus": "ON",203 }204 _botocore_serializer_integration_test("s3", "GetObject", parameters)205def test_query_serializer_cloudformation_with_botocore():206 parameters = {207 "StackResourceDrift": {208 "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",209 "LogicalResourceId": "MyFunction",210 "PhysicalResourceId": "my-function-SEZV4XMPL4S5",211 "ResourceType": "AWS::Lambda::Function",212 "ExpectedProperties": '{"Description":"Write a file to S3.","Environment":{"Variables":{"bucket":"my-stack-bucket-1vc62xmplgguf"}},"Handler":"index.handler","MemorySize":128,"Role":"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E","Runtime":"nodejs10.x","Tags":[{"Key":"lambda:createdBy","Value":"SAM"}],"Timeout":900,"TracingConfig":{"Mode":"Active"}}',213 "ActualProperties": '{"Description":"Write a file to S3.","Environment":{"Variables":{"bucket":"my-stack-bucket-1vc62xmplgguf"}},"Handler":"index.handler","MemorySize":256,"Role":"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E","Runtime":"nodejs10.x","Tags":[{"Key":"lambda:createdBy","Value":"SAM"}],"Timeout":22,"TracingConfig":{"Mode":"Active"}}',214 "PropertyDifferences": [215 {216 "PropertyPath": "/MemorySize",217 "ExpectedValue": "128",218 "ActualValue": "256",219 "DifferenceType": "NOT_EQUAL",220 },221 {222 "PropertyPath": "/Timeout",223 "ExpectedValue": "900",224 "ActualValue": "22",225 "DifferenceType": "NOT_EQUAL",226 },227 ],228 "StackResourceDriftStatus": "MODIFIED",229 "Timestamp": datetime(2015, 1, 1, tzinfo=tzutc()),230 }231 }232 _botocore_serializer_integration_test("cloudformation", "DetectStackResourceDrift", parameters)233def test_query_serializer_redshift_with_botocore():234 parameters = {235 "Marker": "string",236 "ClusterDbRevisions": [237 {238 "ClusterIdentifier": "string",239 "CurrentDatabaseRevision": "string",240 "DatabaseRevisionReleaseDate": datetime(2015, 1, 1, tzinfo=tzutc()),241 "RevisionTargets": [242 {243 "DatabaseRevision": "string",244 "Description": "string",245 "DatabaseRevisionReleaseDate": datetime(2015, 1, 1, tzinfo=tzutc()),246 },247 ],248 },249 ],250 }251 _botocore_serializer_integration_test("redshift", "DescribeClusterDbRevisions", parameters)252def test_query_serializer_sqs_empty_return_shape_with_botocore():253 _botocore_serializer_integration_test("sqs", "SetQueueAttributes", {})254def test_query_serializer_sqs_flattened_list_with_botocore():255 response = {256 "QueueUrls": [257 "http://localhost:4566/000000000000/myqueue1",258 "http://localhost:4566/000000000000/myqueue2",259 ]260 }261 _botocore_serializer_integration_test("sqs", "ListQueues", response)262def test_query_serializer_sqs_flattened_map_with_botocore():263 response = {264 "Attributes": {265 "QueueArn": "arn:aws:sqs:us-east-1:000000000000:test-queue-01",266 "DelaySeconds": "0",267 }268 }269 _botocore_serializer_integration_test("sqs", "GetQueueAttributes", response)270def test_query_serializer_sqs_flattened_list_map_with_botocore():271 response = {272 "Messages": [273 {274 "MessageId": "ac9baa5c-13b1-4206-aa28-2ac45ae168af",275 "ReceiptHandle": "AQEBZ14sCjWJuot0T8G2Eg3S8C+sJGg+QRKYCJjfd8iiOsrPfUzbXSjlQquT9NZP1Mxxkcud3HcaxvS7I1gxoM9MSjbpenKgkti8TPCc7nQBUk9y6xXYWlhysjgAi9YjExUIxO2ozYZuwyksOvIxS4NZs2aBctyR74N3XjOO/t8GByAz2u7KR5vYJu418Y9apAuYB1n6ZZ6aE1NrjIK9mjGCKSqE3YxN5SNkKXf1zRwTUjq8cE73F7cK7DBXNFWBTZSYkLLnFg/QuqKh0dfwGgLseeKhHUxw2KiP9qH4kvXBn2UdeI8jkFMbPERiSf2KMrGKyMCtz3jL+YVRYkB4BB0hx15Brrgo/zhePXHbT692VxKF98MIMQc/v+dc6aewQZldjuq6ANrp4RM+LdjlTPg7ow==",276 "MD5OfBody": "13c0c73bbf11056450c43bf3159b3585",277 "Body": '{"foo": "bared"}',278 }279 ]280 }281 _botocore_serializer_integration_test("sqs", "ReceiveMessage", response)282def test_query_serializer_sqs_none_value_in_map():283 response = {284 "Messages": [285 {286 "MessageId": "ac9baa5c-13b1-4206-aa28-2ac45ae168af",287 "ReceiptHandle": "AQEBZ14sCjWJuot0T8G2Eg3S8C+sJGg+QRKYCJjfd8iiOsrPfUzbXSjlQquT9NZP1Mxxkcud3HcaxvS7I1gxoM9MSjbpenKgkti8TPCc7nQBUk9y6xXYWlhysjgAi9YjExUIxO2ozYZuwyksOvIxS4NZs2aBctyR74N3XjOO/t8GByAz2u7KR5vYJu418Y9apAuYB1n6ZZ6aE1NrjIK9mjGCKSqE3YxN5SNkKXf1zRwTUjq8cE73F7cK7DBXNFWBTZSYkLLnFg/QuqKh0dfwGgLseeKhHUxw2KiP9qH4kvXBn2UdeI8jkFMbPERiSf2KMrGKyMCtz3jL+YVRYkB4BB0hx15Brrgo/zhePXHbT692VxKF98MIMQc/v+dc6aewQZldjuq6ANrp4RM+LdjlTPg7ow==",288 "Attributes": None,289 "MD5OfBody": "13c0c73bbf11056450c43bf3159b3585",290 "Body": '{"foo": "bared"}',291 }292 ]293 }294 expected_response = copy.deepcopy(response)295 del expected_response["Messages"][0]["Attributes"]296 _botocore_serializer_integration_test("sqs", "ReceiveMessage", response, 200, expected_response)297def test_query_protocol_error_serialization():298 # Specific error of the SendMessage operation in SQS as the scaffold would generate it299 class InvalidMessageContents(ServiceException):300 """The message contains characters outside the allowed set."""301 pass302 exception = InvalidMessageContents("Exception message!")303 _botocore_error_serializer_integration_test(304 "sqs", "SendMessage", exception, "InvalidMessageContents", 400, "Exception message!"305 )306def test_query_protocol_custom_error_serialization():307 exception = CommonServiceException("InvalidParameterValue", "Parameter x was invalid!")308 _botocore_error_serializer_integration_test(309 "sqs", "SendMessage", exception, "InvalidParameterValue", 400, "Parameter x was invalid!"310 )311def test_restxml_protocol_error_serialization():312 class CloudFrontOriginAccessIdentityAlreadyExists(ServiceException):313 pass314 exception = CloudFrontOriginAccessIdentityAlreadyExists("Exception message!")315 _botocore_error_serializer_integration_test(316 "cloudfront",317 "CreateCloudFrontOriginAccessIdentity",318 exception,319 "CloudFrontOriginAccessIdentityAlreadyExists",320 409,321 "Exception message!",322 )323def test_restxml_protocol_custom_error_serialization():324 exception = CommonServiceException(325 "APIAccessCensorship",326 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",327 status_code=451,328 )329 _botocore_error_serializer_integration_test(330 "cloudfront",331 "CreateCloudFrontOriginAccessIdentity",332 exception,333 "APIAccessCensorship",334 451,335 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",336 )337def test_json_protocol_error_serialization():338 class UserPoolTaggingException(ServiceException):339 pass340 exception = UserPoolTaggingException("Exception message!")341 _botocore_error_serializer_integration_test(342 "cognito-idp",343 "CreateUserPool",344 exception,345 "UserPoolTaggingException",346 400,347 "Exception message!",348 )349def test_json_protocol_custom_error_serialization():350 exception = CommonServiceException(351 "APIAccessCensorship",352 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",353 status_code=451,354 )355 _botocore_error_serializer_integration_test(356 "cognito-idp",357 "CreateUserPool",358 exception,359 "APIAccessCensorship",360 451,361 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",362 )363def test_json_serializer_cognito_with_botocore():364 parameters = {365 "UserPool": {366 "Id": "string",367 "Name": "string",368 "Policies": {369 "PasswordPolicy": {370 "MinimumLength": 123,371 "RequireUppercase": True,372 "RequireLowercase": True,373 "RequireNumbers": True,374 "RequireSymbols": True,375 "TemporaryPasswordValidityDays": 123,376 }377 },378 "LambdaConfig": {379 "PreSignUp": "string",380 "CustomMessage": "string",381 "PostConfirmation": "string",382 "PreAuthentication": "string",383 "PostAuthentication": "string",384 "DefineAuthChallenge": "string",385 "CreateAuthChallenge": "string",386 "VerifyAuthChallengeResponse": "string",387 "PreTokenGeneration": "string",388 "UserMigration": "string",389 "CustomSMSSender": {"LambdaVersion": "V1_0", "LambdaArn": "string"},390 "CustomEmailSender": {"LambdaVersion": "V1_0", "LambdaArn": "string"},391 "KMSKeyID": "string",392 },393 "Status": "Enabled",394 "LastModifiedDate": datetime(2015, 1, 1, tzinfo=tzutc()),395 "CreationDate": datetime(2015, 1, 1, tzinfo=tzutc()),396 "SchemaAttributes": [397 {398 "Name": "string",399 "AttributeDataType": "String",400 "DeveloperOnlyAttribute": True,401 "Mutable": True,402 "Required": True,403 "NumberAttributeConstraints": {"MinValue": "string", "MaxValue": "string"},404 "StringAttributeConstraints": {"MinLength": "string", "MaxLength": "string"},405 },406 ],407 "AutoVerifiedAttributes": [408 "phone_number",409 ],410 "AliasAttributes": [411 "phone_number",412 ],413 "UsernameAttributes": [414 "phone_number",415 ],416 "SmsVerificationMessage": "string",417 "EmailVerificationMessage": "string",418 "EmailVerificationSubject": "string",419 "VerificationMessageTemplate": {420 "SmsMessage": "string",421 "EmailMessage": "string",422 "EmailSubject": "string",423 "EmailMessageByLink": "string",424 "EmailSubjectByLink": "string",425 "DefaultEmailOption": "CONFIRM_WITH_LINK",426 },427 "SmsAuthenticationMessage": "string",428 "MfaConfiguration": "OFF",429 "DeviceConfiguration": {430 "ChallengeRequiredOnNewDevice": True,431 "DeviceOnlyRememberedOnUserPrompt": True,432 },433 "EstimatedNumberOfUsers": 123,434 "EmailConfiguration": {435 "SourceArn": "string",436 "ReplyToEmailAddress": "string",437 "EmailSendingAccount": "COGNITO_DEFAULT",438 "From": "string",439 "ConfigurationSet": "string",440 },441 "SmsConfiguration": {"SnsCallerArn": "string", "ExternalId": "string"},442 "UserPoolTags": {"string": "string"},443 "SmsConfigurationFailure": "string",444 "EmailConfigurationFailure": "string",445 "Domain": "string",446 "CustomDomain": "string",447 "AdminCreateUserConfig": {448 "AllowAdminCreateUserOnly": True,449 "UnusedAccountValidityDays": 123,450 "InviteMessageTemplate": {451 "SMSMessage": "string",452 "EmailMessage": "string",453 "EmailSubject": "string",454 },455 },456 "UserPoolAddOns": {"AdvancedSecurityMode": "OFF"},457 "UsernameConfiguration": {"CaseSensitive": True},458 "Arn": "string",459 "AccountRecoverySetting": {460 "RecoveryMechanisms": [461 {"Priority": 123, "Name": "verified_email"},462 ]463 },464 }465 }466 _botocore_serializer_integration_test("cognito-idp", "DescribeUserPool", parameters)467def test_restjson_protocol_error_serialization():468 class ThrottledException(ServiceException):469 pass470 exception = ThrottledException("Exception message!")471 _botocore_error_serializer_integration_test(472 "xray",473 "UpdateSamplingRule",474 exception,475 "ThrottledException",476 429,477 "Exception message!",478 )479def test_restjson_protocol_custom_error_serialization():480 exception = CommonServiceException(481 "APIAccessCensorship",482 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",483 status_code=451,484 )485 _botocore_error_serializer_integration_test(486 "xray",487 "UpdateSamplingRule",488 exception,489 "APIAccessCensorship",490 451,491 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",492 )493def test_restjson_serializer_xray_with_botocore():494 parameters = {495 "SamplingRuleRecord": {496 "SamplingRule": {497 "RuleName": "string",498 "RuleARN": "123456789001234567890",499 "ResourceARN": "123456789001234567890",500 "Priority": 123,501 "FixedRate": 123.0,502 "ReservoirSize": 123,503 "ServiceName": "string",504 "ServiceType": "string",505 "Host": "string",506 "HTTPMethod": "string",507 "URLPath": "string",508 "Version": 123,509 "Attributes": {"string": "string"},510 },511 "CreatedAt": datetime(2015, 1, 1, tzinfo=tzutc()),512 "ModifiedAt": datetime(2015, 1, 1, tzinfo=tzutc()),513 }514 }515 _botocore_serializer_integration_test("xray", "UpdateSamplingRule", parameters)516def test_ec2_serializer_ec2_with_botocore():517 parameters = {518 "InstanceEventWindow": {519 "InstanceEventWindowId": "string",520 "TimeRanges": [521 {522 "StartWeekDay": "sunday",523 "StartHour": 123,524 "EndWeekDay": "sunday",525 "EndHour": 123,526 },527 ],528 "Name": "string",529 "CronExpression": "string",530 "AssociationTarget": {531 "InstanceIds": [532 "string",533 ],534 "Tags": [535 {"Key": "string", "Value": "string"},536 ],537 "DedicatedHostIds": [538 "string",539 ],540 },541 "State": "creating",542 "Tags": [543 {"Key": "string", "Value": "string"},544 ],545 }546 }547 _botocore_serializer_integration_test("ec2", "CreateInstanceEventWindow", parameters)548def test_ec2_protocol_custom_error_serialization():549 exception = CommonServiceException(550 "IdempotentParameterMismatch", "Different payload, same token?!"551 )552 _botocore_error_serializer_integration_test(553 "ec2",554 "StartInstances",555 exception,556 "IdempotentParameterMismatch",557 400,558 "Different payload, same token?!",559 )560# TODO Add additional tests (or even automate the creation)561# - Go to the AWS CLI reference (https://docs.aws.amazon.com)562# - Look at the CLI reference for APIs that use the protocol you want to test...
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!!