Best Python code snippet using localstack_python
test_serializer.py
Source:test_serializer.py
...14)15from localstack.aws.spec import load_service16from localstack.utils.common import to_str17_skip_assert = {}18def _botocore_serializer_integration_test(19 service: str,20 action: str,21 response: dict,22 status_code=200,23 expected_response_content: dict = None,24):25 """26 Performs an integration test for the serializer using botocore as parser.27 It executes the following steps:28 - Load the given service (f.e. "sqs")29 - Serialize the response with the appropriate serializer from the AWS Serivce Framework30 - Parse the serialized response using the botocore parser31 - Checks if the metadata is correct (status code, requestID,...)32 - Checks if the parsed response content is equal to the input to the serializer33 :param service: to load the correct service specification, serializer, and parser34 :param action: to load the correct service specification, serializer, and parser35 :param response: which should be serialized and tested against36 :param status_code: Optional - expected status code of the response - defaults to 20037 :param expected_response_content: Optional - if the input data ("response") differs from the actually expected data38 (because f.e. it contains None values)39 :return: None40 """41 # Load the appropriate service42 service = load_service(service)43 # Use our serializer to serialize the response44 response_serializer = create_serializer(service)45 # The serializer changes the incoming dict, therefore copy it before passing it to the serializer46 response_to_parse = copy.deepcopy(response)47 serialized_response = response_serializer.serialize_to_response(48 response_to_parse, service.operation_model(action)49 )50 # Use the parser from botocore to parse the serialized response51 response_parser = create_parser(service.protocol)52 parsed_response = response_parser.parse(53 serialized_response.to_readonly_response_dict(),54 service.operation_model(action).output_shape,55 )56 return_response = copy.deepcopy(parsed_response)57 # Check if the result is equal to the initial response params58 assert "ResponseMetadata" in parsed_response59 assert "HTTPStatusCode" in parsed_response["ResponseMetadata"]60 assert parsed_response["ResponseMetadata"]["HTTPStatusCode"] == status_code61 assert "RequestId" in parsed_response["ResponseMetadata"]62 assert len(parsed_response["ResponseMetadata"]["RequestId"]) == 5263 del parsed_response["ResponseMetadata"]64 if expected_response_content is None:65 expected_response_content = response66 if expected_response_content is not _skip_assert:67 assert parsed_response == expected_response_content68 return return_response69def _botocore_error_serializer_integration_test(70 service: str,71 action: str,72 exception: ServiceException,73 code: str,74 status_code: int,75 message: Optional[str],76 is_sender_fault: bool = False,77):78 """79 Performs an integration test for the error serialization using botocore as parser.80 It executes the following steps:81 - Load the given service (f.e. "sqs")82 - Serialize the _error_ response with the appropriate serializer from the AWS Serivce Framework83 - Parse the serialized error response using the botocore parser84 - Checks the the metadata is correct (status code, requestID,...)85 - Checks if the parsed error response content is correct86 :param service: to load the correct service specification, serializer, and parser87 :param action: to load the correct service specification, serializer, and parser88 :param exception: which should be serialized and tested against89 :param code: expected "code" of the exception (i.e. the AWS specific exception ID, f.e.90 "CloudFrontOriginAccessIdentityAlreadyExists")91 :param status_code: expected HTTP response status code92 :param message: expected error message93 :return: None94 """95 # Load the appropriate service96 service = load_service(service)97 # Use our serializer to serialize the response98 response_serializer = create_serializer(service)99 serialized_response = response_serializer.serialize_error_to_response(100 exception, service.operation_model(action)101 )102 # Use the parser from botocore to parse the serialized response103 response_parser: ResponseParser = create_parser(service.protocol)104 parsed_response = response_parser.parse(105 serialized_response.to_readonly_response_dict(),106 service.operation_model(action).output_shape,107 )108 # Check if the result is equal to the initial response params109 assert "Error" in parsed_response110 assert "Code" in parsed_response["Error"]111 assert "Message" in parsed_response["Error"]112 assert parsed_response["Error"]["Code"] == code113 assert parsed_response["Error"]["Message"] == message114 assert "ResponseMetadata" in parsed_response115 assert "RequestId" in parsed_response["ResponseMetadata"]116 assert len(parsed_response["ResponseMetadata"]["RequestId"]) == 52117 assert "HTTPStatusCode" in parsed_response["ResponseMetadata"]118 assert parsed_response["ResponseMetadata"]["HTTPStatusCode"] == status_code119 type = parsed_response["Error"].get("Type")120 if is_sender_fault:121 assert type == "Sender"122 else:123 assert type is None124def test_rest_xml_serializer_cloudfront_with_botocore():125 parameters = {126 "TestResult": {127 "FunctionSummary": {128 "Name": "string",129 "Status": "string",130 "FunctionConfig": {"Comment": "string", "Runtime": "cloudfront-js-1.0"},131 "FunctionMetadata": {132 "FunctionARN": "string",133 "Stage": "LIVE",134 # Test the timestamp precision by adding hours, minutes, seconds and some milliseconds135 # (as microseconds).136 "CreatedTime": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),137 "LastModifiedTime": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),138 },139 },140 "ComputeUtilization": "string",141 "FunctionExecutionLogs": [142 "string",143 ],144 "FunctionErrorMessage": "string",145 "FunctionOutput": "string",146 }147 }148 _botocore_serializer_integration_test("cloudfront", "TestFunction", parameters)149def test_rest_xml_serializer_route53_with_botocore():150 parameters = {151 "HostedZone": {152 "Id": "/hostedzone/9WXI4LV03NAZVS1",153 "Name": "fuu.",154 "Config": {"PrivateZone": False},155 "ResourceRecordSetCount": 0,156 },157 "DelegationSet": {"NameServers": ["dns.localhost.localstack.cloud"]},158 }159 _botocore_serializer_integration_test("route53", "CreateHostedZone", parameters, 201)160def test_rest_xml_serializer_s3_with_botocore():161 parameters = {162 "AnalyticsConfiguration": {163 "Id": "string",164 "Filter": {165 "Prefix": "string",166 "Tag": {"Key": "string", "Value": "string"},167 "And": {168 "Prefix": "string",169 "Tags": [170 {"Key": "string", "Value": "string"},171 ],172 },173 },174 "StorageClassAnalysis": {175 "DataExport": {176 "OutputSchemaVersion": "V_1",177 "Destination": {178 "S3BucketDestination": {179 "Format": "CSV",180 "BucketAccountId": "string",181 "Bucket": "string",182 "Prefix": "string",183 }184 },185 }186 },187 }188 }189 _botocore_serializer_integration_test("s3", "GetBucketAnalyticsConfiguration", parameters)190def test_rest_xml_serializer_s3_2_with_botocore():191 # These date fields in this response are encoded in the header. The max precision is seconds.192 parameters = {193 "Body": "body",194 "DeleteMarker": True,195 "AcceptRanges": "string",196 "Expiration": "string",197 "Restore": "string",198 "LastModified": datetime(2015, 1, 1, 23, 59, 59, tzinfo=tzutc()),199 "ContentLength": 4,200 "ETag": "string",201 "MissingMeta": 123,202 "VersionId": "string",203 "CacheControl": "string",204 "ContentDisposition": "string",205 "ContentEncoding": "string",206 "ContentLanguage": "string",207 "ContentRange": "string",208 "ContentType": "string",209 "Expires": datetime(2015, 1, 1, 23, 59, 59, tzinfo=tzutc()),210 "WebsiteRedirectLocation": "string",211 "ServerSideEncryption": "AES256",212 "Metadata": {"string": "string"},213 "SSECustomerAlgorithm": "string",214 "SSECustomerKeyMD5": "string",215 "SSEKMSKeyId": "string",216 "BucketKeyEnabled": True | False,217 "StorageClass": "STANDARD",218 "RequestCharged": "requester",219 "ReplicationStatus": "COMPLETE",220 "PartsCount": 123,221 "TagCount": 123,222 "ObjectLockMode": "GOVERNANCE",223 "ObjectLockRetainUntilDate": datetime(2015, 1, 1, 23, 59, 59, tzinfo=tzutc()),224 "ObjectLockLegalHoldStatus": "ON",225 }226 _botocore_serializer_integration_test("s3", "GetObject", parameters)227def test_query_serializer_cloudformation_with_botocore():228 parameters = {229 "StackResourceDrift": {230 "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",231 "LogicalResourceId": "MyFunction",232 "PhysicalResourceId": "my-function-SEZV4XMPL4S5",233 "ResourceType": "AWS::Lambda::Function",234 "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"}}',235 "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"}}',236 "PropertyDifferences": [237 {238 "PropertyPath": "/MemorySize",239 "ExpectedValue": "128",240 "ActualValue": "256",241 "DifferenceType": "NOT_EQUAL",242 },243 {244 "PropertyPath": "/Timeout",245 "ExpectedValue": "900",246 "ActualValue": "22",247 "DifferenceType": "NOT_EQUAL",248 },249 ],250 "StackResourceDriftStatus": "MODIFIED",251 "Timestamp": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),252 }253 }254 _botocore_serializer_integration_test("cloudformation", "DetectStackResourceDrift", parameters)255def test_query_serializer_redshift_with_botocore():256 parameters = {257 "Marker": "string",258 "ClusterDbRevisions": [259 {260 "ClusterIdentifier": "string",261 "CurrentDatabaseRevision": "string",262 "DatabaseRevisionReleaseDate": datetime(263 2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()264 ),265 "RevisionTargets": [266 {267 "DatabaseRevision": "string",268 "Description": "string",269 "DatabaseRevisionReleaseDate": datetime(270 2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()271 ),272 },273 ],274 },275 ],276 }277 _botocore_serializer_integration_test("redshift", "DescribeClusterDbRevisions", parameters)278def test_query_serializer_sqs_empty_return_shape_with_botocore():279 _botocore_serializer_integration_test("sqs", "SetQueueAttributes", {})280def test_query_serializer_sqs_flattened_list_with_botocore():281 response = {282 "QueueUrls": [283 "http://localhost:4566/000000000000/myqueue1",284 "http://localhost:4566/000000000000/myqueue2",285 ]286 }287 _botocore_serializer_integration_test("sqs", "ListQueues", response)288def test_query_serializer_sqs_flattened_map_with_botocore():289 response = {290 "Attributes": {291 "QueueArn": "arn:aws:sqs:us-east-1:000000000000:test-queue-01",292 "DelaySeconds": "0",293 }294 }295 _botocore_serializer_integration_test("sqs", "GetQueueAttributes", response)296def test_query_serializer_sqs_flattened_list_map_with_botocore():297 response = {298 "Messages": [299 {300 "MessageId": "ac9baa5c-13b1-4206-aa28-2ac45ae168af",301 "ReceiptHandle": "AQEBZ14sCjWJuot0T8G2Eg3S8C+sJGg+QRKYCJjfd8iiOsrPfUzbXSjlQquT9NZP1Mxxkcud3HcaxvS7I1gxoM9MSjbpenKgkti8TPCc7nQBUk9y6xXYWlhysjgAi9YjExUIxO2ozYZuwyksOvIxS4NZs2aBctyR74N3XjOO/t8GByAz2u7KR5vYJu418Y9apAuYB1n6ZZ6aE1NrjIK9mjGCKSqE3YxN5SNkKXf1zRwTUjq8cE73F7cK7DBXNFWBTZSYkLLnFg/QuqKh0dfwGgLseeKhHUxw2KiP9qH4kvXBn2UdeI8jkFMbPERiSf2KMrGKyMCtz3jL+YVRYkB4BB0hx15Brrgo/zhePXHbT692VxKF98MIMQc/v+dc6aewQZldjuq6ANrp4RM+LdjlTPg7ow==",302 "MD5OfBody": "13c0c73bbf11056450c43bf3159b3585",303 "Body": '{"foo": "bared"}',304 }305 ]306 }307 _botocore_serializer_integration_test("sqs", "ReceiveMessage", response)308def test_query_serializer_sqs_none_value_in_map():309 response = {310 "Messages": [311 {312 "MessageId": "ac9baa5c-13b1-4206-aa28-2ac45ae168af",313 "ReceiptHandle": "AQEBZ14sCjWJuot0T8G2Eg3S8C+sJGg+QRKYCJjfd8iiOsrPfUzbXSjlQquT9NZP1Mxxkcud3HcaxvS7I1gxoM9MSjbpenKgkti8TPCc7nQBUk9y6xXYWlhysjgAi9YjExUIxO2ozYZuwyksOvIxS4NZs2aBctyR74N3XjOO/t8GByAz2u7KR5vYJu418Y9apAuYB1n6ZZ6aE1NrjIK9mjGCKSqE3YxN5SNkKXf1zRwTUjq8cE73F7cK7DBXNFWBTZSYkLLnFg/QuqKh0dfwGgLseeKhHUxw2KiP9qH4kvXBn2UdeI8jkFMbPERiSf2KMrGKyMCtz3jL+YVRYkB4BB0hx15Brrgo/zhePXHbT692VxKF98MIMQc/v+dc6aewQZldjuq6ANrp4RM+LdjlTPg7ow==",314 "Attributes": None,315 "MD5OfBody": "13c0c73bbf11056450c43bf3159b3585",316 "Body": '{"foo": "bared"}',317 }318 ]319 }320 expected_response = copy.deepcopy(response)321 del expected_response["Messages"][0]["Attributes"]322 _botocore_serializer_integration_test("sqs", "ReceiveMessage", response, 200, expected_response)323def test_query_protocol_error_serialization():324 # Specific error of the SendMessage operation in SQS as the scaffold would generate it325 class InvalidMessageContents(ServiceException):326 """The message contains characters outside the allowed set."""327 pass328 exception = InvalidMessageContents("Exception message!")329 _botocore_error_serializer_integration_test(330 "sqs", "SendMessage", exception, "InvalidMessageContents", 400, "Exception message!"331 )332def test_query_protocol_error_serialization_plain():333 # Specific error of the ChangeMessageVisibility operation in SQS as the scaffold would generate it334 class ReceiptHandleIsInvalid(ServiceException):335 pass336 exception = ReceiptHandleIsInvalid(337 'The input receipt handle "garbage" is not a valid receipt handle.'338 )339 # Load the SQS service340 service = load_service("sqs")341 # Use our serializer to serialize the response342 response_serializer = create_serializer(service)343 serialized_response = response_serializer.serialize_error_to_response(344 exception, service.operation_model("ChangeMessageVisibility")345 )346 serialized_response_dict = serialized_response.to_readonly_response_dict()347 # Replace the random request ID with a static value for comparison348 serialized_response_body = re.sub(349 "<RequestId>.*</RequestId>",350 "<RequestId>static_request_id</RequestId>",351 to_str(serialized_response_dict["body"]),352 )353 # This expected_response_body differs from the actual response in the following ways:354 # - The original response does not define an encoding.355 # - There is no newline after the XML declaration.356 # - The response does not contain a Type nor Detail tag (since they aren't contained in the spec).357 # - The original response uses double quotes for the xml declaration.358 # Most of these differences should be handled equally by parsing clients, however, we might adopt some of these359 # changes in the future.360 expected_response_body = (361 "<?xml version='1.0' encoding='utf-8'?>\n"362 '<ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">'363 "<Error>"364 "<Code>ReceiptHandleIsInvalid</Code>"365 "<Message>The input receipt handle "garbage" is not a valid receipt handle."366 "</Message>"367 "</Error>"368 "<RequestId>static_request_id</RequestId>"369 "</ErrorResponse>"370 )371 assert serialized_response_body == expected_response_body372 assert serialized_response_dict["headers"].get("Content-Type") is not None373 assert serialized_response_dict["headers"]["Content-Type"] == "text/xml"374def test_query_protocol_custom_error_serialization():375 exception = CommonServiceException("InvalidParameterValue", "Parameter x was invalid!")376 _botocore_error_serializer_integration_test(377 "sqs", "SendMessage", exception, "InvalidParameterValue", 400, "Parameter x was invalid!"378 )379def test_query_protocol_error_serialization_sender_fault():380 # Specific exception thrown by SQS which defines the "Sender" fault381 class UnsupportedOperation(ServiceException):382 pass383 exception = UnsupportedOperation("Operation not supported.")384 _botocore_error_serializer_integration_test(385 "sqs",386 "SendMessage",387 exception,388 "AWS.SimpleQueueService.UnsupportedOperation",389 400,390 "Operation not supported.",391 True,392 )393def test_restxml_protocol_error_serialization_not_specified_for_operation():394 """395 Tests if the serializer can serialize an error which is not explicitly defined as an error shape for the396 specific operation.397 This can happen if the specification is not specific enough (f.e. S3's GetBucketAcl does not define the NoSuchBucket398 error, even though it obviously can be raised).399 """400 class NoSuchBucket(ServiceException):401 pass402 exception = NoSuchBucket("Exception message!")403 _botocore_error_serializer_integration_test(404 "s3",405 "GetBucketAcl",406 exception,407 "NoSuchBucket",408 400,409 "Exception message!",410 )411def test_restxml_protocol_error_serialization():412 class CloudFrontOriginAccessIdentityAlreadyExists(ServiceException):413 pass414 exception = CloudFrontOriginAccessIdentityAlreadyExists("Exception message!")415 _botocore_error_serializer_integration_test(416 "cloudfront",417 "CreateCloudFrontOriginAccessIdentity",418 exception,419 "CloudFrontOriginAccessIdentityAlreadyExists",420 409,421 "Exception message!",422 )423def test_restxml_protocol_custom_error_serialization():424 exception = CommonServiceException(425 "APIAccessCensorship",426 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",427 status_code=451,428 )429 _botocore_error_serializer_integration_test(430 "cloudfront",431 "CreateCloudFrontOriginAccessIdentity",432 exception,433 "APIAccessCensorship",434 451,435 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",436 )437def test_json_protocol_error_serialization():438 class UserPoolTaggingException(ServiceException):439 pass440 exception = UserPoolTaggingException("Exception message!")441 _botocore_error_serializer_integration_test(442 "cognito-idp",443 "CreateUserPool",444 exception,445 "UserPoolTaggingException",446 400,447 "Exception message!",448 )449def test_json_protocol_custom_error_serialization():450 exception = CommonServiceException(451 "APIAccessCensorship",452 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",453 status_code=451,454 )455 _botocore_error_serializer_integration_test(456 "cognito-idp",457 "CreateUserPool",458 exception,459 "APIAccessCensorship",460 451,461 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",462 )463def test_json_serializer_cognito_with_botocore():464 parameters = {465 "UserPool": {466 "Id": "string",467 "Name": "string",468 "Policies": {469 "PasswordPolicy": {470 "MinimumLength": 123,471 "RequireUppercase": True,472 "RequireLowercase": True,473 "RequireNumbers": True,474 "RequireSymbols": True,475 "TemporaryPasswordValidityDays": 123,476 }477 },478 "LambdaConfig": {479 "PreSignUp": "string",480 "CustomMessage": "string",481 "PostConfirmation": "string",482 "PreAuthentication": "string",483 "PostAuthentication": "string",484 "DefineAuthChallenge": "string",485 "CreateAuthChallenge": "string",486 "VerifyAuthChallengeResponse": "string",487 "PreTokenGeneration": "string",488 "UserMigration": "string",489 "CustomSMSSender": {"LambdaVersion": "V1_0", "LambdaArn": "string"},490 "CustomEmailSender": {"LambdaVersion": "V1_0", "LambdaArn": "string"},491 "KMSKeyID": "string",492 },493 "Status": "Enabled",494 "LastModifiedDate": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),495 "CreationDate": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),496 "SchemaAttributes": [497 {498 "Name": "string",499 "AttributeDataType": "String",500 "DeveloperOnlyAttribute": True,501 "Mutable": True,502 "Required": True,503 "NumberAttributeConstraints": {"MinValue": "string", "MaxValue": "string"},504 "StringAttributeConstraints": {"MinLength": "string", "MaxLength": "string"},505 },506 ],507 "AutoVerifiedAttributes": [508 "phone_number",509 ],510 "AliasAttributes": [511 "phone_number",512 ],513 "UsernameAttributes": [514 "phone_number",515 ],516 "SmsVerificationMessage": "string",517 "EmailVerificationMessage": "string",518 "EmailVerificationSubject": "string",519 "VerificationMessageTemplate": {520 "SmsMessage": "string",521 "EmailMessage": "string",522 "EmailSubject": "string",523 "EmailMessageByLink": "string",524 "EmailSubjectByLink": "string",525 "DefaultEmailOption": "CONFIRM_WITH_LINK",526 },527 "SmsAuthenticationMessage": "string",528 "MfaConfiguration": "OFF",529 "DeviceConfiguration": {530 "ChallengeRequiredOnNewDevice": True,531 "DeviceOnlyRememberedOnUserPrompt": True,532 },533 "EstimatedNumberOfUsers": 123,534 "EmailConfiguration": {535 "SourceArn": "string",536 "ReplyToEmailAddress": "string",537 "EmailSendingAccount": "COGNITO_DEFAULT",538 "From": "string",539 "ConfigurationSet": "string",540 },541 "SmsConfiguration": {"SnsCallerArn": "string", "ExternalId": "string"},542 "UserPoolTags": {"string": "string"},543 "SmsConfigurationFailure": "string",544 "EmailConfigurationFailure": "string",545 "Domain": "string",546 "CustomDomain": "string",547 "AdminCreateUserConfig": {548 "AllowAdminCreateUserOnly": True,549 "UnusedAccountValidityDays": 123,550 "InviteMessageTemplate": {551 "SMSMessage": "string",552 "EmailMessage": "string",553 "EmailSubject": "string",554 },555 },556 "UserPoolAddOns": {"AdvancedSecurityMode": "OFF"},557 "UsernameConfiguration": {"CaseSensitive": True},558 "Arn": "string",559 "AccountRecoverySetting": {560 "RecoveryMechanisms": [561 {"Priority": 123, "Name": "verified_email"},562 ]563 },564 }565 }566 _botocore_serializer_integration_test("cognito-idp", "DescribeUserPool", parameters)567def test_json_serializer_date_serialization_with_botocore():568 parameters = {569 "UserPool": {570 "LastModifiedDate": datetime(2022, 2, 8, 9, 17, 40, 122939, tzinfo=tzlocal()),571 }572 }573 _botocore_serializer_integration_test("cognito-idp", "DescribeUserPool", parameters)574def test_restjson_protocol_error_serialization():575 class ThrottledException(ServiceException):576 pass577 exception = ThrottledException("Exception message!")578 _botocore_error_serializer_integration_test(579 "xray",580 "UpdateSamplingRule",581 exception,582 "ThrottledException",583 429,584 "Exception message!",585 )586def test_restjson_protocol_custom_error_serialization():587 exception = CommonServiceException(588 "APIAccessCensorship",589 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",590 status_code=451,591 )592 _botocore_error_serializer_integration_test(593 "xray",594 "UpdateSamplingRule",595 exception,596 "APIAccessCensorship",597 451,598 "You shall not access this API! Sincerely, your friendly neighbourhood firefighter.",599 )600def test_restjson_serializer_xray_with_botocore():601 parameters = {602 "SamplingRuleRecord": {603 "SamplingRule": {604 "RuleName": "string",605 "RuleARN": "123456789001234567890",606 "ResourceARN": "123456789001234567890",607 "Priority": 123,608 "FixedRate": 123.0,609 "ReservoirSize": 123,610 "ServiceName": "string",611 "ServiceType": "string",612 "Host": "string",613 "HTTPMethod": "string",614 "URLPath": "string",615 "Version": 123,616 "Attributes": {"string": "string"},617 },618 "CreatedAt": datetime(2015, 1, 1, 23, 59, 59, 6000, tzinfo=tzutc()),619 "ModifiedAt": datetime(2015, 1, 1, 23, 59, 59, 1000, tzinfo=tzutc()),620 }621 }622 _botocore_serializer_integration_test("xray", "UpdateSamplingRule", parameters)623def test_restjson_header_target_serialization():624 """625 Tests the serialization of attributes into a specified header key based on this example from glacier:626 "InitiateJobOutput":{627 "type":"structure",628 "members":{629 "location":{630 "shape":"string",631 "location":"header",632 "locationName":"Location"633 },634 "jobId":{635 "shape":"string",636 "location":"header",637 "locationName":"x-amz-job-id"638 },639 "jobOutputPath":{640 "shape":"string",641 "location":"header",642 "locationName":"x-amz-job-output-path"643 }644 },645 "documentation":"<p>Contains the Amazon S3 Glacier response to your request.</p>"646 },647 """648 response = {649 "location": "/here",650 "jobId": "42069",651 "jobOutputPath": "/there",652 }653 result = _botocore_serializer_integration_test(654 "glacier",655 "InitiateJob",656 response,657 status_code=202,658 )659 headers = result["ResponseMetadata"]["HTTPHeaders"]660 assert "location" in headers661 assert "x-amz-job-id" in headers662 assert "x-amz-job-output-path" in headers663 assert "locationName" not in headers664 assert "jobOutputPath" not in headers665 assert headers["location"] == "/here"666 assert headers["x-amz-job-id"] == "42069"667 assert headers["x-amz-job-output-path"] == "/there"668def test_restjson_headers_target_serialization():669 # SendApiAssetResponse670 response = {671 "Body": "hello",672 "ResponseHeaders": {673 "foo": "bar",674 "baz": "ed",675 },676 }677 # skipping assert here, because the response will contain all HTTP headers (given the nature of "ResponseHeaders"678 # attribute).679 result = _botocore_serializer_integration_test(680 "dataexchange", "SendApiAsset", response, expected_response_content=_skip_assert681 )682 assert result["Body"] == "hello"683 assert result["ResponseHeaders"]["foo"] == "bar"684 assert result["ResponseHeaders"]["baz"] == "ed"685 headers = result["ResponseMetadata"]["HTTPHeaders"]686 assert "foo" in headers687 assert "baz" in headers688 assert headers["foo"] == "bar"689 assert headers["baz"] == "ed"690def test_restjson_statuscode_target_serialization():691 _botocore_serializer_integration_test(692 "lambda",693 "Invoke",694 {695 "StatusCode": 203,696 "LogResult": "Log Message!",697 "ExecutedVersion": "Latest",698 "Payload": "test payload",699 },700 status_code=203,701 )702def test_restjson_payload_serialization():703 """704 Tests the serialization of specific member attributes as payload, based on an appconfig example:705 "Configuration":{706 "type":"structure",707 "members":{708 "Content":{709 "shape":"Blob",710 },711 "ConfigurationVersion":{712 "shape":"Version",713 "location":"header",714 "locationName":"Configuration-Version"715 },716 "ContentType":{717 "shape":"String",718 "location":"header",719 "locationName":"Content-Type"720 }721 },722 "payload":"Content"723 },724 """725 response = {726 "Content": '{"foo": "bar"}',727 "ConfigurationVersion": "123",728 "ContentType": "application/json",729 }730 result = _botocore_serializer_integration_test(731 "appconfig",732 "GetConfiguration",733 response,734 status_code=200,735 )736 headers = result["ResponseMetadata"]["HTTPHeaders"]737 assert "configuration-version" in headers738 assert headers["configuration-version"] == "123"739 assert headers["content-type"] == "application/json"740def test_restjson_none_serialization():741 parameters = {742 "FunctionName": "test-name",743 "VpcConfig": {"SubnetIds": None, "SecurityGroupIds": [None], "VpcId": "123"},744 "TracingConfig": None,745 "DeadLetterConfig": {},746 }747 expected = {748 "FunctionName": "test-name",749 "VpcConfig": {"SecurityGroupIds": [], "VpcId": "123"},750 "DeadLetterConfig": {},751 }752 _botocore_serializer_integration_test(753 "lambda", "CreateFunction", parameters, status_code=201, expected_response_content=expected754 )755 exception = CommonServiceException("CodeVerificationFailedException", None)756 _botocore_error_serializer_integration_test(757 "lambda",758 "CreateFunction",759 exception,760 "CodeVerificationFailedException",761 400,762 "",763 )764def test_restxml_none_serialization():765 # Structure = None766 _botocore_serializer_integration_test(767 "route53", "ListHostedZonesByName", {}, expected_response_content={}768 )769 # Structure Value = None770 parameters = {"HostedZones": None}771 _botocore_serializer_integration_test(772 "route53", "ListHostedZonesByName", parameters, expected_response_content={}773 )774 # List Value = None775 parameters = {"HostedZones": [None]}776 expected = {"HostedZones": []}777 _botocore_serializer_integration_test(778 "route53", "ListHostedZonesByName", parameters, expected_response_content=expected779 )780 # Exception without a message781 exception = CommonServiceException("NoSuchKeySigningKey", None)782 _botocore_error_serializer_integration_test(783 "route53",784 "DeleteKeySigningKey",785 exception,786 "NoSuchKeySigningKey",787 400,788 "",789 )790def test_restjson_int_header_serialization():791 response = {792 "Configuration": '{"foo": "bar"}',793 "ContentType": "application/json",794 "NextPollConfigurationToken": "abcdefg",795 "NextPollIntervalInSeconds": 42,796 }797 _botocore_serializer_integration_test("appconfigdata", "GetLatestConfiguration", response)798def test_ec2_serializer_ec2_with_botocore():799 parameters = {800 "InstanceEventWindow": {801 "InstanceEventWindowId": "string",802 "TimeRanges": [803 {804 "StartWeekDay": "sunday",805 "StartHour": 123,806 "EndWeekDay": "sunday",807 "EndHour": 123,808 },809 ],810 "Name": "string",811 "CronExpression": "string",812 "AssociationTarget": {813 "InstanceIds": [814 "string",815 ],816 "Tags": [817 {"Key": "string", "Value": "string"},818 ],819 "DedicatedHostIds": [820 "string",821 ],822 },823 "State": "creating",824 "Tags": [825 {"Key": "string", "Value": "string"},826 ],827 }828 }829 _botocore_serializer_integration_test("ec2", "CreateInstanceEventWindow", parameters)830def test_ec2_serializer_ec2_with_empty_response():831 _botocore_serializer_integration_test("ec2", "CreateTags", {})832def test_ec2_protocol_custom_error_serialization():833 exception = CommonServiceException(834 "IdempotentParameterMismatch", "Different payload, same token?!"835 )836 _botocore_error_serializer_integration_test(837 "ec2",838 "StartInstances",839 exception,840 "IdempotentParameterMismatch",841 400,842 "Different payload, same token?!",843 )844def test_restxml_without_output_shape():845 _botocore_serializer_integration_test("cloudfront", "DeleteDistribution", {}, status_code=204)846def test_restxml_header_location():847 """Tests fields with the location trait "header" for rest-xml."""848 _botocore_serializer_integration_test(849 "cloudfront",850 "CreateCloudFrontOriginAccessIdentity",851 {852 "Location": "location-header-field",853 "ETag": "location-etag-field",854 "CloudFrontOriginAccessIdentity": {},855 },856 status_code=201,857 )858 # Test a boolean header location field859 parameters = {860 "ContentLength": 0,861 "Body": "",862 "DeleteMarker": True,863 "ContentType": "string",864 "Metadata": {"string": "string"},865 }866 _botocore_serializer_integration_test("s3", "GetObject", parameters)867def test_restxml_headers_location():868 """Tests fields with the location trait "headers" for rest-xml."""869 _botocore_serializer_integration_test(870 "s3",871 "HeadObject",872 {873 "DeleteMarker": False,874 "Metadata": {"headers_key1": "headers_value1", "headers_key2": "headers_value2"},875 "ContentType": "application/octet-stream",876 # The content length should explicitly be tested here.877 "ContentLength": 159,878 },879 )880def test_restjson_header_location():881 """Tests fields with the location trait "header" for rest-xml."""882 _botocore_serializer_integration_test(883 "ebs", "GetSnapshotBlock", {"BlockData": "binary-data", "DataLength": 15}884 )885def test_restjson_headers_location():886 """Tests fields with the location trait "headers" for rest-json."""887 response = _botocore_serializer_integration_test(888 "dataexchange",889 "SendApiAsset",890 {891 "ResponseHeaders": {"headers_key1": "headers_value1", "headers_key2": "headers_value2"},892 },893 expected_response_content=_skip_assert,894 )895 # The spec does not define a locationName for ResponseHeaders, which means there is no header field prefix.896 # Therefore, _all_ header fields are parsed by botocore (which is technically correct).897 # We only check if the two header fields are present.898 assert "ResponseHeaders" in response899 assert "headers_key1" in response["ResponseHeaders"]900 assert "headers_key2" in response["ResponseHeaders"]901 assert "headers_value1" == response["ResponseHeaders"]["headers_key1"]902 assert "headers_value2" == response["ResponseHeaders"]["headers_key2"]903def test_all_non_existing_key():904 """Tests the different protocols to allow non-existing keys in strucutres / dicts."""905 # query906 _botocore_serializer_integration_test(907 "cloudformation",908 "DetectStackResourceDrift",909 {910 "StackResourceDrift": {911 "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",912 "unknown": {"foo": "bar"},913 }914 },915 expected_response_content={916 "StackResourceDrift": {917 "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",918 }919 },920 )921 # ec2922 _botocore_serializer_integration_test(923 "ec2",924 "CreateInstanceEventWindow",925 {926 "InstanceEventWindow": {927 "InstanceEventWindowId": "string",928 "unknown": {"foo": "bar"},929 },930 "unknown": {"foo": "bar"},931 },932 expected_response_content={933 "InstanceEventWindow": {934 "InstanceEventWindowId": "string",935 }936 },937 )938 # json939 _botocore_serializer_integration_test(940 "cognito-idp",941 "DescribeUserPool",942 {943 "UserPool": {944 "Id": "string",945 "Unknown": "Ignored",946 }947 },948 expected_response_content={949 "UserPool": {950 "Id": "string",951 }952 },953 )954 # rest-json955 _botocore_serializer_integration_test(956 "xray",957 "UpdateSamplingRule",958 {959 "SamplingRuleRecord": {960 "SamplingRule": {961 "ResourceARN": "123456789001234567890",962 "Unknown": "Ignored",963 },964 }965 },966 expected_response_content={967 "SamplingRuleRecord": {968 "SamplingRule": {969 "ResourceARN": "123456789001234567890",970 },971 }972 },973 )974 # rest-xml975 _botocore_serializer_integration_test(976 "cloudfront",977 "TestFunction",978 {979 "TestResult": {980 "FunctionErrorMessage": "string",981 },982 "Unknown": "Ignored",983 },984 expected_response_content={985 "TestResult": {986 "FunctionErrorMessage": "string",987 },988 },989 )...
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!!