diff --git a/Makefile b/Makefile index 2fc6aea96..0df12ac17 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ ifeq ($(TEST_SERVER_MODE), true) # exclude test_kinesisvideoarchivedmedia # because testing with moto_server is difficult with data-endpoint - TEST_EXCLUDE := --exclude='test_iot.*' --exclude="test_kinesisvideoarchivedmedia.*" + TEST_EXCLUDE := -k 'not (test_iot or test_kinesisvideoarchivedmedia)' else TEST_EXCLUDE := endif @@ -23,13 +23,13 @@ lint: test-only: rm -f .coverage rm -rf cover - @nosetests -sv --with-coverage --cover-html ./tests/ $(TEST_EXCLUDE) + @pytest -sv --cov=moto --cov-report html ./tests/ $(TEST_EXCLUDE) test: lint test-only test_server: - @TEST_SERVER_MODE=true nosetests -sv --with-coverage --cover-html ./tests/ + @TEST_SERVER_MODE=true pytest -sv --cov=moto --cov-report html ./tests/ aws_managed_policies: scripts/update_managed_policies.py diff --git a/requirements-tests.txt b/requirements-tests.txt index c19f35c7d..817c38640 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,4 +1,5 @@ pytest +pytest-cov sure==1.4.11 freezegun parameterized>=0.7.0 diff --git a/setup.cfg b/setup.cfg index 3c6e79cf3..1c247ef3d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,6 @@ [bdist_wheel] universal=1 + +[tool:pytest] +markers = + network: marks tests which require network connection diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py index 4a6c3eea3..c34ddfa72 100644 --- a/tests/test_apigateway/test_apigateway.py +++ b/tests/test_apigateway/test_apigateway.py @@ -96,7 +96,7 @@ def test_create_rest_api_invalid_apikeysource(): description="this is my api", apiKeySource="not a valid api key source", ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") @mock_apigateway @@ -132,7 +132,7 @@ def test_create_rest_api_invalid_endpointconfiguration(): description="this is my api", endpointConfiguration={"types": ["INVALID"]}, ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") @mock_apigateway @@ -196,8 +196,8 @@ def test_create_resource__validate_name(): for name in invalid_names: with pytest.raises(ClientError) as ex: client.create_resource(restApiId=api_id, parentId=root_id, pathPart=name) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Resource's path part only allow a-zA-Z0-9._- and curly braces at the beginning and the end and an optional plus sign before the closing brace." ) # All valid names should go through @@ -1196,8 +1196,8 @@ def test_create_deployment_requires_REST_methods(): with pytest.raises(ClientError) as ex: client.create_deployment(restApiId=api_id, stageName=stage_name)["id"] - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "The REST API doesn't contain any methods" ) @@ -1219,8 +1219,8 @@ def test_create_deployment_requires_REST_method_integrations(): with pytest.raises(ClientError) as ex: client.create_deployment(restApiId=api_id, stageName=stage_name)["id"] - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "No integration defined for method" ) @@ -1277,8 +1277,8 @@ def test_put_integration_response_requires_responseTemplate(): client.put_integration_response( restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal("Invalid request input") + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal("Invalid request input") # Works fine if responseTemplate is defined client.put_integration_response( restApiId=api_id, @@ -1319,8 +1319,8 @@ def test_put_integration_response_with_response_template(): restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal("Invalid request input") + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal("Invalid request input") client.put_integration_response( restApiId=api_id, @@ -1380,8 +1380,8 @@ def test_put_integration_validation(): type=type, uri="http://httpbin.org/robots.txt", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Enumeration value for HttpMethod must be non-empty" ) for type in types_not_requiring_integration_method: @@ -1440,8 +1440,8 @@ def test_put_integration_validation(): uri="arn:aws:apigateway:us-west-2:s3:path/b/k", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Integrations of type 'AWS_PROXY' currently only supports Lambda function and Firehose stream invocations." ) for type in aws_types: @@ -1456,8 +1456,8 @@ def test_put_integration_validation(): uri="arn:aws:apigateway:us-west-2:s3:path/b/k", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("AccessDeniedException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDeniedException") + ex.value.response["Error"]["Message"].should.equal( "Cross-account pass role is not allowed." ) for type in ["AWS"]: @@ -1471,8 +1471,8 @@ def test_put_integration_validation(): uri="arn:aws:apigateway:us-west-2:s3:path/b/k", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Role ARN must be specified for AWS integrations" ) for type in http_types: @@ -1486,8 +1486,8 @@ def test_put_integration_validation(): uri="non-valid-http", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Invalid HTTP endpoint specified for URI" ) for type in aws_types: @@ -1501,8 +1501,8 @@ def test_put_integration_validation(): uri="non-valid-arn", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "Invalid ARN specified in the request" ) for type in aws_types: @@ -1516,8 +1516,8 @@ def test_put_integration_validation(): uri="arn:aws:iam::0000000000:role/service-role/asdf", integrationHttpMethod="POST", ) - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal( "AWS ARN for integration must contain path or action" ) @@ -1635,8 +1635,8 @@ def test_create_domain_names(): with pytest.raises(ClientError) as ex: client.create_domain_name(domainName="") - ex.exception.response["Error"]["Message"].should.equal("No Domain Name specified") - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal("No Domain Name specified") + ex.value.response["Error"]["Code"].should.equal("BadRequestException") @mock_apigateway @@ -1669,10 +1669,10 @@ def test_get_domain_name(): with pytest.raises(ClientError) as ex: client.get_domain_name(domainName=domain_name) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "Invalid Domain Name specified" ) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Code"].should.equal("NotFoundException") # adding a domain name client.create_domain_name(domainName=domain_name) # retrieving the data of added domain name. @@ -1708,10 +1708,10 @@ def test_create_model(): description=description, contentType=content_type, ) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "Invalid Rest API Id specified" ) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Code"].should.equal("NotFoundException") with pytest.raises(ClientError) as ex: client.create_model( @@ -1721,8 +1721,8 @@ def test_create_model(): contentType=content_type, ) - ex.exception.response["Error"]["Message"].should.equal("No Model Name specified") - ex.exception.response["Error"]["Code"].should.equal("BadRequestException") + ex.value.response["Error"]["Message"].should.equal("No Model Name specified") + ex.value.response["Error"]["Code"].should.equal("BadRequestException") @mock_apigateway @@ -1772,10 +1772,10 @@ def test_get_model_by_name(): with pytest.raises(ClientError) as ex: client.get_model(restApiId=dummy_rest_api_id, modelName=model_name) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "Invalid Rest API Id specified" ) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Code"].should.equal("NotFoundException") @mock_apigateway @@ -1786,10 +1786,10 @@ def test_get_model_with_invalid_name(): # test with an invalid model name with pytest.raises(ClientError) as ex: client.get_model(restApiId=rest_api_id, modelName="fake") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "Invalid Model Name specified" ) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Code"].should.equal("NotFoundException") @mock_apigateway @@ -1870,9 +1870,9 @@ def test_create_api_headers(): client.create_api_key(**payload) with pytest.raises(ClientError) as ex: client.create_api_key(**payload) - ex.exception.response["Error"]["Code"].should.equal("ConflictException") + ex.value.response["Error"]["Code"].should.equal("ConflictException") if not settings.TEST_SERVER_MODE: - ex.exception.response["ResponseMetadata"]["HTTPHeaders"].should.equal({}) + ex.value.response["ResponseMetadata"]["HTTPHeaders"].should.equal({}) @mock_apigateway @@ -1941,8 +1941,8 @@ def test_usage_plans(): # # Try to get info about a non existing usage with pytest.raises(ClientError) as ex: client.get_usage_plan(usagePlanId="not_existing") - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Message"].should.equal( "Invalid Usage Plan ID specified" ) @@ -2032,24 +2032,24 @@ def test_usage_plan_keys(): # Try to get info about a non existing api key with pytest.raises(ClientError) as ex: client.get_usage_plan_key(usagePlanId=usage_plan_id, keyId="not_existing_key") - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Message"].should.equal( "Invalid API Key identifier specified" ) # Try to get info about an existing api key that has not jet added to a valid usage plan with pytest.raises(ClientError) as ex: client.get_usage_plan_key(usagePlanId=usage_plan_id, keyId=key_id) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Message"].should.equal( "Invalid Usage Plan ID specified" ) # Try to get info about an existing api key that has not jet added to a valid usage plan with pytest.raises(ClientError) as ex: client.get_usage_plan_key(usagePlanId="not_existing_plan_id", keyId=key_id) - ex.exception.response["Error"]["Code"].should.equal("NotFoundException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("NotFoundException") + ex.value.response["Error"]["Message"].should.equal( "Invalid Usage Plan ID specified" ) diff --git a/tests/test_athena/test_athena.py b/tests/test_athena/test_athena.py index 98e1dc4b9..f667f2316 100644 --- a/tests/test_athena/test_athena.py +++ b/tests/test_athena/test_athena.py @@ -111,8 +111,8 @@ def test_start_query_validate_workgroup(): ResultConfiguration={"OutputLocation": "string"}, WorkGroup="unknown_workgroup", ) - err.exception.response["Error"]["Code"].should.equal("InvalidRequestException") - err.exception.response["Error"]["Message"].should.equal("WorkGroup does not exist") + err.value.response["Error"]["Code"].should.equal("InvalidRequestException") + err.value.response["Error"]["Message"].should.equal("WorkGroup does not exist") @mock_athena diff --git a/tests/test_autoscaling/test_autoscaling.py b/tests/test_autoscaling/test_autoscaling.py index 9e51c4b12..25b9cc063 100644 --- a/tests/test_autoscaling/test_autoscaling.py +++ b/tests/test_autoscaling/test_autoscaling.py @@ -791,9 +791,9 @@ def test_create_autoscaling_group_from_invalid_instance_id(): VPCZoneIdentifier=mocked_networking["subnet1"], NewInstancesProtectedFromScaleIn=False, ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Code"].should.equal("ValidationError") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.equal( "Instance [{0}] is invalid.".format(invalid_instance_id) ) @@ -842,7 +842,7 @@ def test_create_autoscaling_group_no_template_ref(): )["LaunchTemplate"] client = boto3.client("autoscaling", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_auto_scaling_group( AutoScalingGroupName="test_asg", LaunchTemplate={"Version": str(template["LatestVersionNumber"])}, @@ -852,9 +852,9 @@ def test_create_autoscaling_group_no_template_ref(): VPCZoneIdentifier=mocked_networking["subnet1"], NewInstancesProtectedFromScaleIn=False, ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Code"].should.equal("ValidationError") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.equal( "Valid requests must contain either launchTemplateId or LaunchTemplateName" ) @@ -874,7 +874,7 @@ def test_create_autoscaling_group_multiple_template_ref(): )["LaunchTemplate"] client = boto3.client("autoscaling", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_auto_scaling_group( AutoScalingGroupName="test_asg", LaunchTemplate={ @@ -888,9 +888,9 @@ def test_create_autoscaling_group_multiple_template_ref(): VPCZoneIdentifier=mocked_networking["subnet1"], NewInstancesProtectedFromScaleIn=False, ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Code"].should.equal("ValidationError") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.equal( "Valid requests must contain either launchTemplateId or LaunchTemplateName" ) @@ -899,7 +899,7 @@ def test_create_autoscaling_group_multiple_template_ref(): def test_create_autoscaling_group_boto3_no_launch_configuration(): mocked_networking = setup_networking() client = boto3.client("autoscaling", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_auto_scaling_group( AutoScalingGroupName="test_asg", MinSize=0, @@ -908,9 +908,9 @@ def test_create_autoscaling_group_boto3_no_launch_configuration(): VPCZoneIdentifier=mocked_networking["subnet1"], NewInstancesProtectedFromScaleIn=False, ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Code"].should.equal("ValidationError") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.equal( "Valid requests must contain either LaunchTemplate, LaunchConfigurationName, " "InstanceId or MixedInstancesPolicy parameter." ) @@ -934,7 +934,7 @@ def test_create_autoscaling_group_boto3_multiple_launch_configurations(): LaunchConfigurationName="test_launch_configuration" ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_auto_scaling_group( AutoScalingGroupName="test_asg", LaunchConfigurationName="test_launch_configuration", @@ -948,9 +948,9 @@ def test_create_autoscaling_group_boto3_multiple_launch_configurations(): VPCZoneIdentifier=mocked_networking["subnet1"], NewInstancesProtectedFromScaleIn=False, ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Code"].should.equal("ValidationError") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.equal( "Valid requests must contain either LaunchTemplate, LaunchConfigurationName, " "InstanceId or MixedInstancesPolicy parameter." ) diff --git a/tests/test_awslambda/test_awslambda_cloudformation.py b/tests/test_awslambda/test_awslambda_cloudformation.py index f87918328..6d998bfd4 100644 --- a/tests/test_awslambda/test_awslambda_cloudformation.py +++ b/tests/test_awslambda/test_awslambda_cloudformation.py @@ -111,7 +111,7 @@ def test_lambda_can_be_deleted_by_cloudformation(): # Verify function was deleted with pytest.raises(ClientError) as e: lmbda.get_function(FunctionName=created_fn_name) - e.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") + e.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") @mock_cloudformation diff --git a/tests/test_awslambda/test_lambda.py b/tests/test_awslambda/test_lambda.py index 2de95cb3c..071c6fed6 100644 --- a/tests/test_awslambda/test_lambda.py +++ b/tests/test_awslambda/test_lambda.py @@ -1662,7 +1662,7 @@ def test_update_function_s3(): @mock_lambda def test_create_function_with_invalid_arn(): err = create_invalid_lambda("test-iam-role") - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Message"].should.equal( r"1 validation error detected: Value 'test-iam-role' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:(aws[a-zA-Z-]*)?:iam::(\d{12}):role/?[a-zA-Z_0-9+=,.@\-_/]+" ) @@ -1670,7 +1670,7 @@ def test_create_function_with_invalid_arn(): @mock_lambda def test_create_function_with_arn_from_different_account(): err = create_invalid_lambda("arn:aws:iam::000000000000:role/example_role") - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Message"].should.equal( "Cross-account pass role is not allowed." ) @@ -1680,7 +1680,7 @@ def test_create_function_with_unknown_arn(): err = create_invalid_lambda( "arn:aws:iam::" + str(ACCOUNT_ID) + ":role/service-role/unknown_role" ) - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Message"].should.equal( "The role defined for the function cannot be assumed by Lambda." ) diff --git a/tests/test_batch/test_batch.py b/tests/test_batch/test_batch.py index 511042d1f..1d4aa1cf2 100644 --- a/tests/test_batch/test_batch.py +++ b/tests/test_batch/test_batch.py @@ -6,6 +6,7 @@ import boto3 from botocore.exceptions import ClientError import sure # noqa from moto import mock_batch, mock_iam, mock_ec2, mock_ecs, mock_logs +import pytest DEFAULT_REGION = "eu-central-1" @@ -685,6 +686,7 @@ def test_submit_job_by_name(): @mock_ecs @mock_iam @mock_batch +@pytest.mark.network def test_submit_job(): ec2_client, iam_client, ecs_client, logs_client, batch_client = _get_clients() vpc_id, subnet_id, sg_id, iam_arn = _setup(ec2_client, iam_client) @@ -751,6 +753,7 @@ def test_submit_job(): @mock_ecs @mock_iam @mock_batch +@pytest.mark.network def test_list_jobs(): ec2_client, iam_client, ecs_client, logs_client, batch_client = _get_clients() vpc_id, subnet_id, sg_id, iam_arn = _setup(ec2_client, iam_client) diff --git a/tests/test_cloudformation/test_cloudformation_stack_crud.py b/tests/test_cloudformation/test_cloudformation_stack_crud.py index 6baae83bc..40004f805 100644 --- a/tests/test_cloudformation/test_cloudformation_stack_crud.py +++ b/tests/test_cloudformation/test_cloudformation_stack_crud.py @@ -520,7 +520,7 @@ def test_update_stack_when_rolled_back(): with pytest.raises(BotoServerError) as err: conn.update_stack("test_stack", dummy_template_json) - ex = err.exception + ex = err.value ex.body.should.match(r"is in ROLLBACK_COMPLETE state and can not be updated") ex.error_code.should.equal("ValidationError") ex.reason.should.equal("Bad Request") diff --git a/tests/test_cloudwatch/test_cloudwatch_boto3.py b/tests/test_cloudwatch/test_cloudwatch_boto3.py index c62f31459..d448b0c58 100644 --- a/tests/test_cloudwatch/test_cloudwatch_boto3.py +++ b/tests/test_cloudwatch/test_cloudwatch_boto3.py @@ -113,7 +113,7 @@ def test_delete_invalid_alarm(): # trying to delete an alarm which is not created along with valid alarm. with pytest.raises(ClientError) as e: cloudwatch.delete_alarms(AlarmNames=["InvalidAlarmName", "testalarm1"]) - e.exception.response["Error"]["Code"].should.equal("ResourceNotFound") + e.value.response["Error"]["Code"].should.equal("ResourceNotFound") resp = cloudwatch.describe_alarms(AlarmNames=["testalarm1"]) # making sure other alarms are not deleted in case of an error. @@ -122,7 +122,7 @@ def test_delete_invalid_alarm(): # test to check if the error raises if only one invalid alarm is tried to delete. with pytest.raises(ClientError) as e: cloudwatch.delete_alarms(AlarmNames=["InvalidAlarmName"]) - e.exception.response["Error"]["Code"].should.equal("ResourceNotFound") + e.value.response["Error"]["Code"].should.equal("ResourceNotFound") @mock_cloudwatch @@ -425,7 +425,7 @@ def test_list_metrics_paginated(): # Verify we can't pass a random NextToken with pytest.raises(ClientError) as e: cloudwatch.list_metrics(NextToken=str(uuid4())) - e.exception.response["Error"]["Message"].should.equal( + e.value.response["Error"]["Message"].should.equal( "Request parameter NextToken is invalid" ) # Add a boatload of metrics @@ -454,7 +454,7 @@ def test_list_metrics_paginated(): # Verify that we can't reuse an existing token with pytest.raises(ClientError) as e: cloudwatch.list_metrics(NextToken=first_page["NextToken"]) - e.exception.response["Error"]["Message"].should.equal( + e.value.response["Error"]["Message"].should.equal( "Request parameter NextToken is invalid" ) diff --git a/tests/test_codecommit/test_codecommit.py b/tests/test_codecommit/test_codecommit.py index 7a5867d44..4c38252ff 100644 --- a/tests/test_codecommit/test_codecommit.py +++ b/tests/test_codecommit/test_codecommit.py @@ -86,7 +86,7 @@ def test_create_repository_repository_name_exists(): repositoryName="repository_two", repositoryDescription="description repo two", ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateRepository") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("RepositoryNameExistsException") @@ -101,7 +101,7 @@ def test_create_repository_invalid_repository_name(): with pytest.raises(ClientError) as e: client.create_repository(repositoryName="in_123_valid_@#$_characters") - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateRepository") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidRepositoryNameException") @@ -158,7 +158,7 @@ def test_get_repository(): with pytest.raises(ClientError) as e: client.get_repository(repositoryName=repository_name) - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetRepository") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("RepositoryDoesNotExistException") @@ -173,7 +173,7 @@ def test_get_repository_invalid_repository_name(): with pytest.raises(ClientError) as e: client.get_repository(repositoryName="repository_one-@#@") - ex = e.exception + ex = e.value ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidRepositoryNameException") ex.response["Error"]["Message"].should.equal( @@ -209,7 +209,7 @@ def test_delete_repository_invalid_repository_name(): with pytest.raises(ClientError) as e: client.delete_repository(repositoryName="_rep@ository_one") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeleteRepository") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidRepositoryNameException") diff --git a/tests/test_codepipeline/test_codepipeline.py b/tests/test_codepipeline/test_codepipeline.py index ac72f9981..ca1094582 100644 --- a/tests/test_codepipeline/test_codepipeline.py +++ b/tests/test_codepipeline/test_codepipeline.py @@ -79,7 +79,7 @@ def test_create_pipeline_errors(): with pytest.raises(ClientError) as e: create_basic_codepipeline(client, "test-pipeline") - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreatePipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidStructureException") @@ -115,7 +115,7 @@ def test_create_pipeline_errors(): ], } ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreatePipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidStructureException") @@ -167,7 +167,7 @@ def test_create_pipeline_errors(): ], } ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreatePipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidStructureException") @@ -203,7 +203,7 @@ def test_create_pipeline_errors(): ], } ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreatePipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidStructureException") @@ -284,7 +284,7 @@ def test_get_pipeline_errors(): with pytest.raises(ClientError) as e: client.get_pipeline(name="not-existing") - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetPipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("PipelineNotFoundException") @@ -456,7 +456,7 @@ def test_update_pipeline_errors(): ], } ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("UpdatePipeline") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -521,7 +521,7 @@ def test_list_tags_for_resource_errors(): client.list_tags_for_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListTagsForResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -560,7 +560,7 @@ def test_tag_resource_errors(): resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing", tags=[{"key": "key-2", "value": "value-2"}], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("TagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -573,7 +573,7 @@ def test_tag_resource_errors(): resourceArn="arn:aws:codepipeline:us-east-1:123456789012:{}".format(name), tags=[{"key": "aws:key", "value": "value"}], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("TagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidTagsException") @@ -591,7 +591,7 @@ def test_tag_resource_errors(): for i in range(50) ], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("TagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("TooManyTagsException") @@ -639,7 +639,7 @@ def test_untag_resource_errors(): resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing", tagKeys=["key"], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("UntagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") diff --git a/tests/test_cognitoidentity/test_cognitoidentity.py b/tests/test_cognitoidentity/test_cognitoidentity.py index a15903329..cfe673cdf 100644 --- a/tests/test_cognitoidentity/test_cognitoidentity.py +++ b/tests/test_cognitoidentity/test_cognitoidentity.py @@ -78,9 +78,9 @@ def test_describe_identity_pool_with_invalid_id_raises_error(): with pytest.raises(ClientError) as cm: conn.describe_identity_pool(IdentityPoolId="us-west-2_non-existent") - cm.exception.operation_name.should.equal("DescribeIdentityPool") - cm.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.operation_name.should.equal("DescribeIdentityPool") + cm.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # testing a helper function diff --git a/tests/test_cognitoidp/test_cognitoidp.py b/tests/test_cognitoidp/test_cognitoidp.py index bbd8d5a39..54ee9528f 100644 --- a/tests/test_cognitoidp/test_cognitoidp.py +++ b/tests/test_cognitoidp/test_cognitoidp.py @@ -608,9 +608,9 @@ def test_update_identity_provider_no_user_pool(): UserPoolId="foo", ProviderName="bar", ProviderDetails={"thing": new_value} ) - cm.exception.operation_name.should.equal("UpdateIdentityProvider") - cm.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.operation_name.should.equal("UpdateIdentityProvider") + cm.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_cognitoidp @@ -630,9 +630,9 @@ def test_update_identity_provider_no_identity_provider(): ProviderDetails={"thing": new_value}, ) - cm.exception.operation_name.should.equal("UpdateIdentityProvider") - cm.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.operation_name.should.equal("UpdateIdentityProvider") + cm.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_cognitoidp @@ -701,9 +701,9 @@ def test_create_group_with_duplicate_name_raises_error(): with pytest.raises(ClientError) as cm: conn.create_group(GroupName=group_name, UserPoolId=user_pool_id) - cm.exception.operation_name.should.equal("CreateGroup") - cm.exception.response["Error"]["Code"].should.equal("GroupExistsException") - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.operation_name.should.equal("CreateGroup") + cm.value.response["Error"]["Code"].should.equal("GroupExistsException") + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_cognitoidp @@ -749,7 +749,7 @@ def test_delete_group(): with pytest.raises(ClientError) as cm: conn.get_group(GroupName=group_name, UserPoolId=user_pool_id) - cm.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") + cm.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") @mock_cognitoidp @@ -1570,12 +1570,12 @@ def test_resource_server(): UserPoolId=user_pool_id, Identifier=identifier, Name=name, Scopes=scopes ) - ex.exception.operation_name.should.equal("CreateResourceServer") - ex.exception.response["Error"]["Code"].should.equal("InvalidParameterException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.operation_name.should.equal("CreateResourceServer") + ex.value.response["Error"]["Code"].should.equal("InvalidParameterException") + ex.value.response["Error"]["Message"].should.equal( "%s already exists in user pool %s." % (identifier, user_pool_id) ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_cognitoidp diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index 716792863..a99efceae 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -23,20 +23,20 @@ def test_put_configuration_recorder(): with pytest.raises(ClientError) as ce: client.put_configuration_recorder(ConfigurationRecorder={"roleARN": "somearn"}) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "InvalidConfigurationRecorderNameException" ) - assert "is not valid, blank string." in ce.exception.response["Error"]["Message"] + assert "is not valid, blank string." in ce.value.response["Error"]["Message"] # Try with a really long name: with pytest.raises(ClientError) as ce: client.put_configuration_recorder( ConfigurationRecorder={"name": "a" * 257, "roleARN": "somearn"} ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" assert ( "Member must have length less than or equal to 256" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With resource types and flags set to True: @@ -77,10 +77,10 @@ def test_put_configuration_recorder(): } ) assert ( - ce.exception.response["Error"]["Code"] == "InvalidRecordingGroupException" + ce.value.response["Error"]["Code"] == "InvalidRecordingGroupException" ) assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "The recording group provided is not valid" ) @@ -103,11 +103,11 @@ def test_put_configuration_recorder(): }, } ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" assert "2 validation error detected: Value '['LOLNO', 'LOLSTILLNO']" in str( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] ) - assert "AWS::EC2::Instance" in ce.exception.response["Error"]["Message"] + assert "AWS::EC2::Instance" in ce.value.response["Error"]["Message"] # Create a proper one: client.put_configuration_recorder( @@ -178,12 +178,12 @@ def test_put_configuration_recorder(): } ) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "MaxNumberOfConfigurationRecordersExceededException" ) assert ( "maximum number of configuration recorders: 1 is reached." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) @@ -208,9 +208,9 @@ def test_put_configuration_aggregator(): ) assert ( "Member must have length less than or equal to 1" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # With an invalid region config (no regions defined): with pytest.raises(ClientError) as ce: @@ -225,9 +225,9 @@ def test_put_configuration_aggregator(): ) assert ( "Your request does not specify any regions" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( @@ -238,9 +238,9 @@ def test_put_configuration_aggregator(): ) assert ( "Your request does not specify any regions" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" # With both region flags defined: with pytest.raises(ClientError) as ce: @@ -256,9 +256,9 @@ def test_put_configuration_aggregator(): ) assert ( "You must choose one of these options" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( @@ -271,9 +271,9 @@ def test_put_configuration_aggregator(): ) assert ( "You must choose one of these options" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" # Name too long: with pytest.raises(ClientError) as ce: @@ -283,8 +283,8 @@ def test_put_configuration_aggregator(): {"AccountIds": ["012345678910"], "AllAwsRegions": True} ], ) - assert "configurationAggregatorName" in ce.exception.response["Error"]["Message"] - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert "configurationAggregatorName" in ce.value.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "ValidationException" # Too many tags (>50): with pytest.raises(ClientError) as ce: @@ -299,9 +299,9 @@ def test_put_configuration_aggregator(): ) assert ( "Member must have length less than or equal to 50" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Tag key is too big (>128 chars): with pytest.raises(ClientError) as ce: @@ -314,9 +314,9 @@ def test_put_configuration_aggregator(): ) assert ( "Member must have length less than or equal to 128" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Tag value is too big (>256 chars): with pytest.raises(ClientError) as ce: @@ -329,9 +329,9 @@ def test_put_configuration_aggregator(): ) assert ( "Member must have length less than or equal to 256" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Duplicate Tags: with pytest.raises(ClientError) as ce: @@ -342,8 +342,8 @@ def test_put_configuration_aggregator(): ], Tags=[{"Key": "a", "Value": "a"}, {"Key": "a", "Value": "a"}], ) - assert "Duplicate tag keys found." in ce.exception.response["Error"]["Message"] - assert ce.exception.response["Error"]["Code"] == "InvalidInput" + assert "Duplicate tag keys found." in ce.value.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "InvalidInput" # Invalid characters in the tag key: with pytest.raises(ClientError) as ce: @@ -356,9 +356,9 @@ def test_put_configuration_aggregator(): ) assert ( "Member must satisfy regular expression pattern:" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # If it contains both the AccountAggregationSources and the OrganizationAggregationSource with pytest.raises(ClientError) as ce: @@ -374,18 +374,18 @@ def test_put_configuration_aggregator(): ) assert ( "AccountAggregationSource and the OrganizationAggregationSource" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" # If it contains neither: with pytest.raises(ClientError) as ce: client.put_configuration_aggregator(ConfigurationAggregatorName="testing") assert ( "AccountAggregationSource or the OrganizationAggregationSource" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" # Just make one: account_aggregation_source = { @@ -472,10 +472,10 @@ def test_describe_configuration_aggregators(): ) assert ( "The configuration aggregator does not exist." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoSuchConfigurationAggregatorException" ) @@ -486,10 +486,10 @@ def test_describe_configuration_aggregators(): ) assert ( "At least one of the configuration aggregators does not exist." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoSuchConfigurationAggregatorException" ) @@ -554,9 +554,9 @@ def test_describe_configuration_aggregators(): with pytest.raises(ClientError) as ce: client.describe_configuration_aggregators(NextToken="WRONG") assert ( - "The nextToken provided is invalid" == ce.exception.response["Error"]["Message"] + "The nextToken provided is invalid" == ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidNextTokenException" + assert ce.value.response["Error"]["Code"] == "InvalidNextTokenException" @mock_config @@ -574,9 +574,9 @@ def test_put_aggregation_authorization(): ) assert ( "Member must have length less than or equal to 50" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Tag key is too big (>128 chars): with pytest.raises(ClientError) as ce: @@ -587,9 +587,9 @@ def test_put_aggregation_authorization(): ) assert ( "Member must have length less than or equal to 128" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Tag value is too big (>256 chars): with pytest.raises(ClientError) as ce: @@ -600,9 +600,9 @@ def test_put_aggregation_authorization(): ) assert ( "Member must have length less than or equal to 256" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Duplicate Tags: with pytest.raises(ClientError) as ce: @@ -611,8 +611,8 @@ def test_put_aggregation_authorization(): AuthorizedAwsRegion="us-west-2", Tags=[{"Key": "a", "Value": "a"}, {"Key": "a", "Value": "a"}], ) - assert "Duplicate tag keys found." in ce.exception.response["Error"]["Message"] - assert ce.exception.response["Error"]["Code"] == "InvalidInput" + assert "Duplicate tag keys found." in ce.value.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "InvalidInput" # Invalid characters in the tag key: with pytest.raises(ClientError) as ce: @@ -623,9 +623,9 @@ def test_put_aggregation_authorization(): ) assert ( "Member must satisfy regular expression pattern:" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" # Put a normal one there: result = client.put_aggregation_authorization( @@ -711,9 +711,9 @@ def test_describe_aggregation_authorizations(): with pytest.raises(ClientError) as ce: client.describe_aggregation_authorizations(NextToken="WRONG") assert ( - "The nextToken provided is invalid" == ce.exception.response["Error"]["Message"] + "The nextToken provided is invalid" == ce.value.response["Error"]["Message"] ) - assert ce.exception.response["Error"]["Code"] == "InvalidNextTokenException" + assert ce.value.response["Error"]["Code"] == "InvalidNextTokenException" @mock_config @@ -755,10 +755,10 @@ def test_delete_configuration_aggregator(): client.delete_configuration_aggregator(ConfigurationAggregatorName="testing") assert ( "The configuration aggregator does not exist." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoSuchConfigurationAggregatorException" ) @@ -799,9 +799,9 @@ def test_describe_configurations(): with pytest.raises(ClientError) as ce: client.describe_configuration_recorders(ConfigurationRecorderNames=["wrong"]) assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) - assert "wrong" in ce.exception.response["Error"]["Message"] + assert "wrong" in ce.value.response["Error"]["Message"] # And with both a good and wrong name: with pytest.raises(ClientError) as ce: @@ -809,9 +809,9 @@ def test_describe_configurations(): ConfigurationRecorderNames=["testrecorder", "wrong"] ) assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) - assert "wrong" in ce.exception.response["Error"]["Message"] + assert "wrong" in ce.value.response["Error"]["Message"] @mock_config @@ -822,11 +822,11 @@ def test_delivery_channels(): with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={}) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoAvailableConfigurationRecorderException" ) assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "Configuration recorder is not available to " "put delivery channel." ) @@ -848,25 +848,25 @@ def test_delivery_channels(): with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={}) assert ( - ce.exception.response["Error"]["Code"] == "InvalidDeliveryChannelNameException" + ce.value.response["Error"]["Code"] == "InvalidDeliveryChannelNameException" ) - assert "is not valid, blank string." in ce.exception.response["Error"]["Message"] + assert "is not valid, blank string." in ce.value.response["Error"]["Message"] # Try with a really long name: with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={"name": "a" * 257}) - assert ce.exception.response["Error"]["Code"] == "ValidationException" + assert ce.value.response["Error"]["Code"] == "ValidationException" assert ( "Member must have length less than or equal to 256" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Without specifying a bucket name: with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={"name": "testchannel"}) - assert ce.exception.response["Error"]["Code"] == "NoSuchBucketException" + assert ce.value.response["Error"]["Code"] == "NoSuchBucketException" assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "Cannot find a S3 bucket with an empty bucket name." ) @@ -874,9 +874,9 @@ def test_delivery_channels(): client.put_delivery_channel( DeliveryChannel={"name": "testchannel", "s3BucketName": ""} ) - assert ce.exception.response["Error"]["Code"] == "NoSuchBucketException" + assert ce.value.response["Error"]["Code"] == "NoSuchBucketException" assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "Cannot find a S3 bucket with an empty bucket name." ) @@ -889,8 +889,8 @@ def test_delivery_channels(): "s3KeyPrefix": "", } ) - assert ce.exception.response["Error"]["Code"] == "InvalidS3KeyPrefixException" - assert "empty s3 key prefix." in ce.exception.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "InvalidS3KeyPrefixException" + assert "empty s3 key prefix." in ce.value.response["Error"]["Message"] # With an empty string for the SNS ARN: with pytest.raises(ClientError) as ce: @@ -901,8 +901,8 @@ def test_delivery_channels(): "snsTopicARN": "", } ) - assert ce.exception.response["Error"]["Code"] == "InvalidSNSTopicARNException" - assert "The sns topic arn" in ce.exception.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "InvalidSNSTopicARNException" + assert "The sns topic arn" in ce.value.response["Error"]["Message"] # With an invalid delivery frequency: with pytest.raises(ClientError) as ce: @@ -913,9 +913,9 @@ def test_delivery_channels(): "configSnapshotDeliveryProperties": {"deliveryFrequency": "WRONG"}, } ) - assert ce.exception.response["Error"]["Code"] == "InvalidDeliveryFrequency" - assert "WRONG" in ce.exception.response["Error"]["Message"] - assert "TwentyFour_Hours" in ce.exception.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "InvalidDeliveryFrequency" + assert "WRONG" in ce.value.response["Error"]["Message"] + assert "TwentyFour_Hours" in ce.value.response["Error"]["Message"] # Create a proper one: client.put_delivery_channel( @@ -955,12 +955,12 @@ def test_delivery_channels(): DeliveryChannel={"name": "testchannel2", "s3BucketName": "somebucket"} ) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "MaxNumberOfDeliveryChannelsExceededException" ) assert ( "because the maximum number of delivery channels: 1 is reached." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) @@ -1017,14 +1017,14 @@ def test_describe_delivery_channels(): # Specify an incorrect name: with pytest.raises(ClientError) as ce: client.describe_delivery_channels(DeliveryChannelNames=["wrong"]) - assert ce.exception.response["Error"]["Code"] == "NoSuchDeliveryChannelException" - assert "wrong" in ce.exception.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "NoSuchDeliveryChannelException" + assert "wrong" in ce.value.response["Error"]["Message"] # And with both a good and wrong name: with pytest.raises(ClientError) as ce: client.describe_delivery_channels(DeliveryChannelNames=["testchannel", "wrong"]) - assert ce.exception.response["Error"]["Code"] == "NoSuchDeliveryChannelException" - assert "wrong" in ce.exception.response["Error"]["Message"] + assert ce.value.response["Error"]["Code"] == "NoSuchDeliveryChannelException" + assert "wrong" in ce.value.response["Error"]["Message"] @mock_config @@ -1035,7 +1035,7 @@ def test_start_configuration_recorder(): with pytest.raises(ClientError) as ce: client.start_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) # Make the config recorder; @@ -1055,7 +1055,7 @@ def test_start_configuration_recorder(): with pytest.raises(ClientError) as ce: client.start_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( - ce.exception.response["Error"]["Code"] == "NoAvailableDeliveryChannelException" + ce.value.response["Error"]["Code"] == "NoAvailableDeliveryChannelException" ) # Make the delivery channel: @@ -1093,7 +1093,7 @@ def test_stop_configuration_recorder(): with pytest.raises(ClientError) as ce: client.stop_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) # Make the config recorder; @@ -1185,9 +1185,9 @@ def test_describe_configuration_recorder_status(): ConfigurationRecorderNames=["testrecorder", "wrong"] ) assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) - assert "wrong" in ce.exception.response["Error"]["Message"] + assert "wrong" in ce.value.response["Error"]["Message"] @mock_config @@ -1214,7 +1214,7 @@ def test_delete_configuration_recorder(): with pytest.raises(ClientError) as ce: client.delete_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( - ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" + ce.value.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" ) @@ -1243,12 +1243,12 @@ def test_delete_delivery_channel(): with pytest.raises(ClientError) as ce: client.delete_delivery_channel(DeliveryChannelName="testchannel") assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "LastDeliveryChannelDeleteFailedException" ) assert ( "because there is a running configuration recorder." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Stop recording: @@ -1260,7 +1260,7 @@ def test_delete_delivery_channel(): # Verify: with pytest.raises(ClientError) as ce: client.delete_delivery_channel(DeliveryChannelName="testchannel") - assert ce.exception.response["Error"]["Code"] == "NoSuchDeliveryChannelException" + assert ce.value.response["Error"]["Code"] == "NoSuchDeliveryChannelException" @mock_config @@ -1343,7 +1343,7 @@ def test_list_discovered_resource(): # Test with an invalid page num > 100: with pytest.raises(ClientError) as ce: client.list_discovered_resources(resourceType="AWS::S3::Bucket", limit=101) - assert "101" in ce.exception.response["Error"]["Message"] + assert "101" in ce.value.response["Error"]["Message"] # Test by supplying both resourceName and also resourceIds: with pytest.raises(ClientError) as ce: @@ -1354,7 +1354,7 @@ def test_list_discovered_resource(): ) assert ( "Both Resource ID and Resource Name cannot be specified in the request" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # More than 20 resourceIds: @@ -1365,7 +1365,7 @@ def test_list_discovered_resource(): ) assert ( "The specified list had more than 20 resource ID's." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) @@ -1384,7 +1384,7 @@ def test_list_aggregate_discovered_resource(): ) assert ( "The configuration aggregator does not exist" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Create the aggregator: @@ -1510,7 +1510,7 @@ def test_list_aggregate_discovered_resource(): ResourceType="AWS::S3::Bucket", Limit=101, ) - assert "101" in ce.exception.response["Error"]["Message"] + assert "101" in ce.value.response["Error"]["Message"] @mock_config @@ -1526,7 +1526,7 @@ def test_get_resource_config_history(): client.get_resource_config_history( resourceType="NOT::A::RESOURCE", resourceId="notcreatedyet" ) - assert ce.exception.response["Error"] == { + assert ce.value.response["Error"] == { "Message": "Resource notcreatedyet of resourceType:NOT::A::RESOURCE is unknown or has " "not been discovered", "Code": "ResourceNotDiscoveredException", @@ -1537,7 +1537,7 @@ def test_get_resource_config_history(): client.get_resource_config_history( resourceType="AWS::S3::Bucket", resourceId="notcreatedyet" ) - assert ce.exception.response["Error"] == { + assert ce.value.response["Error"] == { "Message": "Resource notcreatedyet of resourceType:AWS::S3::Bucket is unknown or has " "not been discovered", "Code": "ResourceNotDiscoveredException", @@ -1569,7 +1569,7 @@ def test_get_resource_config_history(): client.get_resource_config_history( resourceType="AWS::S3::Bucket", resourceId="eu-bucket" ) - assert ce.exception.response["Error"]["Code"] == "ResourceNotDiscoveredException" + assert ce.value.response["Error"]["Code"] == "ResourceNotDiscoveredException" @mock_config @@ -1590,7 +1590,7 @@ def test_batch_get_resource_config(): ) assert ( "Member must have length less than or equal to 100" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With invalid resource types and resources that don't exist: @@ -1659,7 +1659,7 @@ def test_batch_get_aggregate_resource_config(): ) assert ( "The configuration aggregator does not exist" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Create the aggregator: @@ -1679,7 +1679,7 @@ def test_batch_get_aggregate_resource_config(): ) assert ( "Member must have length less than or equal to 100" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Create some S3 buckets: @@ -1816,10 +1816,10 @@ def test_put_evaluations(): # Try without Evaluations supplied: with pytest.raises(ClientError) as ce: client.put_evaluations(Evaluations=[], ResultToken="test", TestMode=True) - assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" + assert ce.value.response["Error"]["Code"] == "InvalidParameterValueException" assert ( "The Evaluations object in your request cannot be null" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Try without a ResultToken supplied: @@ -1836,7 +1836,7 @@ def test_put_evaluations(): ResultToken="", TestMode=True, ) - assert ce.exception.response["Error"]["Code"] == "InvalidResultTokenException" + assert ce.value.response["Error"]["Code"] == "InvalidResultTokenException" if os.environ.get("TEST_SERVER_MODE", "false").lower() == "true": raise SkipTest("Does not work in server mode due to error in Workzeug") @@ -1920,7 +1920,7 @@ def test_put_organization_conformance_pack_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutOrganizationConformancePack") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ValidationException") @@ -1935,7 +1935,7 @@ def test_put_organization_conformance_pack_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutOrganizationConformancePack") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ValidationException") @@ -1985,7 +1985,7 @@ def test_describe_organization_conformance_packs_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeOrganizationConformancePacks") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain( @@ -2061,7 +2061,7 @@ def test_describe_organization_conformance_pack_statuses_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeOrganizationConformancePackStatuses") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain( @@ -2133,7 +2133,7 @@ def test_get_organization_conformance_pack_detailed_status_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetOrganizationConformancePackDetailedStatus") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain( @@ -2177,7 +2177,7 @@ def test_delete_organization_conformance_pack_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeleteOrganizationConformancePack") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain( diff --git a/tests/test_core/test_auth.py b/tests/test_core/test_auth.py index 67c3b67a2..b6fc8a135 100644 --- a/tests/test_core/test_auth.py +++ b/tests/test_core/test_auth.py @@ -179,9 +179,9 @@ def test_invalid_client_token_id(): ) with pytest.raises(ClientError) as ex: client.get_user() - ex.exception.response["Error"]["Code"].should.equal("InvalidClientTokenId") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidClientTokenId") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "The security token included in the request is invalid." ) @@ -197,9 +197,9 @@ def test_auth_failure(): ) with pytest.raises(ClientError) as ex: client.describe_instances() - ex.exception.response["Error"]["Code"].should.equal("AuthFailure") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(401) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AuthFailure") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(401) + ex.value.response["Error"]["Message"].should.equal( "AWS was not able to validate the provided access credentials" ) @@ -216,9 +216,9 @@ def test_signature_does_not_match(): ) with pytest.raises(ClientError) as ex: client.get_user() - ex.exception.response["Error"]["Code"].should.equal("SignatureDoesNotMatch") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("SignatureDoesNotMatch") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details." ) @@ -235,9 +235,9 @@ def test_auth_failure_with_valid_access_key_id(): ) with pytest.raises(ClientError) as ex: client.describe_instances() - ex.exception.response["Error"]["Code"].should.equal("AuthFailure") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(401) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AuthFailure") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(401) + ex.value.response["Error"]["Message"].should.equal( "AWS was not able to validate the provided access credentials" ) @@ -255,9 +255,9 @@ def test_access_denied_with_no_policy(): ) with pytest.raises(ClientError) as ex: client.describe_instances() - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:iam::{account_id}:user/{user_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, user_name=user_name, @@ -283,11 +283,11 @@ def test_access_denied_with_not_allowing_policy(): aws_access_key_id=access_key["AccessKeyId"], aws_secret_access_key=access_key["SecretAccessKey"], ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.describe_instances() - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:iam::{account_id}:user/{user_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, user_name=user_name, @@ -321,9 +321,9 @@ def test_access_denied_for_run_instances(): ) with pytest.raises(ClientError) as ex: client.run_instances(MaxCount=1, MinCount=1) - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:iam::{account_id}:user/{user_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, user_name=user_name, operation="ec2:RunInstances", ) @@ -352,9 +352,9 @@ def test_access_denied_with_denying_policy(): ) with pytest.raises(ClientError) as ex: client.create_vpc(CidrBlock="10.0.0.0/16") - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:iam::{account_id}:user/{user_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, user_name=user_name, operation="ec2:CreateVpc" ) @@ -452,9 +452,9 @@ def test_s3_access_denied_with_denying_attached_group_policy(): ) with pytest.raises(ClientError) as ex: client.list_buckets() - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal("Access Denied") + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal("Access Denied") @set_initial_no_auth_action_count(6) @@ -486,9 +486,9 @@ def test_s3_access_denied_with_denying_inline_group_policy(): client.create_bucket(Bucket=bucket_name) with pytest.raises(ClientError) as ex: client.get_object(Bucket=bucket_name, Key="sdfsdf") - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal("Access Denied") + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal("Access Denied") @set_initial_no_auth_action_count(10) @@ -532,9 +532,9 @@ def test_access_denied_with_many_irrelevant_policies(): ) with pytest.raises(ClientError) as ex: client.create_key_pair(KeyName="TestKey") - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:iam::{account_id}:user/{user_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, user_name=user_name, operation="ec2:CreateKeyPair" ) @@ -635,9 +635,9 @@ def test_access_denied_with_temporary_credentials(): DBInstanceClass="db.t3", Engine="aurora-postgresql", ) - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "User: arn:aws:sts::{account_id}:assumed-role/{role_name}/{session_name} is not authorized to perform: {operation}".format( account_id=ACCOUNT_ID, role_name=role_name, @@ -678,9 +678,9 @@ def test_s3_invalid_access_key_id(): ) with pytest.raises(ClientError) as ex: client.list_buckets() - ex.exception.response["Error"]["Code"].should.equal("InvalidAccessKeyId") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidAccessKeyId") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "The AWS Access Key Id you provided does not exist in our records." ) @@ -700,9 +700,9 @@ def test_s3_signature_does_not_match(): client.create_bucket(Bucket=bucket_name) with pytest.raises(ClientError) as ex: client.put_object(Bucket=bucket_name, Key="abc") - ex.exception.response["Error"]["Code"].should.equal("SignatureDoesNotMatch") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("SignatureDoesNotMatch") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal( "The request signature we calculated does not match the signature you provided. Check your key and signing method." ) @@ -736,9 +736,9 @@ def test_s3_access_denied_not_action(): client.create_bucket(Bucket=bucket_name) with pytest.raises(ClientError) as ex: client.delete_object(Bucket=bucket_name, Key="sdfsdf") - ex.exception.response["Error"]["Code"].should.equal("AccessDenied") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) - ex.exception.response["Error"]["Message"].should.equal("Access Denied") + ex.value.response["Error"]["Code"].should.equal("AccessDenied") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) + ex.value.response["Error"]["Message"].should.equal("Access Denied") @set_initial_no_auth_action_count(4) @@ -776,8 +776,8 @@ def test_s3_invalid_token_with_temporary_credentials(): client.create_bucket(Bucket=bucket_name) with pytest.raises(ClientError) as ex: client.list_bucket_metrics_configurations(Bucket=bucket_name) - ex.exception.response["Error"]["Code"].should.equal("InvalidToken") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidToken") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "The provided token is malformed or otherwise invalid." ) diff --git a/tests/test_core/test_decorator_calls.py b/tests/test_core/test_decorator_calls.py index 5e04f075c..c57d62485 100644 --- a/tests/test_core/test_decorator_calls.py +++ b/tests/test_core/test_decorator_calls.py @@ -24,6 +24,7 @@ def test_basic_decorator(): list(conn.get_all_instances()).should.equal([]) +@pytest.mark.network def test_context_manager(): conn = boto.connect_ec2("the_key", "the_secret") with pytest.raises(EC2ResponseError): @@ -38,6 +39,7 @@ def test_context_manager(): conn.get_all_instances() +@pytest.mark.network def test_decorator_start_and_stop(): conn = boto.connect_ec2("the_key", "the_secret") with pytest.raises(EC2ResponseError): diff --git a/tests/test_core/test_request_mocking.py b/tests/test_core/test_request_mocking.py index 2c44d52ce..3c56c7242 100644 --- a/tests/test_core/test_request_mocking.py +++ b/tests/test_core/test_request_mocking.py @@ -1,4 +1,5 @@ import requests +import pytest import sure # noqa import boto3 @@ -6,6 +7,7 @@ from moto import mock_sqs, settings @mock_sqs +@pytest.mark.network def test_passthrough_requests(): conn = boto3.client("sqs", region_name="us-west-1") conn.create_queue(QueueName="queue1") diff --git a/tests/test_datasync/test_datasync.py b/tests/test_datasync/test_datasync.py index d8d919f13..2214032c9 100644 --- a/tests/test_datasync/test_datasync.py +++ b/tests/test_datasync/test_datasync.py @@ -139,7 +139,7 @@ def test_delete_location(): response = client.list_locations() assert len(response["Locations"]) == 0 - with assert_raises(ClientError) as e: + with pytest.raises(ClientError): response = client.delete_location(LocationArn=location_arn) @@ -262,7 +262,7 @@ def test_update_task(): assert response["Name"] == updated_name assert response["Options"] == updated_options - with assert_raises(ClientError) as e: + with pytest.raises(ClientError): client.update_task(TaskArn="doesnt_exist") @@ -286,7 +286,7 @@ def test_delete_task(): response = client.list_tasks() assert len(response["Tasks"]) == 0 - with assert_raises(ClientError) as e: + with pytest.raises(ClientError): response = client.delete_task(TaskArn=task_arn) diff --git a/tests/test_dynamodb2/test_dynamodb.py b/tests/test_dynamodb2/test_dynamodb.py index 6704bbcc7..04b231773 100644 --- a/tests/test_dynamodb2/test_dynamodb.py +++ b/tests/test_dynamodb2/test_dynamodb.py @@ -213,9 +213,9 @@ def test_item_add_empty_string_exception(): }, ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: An AttributeValue may not contain an empty string" ) @@ -256,9 +256,9 @@ def test_update_item_with_empty_string_exception(): ExpressionAttributeValues={":Body": {"S": ""}}, ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: An AttributeValue may not contain an empty string" ) @@ -1356,10 +1356,10 @@ def test_put_empty_item(): with pytest.raises(ClientError) as ex: table.put_item(Item={}) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key structure_id in the item" ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") @mock_dynamodb2 @@ -1375,10 +1375,10 @@ def test_put_item_nonexisting_hash_key(): with pytest.raises(ClientError) as ex: table.put_item(Item={"a_terribly_misguided_id_attribute": "abcdef"}) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key structure_id in the item" ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") @mock_dynamodb2 @@ -1400,10 +1400,10 @@ def test_put_item_nonexisting_range_key(): with pytest.raises(ClientError) as ex: table.put_item(Item={"structure_id": "abcdef"}) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key added_at in the item" ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") def test_filter_expression(): @@ -2089,7 +2089,7 @@ def test_describe_continuous_backups_errors(): client.describe_continuous_backups(TableName="not-existing-table") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeContinuousBackups") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("TableNotFoundException") @@ -2178,7 +2178,7 @@ def test_update_continuous_backups_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("UpdateContinuousBackups") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("TableNotFoundException") @@ -2444,9 +2444,9 @@ def test_put_return_attributes(): Item={"id": {"S": "foo"}, "col1": {"S": "val3"}}, ReturnValues="ALL_NEW", ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Return values set to invalid value" ) @@ -2969,9 +2969,9 @@ def test_scan_by_non_exists_index(): with pytest.raises(ClientError) as ex: dynamodb.scan(TableName="test", IndexName="non_exists_index") - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "The table does not have the specified index: non_exists_index" ) @@ -3008,8 +3008,8 @@ def test_query_by_non_exists_index(): KeyConditionExpression="CarModel=M", ) - ex.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + ex.value.response["Error"]["Message"].should.equal( "Invalid index: non_exists_index for table: test. Available indexes are: test_gsi" ) @@ -3052,8 +3052,8 @@ def test_batch_items_throws_exception_when_requesting_100_items_for_single_table } } ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - msg = ex.exception.response["Error"]["Message"] + ex.value.response["Error"]["Code"].should.equal("ValidationException") + msg = ex.value.response["Error"]["Message"] msg.should.contain("1 validation error detected: Value") msg.should.contain( "at 'requestItems.users.member.keys' failed to satisfy constraint: Member must have length less than or equal to 100" @@ -3080,8 +3080,8 @@ def test_batch_items_throws_exception_when_requesting_100_items_across_all_table }, } ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Too many items requested for the BatchGetItem call" ) @@ -3172,8 +3172,8 @@ def test_batch_items_should_throw_exception_for_duplicate_request(): } } ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Provided list of item keys contains duplicates" ) @@ -3210,8 +3210,8 @@ def test_index_with_unknown_attributes_should_fail(): BillingMode="PAY_PER_REQUEST", ) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.contain(expected_exception) + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.contain(expected_exception) @mock_dynamodb2 @@ -3377,8 +3377,8 @@ def test_update_list_index__set_index_of_a_string(): "Item" ] - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "The document path provided in the update expression is invalid for update" ) @@ -3617,8 +3617,8 @@ def test_item_size_is_under_400KB(): def assert_failure_due_to_item_size(func, **kwargs): with pytest.raises(ClientError) as ex: func(**kwargs) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Item size has exceeded the maximum allowed size" ) @@ -3626,8 +3626,8 @@ def assert_failure_due_to_item_size(func, **kwargs): def assert_failure_due_to_item_size_to_update(func, **kwargs): with pytest.raises(ClientError) as ex: func(**kwargs) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Item size to update has exceeded the maximum allowed size" ) @@ -3656,8 +3656,8 @@ def test_hash_key_cannot_use_begins_with_operations(): table = dynamodb.Table("test-table") with pytest.raises(ClientError) as ex: table.query(KeyConditionExpression=Key("key").begins_with("prefix-")) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Query key condition not supported" ) @@ -4056,8 +4056,8 @@ def test_update_catches_invalid_list_append_operation(): ) # Verify correct error is returned - str(ex.exception).should.match("Parameter validation failed:") - str(ex.exception).should.match( + str(ex.value).should.match("Parameter validation failed:") + str(ex.value).should.match( "Invalid type for parameter ExpressionAttributeValues." ) @@ -4169,9 +4169,9 @@ def test_query_catches_when_no_filters(): with pytest.raises(ClientError) as ex: table.query(TableName="original-rbu-dev") - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Either KeyConditions or QueryFilter should be present" ) @@ -4205,8 +4205,8 @@ def test_invalid_transact_get_items(): ] ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.match( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.match( r"failed to satisfy constraint: Member must have length less than or equal to 25", re.I, ) @@ -4219,9 +4219,9 @@ def test_invalid_transact_get_items(): ] ) - ex.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Requested resource not found" ) @@ -4514,8 +4514,8 @@ def test_transact_write_items_put_conditional_expressions(): ] ) # Assert the exception is correct - ex.exception.response["Error"]["Code"].should.equal("TransactionCanceledException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("TransactionCanceledException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Assert all are present items = dynamodb.scan(TableName="test-table")["Items"] items.should.have.length_of(1) @@ -4604,8 +4604,8 @@ def test_transact_write_items_conditioncheck_fails(): ] ) # Assert the exception is correct - ex.exception.response["Error"]["Code"].should.equal("TransactionCanceledException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("TransactionCanceledException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Assert the original email address is still present items = dynamodb.scan(TableName="test-table")["Items"] @@ -4701,8 +4701,8 @@ def test_transact_write_items_delete_with_failed_condition_expression(): ] ) # Assert the exception is correct - ex.exception.response["Error"]["Code"].should.equal("TransactionCanceledException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("TransactionCanceledException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Assert the original item is still present items = dynamodb.scan(TableName="test-table")["Items"] items.should.have.length_of(1) @@ -4774,8 +4774,8 @@ def test_transact_write_items_update_with_failed_condition_expression(): ] ) # Assert the exception is correct - ex.exception.response["Error"]["Code"].should.equal("TransactionCanceledException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("TransactionCanceledException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Assert the original item is still present items = dynamodb.scan(TableName="test-table")["Items"] items.should.have.length_of(1) @@ -5343,9 +5343,9 @@ def test_transact_write_items_fails_with_transaction_canceled_exception(): }, ] ) - ex.exception.response["Error"]["Code"].should.equal("TransactionCanceledException") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("TransactionCanceledException") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Transaction cancelled, please refer cancellation reasons for specific reasons [None, ConditionalCheckFailed]" ) diff --git a/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py b/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py index e50cd45c1..1c8c12110 100644 --- a/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py +++ b/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py @@ -1355,8 +1355,8 @@ def test_update_item_with_expression(): def assert_failure_due_to_key_not_in_schema(func, **kwargs): with pytest.raises(ClientError) as ex: func(**kwargs) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "The provided key element does not match the schema" ) diff --git a/tests/test_ec2/test_amis.py b/tests/test_ec2/test_amis.py index b23eae4ab..eb3fe6549 100644 --- a/tests/test_ec2/test_amis.py +++ b/tests/test_ec2/test_amis.py @@ -6,7 +6,7 @@ import boto3 from boto.exception import EC2ResponseError from botocore.exceptions import ClientError -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import sure # noqa @@ -31,9 +31,9 @@ def test_ami_create_and_delete(): image_id = conn.create_image( instance.id, "test-ami", "this is a test ami", dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateImage operation: Request would have succeeded, but DryRun flag is set" ) @@ -78,9 +78,9 @@ def test_ami_create_and_delete(): # Deregister with pytest.raises(EC2ResponseError) as ex: success = conn.deregister_image(image_id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeregisterImage operation: Request would have succeeded, but DryRun flag is set" ) @@ -89,9 +89,9 @@ def test_ami_create_and_delete(): with pytest.raises(EC2ResponseError) as cm: conn.deregister_image(image_id) - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @requires_boto_gte("2.14.0") @@ -120,9 +120,9 @@ def test_ami_copy(): "this is a test copy ami", dry_run=True, ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CopyImage operation: Request would have succeeded, but DryRun flag is set" ) @@ -159,9 +159,9 @@ def test_ami_copy(): "test-copy-ami", "this is a test copy ami", ) - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Copy from non-existent source region. with pytest.raises(EC2ResponseError) as cm: @@ -171,9 +171,9 @@ def test_ami_copy(): conn.copy_image( invalid_region, source_image.id, "test-copy-ami", "this is a test copy ami" ) - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 @@ -210,9 +210,9 @@ def test_ami_tagging(): with pytest.raises(EC2ResponseError) as ex: image.add_tag("a key", "some value", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -235,9 +235,9 @@ def test_ami_create_from_missing_instance(): with pytest.raises(EC2ResponseError) as cm: conn.create_image(*args) - cm.exception.code.should.equal("InvalidInstanceID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidInstanceID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -355,9 +355,9 @@ def test_getting_missing_ami(): with pytest.raises(EC2ResponseError) as cm: conn.get_image("ami-missing") - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -366,9 +366,9 @@ def test_getting_malformed_ami(): with pytest.raises(EC2ResponseError) as cm: conn.get_image("foo-missing") - cm.exception.code.should.equal("InvalidAMIID.Malformed") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.Malformed") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -401,9 +401,9 @@ def test_ami_attribute_group_permissions(): # Add 'all' group and confirm with pytest.raises(EC2ResponseError) as ex: conn.modify_image_attribute(**dict(ADD_GROUP_ARGS, **{"dry_run": True})) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyImageAttribute operation: Request would have succeeded, but DryRun flag is set" ) @@ -682,9 +682,9 @@ def test_ami_attribute_error_cases(): conn.modify_image_attribute( image.id, attribute="launchPermission", operation="add", groups="everyone" ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Add with user ID that isn't an integer. with pytest.raises(EC2ResponseError) as cm: @@ -694,9 +694,9 @@ def test_ami_attribute_error_cases(): operation="add", user_ids="12345678901A", ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Add with user ID that is > length 12. with pytest.raises(EC2ResponseError) as cm: @@ -706,9 +706,9 @@ def test_ami_attribute_error_cases(): operation="add", user_ids="1234567890123", ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Add with user ID that is < length 12. with pytest.raises(EC2ResponseError) as cm: @@ -718,9 +718,9 @@ def test_ami_attribute_error_cases(): operation="add", user_ids="12345678901", ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Add with one invalid user ID among other valid IDs, ensure no # partial changes. @@ -731,9 +731,9 @@ def test_ami_attribute_error_cases(): operation="add", user_ids=["123456789011", "foo", "123456789022"], ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none attributes = conn.get_image_attribute(image.id, attribute="launchPermission") attributes.attrs.should.have.length_of(0) @@ -743,9 +743,9 @@ def test_ami_attribute_error_cases(): conn.modify_image_attribute( "ami-abcd1234", attribute="launchPermission", operation="add", groups="all" ) - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Remove with invalid image ID with pytest.raises(EC2ResponseError) as cm: @@ -755,9 +755,9 @@ def test_ami_attribute_error_cases(): operation="remove", groups="all", ) - cm.exception.code.should.equal("InvalidAMIID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 diff --git a/tests/test_ec2/test_dhcp_options.py b/tests/test_ec2/test_dhcp_options.py index c04faa85d..85bc7f244 100644 --- a/tests/test_ec2/test_dhcp_options.py +++ b/tests/test_ec2/test_dhcp_options.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto3 @@ -34,9 +34,9 @@ def test_dhcp_options_associate_invalid_dhcp_id(): with pytest.raises(EC2ResponseError) as cm: conn.associate_dhcp_options("foo", vpc.id) - cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -47,9 +47,9 @@ def test_dhcp_options_associate_invalid_vpc_id(): with pytest.raises(EC2ResponseError) as cm: conn.associate_dhcp_options(dhcp_options.id, "foo") - cm.exception.code.should.equal("InvalidVpcID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -65,17 +65,17 @@ def test_dhcp_options_delete_with_vpc(): with pytest.raises(EC2ResponseError) as cm: conn.delete_dhcp_options(dhcp_options_id) - cm.exception.code.should.equal("DependencyViolation") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("DependencyViolation") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none vpc.delete() with pytest.raises(EC2ResponseError) as cm: conn.get_all_dhcp_options([dhcp_options_id]) - cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -101,15 +101,15 @@ def test_create_dhcp_options_invalid_options(): with pytest.raises(EC2ResponseError) as cm: conn.create_dhcp_options(ntp_servers=servers) - cm.exception.code.should.equal("InvalidParameterValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidParameterValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none with pytest.raises(EC2ResponseError) as cm: conn.create_dhcp_options(netbios_node_type="0") - cm.exception.code.should.equal("InvalidParameterValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidParameterValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -132,9 +132,9 @@ def test_describe_dhcp_options_invalid_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_dhcp_options(["1"]) - cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -150,9 +150,9 @@ def test_delete_dhcp_options(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_dhcp_options([dhcp_option.id]) - cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -163,9 +163,9 @@ def test_delete_dhcp_options_invalid_id(): with pytest.raises(EC2ResponseError) as cm: conn.delete_dhcp_options("dopt-abcd1234") - cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -176,9 +176,9 @@ def test_delete_dhcp_options_malformed_id(): with pytest.raises(EC2ResponseError) as cm: conn.delete_dhcp_options("foo-abcd1234") - cm.exception.code.should.equal("InvalidDhcpOptionsId.Malformed") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidDhcpOptionsId.Malformed") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated diff --git a/tests/test_ec2/test_elastic_block_store.py b/tests/test_ec2/test_elastic_block_store.py index 846d1bacc..9e4a3b7bb 100644 --- a/tests/test_ec2/test_elastic_block_store.py +++ b/tests/test_ec2/test_elastic_block_store.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest from moto.ec2 import ec2_backends @@ -32,9 +32,9 @@ def test_create_and_delete_volume(): with pytest.raises(EC2ResponseError) as ex: volume.delete(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteVolume operation: Request would have succeeded, but DryRun flag is set" ) @@ -47,9 +47,9 @@ def test_create_and_delete_volume(): # Deleting something that was already deleted should throw an error with pytest.raises(EC2ResponseError) as cm: volume.delete() - cm.exception.code.should.equal("InvalidVolume.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVolume.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -71,11 +71,11 @@ def test_delete_attached_volume(): # attempt to delete volume # assert raises VolumeInUseError - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: volume.delete() - ex.exception.error_code.should.equal("VolumeInUse") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("VolumeInUse") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "Volume {0} is currently attached to {1}".format(volume.id, instance.id) ) @@ -96,9 +96,9 @@ def test_create_encrypted_volume_dryrun(): conn = boto.ec2.connect_to_region("us-east-1") with pytest.raises(EC2ResponseError) as ex: conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set" ) @@ -110,9 +110,9 @@ def test_create_encrypted_volume(): with pytest.raises(EC2ResponseError) as ex: conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set" ) @@ -135,9 +135,9 @@ def test_filter_volume_by_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_volumes(volume_ids=["vol-does_not_exist"]) - cm.exception.code.should.equal("InvalidVolume.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVolume.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -260,9 +260,9 @@ def test_volume_attach_and_detach(): with pytest.raises(EC2ResponseError) as ex: volume.attach(instance.id, "/dev/sdh", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AttachVolume operation: Request would have succeeded, but DryRun flag is set" ) @@ -276,9 +276,9 @@ def test_volume_attach_and_detach(): with pytest.raises(EC2ResponseError) as ex: volume.detach(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DetachVolume operation: Request would have succeeded, but DryRun flag is set" ) @@ -289,21 +289,21 @@ def test_volume_attach_and_detach(): with pytest.raises(EC2ResponseError) as cm1: volume.attach("i-1234abcd", "/dev/sdh") - cm1.exception.code.should.equal("InvalidInstanceID.NotFound") - cm1.exception.status.should.equal(400) - cm1.exception.request_id.should_not.be.none + cm1.value.code.should.equal("InvalidInstanceID.NotFound") + cm1.value.status.should.equal(400) + cm1.value.request_id.should_not.be.none with pytest.raises(EC2ResponseError) as cm2: conn.detach_volume(volume.id, instance.id, "/dev/sdh") - cm2.exception.code.should.equal("InvalidAttachment.NotFound") - cm2.exception.status.should.equal(400) - cm2.exception.request_id.should_not.be.none + cm2.value.code.should.equal("InvalidAttachment.NotFound") + cm2.value.status.should.equal(400) + cm2.value.request_id.should_not.be.none with pytest.raises(EC2ResponseError) as cm3: conn.detach_volume(volume.id, "i-1234abcd", "/dev/sdh") - cm3.exception.code.should.equal("InvalidInstanceID.NotFound") - cm3.exception.status.should.equal(400) - cm3.exception.request_id.should_not.be.none + cm3.value.code.should.equal("InvalidInstanceID.NotFound") + cm3.value.status.should.equal(400) + cm3.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -313,9 +313,9 @@ def test_create_snapshot(): with pytest.raises(EC2ResponseError) as ex: snapshot = volume.create_snapshot("a dryrun snapshot", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set" ) @@ -341,9 +341,9 @@ def test_create_snapshot(): # Deleting something that was already deleted should throw an error with pytest.raises(EC2ResponseError) as cm: snapshot.delete() - cm.exception.code.should.equal("InvalidSnapshot.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSnapshot.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -383,9 +383,9 @@ def test_filter_snapshot_by_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_snapshots(snapshot_ids=["snap-does_not_exist"]) - cm.exception.code.should.equal("InvalidSnapshot.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSnapshot.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -485,9 +485,9 @@ def test_snapshot_attribute(): with pytest.raises(EC2ResponseError) as ex: conn.modify_snapshot_attribute(**dict(ADD_GROUP_ARGS, **{"dry_run": True})) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set" ) @@ -507,9 +507,9 @@ def test_snapshot_attribute(): # Remove 'all' group and confirm with pytest.raises(EC2ResponseError) as ex: conn.modify_snapshot_attribute(**dict(REMOVE_GROUP_ARGS, **{"dry_run": True})) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set" ) @@ -533,9 +533,9 @@ def test_snapshot_attribute(): operation="add", groups="everyone", ) - cm.exception.code.should.equal("InvalidAMIAttributeItemValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAMIAttributeItemValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Add with invalid snapshot ID with pytest.raises(EC2ResponseError) as cm: @@ -545,9 +545,9 @@ def test_snapshot_attribute(): operation="add", groups="all", ) - cm.exception.code.should.equal("InvalidSnapshot.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSnapshot.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Remove with invalid snapshot ID with pytest.raises(EC2ResponseError) as cm: @@ -557,9 +557,9 @@ def test_snapshot_attribute(): operation="remove", groups="all", ) - cm.exception.code.should.equal("InvalidSnapshot.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSnapshot.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 @@ -594,12 +594,12 @@ def test_modify_snapshot_attribute(): } # Add 'all' group and confirm - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: ec2_client.modify_snapshot_attribute(**dict(ADD_GROUP_ARGS, **{"DryRun": True})) - cm.exception.response["Error"]["Code"].should.equal("DryRunOperation") - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("DryRunOperation") + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ec2_client.modify_snapshot_attribute(**ADD_GROUP_ARGS) @@ -619,13 +619,13 @@ def test_modify_snapshot_attribute(): ], "This snapshot should have public group permissions." # Remove 'all' group and confirm - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: ec2_client.modify_snapshot_attribute( **dict(REMOVE_GROUP_ARGS, **{"DryRun": True}) ) - cm.exception.response["Error"]["Code"].should.equal("DryRunOperation") - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("DryRunOperation") + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ec2_client.modify_snapshot_attribute(**REMOVE_GROUP_ARGS) @@ -645,40 +645,40 @@ def test_modify_snapshot_attribute(): ], "This snapshot should have no permissions." # Error: Add with group != 'all' - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: ec2_client.modify_snapshot_attribute( SnapshotId=snapshot.id, Attribute="createVolumePermission", OperationType="add", GroupNames=["everyone"], ) - cm.exception.response["Error"]["Code"].should.equal("InvalidAMIAttributeItemValue") - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("InvalidAMIAttributeItemValue") + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Error: Add with invalid snapshot ID - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: ec2_client.modify_snapshot_attribute( SnapshotId="snapshot-abcd1234", Attribute="createVolumePermission", OperationType="add", GroupNames=["all"], ) - cm.exception.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Error: Remove with invalid snapshot ID - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: ec2_client.modify_snapshot_attribute( SnapshotId="snapshot-abcd1234", Attribute="createVolumePermission", OperationType="remove", GroupNames=["all"], ) - cm.exception.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Test adding user id ec2_client.modify_snapshot_attribute( @@ -741,9 +741,9 @@ def test_create_volume_from_snapshot(): with pytest.raises(EC2ResponseError) as ex: snapshot = volume.create_snapshot("a test snapshot", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set" ) @@ -789,9 +789,9 @@ def test_modify_attribute_blockDeviceMapping(): instance.modify_attribute( "blockDeviceMapping", {"/dev/sda1": True}, dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyInstanceAttribute operation: Request would have succeeded, but DryRun flag is set" ) @@ -810,9 +810,9 @@ def test_volume_tag_escaping(): with pytest.raises(EC2ResponseError) as ex: snapshot.add_tags({"key": ""}, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) snaps = [snap for snap in conn.get_all_snapshots() if snap.id == snapshot.id] @@ -880,12 +880,12 @@ def test_copy_snapshot(): # Copy from non-existent source ID. with pytest.raises(ClientError) as cm: create_snapshot_error = ec2_client.create_snapshot(VolumeId="vol-abcd1234") - cm.exception.response["Error"]["Code"].should.equal("InvalidVolume.NotFound") - cm.exception.response["Error"]["Message"].should.equal( + cm.value.response["Error"]["Code"].should.equal("InvalidVolume.NotFound") + cm.value.response["Error"]["Message"].should.equal( "The volume 'vol-abcd1234' does not exist." ) - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) # Copy from non-existent source region. with pytest.raises(ClientError) as cm: @@ -893,10 +893,10 @@ def test_copy_snapshot(): SourceSnapshotId=create_snapshot_response["SnapshotId"], SourceRegion="eu-west-2", ) - cm.exception.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") - cm.exception.response["Error"]["Message"].should.be.none - cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none - cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + cm.value.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound") + cm.value.response["Error"]["Message"].should.be.none + cm.value.response["ResponseMetadata"]["RequestId"].should_not.be.none + cm.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_ec2 diff --git a/tests/test_ec2/test_elastic_ip_addresses.py b/tests/test_ec2/test_elastic_ip_addresses.py index e9a247ea7..8edd92e65 100644 --- a/tests/test_ec2/test_elastic_ip_addresses.py +++ b/tests/test_ec2/test_elastic_ip_addresses.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto @@ -22,9 +22,9 @@ def test_eip_allocate_classic(): with pytest.raises(EC2ResponseError) as ex: standard = conn.allocate_address(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -36,9 +36,9 @@ def test_eip_allocate_classic(): with pytest.raises(EC2ResponseError) as ex: standard.release(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -53,9 +53,9 @@ def test_eip_allocate_vpc(): with pytest.raises(EC2ResponseError) as ex: vpc = conn.allocate_address(domain="vpc", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -85,9 +85,9 @@ def test_eip_allocate_invalid_domain(): with pytest.raises(EC2ResponseError) as cm: conn.allocate_address(domain="bogus") - cm.exception.code.should.equal("InvalidParameterValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidParameterValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -103,17 +103,17 @@ def test_eip_associate_classic(): with pytest.raises(EC2ResponseError) as cm: conn.associate_address(public_ip=eip.public_ip) - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none with pytest.raises(EC2ResponseError) as ex: conn.associate_address( instance_id=instance.id, public_ip=eip.public_ip, dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AssociateAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -124,9 +124,9 @@ def test_eip_associate_classic(): with pytest.raises(EC2ResponseError) as ex: conn.disassociate_address(public_ip=eip.public_ip, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DisAssociateAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -154,9 +154,9 @@ def test_eip_associate_vpc(): with pytest.raises(EC2ResponseError) as cm: conn.associate_address(allocation_id=eip.allocation_id) - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none conn.associate_address(instance_id=instance.id, allocation_id=eip.allocation_id) # no .update() on address ): @@ -170,9 +170,9 @@ def test_eip_associate_vpc(): with pytest.raises(EC2ResponseError) as ex: eip.release(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set" ) @@ -242,9 +242,9 @@ def test_eip_associate_network_interface(): with pytest.raises(EC2ResponseError) as cm: conn.associate_address(network_interface_id=eni.id) - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none conn.associate_address(network_interface_id=eni.id, allocation_id=eip.allocation_id) # no .update() on address ): @@ -279,9 +279,9 @@ def test_eip_reassociate(): conn.associate_address( instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=False ) - cm.exception.code.should.equal("Resource.AlreadyAssociated") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Resource.AlreadyAssociated") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none conn.associate_address.when.called_with( instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=True @@ -313,9 +313,9 @@ def test_eip_reassociate_nic(): # Different ID detects resource association with pytest.raises(EC2ResponseError) as cm: conn.associate_address(network_interface_id=eni2.id, public_ip=eip.public_ip) - cm.exception.code.should.equal("Resource.AlreadyAssociated") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Resource.AlreadyAssociated") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none conn.associate_address.when.called_with( network_interface_id=eni2.id, public_ip=eip.public_ip, allow_reassociation=True @@ -337,9 +337,9 @@ def test_eip_associate_invalid_args(): with pytest.raises(EC2ResponseError) as cm: conn.associate_address(instance_id=instance.id) - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none instance.terminate() @@ -351,9 +351,9 @@ def test_eip_disassociate_bogus_association(): with pytest.raises(EC2ResponseError) as cm: conn.disassociate_address(association_id="bogus") - cm.exception.code.should.equal("InvalidAssociationID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAssociationID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -363,9 +363,9 @@ def test_eip_release_bogus_eip(): with pytest.raises(EC2ResponseError) as cm: conn.release_address(allocation_id="bogus") - cm.exception.code.should.equal("InvalidAllocationID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAllocationID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -375,9 +375,9 @@ def test_eip_disassociate_arg_error(): with pytest.raises(EC2ResponseError) as cm: conn.disassociate_address() - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -387,9 +387,9 @@ def test_eip_release_arg_error(): with pytest.raises(EC2ResponseError) as cm: conn.release_address() - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -439,9 +439,9 @@ def test_eip_describe_none(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_addresses(addresses=["256.256.256.256"]) - cm.exception.code.should.equal("InvalidAddress.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAddress.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 diff --git a/tests/test_ec2/test_elastic_network_interfaces.py b/tests/test_ec2/test_elastic_network_interfaces.py index 259885ee0..a5bb019b0 100644 --- a/tests/test_ec2/test_elastic_network_interfaces.py +++ b/tests/test_ec2/test_elastic_network_interfaces.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto3 @@ -22,9 +22,9 @@ def test_elastic_network_interfaces(): with pytest.raises(EC2ResponseError) as ex: eni = conn.create_network_interface(subnet.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateNetworkInterface operation: Request would have succeeded, but DryRun flag is set" ) @@ -39,9 +39,9 @@ def test_elastic_network_interfaces(): with pytest.raises(EC2ResponseError) as ex: conn.delete_network_interface(eni.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteNetworkInterface operation: Request would have succeeded, but DryRun flag is set" ) @@ -52,9 +52,9 @@ def test_elastic_network_interfaces(): with pytest.raises(EC2ResponseError) as cm: conn.delete_network_interface(eni.id) - cm.exception.error_code.should.equal("InvalidNetworkInterfaceID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.error_code.should.equal("InvalidNetworkInterfaceID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -63,9 +63,9 @@ def test_elastic_network_interfaces_subnet_validation(): with pytest.raises(EC2ResponseError) as cm: conn.create_network_interface("subnet-abcd1234") - cm.exception.error_code.should.equal("InvalidSubnetID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.error_code.should.equal("InvalidSubnetID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -136,9 +136,9 @@ def test_elastic_network_interfaces_modify_attribute(): conn.modify_network_interface_attribute( eni.id, "groupset", [security_group2.id], dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyNetworkInterface operation: Request would have succeeded, but DryRun flag is set" ) @@ -229,9 +229,9 @@ def test_elastic_network_interfaces_get_by_tag_name(): with pytest.raises(ClientError) as ex: eni1.create_tags(Tags=[{"Key": "Name", "Value": "eni1"}], DryRun=True) - ex.exception.response["Error"]["Code"].should.equal("DryRunOperation") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("DryRunOperation") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) diff --git a/tests/test_ec2/test_flow_logs.py b/tests/test_ec2/test_flow_logs.py index 1dba572d3..743466eaa 100644 --- a/tests/test_ec2/test_flow_logs.py +++ b/tests/test_ec2/test_flow_logs.py @@ -44,9 +44,9 @@ def test_create_flow_logs_s3(): LogDestination="arn:aws:s3:::" + bucket.name, DryRun=True, ) - ex.exception.response["Error"]["Code"].should.equal("DryRunOperation") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("DryRunOperation") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "An error occurred (DryRunOperation) when calling the CreateFlowLogs operation: Request would have succeeded, but DryRun flag is set" ) @@ -96,9 +96,9 @@ def test_create_flow_logs_cloud_watch(): DeliverLogsPermissionArn="arn:aws:iam::" + ACCOUNT_ID + ":role/test-role", DryRun=True, ) - ex.exception.response["Error"]["Code"].should.equal("DryRunOperation") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("DryRunOperation") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "An error occurred (DryRunOperation) when calling the CreateFlowLogs operation: Request would have succeeded, but DryRun flag is set" ) @@ -244,17 +244,17 @@ def test_delete_flow_logs_non_existing(): with pytest.raises(ClientError) as ex: client.delete_flow_logs(FlowLogIds=["fl-1a2b3c4d"]) - ex.exception.response["Error"]["Code"].should.equal("InvalidFlowLogId.NotFound") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidFlowLogId.NotFound") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "These flow log ids in the input list are not found: [TotalCount: 1] fl-1a2b3c4d" ) with pytest.raises(ClientError) as ex: client.delete_flow_logs(FlowLogIds=["fl-1a2b3c4d", "fl-2b3c4d5e"]) - ex.exception.response["Error"]["Code"].should.equal("InvalidFlowLogId.NotFound") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidFlowLogId.NotFound") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "These flow log ids in the input list are not found: [TotalCount: 2] fl-1a2b3c4d fl-2b3c4d5e" ) @@ -312,9 +312,9 @@ def test_create_flow_logs_invalid_parameters(): LogDestination="arn:aws:s3:::" + bucket.name, MaxAggregationInterval=10, ) - ex.exception.response["Error"]["Code"].should.equal("InvalidParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Invalid Flow Log Max Aggregation Interval" ) @@ -325,9 +325,9 @@ def test_create_flow_logs_invalid_parameters(): TrafficType="ALL", LogDestinationType="s3", ) - ex.exception.response["Error"]["Code"].should.equal("InvalidParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "LogDestination can't be empty if LogGroupName is not provided." ) @@ -339,9 +339,9 @@ def test_create_flow_logs_invalid_parameters(): LogDestinationType="s3", LogGroupName="test", ) - ex.exception.response["Error"]["Code"].should.equal("InvalidParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "LogDestination type must be cloud-watch-logs if LogGroupName is provided." ) @@ -352,9 +352,9 @@ def test_create_flow_logs_invalid_parameters(): TrafficType="ALL", LogGroupName="test", ) - ex.exception.response["Error"]["Code"].should.equal("InvalidParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("InvalidParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "DeliverLogsPermissionArn can't be empty if LogDestinationType is cloud-watch-logs." ) @@ -375,9 +375,9 @@ def test_create_flow_logs_invalid_parameters(): LogDestinationType="s3", LogDestination="arn:aws:s3:::" + bucket.name, ) - ex.exception.response["Error"]["Code"].should.equal("FlowLogAlreadyExists") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("FlowLogAlreadyExists") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Error. There is an existing Flow Log with the same configuration and log destination." ) @@ -398,9 +398,9 @@ def test_create_flow_logs_invalid_parameters(): LogGroupName="test-group", DeliverLogsPermissionArn="arn:aws:iam::" + ACCOUNT_ID + ":role/test-role", ) - ex.exception.response["Error"]["Code"].should.equal("FlowLogAlreadyExists") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("FlowLogAlreadyExists") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "Error. There is an existing Flow Log with the same configuration and log destination." ) diff --git a/tests/test_ec2/test_general.py b/tests/test_ec2/test_general.py index b6e75ea6a..c2b578929 100644 --- a/tests/test_ec2/test_general.py +++ b/tests/test_ec2/test_general.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto @@ -26,9 +26,9 @@ def test_console_output_without_instance(): with pytest.raises(EC2ResponseError) as cm: conn.get_console_output("i-1234abcd") - cm.exception.code.should.equal("InvalidInstanceID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidInstanceID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index b770862e2..fefeee522 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 from botocore.exceptions import ClientError import pytest @@ -53,9 +53,9 @@ def test_instance_launch_and_terminate(): with pytest.raises(EC2ResponseError) as ex: reservation = conn.run_instances("ami-1234abcd", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the RunInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -88,9 +88,9 @@ def test_instance_launch_and_terminate(): with pytest.raises(EC2ResponseError) as ex: conn.terminate_instances([instance.id], dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the TerminateInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -215,14 +215,14 @@ def test_instance_detach_volume_wrong_path(): ) instance = result[0] for volume in instance.volumes.all(): - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: instance.detach_volume(VolumeId=volume.volume_id, Device="/dev/sdf") - ex.exception.response["Error"]["Code"].should.equal( + ex.value.response["Error"]["Code"].should.equal( "InvalidAttachment.NotFound" ) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "The volume {0} is not attached to instance {1} as device {2}".format( volume.volume_id, instance.instance_id, "/dev/sdf" ) @@ -291,9 +291,9 @@ def test_get_instances_by_id(): # Call get_all_instances with a bad id should raise an error with pytest.raises(EC2ResponseError) as cm: conn.get_all_instances(instance_ids=[instance1.id, "i-1234abcd"]) - cm.exception.code.should.equal("InvalidInstanceID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidInstanceID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 @@ -744,9 +744,9 @@ def test_instance_start_and_stop(): with pytest.raises(EC2ResponseError) as ex: stopped_instances = conn.stop_instances(instance_ids, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the StopInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -757,9 +757,9 @@ def test_instance_start_and_stop(): with pytest.raises(EC2ResponseError) as ex: started_instances = conn.start_instances([instances[0].id], dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the StartInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -775,9 +775,9 @@ def test_instance_reboot(): with pytest.raises(EC2ResponseError) as ex: instance.reboot(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the RebootInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -793,9 +793,9 @@ def test_instance_attribute_instance_type(): with pytest.raises(EC2ResponseError) as ex: instance.modify_attribute("instanceType", "m1.small", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyInstanceType operation: Request would have succeeded, but DryRun flag is set" ) @@ -821,9 +821,9 @@ def test_modify_instance_attribute_security_groups(): with pytest.raises(EC2ResponseError) as ex: instance.modify_attribute("groupSet", [sg_id, sg_id2], dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set" ) @@ -844,9 +844,9 @@ def test_instance_attribute_user_data(): with pytest.raises(EC2ResponseError) as ex: instance.modify_attribute("userData", "this is my user data", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyUserData operation: Request would have succeeded, but DryRun flag is set" ) @@ -874,9 +874,9 @@ def test_instance_attribute_source_dest_check(): with pytest.raises(EC2ResponseError) as ex: instance.modify_attribute("sourceDestCheck", False, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifySourceDestCheck operation: Request would have succeeded, but DryRun flag is set" ) @@ -920,9 +920,9 @@ def test_run_instance_with_security_group_name(): with pytest.raises(EC2ResponseError) as ex: group = conn.create_security_group("group1", "some description", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set" ) @@ -1197,9 +1197,9 @@ def test_instance_with_nic_attach_detach(): # Attach with pytest.raises(EC2ResponseError) as ex: conn.attach_network_interface(eni.id, instance.id, device_index=1, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AttachNetworkInterface operation: Request would have succeeded, but DryRun flag is set" ) @@ -1224,9 +1224,9 @@ def test_instance_with_nic_attach_detach(): # Detach with pytest.raises(EC2ResponseError) as ex: conn.detach_network_interface(instance_eni.attachment.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DetachNetworkInterface operation: Request would have succeeded, but DryRun flag is set" ) @@ -1243,9 +1243,9 @@ def test_instance_with_nic_attach_detach(): # Detach with invalid attachment ID with pytest.raises(EC2ResponseError) as cm: conn.detach_network_interface("eni-attach-1234abcd") - cm.exception.code.should.equal("InvalidAttachmentID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAttachmentID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -1306,12 +1306,12 @@ def test_run_instance_with_block_device_mappings_missing_ebs(): "InstanceType": "t1.micro", "BlockDeviceMappings": [{"DeviceName": "/dev/sda2"}], } - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: ec2_client.run_instances(**kwargs) - ex.exception.response["Error"]["Code"].should.equal("MissingParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("MissingParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "The request must contain the parameter ebs" ) @@ -1330,12 +1330,12 @@ def test_run_instance_with_block_device_mappings_missing_size(): {"DeviceName": "/dev/sda2", "Ebs": {"VolumeType": "standard"}} ], } - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: ec2_client.run_instances(**kwargs) - ex.exception.response["Error"]["Code"].should.equal("MissingParameter") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("MissingParameter") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "The request must contain the parameter size or snapshotId" ) @@ -1411,9 +1411,9 @@ def test_describe_instance_status_with_instance_filter_deprecated(): # Call get_all_instance_status with a bad id should raise an error with pytest.raises(EC2ResponseError) as cm: conn.get_all_instance_status(instance_ids=[instance.id, "i-1234abcd"]) - cm.exception.code.should.equal("InvalidInstanceID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidInstanceID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 @@ -1540,9 +1540,9 @@ def test_get_instance_by_security_group(): conn.modify_instance_attribute( instance.id, "groupSet", [security_group.id], dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set" ) @@ -1664,9 +1664,9 @@ def test_describe_instance_attribute(): client.describe_instance_attribute( InstanceId=instance_id, Attribute=invalid_instance_attribute ) - ex.exception.response["Error"]["Code"].should.equal("InvalidParameterValue") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Code"].should.equal("InvalidParameterValue") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) message = "Value ({invalid_instance_attribute}) for parameter attribute is invalid. Unknown attribute.".format( invalid_instance_attribute=invalid_instance_attribute ) - ex.exception.response["Error"]["Message"].should.equal(message) + ex.value.response["Error"]["Message"].should.equal(message) diff --git a/tests/test_ec2/test_internet_gateways.py b/tests/test_ec2/test_internet_gateways.py index cfa8bafe9..49cc6e38c 100644 --- a/tests/test_ec2/test_internet_gateways.py +++ b/tests/test_ec2/test_internet_gateways.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import re @@ -29,9 +29,9 @@ def test_igw_create(): with pytest.raises(EC2ResponseError) as ex: igw = conn.create_internet_gateway(dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateInternetGateway operation: Request would have succeeded, but DryRun flag is set" ) @@ -52,9 +52,9 @@ def test_igw_attach(): with pytest.raises(EC2ResponseError) as ex: conn.attach_internet_gateway(igw.id, vpc.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the AttachInternetGateway operation: Request would have succeeded, but DryRun flag is set" ) @@ -72,9 +72,9 @@ def test_igw_attach_bad_vpc(): with pytest.raises(EC2ResponseError) as cm: conn.attach_internet_gateway(igw.id, BAD_VPC) - cm.exception.code.should.equal("InvalidVpcID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -88,9 +88,9 @@ def test_igw_attach_twice(): with pytest.raises(EC2ResponseError) as cm: conn.attach_internet_gateway(igw.id, vpc2.id) - cm.exception.code.should.equal("Resource.AlreadyAssociated") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Resource.AlreadyAssociated") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -103,9 +103,9 @@ def test_igw_detach(): with pytest.raises(EC2ResponseError) as ex: conn.detach_internet_gateway(igw.id, vpc.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DetachInternetGateway operation: Request would have succeeded, but DryRun flag is set" ) @@ -125,9 +125,9 @@ def test_igw_detach_wrong_vpc(): with pytest.raises(EC2ResponseError) as cm: conn.detach_internet_gateway(igw.id, vpc2.id) - cm.exception.code.should.equal("Gateway.NotAttached") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Gateway.NotAttached") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -140,9 +140,9 @@ def test_igw_detach_invalid_vpc(): with pytest.raises(EC2ResponseError) as cm: conn.detach_internet_gateway(igw.id, BAD_VPC) - cm.exception.code.should.equal("Gateway.NotAttached") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Gateway.NotAttached") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -154,9 +154,9 @@ def test_igw_detach_unattached(): with pytest.raises(EC2ResponseError) as cm: conn.detach_internet_gateway(igw.id, vpc.id) - cm.exception.code.should.equal("Gateway.NotAttached") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("Gateway.NotAttached") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -170,9 +170,9 @@ def test_igw_delete(): with pytest.raises(EC2ResponseError) as ex: conn.delete_internet_gateway(igw.id, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteInternetGateway operation: Request would have succeeded, but DryRun flag is set" ) @@ -190,9 +190,9 @@ def test_igw_delete_attached(): with pytest.raises(EC2ResponseError) as cm: conn.delete_internet_gateway(igw.id) - cm.exception.code.should.equal("DependencyViolation") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("DependencyViolation") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -210,9 +210,9 @@ def test_igw_describe_bad_id(): conn = boto.connect_vpc("the_key", "the_secret") with pytest.raises(EC2ResponseError) as cm: conn.get_all_internet_gateways([BAD_IGW]) - cm.exception.code.should.equal("InvalidInternetGatewayID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidInternetGatewayID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated diff --git a/tests/test_ec2/test_key_pairs.py b/tests/test_ec2/test_key_pairs.py index 022b4ceeb..dcca8b116 100644 --- a/tests/test_ec2/test_key_pairs.py +++ b/tests/test_ec2/test_key_pairs.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto @@ -57,9 +57,9 @@ def test_key_pairs_invalid_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_key_pairs("foo") - cm.exception.code.should.equal("InvalidKeyPair.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidKeyPair.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -68,9 +68,9 @@ def test_key_pairs_create(): with pytest.raises(EC2ResponseError) as ex: conn.create_key_pair("foo", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateKeyPair operation: Request would have succeeded, but DryRun flag is set" ) @@ -111,9 +111,9 @@ def test_key_pairs_create_exist(): with pytest.raises(EC2ResponseError) as cm: conn.create_key_pair("foo") - cm.exception.code.should.equal("InvalidKeyPair.Duplicate") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidKeyPair.Duplicate") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -131,9 +131,9 @@ def test_key_pairs_delete_exist(): with pytest.raises(EC2ResponseError) as ex: r = conn.delete_key_pair("foo", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteKeyPair operation: Request would have succeeded, but DryRun flag is set" ) @@ -148,9 +148,9 @@ def test_key_pairs_import(): with pytest.raises(EC2ResponseError) as ex: conn.import_key_pair("foo", RSA_PUBLIC_KEY_OPENSSH, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the ImportKeyPair operation: Request would have succeeded, but DryRun flag is set" ) @@ -177,9 +177,9 @@ def test_key_pairs_import_exist(): with pytest.raises(EC2ResponseError) as cm: conn.create_key_pair("foo") - cm.exception.code.should.equal("InvalidKeyPair.Duplicate") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidKeyPair.Duplicate") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -188,21 +188,21 @@ def test_key_pairs_invalid(): with pytest.raises(EC2ResponseError) as ex: conn.import_key_pair("foo", b"") - ex.exception.error_code.should.equal("InvalidKeyPair.Format") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal("Key is not in valid OpenSSH public key format") + ex.value.error_code.should.equal("InvalidKeyPair.Format") + ex.value.status.should.equal(400) + ex.value.message.should.equal("Key is not in valid OpenSSH public key format") with pytest.raises(EC2ResponseError) as ex: conn.import_key_pair("foo", b"garbage") - ex.exception.error_code.should.equal("InvalidKeyPair.Format") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal("Key is not in valid OpenSSH public key format") + ex.value.error_code.should.equal("InvalidKeyPair.Format") + ex.value.status.should.equal(400) + ex.value.message.should.equal("Key is not in valid OpenSSH public key format") with pytest.raises(EC2ResponseError) as ex: conn.import_key_pair("foo", DSA_PUBLIC_KEY_OPENSSH) - ex.exception.error_code.should.equal("InvalidKeyPair.Format") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal("Key is not in valid OpenSSH public key format") + ex.value.error_code.should.equal("InvalidKeyPair.Format") + ex.value.status.should.equal(400) + ex.value.message.should.equal("Key is not in valid OpenSSH public key format") @mock_ec2_deprecated diff --git a/tests/test_ec2/test_launch_templates.py b/tests/test_ec2/test_launch_templates.py index 0bcf188ce..41896be96 100644 --- a/tests/test_ec2/test_launch_templates.py +++ b/tests/test_ec2/test_launch_templates.py @@ -43,7 +43,7 @@ def test_launch_template_create(): }, ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidLaunchTemplateName.AlreadyExistsException) when calling the CreateLaunchTemplate operation: Launch template name already in use." ) diff --git a/tests/test_ec2/test_network_acls.py b/tests/test_ec2/test_network_acls.py index 1bb058733..c2a790ed7 100644 --- a/tests/test_ec2/test_network_acls.py +++ b/tests/test_ec2/test_network_acls.py @@ -269,7 +269,7 @@ def test_duplicate_network_acl_entry(): RuleAction="deny", RuleNumber=rule_number, ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (NetworkAclEntryAlreadyExists) when calling the CreateNetworkAclEntry " "operation: The network acl entry identified by {} already exists.".format( rule_number @@ -297,10 +297,10 @@ def test_describe_network_acls(): resp2 = conn.describe_network_acls()["NetworkAcls"] resp2.should.have.length_of(3) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.describe_network_acls(NetworkAclIds=["1"]) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidRouteTableID.NotFound) when calling the " "DescribeNetworkAcls operation: The routeTable ID '1' does not exist" ) diff --git a/tests/test_ec2/test_route_tables.py b/tests/test_ec2/test_route_tables.py index 4ebfeb737..1eff22315 100644 --- a/tests/test_ec2/test_route_tables.py +++ b/tests/test_ec2/test_route_tables.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto @@ -62,9 +62,9 @@ def test_route_tables_additional(): with pytest.raises(EC2ResponseError) as cm: conn.delete_vpc(vpc.id) - cm.exception.code.should.equal("DependencyViolation") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("DependencyViolation") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none conn.delete_route_table(route_table.id) @@ -73,9 +73,9 @@ def test_route_tables_additional(): with pytest.raises(EC2ResponseError) as cm: conn.delete_route_table("rtb-1234abcd") - cm.exception.code.should.equal("InvalidRouteTableID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidRouteTableID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -198,9 +198,9 @@ def test_route_table_associations(): # Error: Attempt delete associated route table. with pytest.raises(EC2ResponseError) as cm: conn.delete_route_table(route_table.id) - cm.exception.code.should.equal("DependencyViolation") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("DependencyViolation") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Disassociate conn.disassociate_route_table(association_id) @@ -212,23 +212,23 @@ def test_route_table_associations(): # Error: Disassociate with invalid association ID with pytest.raises(EC2ResponseError) as cm: conn.disassociate_route_table(association_id) - cm.exception.code.should.equal("InvalidAssociationID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAssociationID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Associate with invalid subnet ID with pytest.raises(EC2ResponseError) as cm: conn.associate_route_table(route_table.id, "subnet-1234abcd") - cm.exception.code.should.equal("InvalidSubnetID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSubnetID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Associate with invalid route table ID with pytest.raises(EC2ResponseError) as cm: conn.associate_route_table("rtb-1234abcd", subnet.id) - cm.exception.code.should.equal("InvalidRouteTableID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidRouteTableID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @requires_boto_gte("2.16.0") @@ -296,16 +296,16 @@ def test_route_table_replace_route_table_association(): conn.replace_route_table_association_with_assoc( "rtbassoc-1234abcd", route_table1.id ) - cm.exception.code.should.equal("InvalidAssociationID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidAssociationID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Error: Replace association with invalid route table ID with pytest.raises(EC2ResponseError) as cm: conn.replace_route_table_association_with_assoc(association_id2, "rtb-1234abcd") - cm.exception.code.should.equal("InvalidRouteTableID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidRouteTableID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -390,9 +390,9 @@ def test_routes_additional(): with pytest.raises(EC2ResponseError) as cm: conn.delete_route(main_route_table.id, ROUTE_CIDR) - cm.exception.code.should.equal("InvalidRoute.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidRoute.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -443,9 +443,9 @@ def test_routes_replace(): with pytest.raises(EC2ResponseError) as cm: conn.replace_route("rtb-1234abcd", ROUTE_CIDR, gateway_id=igw.id) - cm.exception.code.should.equal("InvalidRouteTableID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidRouteTableID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @requires_boto_gte("2.19.0") @@ -574,7 +574,7 @@ def test_create_route_with_invalid_destination_cidr_block_parameter(): route = route_table.create_route( DestinationCidrBlock=destination_cidr_block, GatewayId=internet_gateway.id ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidParameterValue) when calling the CreateRoute " "operation: Value ({}) for parameter destinationCidrBlock is invalid. This is not a valid CIDR block.".format( destination_cidr_block diff --git a/tests/test_ec2/test_security_groups.py b/tests/test_ec2/test_security_groups.py index 9f8c1aecd..7ce9f3c5c 100644 --- a/tests/test_ec2/test_security_groups.py +++ b/tests/test_ec2/test_security_groups.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import copy import json -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto3 @@ -23,9 +23,9 @@ def test_create_and_describe_security_group(): security_group = conn.create_security_group( "test security group", "this is a test security group", dry_run=True ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set" ) @@ -41,9 +41,9 @@ def test_create_and_describe_security_group(): conn.create_security_group( "test security group", "this is a test security group" ) - cm.exception.code.should.equal("InvalidGroup.Duplicate") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidGroup.Duplicate") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none all_groups = conn.get_all_security_groups() # The default group gets created automatically @@ -58,9 +58,9 @@ def test_create_security_group_without_description_raises_error(): with pytest.raises(EC2ResponseError) as cm: conn.create_security_group("test security group", "") - cm.exception.code.should.equal("MissingParameter") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("MissingParameter") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -90,9 +90,9 @@ def test_create_and_describe_vpc_security_group(): conn.create_security_group( "test security group", "this is a test security group", vpc_id ) - cm.exception.code.should.equal("InvalidGroup.Duplicate") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidGroup.Duplicate") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none all_groups = conn.get_all_security_groups(filters={"vpc_id": [vpc_id]}) @@ -147,16 +147,16 @@ def test_deleting_security_groups(): # Deleting a group that doesn't exist should throw an error with pytest.raises(EC2ResponseError) as cm: conn.delete_security_group("foobar") - cm.exception.code.should.equal("InvalidGroup.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidGroup.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Delete by name with pytest.raises(EC2ResponseError) as ex: conn.delete_security_group("test2", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteSecurityGroup operation: Request would have succeeded, but DryRun flag is set" ) @@ -191,9 +191,9 @@ def test_authorize_ip_range_and_revoke(): cidr_ip="123.123.123.123/32", dry_run=True, ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the GrantSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set" ) @@ -214,9 +214,9 @@ def test_authorize_ip_range_and_revoke(): to_port="2222", cidr_ip="123.123.123.122/32", ) - cm.exception.code.should.equal("InvalidPermission.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidPermission.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Actually revoke with pytest.raises(EC2ResponseError) as ex: @@ -227,9 +227,9 @@ def test_authorize_ip_range_and_revoke(): cidr_ip="123.123.123.123/32", dry_run=True, ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the RevokeSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set" ) @@ -254,9 +254,9 @@ def test_authorize_ip_range_and_revoke(): cidr_ip="123.123.123.123/32", dry_run=True, ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the GrantSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set" ) @@ -293,9 +293,9 @@ def test_authorize_ip_range_and_revoke(): cidr_ip="123.123.123.123/32", dry_run=True, ) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the RevokeSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set" ) @@ -338,9 +338,9 @@ def test_authorize_other_group_and_revoke(): security_group.revoke( ip_protocol="tcp", from_port="22", to_port="2222", src_group=wrong_group ) - cm.exception.code.should.equal("InvalidPermission.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidPermission.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none # Actually revoke security_group.revoke( @@ -441,9 +441,9 @@ def test_get_all_security_groups(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_security_groups(groupnames=["does_not_exist"]) - cm.exception.code.should.equal("InvalidGroup.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidGroup.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none resp.should.have.length_of(1) resp[0].id.should.equal(sg1.id) @@ -472,9 +472,9 @@ def test_authorize_bad_cidr_throws_invalid_parameter_value(): security_group.authorize( ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123" ) - cm.exception.code.should.equal("InvalidParameterValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidParameterValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -486,9 +486,9 @@ def test_security_group_tagging(): with pytest.raises(EC2ResponseError) as ex: sg.add_tag("Test", "Tag", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -539,7 +539,7 @@ def test_sec_group_rule_limit(): ip_protocol="-1", cidr_ip=["{0}.0.0.0/0".format(i) for i in range(110)], ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") sg.rules.should.be.empty # authorize a rule targeting a different sec group (because this count too) @@ -559,13 +559,13 @@ def test_sec_group_rule_limit(): ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", cidr_ip=["100.0.0.0/0"] ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # verify that we cannot authorize past the limit for a different sec group with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", src_security_group_group_id=other_sg.id ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # EGRESS # authorize a rule targeting a different sec group (because this count too) @@ -584,13 +584,13 @@ def test_sec_group_rule_limit(): ec2_conn.authorize_security_group_egress( group_id=sg.id, ip_protocol="-1", cidr_ip="101.0.0.0/0" ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # verify that we cannot authorize past the limit for a different sec group with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group_egress( group_id=sg.id, ip_protocol="-1", src_group_id=other_sg.id ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") @mock_ec2_deprecated @@ -610,7 +610,7 @@ def test_sec_group_rule_limit_vpc(): ip_protocol="-1", cidr_ip=["{0}.0.0.0/0".format(i) for i in range(110)], ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") sg.rules.should.be.empty # authorize a rule targeting a different sec group (because this count too) @@ -630,13 +630,13 @@ def test_sec_group_rule_limit_vpc(): ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", cidr_ip=["100.0.0.0/0"] ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # verify that we cannot authorize past the limit for a different sec group with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", src_security_group_group_id=other_sg.id ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # EGRESS # authorize a rule targeting a different sec group (because this count too) @@ -655,13 +655,13 @@ def test_sec_group_rule_limit_vpc(): ec2_conn.authorize_security_group_egress( group_id=sg.id, ip_protocol="-1", cidr_ip="50.0.0.0/0" ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") # verify that we cannot authorize past the limit for a different sec group with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group_egress( group_id=sg.id, ip_protocol="-1", src_group_id=other_sg.id ) - cm.exception.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") + cm.value.error_code.should.equal("RulesPerSecurityGroupLimitExceeded") """ @@ -766,9 +766,9 @@ def test_security_group_tagging_boto3(): Tags=[{"Key": "Test", "Value": "Tag"}], DryRun=True, ) - ex.exception.response["Error"]["Code"].should.equal("DryRunOperation") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("DryRunOperation") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -927,9 +927,9 @@ def test_get_all_security_groups_filter_with_same_vpc_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_security_groups(group_ids=["does_not_exist"]) - cm.exception.code.should.equal("InvalidGroup.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidGroup.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 diff --git a/tests/test_ec2/test_spot_instances.py b/tests/test_ec2/test_spot_instances.py index c7b965918..bb4ccac3b 100644 --- a/tests/test_ec2/test_spot_instances.py +++ b/tests/test_ec2/test_spot_instances.py @@ -54,9 +54,9 @@ def test_request_spot_instances(): }, DryRun=True, ) - ex.exception.response["Error"]["Code"].should.equal("DryRunOperation") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("DryRunOperation") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal( "An error occurred (DryRunOperation) when calling the RequestSpotInstance operation: Request would have succeeded, but DryRun flag is set" ) @@ -157,9 +157,9 @@ def test_cancel_spot_instance_request(): with pytest.raises(EC2ResponseError) as ex: conn.cancel_spot_instance_requests([requests[0].id], dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CancelSpotInstance operation: Request would have succeeded, but DryRun flag is set" ) diff --git a/tests/test_ec2/test_subnets.py b/tests/test_ec2/test_subnets.py index 1d44999ae..9c14f798f 100644 --- a/tests/test_ec2/test_subnets.py +++ b/tests/test_ec2/test_subnets.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import boto3 @@ -31,9 +31,9 @@ def test_subnets(): with pytest.raises(EC2ResponseError) as cm: conn.delete_subnet(subnet.id) - cm.exception.code.should.equal("InvalidSubnetID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSubnetID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -42,9 +42,9 @@ def test_subnet_create_vpc_validation(): with pytest.raises(EC2ResponseError) as cm: conn.create_subnet("vpc-abcd1234", "10.0.0.0/18") - cm.exception.code.should.equal("InvalidVpcID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -229,9 +229,9 @@ def test_subnet_get_by_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_subnets(subnet_ids=["subnet-does_not_exist"]) - cm.exception.code.should.equal("InvalidSubnetID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidSubnetID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -391,7 +391,7 @@ def test_create_subnet_with_invalid_availability_zone(): CidrBlock="10.0.0.0/24", AvailabilityZone=subnet_availability_zone, ) - assert str(ex.exception).startswith( + assert str(ex.value).startswith( "An error occurred (InvalidParameterValue) when calling the CreateSubnet " "operation: Value ({}) for parameter availabilityZone is invalid. Subnets can currently only be created in the following availability zones: ".format( subnet_availability_zone @@ -410,7 +410,7 @@ def test_create_subnet_with_invalid_cidr_range(): subnet_cidr_block = "10.1.0.0/20" with pytest.raises(ClientError) as ex: subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidSubnet.Range) when calling the CreateSubnet " "operation: The CIDR '{}' is invalid.".format(subnet_cidr_block) ) @@ -445,7 +445,7 @@ def test_create_subnet_with_invalid_cidr_block_parameter(): subnet_cidr_block = "1000.1.0.0/20" with pytest.raises(ClientError) as ex: subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidParameterValue) when calling the CreateSubnet " "operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format( subnet_cidr_block @@ -505,7 +505,7 @@ def test_create_subnets_with_overlapping_cidr_blocks(): with pytest.raises(ClientError) as ex: subnet1 = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) subnet2 = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidSubnet.Conflict) when calling the CreateSubnet " "operation: The CIDR '{}' conflicts with another subnet".format( subnet_cidr_block diff --git a/tests/test_ec2/test_tags.py b/tests/test_ec2/test_tags.py index 918b02623..82a23c91c 100644 --- a/tests/test_ec2/test_tags.py +++ b/tests/test_ec2/test_tags.py @@ -22,9 +22,9 @@ def test_add_tag(): with pytest.raises(EC2ResponseError) as ex: instance.add_tag("a key", "some value", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -53,9 +53,9 @@ def test_remove_tag(): with pytest.raises(EC2ResponseError) as ex: instance.remove_tag("a key", dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the DeleteTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -108,9 +108,9 @@ def test_create_tags(): with pytest.raises(EC2ResponseError) as ex: conn.create_tags(instance.id, tag_dict, dry_run=True) - ex.exception.error_code.should.equal("DryRunOperation") - ex.exception.status.should.equal(400) - ex.exception.message.should.equal( + ex.value.error_code.should.equal("DryRunOperation") + ex.value.status.should.equal(400) + ex.value.message.should.equal( "An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set" ) @@ -133,16 +133,16 @@ def test_tag_limit_exceeded(): with pytest.raises(EC2ResponseError) as cm: conn.create_tags(instance.id, tag_dict) - cm.exception.code.should.equal("TagLimitExceeded") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("TagLimitExceeded") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none instance.add_tag("a key", "a value") with pytest.raises(EC2ResponseError) as cm: conn.create_tags(instance.id, tag_dict) - cm.exception.code.should.equal("TagLimitExceeded") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("TagLimitExceeded") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none tags = conn.get_all_tags() tag = tags[0] @@ -159,9 +159,9 @@ def test_invalid_parameter_tag_null(): with pytest.raises(EC2ResponseError) as cm: instance.add_tag("a key", None) - cm.exception.code.should.equal("InvalidParameterValue") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidParameterValue") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -169,15 +169,15 @@ def test_invalid_id(): conn = boto.connect_ec2("the_key", "the_secret") with pytest.raises(EC2ResponseError) as cm: conn.create_tags("ami-blah", {"key": "tag"}) - cm.exception.code.should.equal("InvalidID") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidID") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none with pytest.raises(EC2ResponseError) as cm: conn.create_tags("blah-blah", {"key": "tag"}) - cm.exception.code.should.equal("InvalidID") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidID") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -451,8 +451,8 @@ def test_create_tag_empty_resource(): # create tag with empty resource with pytest.raises(ClientError) as ex: client.create_tags(Resources=[], Tags=[{"Key": "Value"}]) - ex.exception.response["Error"]["Code"].should.equal("MissingParameter") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("MissingParameter") + ex.value.response["Error"]["Message"].should.equal( "The request must contain the parameter resourceIdSet" ) @@ -464,8 +464,8 @@ def test_delete_tag_empty_resource(): # delete tag with empty resource with pytest.raises(ClientError) as ex: client.delete_tags(Resources=[], Tags=[{"Key": "Value"}]) - ex.exception.response["Error"]["Code"].should.equal("MissingParameter") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("MissingParameter") + ex.value.response["Error"]["Message"].should.equal( "The request must contain the parameter resourceIdSet" ) diff --git a/tests/test_ec2/test_vpc_peering.py b/tests/test_ec2/test_vpc_peering.py index f852ab3ca..2ffe89fca 100644 --- a/tests/test_ec2/test_vpc_peering.py +++ b/tests/test_ec2/test_vpc_peering.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest from moto.ec2.exceptions import EC2ClientError from botocore.exceptions import ClientError @@ -50,9 +50,9 @@ def test_vpc_peering_connections_accept(): with pytest.raises(EC2ResponseError) as cm: conn.reject_vpc_peering_connection(vpc_pcx.id) - cm.exception.code.should.equal("InvalidStateTransition") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidStateTransition") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none all_vpc_pcxs = conn.get_all_vpc_peering_connections() all_vpc_pcxs.should.have.length_of(1) @@ -70,9 +70,9 @@ def test_vpc_peering_connections_reject(): with pytest.raises(EC2ResponseError) as cm: conn.accept_vpc_peering_connection(vpc_pcx.id) - cm.exception.code.should.equal("InvalidStateTransition") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidStateTransition") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none all_vpc_pcxs = conn.get_all_vpc_peering_connections() all_vpc_pcxs.should.have.length_of(1) @@ -94,9 +94,9 @@ def test_vpc_peering_connections_delete(): with pytest.raises(EC2ResponseError) as cm: conn.delete_vpc_peering_connection("pcx-1234abcd") - cm.exception.code.should.equal("InvalidVpcPeeringConnectionId.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcPeeringConnectionId.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2 @@ -132,7 +132,7 @@ def test_vpc_peering_connections_cross_region_fail(): ec2_usw1.create_vpc_peering_connection( VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-2" ) - cm.exception.response["Error"]["Code"].should.equal("InvalidVpcID.NotFound") + cm.value.response["Error"]["Code"].should.equal("InvalidVpcID.NotFound") @mock_ec2 @@ -254,13 +254,13 @@ def test_vpc_peering_connections_cross_region_accept_wrong_region(): ec2_usw1 = boto3.client("ec2", region_name="us-west-1") with pytest.raises(ClientError) as cm: ec2_usw1.accept_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id) - cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted") + cm.value.response["Error"]["Code"].should.equal("OperationNotPermitted") exp_msg = ( "Incorrect region ({0}) specified for this request.VPC " "peering connection {1} must be " "accepted in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1") ) - cm.exception.response["Error"]["Message"].should.equal(exp_msg) + cm.value.response["Error"]["Message"].should.equal(exp_msg) @mock_ec2 @@ -279,10 +279,10 @@ def test_vpc_peering_connections_cross_region_reject_wrong_region(): ec2_usw1 = boto3.client("ec2", region_name="us-west-1") with pytest.raises(ClientError) as cm: ec2_usw1.reject_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id) - cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted") + cm.value.response["Error"]["Code"].should.equal("OperationNotPermitted") exp_msg = ( "Incorrect region ({0}) specified for this request.VPC " "peering connection {1} must be accepted or " "rejected in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1") ) - cm.exception.response["Error"]["Message"].should.equal(exp_msg) + cm.value.response["Error"]["Message"].should.equal(exp_msg) diff --git a/tests/test_ec2/test_vpcs.py b/tests/test_ec2/test_vpcs.py index 32e59a91b..5344098ba 100644 --- a/tests/test_ec2/test_vpcs.py +++ b/tests/test_ec2/test_vpcs.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -# Ensure 'assert_raises' context manager support for Python 2.6 +# Ensure 'pytest.raises' context manager support for Python 2.6 import pytest from moto.ec2.exceptions import EC2ClientError from botocore.exceptions import ClientError @@ -32,9 +32,9 @@ def test_vpcs(): with pytest.raises(EC2ResponseError) as cm: conn.delete_vpc("vpc-1234abcd") - cm.exception.code.should.equal("InvalidVpcID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -115,9 +115,9 @@ def test_vpc_get_by_id(): with pytest.raises(EC2ResponseError) as cm: conn.get_all_vpcs(vpc_ids=["vpc-does_not_exist"]) - cm.exception.code.should.equal("InvalidVpcID.NotFound") - cm.exception.status.should.equal(400) - cm.exception.request_id.should_not.be.none + cm.value.code.should.equal("InvalidVpcID.NotFound") + cm.value.status.should.equal(400) + cm.value.request_id.should_not.be.none @mock_ec2_deprecated @@ -405,7 +405,7 @@ def test_associate_vpc_ipv4_cidr_block(): response = ec2.meta.client.associate_vpc_cidr_block( VpcId=vpc.id, CidrBlock="10.10.50.0/22" ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (CidrLimitExceeded) when calling the AssociateVpcCidrBlock " "operation: This network '{}' has met its maximum number of allowed CIDRs: 5".format( vpc.id @@ -450,7 +450,7 @@ def test_disassociate_vpc_ipv4_cidr_block(): response = ec2.meta.client.disassociate_vpc_cidr_block( AssociationId="vpc-cidr-assoc-BORING123" ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidVpcCidrBlockAssociationIdError.NotFound) when calling the " "DisassociateVpcCidrBlock operation: The vpc CIDR block association ID " "'vpc-cidr-assoc-BORING123' does not exist" @@ -472,7 +472,7 @@ def test_disassociate_vpc_ipv4_cidr_block(): response = ec2.meta.client.disassociate_vpc_cidr_block( AssociationId=vpc_base_cidr_assoc_id ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (OperationNotPermitted) when calling the DisassociateVpcCidrBlock operation: " "The vpc CIDR block with association ID {} may not be disassociated. It is the primary " "IPv4 CIDR block of the VPC".format(vpc_base_cidr_assoc_id) @@ -552,7 +552,7 @@ def test_vpc_associate_ipv6_cidr_block(): response = ec2.meta.client.associate_vpc_cidr_block( VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True ) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (CidrLimitExceeded) when calling the AssociateVpcCidrBlock " "operation: This network '{}' has met its maximum number of allowed CIDRs: 1".format( vpc.id @@ -658,7 +658,7 @@ def test_create_vpc_with_invalid_cidr_block_parameter(): vpc_cidr_block = "1000.1.0.0/20" with pytest.raises(ClientError) as ex: vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidParameterValue) when calling the CreateVpc " "operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format( vpc_cidr_block @@ -673,7 +673,7 @@ def test_create_vpc_with_invalid_cidr_range(): vpc_cidr_block = "10.1.0.0/29" with pytest.raises(ClientError) as ex: vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block) - str(ex.exception).should.equal( + str(ex.value).should.equal( "An error occurred (InvalidVpc.Range) when calling the CreateVpc " "operation: The CIDR '{}' is invalid.".format(vpc_cidr_block) ) diff --git a/tests/test_ecs/test_ecs_boto3.py b/tests/test_ecs/test_ecs_boto3.py index afec17da2..8b6b27987 100644 --- a/tests/test_ecs/test_ecs_boto3.py +++ b/tests/test_ecs/test_ecs_boto3.py @@ -2611,7 +2611,7 @@ def test_delete_task_set(): assert len(task_sets) == 0 - with assert_raises(ClientError): + with pytest.raises(ClientError): _ = client.delete_task_set( cluster=cluster_name, service=service_name, taskSet=task_set["taskSetArn"], ) diff --git a/tests/test_elb/test_elb.py b/tests/test_elb/test_elb.py index dd51e8f60..a2e8871d8 100644 --- a/tests/test_elb/test_elb.py +++ b/tests/test_elb/test_elb.py @@ -184,9 +184,8 @@ def test_apply_security_groups_to_load_balancer(): response = client.apply_security_groups_to_load_balancer( LoadBalancerName="my-lb", SecurityGroups=["not-really-a-security-group"] ) - assert "One or more of the specified security groups do not exist." in str( - error.exception - ) + assert "One or more of the specified security groups do not exist." \ + in str(error.value) @mock_elb_deprecated diff --git a/tests/test_elbv2/test_elbv2.py b/tests/test_elbv2/test_elbv2.py index 6ff48095d..cb8e13e52 100644 --- a/tests/test_elbv2/test_elbv2.py +++ b/tests/test_elbv2/test_elbv2.py @@ -391,8 +391,8 @@ def test_create_target_group_and_listeners(): # listener referencing it with pytest.raises(ClientError) as e: conn.delete_target_group(TargetGroupArn=target_group.get("TargetGroupArn")) - e.exception.operation_name.should.equal("DeleteTargetGroup") - e.exception.args.should.equal( + e.value.operation_name.should.equal("DeleteTargetGroup") + e.value.args.should.equal( ( "An error occurred (ResourceInUse) when calling the DeleteTargetGroup operation: The target group 'arn:aws:elasticloadbalancing:us-east-1:1:targetgroup/a-target/50dc6c495c0c9188' is currently in use by a listener or a rule", ) @@ -1959,7 +1959,7 @@ def test_fixed_response_action_listener_rule_validates_status_code(): DefaultActions=[invalid_status_code_action], ) - invalid_status_code_exception.exception.response["Error"]["Code"].should.equal( + invalid_status_code_exception.value.response["Error"]["Code"].should.equal( "ValidationError" ) @@ -2005,6 +2005,6 @@ def test_fixed_response_action_listener_rule_validates_content_type(): Port=80, DefaultActions=[invalid_content_type_action], ) - invalid_content_type_exception.exception.response["Error"]["Code"].should.equal( + invalid_content_type_exception.value.response["Error"]["Code"].should.equal( "InvalidLoadBalancerAction" ) diff --git a/tests/test_emr/test_emr_boto3.py b/tests/test_emr/test_emr_boto3.py index a3308e3fe..c6b93957a 100644 --- a/tests/test_emr/test_emr_boto3.py +++ b/tests/test_emr/test_emr_boto3.py @@ -401,7 +401,7 @@ def test_run_job_flow_with_invalid_params(): args["AmiVersion"] = "2.4" args["ReleaseLabel"] = "emr-5.0.0" client.run_job_flow(**args) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Code"].should.equal("ValidationException") @mock_emr @@ -598,16 +598,16 @@ def test_run_job_flow_with_custom_ami(): args["CustomAmiId"] = "MyEmrCustomId" args["ReleaseLabel"] = "emr-5.6.0" client.run_job_flow(**args) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal("Custom AMI is not allowed") + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal("Custom AMI is not allowed") with pytest.raises(ClientError) as ex: args = deepcopy(run_job_flow_args) args["CustomAmiId"] = "MyEmrCustomId" args["AmiVersion"] = "3.8.1" client.run_job_flow(**args) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.equal( "Custom AMI is not supported in this version of EMR" ) @@ -618,8 +618,8 @@ def test_run_job_flow_with_custom_ami(): args["ReleaseLabel"] = "emr-5.6.0" args["AmiVersion"] = "3.8.1" client.run_job_flow(**args) - ex.exception.response["Error"]["Code"].should.equal("ValidationException") - ex.exception.response["Error"]["Message"].should.contain( + ex.value.response["Error"]["Code"].should.equal("ValidationException") + ex.value.response["Error"]["Message"].should.contain( "Only one AMI version and release label may be specified." ) diff --git a/tests/test_glue/test_datacatalog.py b/tests/test_glue/test_datacatalog.py index ac63932ef..575528239 100644 --- a/tests/test_glue/test_datacatalog.py +++ b/tests/test_glue/test_datacatalog.py @@ -35,7 +35,7 @@ def test_create_database_already_exists(): with pytest.raises(ClientError) as exc: helpers.create_database(client, database_name) - exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") + exc.value.response["Error"]["Code"].should.equal("AlreadyExistsException") @mock_glue @@ -46,8 +46,8 @@ def test_get_database_not_exits(): with pytest.raises(ClientError) as exc: helpers.get_database(client, database_name) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match( + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match( "Database nosuchdatabase not found" ) @@ -105,7 +105,7 @@ def test_create_table_already_exists(): with pytest.raises(ClientError) as exc: helpers.create_table(client, database_name, table_name) - exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") + exc.value.response["Error"]["Code"].should.equal("AlreadyExistsException") @mock_glue @@ -195,8 +195,8 @@ def test_get_table_version_not_found(): with pytest.raises(ClientError) as exc: helpers.get_table_version(client, database_name, "myfirsttable", "20") - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match("version", re.I) + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match("version", re.I) @mock_glue @@ -210,7 +210,7 @@ def test_get_table_version_invalid_input(): with pytest.raises(ClientError) as exc: helpers.get_table_version(client, database_name, "myfirsttable", "10not-an-int") - exc.exception.response["Error"]["Code"].should.equal("InvalidInputException") + exc.value.response["Error"]["Code"].should.equal("InvalidInputException") @mock_glue @@ -222,8 +222,8 @@ def test_get_table_not_exits(): with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, "myfirsttable") - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match( + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match( "Table myfirsttable not found" ) @@ -236,8 +236,8 @@ def test_get_table_when_database_not_exits(): with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, "myfirsttable") - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match( + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match( "Database nosuchdatabase not found" ) @@ -259,8 +259,8 @@ def test_delete_table(): with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, table_name) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match( + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match( "Table myspecialtable not found" ) @@ -284,8 +284,8 @@ def test_batch_delete_table(): with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, table_name) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match( + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match( "Table myspecialtable not found" ) @@ -353,7 +353,7 @@ def test_create_partition_already_exist(): with pytest.raises(ClientError) as exc: helpers.create_partition(client, database_name, table_name, values=values) - exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") + exc.value.response["Error"]["Code"].should.equal("AlreadyExistsException") @mock_glue @@ -369,8 +369,8 @@ def test_get_partition_not_found(): with pytest.raises(ClientError) as exc: helpers.get_partition(client, database_name, table_name, values) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match("partition") + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match("partition") @mock_glue @@ -551,8 +551,8 @@ def test_update_partition_not_found_moving(): values=["2018-10-02"], ) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match("partition") + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match("partition") @mock_glue @@ -570,8 +570,8 @@ def test_update_partition_not_found_change_in_place(): client, database_name, table_name, old_values=values, values=values ) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") - exc.exception.response["Error"]["Message"].should.match("partition") + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Message"].should.match("partition") @mock_glue @@ -593,7 +593,7 @@ def test_update_partition_cannot_overwrite(): client, database_name, table_name, old_values=values[0], values=values[1] ) - exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") + exc.value.response["Error"]["Code"].should.equal("AlreadyExistsException") @mock_glue @@ -652,7 +652,7 @@ def test_update_partition_move(): helpers.get_partition(client, database_name, table_name, values) # Old partition shouldn't exist anymore - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") response = client.get_partition( DatabaseName=database_name, TableName=table_name, PartitionValues=new_values @@ -702,7 +702,7 @@ def test_delete_partition_bad_partition(): DatabaseName=database_name, TableName=table_name, PartitionValues=values ) - exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") + exc.value.response["Error"]["Code"].should.equal("EntityNotFoundException") @mock_glue diff --git a/tests/test_iam/test_iam.py b/tests/test_iam/test_iam.py index d63e1777f..b404a4106 100644 --- a/tests/test_iam/test_iam.py +++ b/tests/test_iam/test_iam.py @@ -445,9 +445,9 @@ def test_create_policy_already_exists(): response = conn.create_policy( PolicyName="TestCreatePolicy", PolicyDocument=MOCK_POLICY ) - ex.exception.response["Error"]["Code"].should.equal("EntityAlreadyExists") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(409) - ex.exception.response["Error"]["Message"].should.contain("TestCreatePolicy") + ex.value.response["Error"]["Code"].should.equal("EntityAlreadyExists") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(409) + ex.value.response["Error"]["Message"].should.contain("TestCreatePolicy") @mock_iam @@ -1825,7 +1825,7 @@ def test_signing_certs(): client.upload_signing_certificate( UserName="testing", CertificateBody="notacert" ) - assert ce.exception.response["Error"]["Code"] == "MalformedCertificate" + assert ce.value.response["Error"]["Code"] == "MalformedCertificate" # Upload with an invalid user: with pytest.raises(ClientError): @@ -1848,7 +1848,7 @@ def test_signing_certs(): UserName="testing", CertificateId="x" * 32, Status="Inactive" ) - assert ce.exception.response["Error"][ + assert ce.value.response["Error"][ "Message" ] == "The Certificate with id {id} cannot be found.".format(id="x" * 32) @@ -1918,7 +1918,7 @@ def test_delete_saml_provider(): with pytest.raises(ClientError) as ce: conn.delete_signing_certificate(UserName="testing", CertificateId=cert_id) - assert ce.exception.response["Error"][ + assert ce.value.response["Error"][ "Message" ] == "The Certificate with id {id} cannot be found.".format(id=cert_id) @@ -1985,7 +1985,7 @@ def test_create_role_with_tags(): ) assert ( "failed to satisfy constraint: Member must have length less than or equal to 50." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a duplicate tag: @@ -1997,7 +1997,7 @@ def test_create_role_with_tags(): ) assert ( "Duplicate tag keys found. Please note that Tag keys are case insensitive." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Duplicate tag with different casing: @@ -2009,7 +2009,7 @@ def test_create_role_with_tags(): ) assert ( "Duplicate tag keys found. Please note that Tag keys are case insensitive." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a really big key: @@ -2021,7 +2021,7 @@ def test_create_role_with_tags(): ) assert ( "Member must have length less than or equal to 128." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a really big value: @@ -2033,7 +2033,7 @@ def test_create_role_with_tags(): ) assert ( "Member must have length less than or equal to 256." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With an invalid character: @@ -2045,7 +2045,7 @@ def test_create_role_with_tags(): ) assert ( "Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) @@ -2126,7 +2126,7 @@ def test_tag_role(): conn.tag_role(RoleName="my-role", Tags=too_many_tags) assert ( "failed to satisfy constraint: Member must have length less than or equal to 50." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a duplicate tag: @@ -2137,7 +2137,7 @@ def test_tag_role(): ) assert ( "Duplicate tag keys found. Please note that Tag keys are case insensitive." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Duplicate tag with different casing: @@ -2148,7 +2148,7 @@ def test_tag_role(): ) assert ( "Duplicate tag keys found. Please note that Tag keys are case insensitive." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a really big key: @@ -2156,7 +2156,7 @@ def test_tag_role(): conn.tag_role(RoleName="my-role", Tags=[{"Key": "0" * 129, "Value": ""}]) assert ( "Member must have length less than or equal to 128." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a really big value: @@ -2164,7 +2164,7 @@ def test_tag_role(): conn.tag_role(RoleName="my-role", Tags=[{"Key": "0", "Value": "0" * 257}]) assert ( "Member must have length less than or equal to 256." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With an invalid character: @@ -2172,7 +2172,7 @@ def test_tag_role(): conn.tag_role(RoleName="my-role", Tags=[{"Key": "NOWAY!", "Value": ""}]) assert ( "Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # With a role that doesn't exist: @@ -2212,27 +2212,27 @@ def test_untag_role(): conn.untag_role(RoleName="my-role", TagKeys=[str(x) for x in range(0, 51)]) assert ( "failed to satisfy constraint: Member must have length less than or equal to 50." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert "tagKeys" in ce.exception.response["Error"]["Message"] + assert "tagKeys" in ce.value.response["Error"]["Message"] # With a really big key: with pytest.raises(ClientError) as ce: conn.untag_role(RoleName="my-role", TagKeys=["0" * 129]) assert ( "Member must have length less than or equal to 128." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert "tagKeys" in ce.exception.response["Error"]["Message"] + assert "tagKeys" in ce.value.response["Error"]["Message"] # With an invalid character: with pytest.raises(ClientError) as ce: conn.untag_role(RoleName="my-role", TagKeys=["NOWAY!"]) assert ( "Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+" - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) - assert "tagKeys" in ce.exception.response["Error"]["Message"] + assert "tagKeys" in ce.value.response["Error"]["Message"] # With a role that doesn't exist: with pytest.raises(ClientError): @@ -2461,8 +2461,8 @@ def test_create_role_with_same_name_should_fail(): AssumeRolePolicyDocument="policy", Description="test", ) - err.exception.response["Error"]["Code"].should.equal("EntityAlreadyExists") - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Code"].should.equal("EntityAlreadyExists") + err.value.response["Error"]["Message"].should.equal( "Role with name {0} already exists.".format(test_role_name) ) @@ -2475,8 +2475,8 @@ def test_create_policy_with_same_name_should_fail(): # Create the role again, and verify that it fails with pytest.raises(ClientError) as err: iam.create_policy(PolicyName=test_policy_name, PolicyDocument=MOCK_POLICY) - err.exception.response["Error"]["Code"].should.equal("EntityAlreadyExists") - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Code"].should.equal("EntityAlreadyExists") + err.value.response["Error"]["Message"].should.equal( "A policy called {0} already exists. Duplicate names are not allowed.".format( test_policy_name ) diff --git a/tests/test_iam/test_iam_cloudformation.py b/tests/test_iam/test_iam_cloudformation.py index 737e76323..a50ed8234 100644 --- a/tests/test_iam/test_iam_cloudformation.py +++ b/tests/test_iam/test_iam_cloudformation.py @@ -113,7 +113,7 @@ Resources: with pytest.raises(ClientError) as e: iam_client.get_user(UserName=original_user_name) - e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") + e.value.response["Error"]["Code"].should.equal("NoSuchEntity") iam_client.get_user(UserName=new_user_name) @@ -177,7 +177,7 @@ Resources: iam_client.get_user(UserName=second_user_name) with pytest.raises(ClientError) as e: iam_client.get_user(UserName=first_user_name) - e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") + e.value.response["Error"]["Code"].should.equal("NoSuchEntity") @mock_iam @@ -207,7 +207,7 @@ Resources: with pytest.raises(ClientError) as e: user = iam_client.get_user(UserName=user_name) - e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") + e.value.response["Error"]["Code"].should.equal("NoSuchEntity") @mock_iam @@ -237,7 +237,7 @@ Resources: with pytest.raises(ClientError) as e: user = iam_client.get_user(UserName=user_name) - e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") + e.value.response["Error"]["Code"].should.equal("NoSuchEntity") @mock_iam diff --git a/tests/test_iam/test_iam_groups.py b/tests/test_iam/test_iam_groups.py index a6bb5f4c0..85464b44d 100644 --- a/tests/test_iam/test_iam_groups.py +++ b/tests/test_iam/test_iam_groups.py @@ -199,9 +199,9 @@ def test_delete_group(): @mock_iam def test_delete_unknown_group(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: conn.delete_group(GroupName="unknown-group") - err.exception.response["Error"]["Code"].should.equal("NoSuchEntity") - err.exception.response["Error"]["Message"].should.equal( + err.value.response["Error"]["Code"].should.equal("NoSuchEntity") + err.value.response["Error"]["Message"].should.equal( "The group with name unknown-group cannot be found." ) diff --git a/tests/test_iam/test_iam_policies.py b/tests/test_iam/test_iam_policies.py index dae533827..fec291c94 100644 --- a/tests/test_iam/test_iam_policies.py +++ b/tests/test_iam/test_iam_policies.py @@ -1629,9 +1629,9 @@ def check_create_policy_with_invalid_policy_document(test_case): PolicyName="TestCreatePolicy", PolicyDocument=json.dumps(test_case["document"]), ) - ex.exception.response["Error"]["Code"].should.equal("MalformedPolicyDocument") - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) - ex.exception.response["Error"]["Message"].should.equal(test_case["error_message"]) + ex.value.response["Error"]["Code"].should.equal("MalformedPolicyDocument") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + ex.value.response["Error"]["Message"].should.equal(test_case["error_message"]) @mock_iam diff --git a/tests/test_iot/test_iot.py b/tests/test_iot/test_iot.py index 44b365182..bea6958ac 100644 --- a/tests/test_iot/test_iot.py +++ b/tests/test_iot/test_iot.py @@ -604,7 +604,7 @@ def test_create_certificate_validation(): client = boto3.client("iot", region_name="us-east-1") cert = client.create_keys_and_certificate(setAsActive=False) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_certificate( certificatePem=cert["certificatePem"], setAsActive=False ) @@ -612,7 +612,7 @@ def test_create_certificate_validation(): "The certificate is already provisioned or registered" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_certificate_without_ca( certificatePem=cert["certificatePem"], status="ACTIVE" ) @@ -645,7 +645,7 @@ def test_delete_policy_validation(): with pytest.raises(ClientError) as e: client.delete_policy(policyName=policy_name) - e.exception.response["Error"]["Message"].should.contain( + e.value.response["Error"]["Message"].should.contain( "The policy cannot be deleted as the policy is attached to one or more principals (name=%s)" % policy_name ) @@ -686,7 +686,7 @@ def test_delete_certificate_validation(): with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) - e.exception.response["Error"]["Message"].should.contain( + e.value.response["Error"]["Message"].should.contain( "Certificate must be deactivated (not ACTIVE) before deletion." ) res = client.list_certificates() @@ -695,7 +695,7 @@ def test_delete_certificate_validation(): client.update_certificate(certificateId=cert_id, newStatus="REVOKED") with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) - e.exception.response["Error"]["Message"].should.contain( + e.value.response["Error"]["Message"].should.contain( "Things must be detached before deletion (arn: %s)" % cert_arn ) res = client.list_certificates() @@ -704,7 +704,7 @@ def test_delete_certificate_validation(): client.detach_thing_principal(thingName=thing_name, principal=cert_arn) with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) - e.exception.response["Error"]["Message"].should.contain( + e.value.response["Error"]["Message"].should.contain( "Certificate policies must be detached before deletion (arn: %s)" % cert_arn ) res = client.list_certificates() @@ -800,7 +800,7 @@ def test_principal_policy(): res.should.have.key("principals").which.should.have.length_of(0) with pytest.raises(ClientError) as e: client.detach_policy(policyName=policy_name, target=cert_arn) - e.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") + e.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") @mock_iot @@ -857,11 +857,11 @@ def test_principal_thing(): res = client.list_thing_principals(thingName=thing_name) res.should.have.key("principals").which.should.have.length_of(0) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_thing_principals(thingName="xxx") - e.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") - e.exception.response["Error"]["Message"].should.equal( + e.value.response["Error"]["Code"].should.equal("ResourceNotFoundException") + e.value.response["Error"]["Message"].should.equal( "Failed to list principals for thing xxx because the thing does not exist in your account" ) @@ -937,9 +937,9 @@ class TestListThingGroup: resp = client.list_thing_groups(parentGroup=self.group_name_1b) resp.should.have.key("thingGroups") resp["thingGroups"].should.have.length_of(0) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_thing_groups(parentGroup="inexistant-group-name") - e.exception.response["Error"]["Code"].should.equal( + e.value.response["Error"]["Code"].should.equal( "ResourceNotFoundException" ) diff --git a/tests/test_iotdata/test_iotdata.py b/tests/test_iotdata/test_iotdata.py index caebdbde8..bbef49348 100644 --- a/tests/test_iotdata/test_iotdata.py +++ b/tests/test_iotdata/test_iotdata.py @@ -101,8 +101,8 @@ def test_update(): raw_payload = b'{"state": {"desired": {"led": "on"}}, "version": 1}' with pytest.raises(ClientError) as ex: client.update_thing_shadow(thingName=name, payload=raw_payload) - ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(409) - ex.exception.response["Error"]["Message"].should.equal("Version conflict") + ex.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(409) + ex.value.response["Error"]["Message"].should.equal("Version conflict") @mock_iotdata diff --git a/tests/test_kms/test_kms.py b/tests/test_kms/test_kms.py index 64c70078e..e79bf8bbf 100644 --- a/tests/test_kms/test_kms.py +++ b/tests/test_kms/test_kms.py @@ -367,7 +367,7 @@ def test__create_alias__raises_if_reserved_alias(): with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) - ex = err.exception + ex = err.value ex.error_message.should.be.none ex.error_code.should.equal("NotAuthorizedException") ex.body.should.equal({"__type": "NotAuthorizedException"}) @@ -395,7 +395,7 @@ def test__create_alias__raises_if_wrong_prefix(): with pytest.raises(JSONResponseError) as err: kms.create_alias("wrongprefix/my-alias", key_id) - ex = err.exception + ex = err.value ex.error_message.should.equal("Invalid identifier") ex.error_code.should.equal("ValidationException") ex.body.should.equal( @@ -418,7 +418,7 @@ def test__create_alias__raises_if_duplicate(): with pytest.raises(AlreadyExistsException) as err: kms.create_alias(alias, key_id) - ex = err.exception + ex = err.value ex.error_message.should.match( r"An alias with the name arn:aws:kms:{region}:\d{{12}}:{alias} already exists".format( **locals() @@ -452,7 +452,7 @@ def test__create_alias__raises_if_alias_has_restricted_characters(): for alias_name in alias_names_with_restricted_characters: with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) - ex = err.exception + ex = err.value ex.body["__type"].should.equal("ValidationException") ex.body["message"].should.equal( "1 validation error detected: Value '{alias_name}' at 'aliasName' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9:/_-]+$".format( @@ -482,7 +482,7 @@ def test__create_alias__raises_if_alias_has_colon_character(): for alias_name in alias_names_with_restricted_characters: with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) - ex = err.exception + ex = err.value ex.body["__type"].should.equal("ValidationException") ex.body["message"].should.equal( "{alias_name} contains invalid characters for an alias".format(**locals()) @@ -517,7 +517,7 @@ def test__create_alias__raises_if_target_key_id_is_existing_alias(): with pytest.raises(JSONResponseError) as err: kms.create_alias(alias, alias) - ex = err.exception + ex = err.value ex.body["__type"].should.equal("ValidationException") ex.body["message"].should.equal("Aliases must refer to keys. Not aliases") ex.error_code.should.equal("ValidationException") @@ -557,7 +557,7 @@ def test__delete_alias__raises_if_wrong_prefix(): with pytest.raises(JSONResponseError) as err: kms.delete_alias("wrongprefix/my-alias") - ex = err.exception + ex = err.value ex.body["__type"].should.equal("ValidationException") ex.body["message"].should.equal("Invalid identifier") ex.error_code.should.equal("ValidationException") @@ -578,7 +578,7 @@ def test__delete_alias__raises_if_alias_is_not_found(): expected_message_match = r"Alias arn:aws:kms:{region}:[0-9]{{12}}:{alias_name} is not found.".format( region=region, alias_name=alias_name ) - ex = err.exception + ex = err.value ex.body["__type"].should.equal("NotFoundException") ex.body["message"].should.match(expected_message_match) ex.box_usage.should.be.none diff --git a/tests/test_logs/test_integration.py b/tests/test_logs/test_integration.py index bda233485..eab839970 100644 --- a/tests/test_logs/test_integration.py +++ b/tests/test_logs/test_integration.py @@ -7,7 +7,7 @@ import zlib from botocore.exceptions import ClientError from io import BytesIO from moto import mock_logs, mock_lambda, mock_iam -from nose.tools import assert_raises +import pytest from zipfile import ZipFile, ZIP_DEFLATED @@ -78,7 +78,7 @@ def test_put_subscription_filter_update(): # when # only one subscription filter can be associated with a log group - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client_logs.put_subscription_filter( logGroupName=log_group_name, filterName="test-2", @@ -87,7 +87,7 @@ def test_put_subscription_filter_update(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("LimitExceededException") @@ -96,6 +96,7 @@ def test_put_subscription_filter_update(): @mock_lambda @mock_logs +@pytest.mark.network def test_put_subscription_filter_with_lambda(): # given region_name = "us-east-1" @@ -240,13 +241,13 @@ def test_delete_subscription_filter_errors(): ) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client_logs.delete_subscription_filter( logGroupName="not-existing-log-group", filterName="test", ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeleteSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -255,13 +256,13 @@ def test_delete_subscription_filter_errors(): ) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client_logs.delete_subscription_filter( logGroupName="/test", filterName="wrong-filter-name", ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeleteSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -278,7 +279,7 @@ def test_put_subscription_filter_errors(): client.create_log_group(logGroupName=log_group_name) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.put_subscription_filter( logGroupName="not-existing-log-group", filterName="test", @@ -287,7 +288,7 @@ def test_put_subscription_filter_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") @@ -296,7 +297,7 @@ def test_put_subscription_filter_errors(): ) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.put_subscription_filter( logGroupName="/test", filterName="test", @@ -305,7 +306,7 @@ def test_put_subscription_filter_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterException") @@ -315,7 +316,7 @@ def test_put_subscription_filter_errors(): ) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.put_subscription_filter( logGroupName="/test", filterName="test", @@ -324,7 +325,7 @@ def test_put_subscription_filter_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("PutSubscriptionFilter") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterException") diff --git a/tests/test_logs/test_logs.py b/tests/test_logs/test_logs.py index f693aeb1e..fc9868ffb 100644 --- a/tests/test_logs/test_logs.py +++ b/tests/test_logs/test_logs.py @@ -338,7 +338,7 @@ def test_get_log_events_errors(): logStreamName=log_stream_name, nextToken="n/00000000000000000000000000000000000000000000000000000000", ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetLogEvents") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.equal("InvalidParameterException") @@ -352,7 +352,7 @@ def test_get_log_events_errors(): logStreamName=log_stream_name, nextToken="not-existing-token", ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetLogEvents") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.equal("InvalidParameterException") @@ -451,7 +451,7 @@ def test_describe_subscription_filters_errors(): client.describe_subscription_filters(logGroupName="not-existing-log-group",) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeSubscriptionFilters") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ResourceNotFoundException") diff --git a/tests/test_organizations/test_organizations_boto3.py b/tests/test_organizations/test_organizations_boto3.py index 1d2ef3715..07cd3afa6 100644 --- a/tests/test_organizations/test_organizations_boto3.py +++ b/tests/test_organizations/test_organizations_boto3.py @@ -63,7 +63,7 @@ def test_describe_organization_exception(): client = boto3.client("organizations", region_name="us-east-1") with pytest.raises(ClientError) as e: response = client.describe_organization() - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeOrganization") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AWSOrganizationsNotInUseException") @@ -114,7 +114,7 @@ def test_describe_organizational_unit_exception(): response = client.describe_organizational_unit( OrganizationalUnitId=utils.make_random_root_id() ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeOrganizationalUnit") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -143,7 +143,7 @@ def test_list_organizational_units_for_parent_exception(): response = client.list_organizational_units_for_parent( ParentId=utils.make_random_root_id() ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListOrganizationalUnitsForParent") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("ParentNotFoundException") @@ -195,7 +195,7 @@ def test_describe_account_exception(): client = boto3.client("organizations", region_name="us-east-1") with pytest.raises(ClientError) as e: response = client.describe_account(AccountId=utils.make_random_account_id()) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribeAccount") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -339,13 +339,13 @@ def test_list_children_exception(): response = client.list_children( ParentId=utils.make_random_root_id(), ChildType="ACCOUNT" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListChildren") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("ParentNotFoundException") with pytest.raises(ClientError) as e: response = client.list_children(ParentId=root_id, ChildType="BLEE") - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListChildren") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -396,7 +396,7 @@ def test_create_policy_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreatePolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -429,13 +429,13 @@ def test_describe_policy_exception(): policy_id = "p-47fhe9s3" with pytest.raises(ClientError) as e: response = client.describe_policy(PolicyId=policy_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribePolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") with pytest.raises(ClientError) as e: response = client.describe_policy(PolicyId="meaninglessstring") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DescribePolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -514,9 +514,9 @@ def test_detach_policy_root_ou_not_found_exception(): )["Policy"]["PolicySummary"]["Id"] client.attach_policy(PolicyId=policy_id, TargetId=root_id) client.attach_policy(PolicyId=policy_id, TargetId=account_id) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.detach_policy(PolicyId=policy_id, TargetId="r-xy85") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DetachPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -539,11 +539,11 @@ def test_detach_policy_ou_not_found_exception(): Type="SERVICE_CONTROL_POLICY", )["Policy"]["PolicySummary"]["Id"] client.attach_policy(PolicyId=policy_id, TargetId=ou_id) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.detach_policy( PolicyId=policy_id, TargetId="ou-zx86-z3x4yr2t7" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DetachPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -565,9 +565,9 @@ def test_detach_policy_account_id_not_found_exception(): Type="SERVICE_CONTROL_POLICY", )["Policy"]["PolicySummary"]["Id"] client.attach_policy(PolicyId=policy_id, TargetId=account_id) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.detach_policy(PolicyId=policy_id, TargetId="111619863336") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DetachPolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -591,9 +591,9 @@ def test_detach_policy_invalid_target_exception(): Type="SERVICE_CONTROL_POLICY", )["Policy"]["PolicySummary"]["Id"] client.attach_policy(PolicyId=policy_id, TargetId=ou_id) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.detach_policy(PolicyId=policy_id, TargetId="invalidtargetid") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DetachPolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -628,7 +628,7 @@ def test_delete_policy_exception(): non_existent_policy_id = utils.make_random_policy_id() with pytest.raises(ClientError) as e: response = client.delete_policy(PolicyId=non_existent_policy_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeletePolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") @@ -644,7 +644,7 @@ def test_delete_policy_exception(): client.attach_policy(PolicyId=policy_id, TargetId=root_id) with pytest.raises(ClientError) as e: response = client.delete_policy(PolicyId=policy_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeletePolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyInUseException") @@ -665,7 +665,7 @@ def test_attach_policy_exception(): )["Policy"]["PolicySummary"]["Id"] with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=root_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AttachPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -673,7 +673,7 @@ def test_attach_policy_exception(): ) with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=ou_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AttachPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -681,7 +681,7 @@ def test_attach_policy_exception(): ) with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=account_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AttachPolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -692,7 +692,7 @@ def test_attach_policy_exception(): response = client.attach_policy( PolicyId=policy_id, TargetId="meaninglessstring" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AttachPolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -731,7 +731,7 @@ def test_update_policy_exception(): non_existent_policy_id = utils.make_random_policy_id() with pytest.raises(ClientError) as e: response = client.update_policy(PolicyId=non_existent_policy_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("UpdatePolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") @@ -795,7 +795,7 @@ def test_list_policies_for_target_exception(): response = client.list_policies_for_target( TargetId=ou_id, Filter="SERVICE_CONTROL_POLICY" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListPoliciesForTarget") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain( @@ -805,7 +805,7 @@ def test_list_policies_for_target_exception(): response = client.list_policies_for_target( TargetId=account_id, Filter="SERVICE_CONTROL_POLICY" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListPoliciesForTarget") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -816,7 +816,7 @@ def test_list_policies_for_target_exception(): response = client.list_policies_for_target( TargetId="meaninglessstring", Filter="SERVICE_CONTROL_POLICY" ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListPoliciesForTarget") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -830,7 +830,7 @@ def test_list_policies_for_target_exception(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListPoliciesForTarget") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("TargetNotFoundException") @@ -844,7 +844,7 @@ def test_list_policies_for_target_exception(): client.list_policies_for_target(TargetId=root_id, Filter="MOTO") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListPoliciesForTarget") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -889,13 +889,13 @@ def test_list_targets_for_policy_exception(): policy_id = "p-47fhe9s3" with pytest.raises(ClientError) as e: response = client.list_targets_for_policy(PolicyId=policy_id) - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListTargetsForPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") with pytest.raises(ClientError) as e: response = client.list_targets_for_policy(PolicyId="meaninglessstring") - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListTargetsForPolicy") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -933,7 +933,7 @@ def test_tag_resource_errors(): client.tag_resource( ResourceId="000000000000", Tags=[{"Key": "key", "Value": "value"},], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("TagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -963,7 +963,7 @@ def test_list_tags_for_resource_errors(): with pytest.raises(ClientError) as e: client.list_tags_for_resource(ResourceId="000000000000") - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListTagsForResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1000,7 +1000,7 @@ def test_untag_resource_errors(): with pytest.raises(ClientError) as e: client.untag_resource(ResourceId="000000000000", TagKeys=["key"]) - ex = e.exception + ex = e.value ex.operation_name.should.equal("UntagResource") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1039,7 +1039,7 @@ def test_update_organizational_unit_duplicate_error(): client.update_organizational_unit( OrganizationalUnitId=response["OrganizationalUnit"]["Id"], Name=ou_name ) - exc = e.exception + exc = e.value exc.operation_name.should.equal("UpdateOrganizationalUnit") exc.response["Error"]["Code"].should.contain("DuplicateOrganizationalUnitException") exc.response["Error"]["Message"].should.equal( @@ -1083,7 +1083,7 @@ def test_enable_aws_service_access(): with pytest.raises(ClientError) as e: client.enable_aws_service_access(ServicePrincipal="moto.amazonaws.com") - ex = e.exception + ex = e.value ex.operation_name.should.equal("EnableAWSServiceAccess") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1144,7 +1144,7 @@ def test_disable_aws_service_access_errors(): with pytest.raises(ClientError) as e: client.disable_aws_service_access(ServicePrincipal="moto.amazonaws.com") - ex = e.exception + ex = e.value ex.operation_name.should.equal("DisableAWSServiceAccess") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1205,7 +1205,7 @@ def test_register_delegated_administrator_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("RegisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ConstraintViolationException") @@ -1221,7 +1221,7 @@ def test_register_delegated_administrator_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("RegisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -1237,7 +1237,7 @@ def test_register_delegated_administrator_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("RegisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1253,7 +1253,7 @@ def test_register_delegated_administrator_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("RegisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountAlreadyRegisteredException") @@ -1323,7 +1323,7 @@ def test_list_delegated_administrators_erros(): client.list_delegated_administrators(ServicePrincipal="moto.amazonaws.com") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListDelegatedAdministrators") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1369,7 +1369,7 @@ def test_list_delegated_services_for_account_erros(): client.list_delegated_services_for_account(AccountId="000000000000") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListDelegatedServicesForAccount") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AWSOrganizationsNotInUseException") @@ -1383,7 +1383,7 @@ def test_list_delegated_services_for_account_erros(): client.list_delegated_services_for_account(AccountId=ACCOUNT_ID) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("ListDelegatedServicesForAccount") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotRegisteredException") @@ -1431,7 +1431,7 @@ def test_deregister_delegated_administrator_erros(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeregisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ConstraintViolationException") @@ -1447,7 +1447,7 @@ def test_deregister_delegated_administrator_erros(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeregisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotFoundException") @@ -1463,7 +1463,7 @@ def test_deregister_delegated_administrator_erros(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeregisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("AccountNotRegisteredException") @@ -1484,7 +1484,7 @@ def test_deregister_delegated_administrator_erros(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeregisterDelegatedAdministrator") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1535,7 +1535,7 @@ def test_enable_policy_type_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("EnablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("RootNotFoundException") @@ -1549,7 +1549,7 @@ def test_enable_policy_type_errors(): client.enable_policy_type(RootId=root_id, PolicyType="SERVICE_CONTROL_POLICY") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("EnablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("PolicyTypeAlreadyEnabledException") @@ -1563,7 +1563,7 @@ def test_enable_policy_type_errors(): client.enable_policy_type(RootId=root_id, PolicyType="MOTO") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("EnablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") @@ -1610,7 +1610,7 @@ def test_disable_policy_type_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DisablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("RootNotFoundException") @@ -1626,7 +1626,7 @@ def test_disable_policy_type_errors(): ) # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DisablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("PolicyTypeNotEnabledException") @@ -1640,7 +1640,7 @@ def test_disable_policy_type_errors(): client.disable_policy_type(RootId=root_id, PolicyType="MOTO") # then - ex = e.exception + ex = e.value ex.operation_name.should.equal("DisablePolicyType") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidInputException") diff --git a/tests/test_ram/test_ram.py b/tests/test_ram/test_ram.py index dbc57a2c0..73a23331b 100644 --- a/tests/test_ram/test_ram.py +++ b/tests/test_ram/test_ram.py @@ -67,7 +67,7 @@ def test_create_resource_share_errors(): # when with pytest.raises(ClientError) as e: client.create_resource_share(name="test", resourceArns=["inalid-arn"]) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("MalformedArnException") @@ -82,7 +82,7 @@ def test_create_resource_share_errors(): client.create_resource_share( name="test", resourceArns=["arn:aws:iam::{}:role/test".format(ACCOUNT_ID)] ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("MalformedArnException") @@ -102,7 +102,7 @@ def test_create_resource_share_errors(): ) ], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterException") @@ -174,7 +174,7 @@ def test_create_resource_share_with_organization_errors(): ) ], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("UnknownResourceException") @@ -196,7 +196,7 @@ def test_create_resource_share_with_organization_errors(): ) ], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("CreateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("UnknownResourceException") @@ -238,7 +238,7 @@ def test_get_resource_shares_errors(): # when with pytest.raises(ClientError) as e: client.get_resource_shares(resourceOwner="invalid") - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetResourceShares") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterException") @@ -289,7 +289,7 @@ def test_update_resource_share_errors(): ), name="test-update", ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("UpdateResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("UnknownResourceException") @@ -334,7 +334,7 @@ def test_delete_resource_share_errors(): ACCOUNT_ID ) ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("DeleteResourceShare") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("UnknownResourceException") @@ -370,7 +370,7 @@ def test_enable_sharing_with_aws_organization_errors(): # when with pytest.raises(ClientError) as e: client.enable_sharing_with_aws_organization() - ex = e.exception + ex = e.value ex.operation_name.should.equal("EnableSharingWithAwsOrganization") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("OperationNotPermittedException") diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py index 933d02c6d..67f247f18 100644 --- a/tests/test_s3/test_s3.py +++ b/tests/test_s3/test_s3.py @@ -666,7 +666,7 @@ def test_delete_keys_invalid(): def test_boto3_delete_empty_keys_list(): with pytest.raises(ClientError) as err: boto3.client("s3").delete_objects(Bucket="foobar", Delete={"Objects": []}) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" @mock_s3_deprecated @@ -1016,7 +1016,7 @@ def test_s3_object_in_public_bucket(): with pytest.raises(ClientError) as exc: s3_anonymous.Object(key="file.txt", bucket_name="test-bucket").get() - exc.exception.response["Error"]["Code"].should.equal("403") + exc.value.response["Error"]["Code"].should.equal("403") @mock_s3 @@ -1090,7 +1090,7 @@ def test_s3_object_in_private_bucket(): with pytest.raises(ClientError) as exc: s3_anonymous.Object(key="file.txt", bucket_name="test-bucket").get() - exc.exception.response["Error"]["Code"].should.equal("403") + exc.value.response["Error"]["Code"].should.equal("403") bucket.put_object(ACL="public-read", Body=b"ABCD", Key="file.txt") contents = ( @@ -1182,7 +1182,7 @@ if not settings.TEST_SERVER_MODE: with pytest.raises(ClientError) as e: s3.create_bucket(Bucket=bucket_name) - e.exception.response["Error"]["Message"].should.equal( + e.value.response["Error"]["Message"].should.equal( "The unspecified location constraint is incompatible for the region specific endpoint this request was sent to." ) @@ -1201,13 +1201,13 @@ if not settings.TEST_SERVER_MODE: # With an invalid account ID: with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId="111111111111") - assert ce.exception.response["Error"]["Code"] == "AccessDenied" + assert ce.value.response["Error"]["Code"] == "AccessDenied" # Without one defined: with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId=ACCOUNT_ID) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" ) @@ -1217,17 +1217,17 @@ if not settings.TEST_SERVER_MODE: AccountId="111111111111", PublicAccessBlockConfiguration={"BlockPublicAcls": True}, ) - assert ce.exception.response["Error"]["Code"] == "AccessDenied" + assert ce.value.response["Error"]["Code"] == "AccessDenied" # Put with an invalid PAB: with pytest.raises(ClientError) as ce: client.put_public_access_block( AccountId=ACCOUNT_ID, PublicAccessBlockConfiguration={} ) - assert ce.exception.response["Error"]["Code"] == "InvalidRequest" + assert ce.value.response["Error"]["Code"] == "InvalidRequest" assert ( "Must specify at least one configuration." - in ce.exception.response["Error"]["Message"] + in ce.value.response["Error"]["Message"] ) # Correct PAB: @@ -1256,7 +1256,7 @@ if not settings.TEST_SERVER_MODE: # Delete with an invalid account ID: with pytest.raises(ClientError) as ce: client.delete_public_access_block(AccountId="111111111111") - assert ce.exception.response["Error"]["Code"] == "AccessDenied" + assert ce.value.response["Error"]["Code"] == "AccessDenied" # Delete successfully: client.delete_public_access_block(AccountId=ACCOUNT_ID) @@ -1265,7 +1265,7 @@ if not settings.TEST_SERVER_MODE: with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId=ACCOUNT_ID) assert ( - ce.exception.response["Error"]["Code"] + ce.value.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" ) @@ -1466,7 +1466,7 @@ if not settings.TEST_SERVER_MODE: resourceType="AWS::S3::AccountPublicAccessBlock", resourceId=ACCOUNT_ID ) assert ( - ce.exception.response["Error"]["Code"] == "ResourceNotDiscoveredException" + ce.value.response["Error"]["Code"] == "ResourceNotDiscoveredException" ) # aggregate result = config_client.batch_get_resource_config( @@ -1635,7 +1635,7 @@ def test_policy(): with pytest.raises(S3ResponseError) as err: bucket.get_policy() - ex = err.exception + ex = err.value ex.box_usage.should.be.none ex.error_code.should.equal("NoSuchBucketPolicy") ex.message.should.equal("The bucket policy does not exist") @@ -1979,7 +1979,7 @@ def test_bucket_create_duplicate(): s3.create_bucket( Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "us-west-2"} ) - exc.exception.response["Error"]["Code"].should.equal("BucketAlreadyExists") + exc.value.response["Error"]["Code"].should.equal("BucketAlreadyExists") @mock_s3 @@ -1990,7 +1990,7 @@ def test_bucket_create_force_us_east_1(): Bucket="blah", CreateBucketConfiguration={"LocationConstraint": DEFAULT_REGION_NAME}, ) - exc.exception.response["Error"]["Code"].should.equal("InvalidLocationConstraint") + exc.value.response["Error"]["Code"].should.equal("InvalidLocationConstraint") @mock_s3 @@ -2012,8 +2012,8 @@ def test_bucket_create_empty_bucket_configuration_should_return_malformed_xml_er s3 = boto3.resource("s3", region_name="us-east-1") with pytest.raises(ClientError) as e: s3.create_bucket(Bucket="whatever", CreateBucketConfiguration={}) - e.exception.response["Error"]["Code"].should.equal("MalformedXML") - e.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) + e.value.response["Error"]["Code"].should.equal("MalformedXML") + e.value.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @mock_s3 @@ -2031,7 +2031,7 @@ def test_boto3_head_object(): s3.Object("blah", "hello2.txt").meta.client.head_object( Bucket="blah", Key="hello_bad.txt" ) - e.exception.response["Error"]["Code"].should.equal("404") + e.value.response["Error"]["Code"].should.equal("404") @mock_s3 @@ -2079,7 +2079,7 @@ def test_boto3_get_object(): with pytest.raises(ClientError) as e: s3.Object("blah", "hello2.txt").get() - e.exception.response["Error"]["Code"].should.equal("NoSuchKey") + e.value.response["Error"]["Code"].should.equal("NoSuchKey") @mock_s3 @@ -2108,7 +2108,7 @@ def test_boto3_get_missing_object_with_part_number(): Bucket="blah", Key="hello.txt", PartNumber=123 ) - e.exception.response["Error"]["Code"].should.equal("404") + e.value.response["Error"]["Code"].should.equal("404") @mock_s3 @@ -2181,7 +2181,7 @@ def test_boto3_copy_object_with_versioning(): Bucket="blah", Key="test5", ) - e.exception.response["Error"]["Code"].should.equal("404") + e.value.response["Error"]["Code"].should.equal("404") response = client.create_multipart_upload(Bucket="blah", Key="test4") upload_id = response["UploadId"] @@ -2215,7 +2215,7 @@ def test_s3_abort_multipart_data_with_invalid_upload_and_key(): client.abort_multipart_upload( Bucket="blah", Key="foobar", UploadId="dummy_upload_id" ) - err.exception.response["Error"]["Code"].should.equal("NoSuchUpload") + err.value.response["Error"]["Code"].should.equal("NoSuchUpload") @mock_s3 @@ -2365,7 +2365,7 @@ def test_boto3_get_object_if_modified_since(): Key=key, IfModifiedSince=datetime.datetime.utcnow() + datetime.timedelta(hours=1), ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "304", "Message": "Not Modified"}) @@ -2379,13 +2379,13 @@ def test_boto3_get_object_if_unmodified_since(): s3.put_object(Bucket=bucket_name, Key=key, Body="test") - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.get_object( Bucket=bucket_name, Key=key, IfUnmodifiedSince=datetime.datetime.utcnow() - datetime.timedelta(hours=1), ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("PreconditionFailed") e.response["Error"]["Condition"].should.equal("If-Unmodified-Since") @@ -2400,11 +2400,11 @@ def test_boto3_get_object_if_match(): s3.put_object(Bucket=bucket_name, Key=key, Body="test") - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.get_object( Bucket=bucket_name, Key=key, IfMatch='"hello"', ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("PreconditionFailed") e.response["Error"]["Condition"].should.equal("If-Match") @@ -2419,11 +2419,11 @@ def test_boto3_get_object_if_none_match(): etag = s3.put_object(Bucket=bucket_name, Key=key, Body="test")["ETag"] - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.get_object( Bucket=bucket_name, Key=key, IfNoneMatch=etag, ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "304", "Message": "Not Modified"}) @@ -2443,7 +2443,7 @@ def test_boto3_head_object_if_modified_since(): Key=key, IfModifiedSince=datetime.datetime.utcnow() + datetime.timedelta(hours=1), ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "304", "Message": "Not Modified"}) @@ -2457,13 +2457,13 @@ def test_boto3_head_object_if_unmodified_since(): s3.put_object(Bucket=bucket_name, Key=key, Body="test") - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.head_object( Bucket=bucket_name, Key=key, IfUnmodifiedSince=datetime.datetime.utcnow() - datetime.timedelta(hours=1), ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "412", "Message": "Precondition Failed"}) @@ -2477,11 +2477,11 @@ def test_boto3_head_object_if_match(): s3.put_object(Bucket=bucket_name, Key=key, Body="test") - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.head_object( Bucket=bucket_name, Key=key, IfMatch='"hello"', ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "412", "Message": "Precondition Failed"}) @@ -2495,11 +2495,11 @@ def test_boto3_head_object_if_none_match(): etag = s3.put_object(Bucket=bucket_name, Key=key, Body="test")["ETag"] - with assert_raises(botocore.exceptions.ClientError) as err: + with pytest.raises(botocore.exceptions.ClientError) as err: s3.head_object( Bucket=bucket_name, Key=key, IfNoneMatch=etag, ) - e = err.exception + e = err.value e.response["Error"].should.equal({"Code": "304", "Message": "Not Modified"}) @@ -2642,7 +2642,7 @@ def test_boto3_put_bucket_tagging(): ] }, ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("InvalidTag") e.response["Error"]["Message"].should.equal( "Cannot provide multiple Tags with the same key" @@ -2654,7 +2654,7 @@ def test_boto3_put_bucket_tagging(): Bucket=bucket_name, Tagging={"TagSet": [{"Key": "aws:sometag", "Value": "nope"}]}, ) - e = ce.exception + e = ce.value e.response["Error"]["Code"].should.equal("InvalidTag") e.response["Error"]["Message"].should.equal( "System tags cannot be added/updated by requester" @@ -2693,7 +2693,7 @@ def test_boto3_get_bucket_tagging(): with pytest.raises(ClientError) as err: s3.get_bucket_tagging(Bucket=bucket_name) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("NoSuchTagSet") e.response["Error"]["Message"].should.equal("The TagSet does not exist") @@ -2720,7 +2720,7 @@ def test_boto3_delete_bucket_tagging(): with pytest.raises(ClientError) as err: s3.get_bucket_tagging(Bucket=bucket_name) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("NoSuchTagSet") e.response["Error"]["Message"].should.equal("The TagSet does not exist") @@ -2764,7 +2764,7 @@ def test_boto3_put_bucket_cors(): ] }, ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("InvalidRequest") e.response["Error"]["Message"].should.equal( "Found unsupported HTTP method in CORS config. " "Unsupported method is NOTREAL" @@ -2772,7 +2772,7 @@ def test_boto3_put_bucket_cors(): with pytest.raises(ClientError) as err: s3.put_bucket_cors(Bucket=bucket_name, CORSConfiguration={"CORSRules": []}) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("MalformedXML") # And 101: @@ -2781,7 +2781,7 @@ def test_boto3_put_bucket_cors(): s3.put_bucket_cors( Bucket=bucket_name, CORSConfiguration={"CORSRules": many_rules} ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("MalformedXML") @@ -2795,7 +2795,7 @@ def test_boto3_get_bucket_cors(): with pytest.raises(ClientError) as err: s3.get_bucket_cors(Bucket=bucket_name) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("NoSuchCORSConfiguration") e.response["Error"]["Message"].should.equal("The CORS configuration does not exist") @@ -2845,7 +2845,7 @@ def test_boto3_delete_bucket_cors(): with pytest.raises(ClientError) as err: s3.get_bucket_cors(Bucket=bucket_name) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("NoSuchCORSConfiguration") e.response["Error"]["Message"].should.equal("The CORS configuration does not exist") @@ -2920,7 +2920,7 @@ def test_put_bucket_acl_body(): ] }, ) - assert err.exception.response["Error"]["Code"] == "MalformedACLError" + assert err.value.response["Error"]["Code"] == "MalformedACLError" # With incorrect permission: with pytest.raises(ClientError) as err: @@ -2939,7 +2939,7 @@ def test_put_bucket_acl_body(): "Owner": bucket_owner, }, ) - assert err.exception.response["Error"]["Code"] == "MalformedACLError" + assert err.value.response["Error"]["Code"] == "MalformedACLError" # Clear the ACLs: result = s3.put_bucket_acl( @@ -3199,9 +3199,9 @@ def test_put_bucket_notification_errors(): }, ) - assert err.exception.response["Error"]["Code"] == "InvalidArgument" + assert err.value.response["Error"]["Code"] == "InvalidArgument" assert ( - err.exception.response["Error"]["Message"] == "The ARN is not well formed" + err.value.response["Error"]["Message"] == "The ARN is not well formed" ) # Region not the same as the bucket: @@ -3218,9 +3218,9 @@ def test_put_bucket_notification_errors(): }, ) - assert err.exception.response["Error"]["Code"] == "InvalidArgument" + assert err.value.response["Error"]["Code"] == "InvalidArgument" assert ( - err.exception.response["Error"]["Message"] + err.value.response["Error"]["Message"] == "The notification destination service region is not valid for the bucket location constraint" ) @@ -3237,9 +3237,9 @@ def test_put_bucket_notification_errors(): ] }, ) - assert err.exception.response["Error"]["Code"] == "InvalidArgument" + assert err.value.response["Error"]["Code"] == "InvalidArgument" assert ( - err.exception.response["Error"]["Message"] + err.value.response["Error"]["Message"] == "The event is not supported for notifications" ) @@ -3269,7 +3269,7 @@ def test_boto3_put_bucket_logging(): "LoggingEnabled": {"TargetBucket": "IAMNOTREAL", "TargetPrefix": ""} }, ) - assert err.exception.response["Error"]["Code"] == "InvalidTargetBucketForLogging" + assert err.value.response["Error"]["Code"] == "InvalidTargetBucketForLogging" # A log-bucket that's missing the proper ACLs for LogDelivery: with pytest.raises(ClientError) as err: @@ -3279,8 +3279,8 @@ def test_boto3_put_bucket_logging(): "LoggingEnabled": {"TargetBucket": log_bucket, "TargetPrefix": ""} }, ) - assert err.exception.response["Error"]["Code"] == "InvalidTargetBucketForLogging" - assert "log-delivery" in err.exception.response["Error"]["Message"] + assert err.value.response["Error"]["Code"] == "InvalidTargetBucketForLogging" + assert "log-delivery" in err.value.response["Error"]["Message"] # Add the proper "log-delivery" ACL to the log buckets: bucket_owner = s3.get_bucket_acl(Bucket=log_bucket)["Owner"] @@ -3323,7 +3323,7 @@ def test_boto3_put_bucket_logging(): } }, ) - assert err.exception.response["Error"]["Code"] == "CrossLocationLoggingProhibitted" + assert err.value.response["Error"]["Code"] == "CrossLocationLoggingProhibitted" # Correct logging: s3.put_bucket_logging( @@ -3420,7 +3420,7 @@ def test_boto3_put_bucket_logging(): } }, ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" @mock_s3 @@ -3442,7 +3442,7 @@ def test_boto3_put_object_tagging(): }, ) - e = err.exception + e = err.value e.response["Error"].should.equal( { "Code": "NoSuchKey", @@ -3490,7 +3490,7 @@ def test_boto3_put_object_tagging_on_earliest_version(): }, ) - e = err.exception + e = err.value e.response["Error"].should.equal( { "Code": "NoSuchKey", @@ -3558,7 +3558,7 @@ def test_boto3_put_object_tagging_on_both_version(): }, ) - e = err.exception + e = err.value e.response["Error"].should.equal( { "Code": "NoSuchKey", @@ -3773,7 +3773,7 @@ def test_boto3_delete_markers(): with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=key) - e.exception.response["Error"]["Code"].should.equal("NoSuchKey") + e.value.response["Error"]["Code"].should.equal("NoSuchKey") response = s3.list_object_versions(Bucket=bucket_name) response["Versions"].should.have.length_of(2) @@ -3893,7 +3893,7 @@ def test_boto3_bucket_name_too_long(): s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) with pytest.raises(ClientError) as exc: s3.create_bucket(Bucket="x" * 64) - exc.exception.response["Error"]["Code"].should.equal("InvalidBucketName") + exc.value.response["Error"]["Code"].should.equal("InvalidBucketName") @mock_s3 @@ -3901,7 +3901,7 @@ def test_boto3_bucket_name_too_short(): s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) with pytest.raises(ClientError) as exc: s3.create_bucket(Bucket="x" * 2) - exc.exception.response["Error"]["Code"].should.equal("InvalidBucketName") + exc.value.response["Error"]["Code"].should.equal("InvalidBucketName") @mock_s3 @@ -3975,7 +3975,7 @@ def test_accelerate_configuration_status_validation(): s3.put_bucket_accelerate_configuration( Bucket=bucket_name, AccelerateConfiguration={"Status": "bad_status"} ) - exc.exception.response["Error"]["Code"].should.equal("MalformedXML") + exc.value.response["Error"]["Code"].should.equal("MalformedXML") @mock_s3 @@ -3987,7 +3987,7 @@ def test_accelerate_configuration_is_not_supported_when_bucket_name_has_dots(): s3.put_bucket_accelerate_configuration( Bucket=bucket_name, AccelerateConfiguration={"Status": "Enabled"} ) - exc.exception.response["Error"]["Code"].should.equal("InvalidRequest") + exc.value.response["Error"]["Code"].should.equal("InvalidRequest") def store_and_read_back_a_key(key): @@ -4029,11 +4029,11 @@ def test_leading_slashes_not_removed(bucket_name): with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=invalid_key_1) - e.exception.response["Error"]["Code"].should.equal("NoSuchKey") + e.value.response["Error"]["Code"].should.equal("NoSuchKey") with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=invalid_key_2) - e.exception.response["Error"]["Code"].should.equal("NoSuchKey") + e.value.response["Error"]["Code"].should.equal("NoSuchKey") @parameterized( @@ -4054,7 +4054,7 @@ def test_delete_objects_with_url_encoded_key(key): with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=key) - e.exception.response["Error"]["Code"].should.equal("NoSuchKey") + e.value.response["Error"]["Code"].should.equal("NoSuchKey") put_object() s3.delete_object(Bucket=bucket_name, Key=key) @@ -4076,13 +4076,13 @@ def test_public_access_block(): client.get_public_access_block(Bucket="mybucket") assert ( - ce.exception.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" + ce.value.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" ) assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "The public access block configuration was not found" ) - assert ce.exception.response["ResponseMetadata"]["HTTPStatusCode"] == 404 + assert ce.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404 # Put a public block in place: test_map = { @@ -4127,12 +4127,12 @@ def test_public_access_block(): Bucket="mybucket", PublicAccessBlockConfiguration={} ) - assert ce.exception.response["Error"]["Code"] == "InvalidRequest" + assert ce.value.response["Error"]["Code"] == "InvalidRequest" assert ( - ce.exception.response["Error"]["Message"] + ce.value.response["Error"]["Message"] == "Must specify at least one configuration." ) - assert ce.exception.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert ce.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 # Test that things work with AWS Config: config_client = boto3.client("config", region_name=DEFAULT_REGION_NAME) @@ -4158,7 +4158,7 @@ def test_public_access_block(): with pytest.raises(ClientError) as ce: client.get_public_access_block(Bucket="mybucket") assert ( - ce.exception.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" + ce.value.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" ) @@ -4303,7 +4303,7 @@ def test_list_config_discovered_resources(): with pytest.raises(InvalidNextTokenException) as inte: s3_config_query.list_config_service_resources(None, None, 1, "notabucket") - assert "The nextToken provided is invalid" in inte.exception.message + assert "The nextToken provided is invalid" in inte.value.message @mock_s3 @@ -4803,7 +4803,7 @@ def test_presigned_url_restrict_parameters(): ClientMethod="put_object", Params={"Bucket": bucket, "Key": key, "Unknown": "metadata"}, ) - assert str(err.exception).should.match( + assert str(err.value).should.match( r'Parameter validation failed:\nUnknown parameter in input: "Unknown", must be one of:.*' ) diff --git a/tests/test_s3/test_s3_lifecycle.py b/tests/test_s3/test_s3_lifecycle.py index da9ffbca4..d3d9344ef 100644 --- a/tests/test_s3/test_s3_lifecycle.py +++ b/tests/test_s3/test_s3_lifecycle.py @@ -84,7 +84,7 @@ def test_lifecycle_with_filters(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" # With a tag: lfc["Rules"][0]["Filter"] = {"Tag": {"Key": "mytag", "Value": "mytagvalue"}} @@ -172,14 +172,14 @@ def test_lifecycle_with_filters(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" lfc["Rules"][0]["Prefix"] = "some/path" with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" # No filters -- just a prefix: del lfc["Rules"][0]["Filter"] @@ -200,7 +200,7 @@ def test_lifecycle_with_filters(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" lfc["Rules"][0]["Filter"] = { "Tag": {"Key": "mytag", "Value": "mytagvalue"}, @@ -216,7 +216,7 @@ def test_lifecycle_with_filters(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" # Make sure multiple rules work: lfc = { @@ -283,7 +283,7 @@ def test_lifecycle_with_eodm(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" del lfc["Rules"][0]["Expiration"]["Days"] lfc["Rules"][0]["Expiration"]["Date"] = datetime(2015, 1, 1) @@ -291,7 +291,7 @@ def test_lifecycle_with_eodm(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" @mock_s3 @@ -387,7 +387,7 @@ def test_lifecycle_with_nvt(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] = 30 del lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"] @@ -395,7 +395,7 @@ def test_lifecycle_with_nvt(): client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) - assert err.exception.response["Error"]["Code"] == "MalformedXML" + assert err.value.response["Error"]["Code"] == "MalformedXML" @mock_s3 diff --git a/tests/test_s3/test_s3_storageclass.py b/tests/test_s3/test_s3_storageclass.py index 0e8152b03..ec7090369 100644 --- a/tests/test_s3/test_s3_storageclass.py +++ b/tests/test_s3/test_s3_storageclass.py @@ -113,7 +113,7 @@ def test_s3_invalid_copied_storage_class(): StorageClass="STANDARD2", ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("InvalidStorageClass") e.response["Error"]["Message"].should.equal( "The storage class you specified is not valid" @@ -133,7 +133,7 @@ def test_s3_invalid_storage_class(): Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="STANDARDD" ) - e = err.exception + e = err.value e.response["Error"]["Code"].should.equal("InvalidStorageClass") e.response["Error"]["Message"].should.equal( "The storage class you specified is not valid" @@ -166,14 +166,14 @@ def test_s3_copy_object_error_for_glacier_storage_class_not_restored(): Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="GLACIER" ) - with pytest.raises(ClientError) as exc: + with pytest.raises(ClientError) as ex: s3.copy_object( CopySource={"Bucket": "Bucket", "Key": "First_Object"}, Bucket="Bucket", Key="Second_Object", ) - exc.exception.response["Error"]["Code"].should.equal("ObjectNotInActiveTierError") + ex.value.response["Error"]["Code"].should.equal("ObjectNotInActiveTierError") @mock_s3 @@ -194,7 +194,7 @@ def test_s3_copy_object_error_for_deep_archive_storage_class_not_restored(): Key="Second_Object", ) - exc.exception.response["Error"]["Code"].should.equal("ObjectNotInActiveTierError") + exc.value.response["Error"]["Code"].should.equal("ObjectNotInActiveTierError") @mock_s3 diff --git a/tests/test_sagemaker/test_sagemaker_endpoint.py b/tests/test_sagemaker/test_sagemaker_endpoint.py index 0d21ad1ef..1e1ecd494 100644 --- a/tests/test_sagemaker/test_sagemaker_endpoint.py +++ b/tests/test_sagemaker/test_sagemaker_endpoint.py @@ -38,7 +38,7 @@ def test_create_endpoint_config(): EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) - assert e.exception.response["Error"]["Message"].startswith("Could not find model") + assert e.value.response["Error"]["Message"].startswith("Could not find model") _create_model(sagemaker, model_name) resp = sagemaker.create_endpoint_config( @@ -88,11 +88,11 @@ def test_delete_endpoint_config(): resp = sagemaker.delete_endpoint_config(EndpointConfigName=endpoint_config_name) with pytest.raises(ClientError) as e: sagemaker.describe_endpoint_config(EndpointConfigName=endpoint_config_name) - assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint configuration") + assert e.value.response["Error"]["Message"].startswith("Could not find endpoint configuration") with pytest.raises(ClientError) as e: sagemaker.delete_endpoint_config(EndpointConfigName=endpoint_config_name) - assert e.exception.response["Error"]["Message"].startswith( "Could not find endpoint configuration") + assert e.value.response["Error"]["Message"].startswith( "Could not find endpoint configuration") @mock_sagemaker @@ -118,11 +118,11 @@ def test_create_endpoint_invalid_instance_type(): EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) - assert e.exception.response["Error"]["Code"] == "ValidationException" + assert e.value.response["Error"]["Code"] == "ValidationException" expected_message = "Value '{}' at 'instanceType' failed to satisfy constraint: Member must satisfy enum value set: [".format( instance_type ) - assert expected_message in e.exception.response["Error"]["Message"] + assert expected_message in e.value.response["Error"]["Message"] @mock_sagemaker @@ -134,7 +134,7 @@ def test_create_endpoint(): sagemaker.create_endpoint( EndpointName=endpoint_name, EndpointConfigName="NonexistentEndpointConfig" ) - assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint configuration") + assert e.value.response["Error"]["Message"].startswith("Could not find endpoint configuration") model_name = "MyModel" _create_model(sagemaker, model_name) @@ -182,11 +182,11 @@ def test_delete_endpoint(): sagemaker.delete_endpoint(EndpointName=endpoint_name) with pytest.raises(ClientError) as e: sagemaker.describe_endpoint(EndpointName=endpoint_name) - assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint") + assert e.value.response["Error"]["Message"].startswith("Could not find endpoint") with pytest.raises(ClientError) as e: sagemaker.delete_endpoint(EndpointName=endpoint_name) - assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint") + assert e.value.response["Error"]["Message"].startswith("Could not find endpoint") def _create_model(boto_client, model_name): diff --git a/tests/test_sagemaker/test_sagemaker_models.py b/tests/test_sagemaker/test_sagemaker_models.py index 1f2f4440d..91fc3bb5b 100644 --- a/tests/test_sagemaker/test_sagemaker_models.py +++ b/tests/test_sagemaker/test_sagemaker_models.py @@ -79,7 +79,7 @@ def test_delete_model_not_found(): boto3.client("sagemaker", region_name="us-east-1").delete_model( ModelName="blah" ) - assert err.exception.response["Error"]["Code"].should.equal("404") + assert err.value.response["Error"]["Code"].should.equal("404") @mock_sagemaker diff --git a/tests/test_sagemaker/test_sagemaker_notebooks.py b/tests/test_sagemaker/test_sagemaker_notebooks.py index 9f6a2be39..9fd082689 100644 --- a/tests/test_sagemaker/test_sagemaker_notebooks.py +++ b/tests/test_sagemaker/test_sagemaker_notebooks.py @@ -136,7 +136,7 @@ def test_create_notebook_instance_bad_volume_size(): with pytest.raises(ParamValidationError) as ex: sagemaker.create_notebook_instance(**args) assert \ - ex.exception.args[0] == \ + ex.value.args[0] == \ "Parameter validation failed:\nInvalid range for parameter VolumeSizeInGB, value: {}, valid range: 5-inf".format(vol_size) @@ -153,12 +153,12 @@ def test_create_notebook_instance_invalid_instance_type(): } with pytest.raises(ClientError) as ex: sagemaker.create_notebook_instance(**args) - assert ex.exception.response["Error"]["Code"] == "ValidationException" + assert ex.value.response["Error"]["Code"] == "ValidationException" expected_message = "Value '{}' at 'instanceType' failed to satisfy constraint: Member must satisfy enum value set: [".format( instance_type ) - assert expected_message in ex.exception.response["Error"]["Message"] + assert expected_message in ex.value.response["Error"]["Message"] @mock_sagemaker @@ -182,11 +182,11 @@ def test_notebook_instance_lifecycle(): with pytest.raises(ClientError) as ex: sagemaker.delete_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert ex.exception.response["Error"]["Code"] == "ValidationException" + assert ex.value.response["Error"]["Code"] == "ValidationException" expected_message = "Status (InService) not in ([Stopped, Failed]). Unable to transition to (Deleting) for Notebook Instance ({})".format( notebook_instance_arn ) - assert expected_message in ex.exception.response["Error"]["Message"] + assert expected_message in ex.value.response["Error"]["Message"] sagemaker.stop_notebook_instance(NotebookInstanceName=NAME_PARAM) @@ -207,7 +207,7 @@ def test_notebook_instance_lifecycle(): with pytest.raises(ClientError) as ex: sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert ex.exception.response["Error"]["Message"] == "RecordNotFound" + assert ex.value.response["Error"]["Message"] == "RecordNotFound" @mock_sagemaker @@ -216,7 +216,7 @@ def test_describe_nonexistent_model(): with pytest.raises(ClientError) as e: sagemaker.describe_model(ModelName="Nonexistent") - assert e.exception.response["Error"]["Message"].startswith("Could not find model") + assert e.value.response["Error"]["Message"].startswith("Could not find model") @mock_sagemaker @@ -239,7 +239,7 @@ def test_notebook_instance_lifecycle_config(): OnStart=on_start, ) assert \ - e.exception.response["Error"]["Message"].endswith( + e.value.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config already exists.)" ) @@ -264,7 +264,7 @@ def test_notebook_instance_lifecycle_config(): NotebookInstanceLifecycleConfigName=name, ) assert \ - e.exception.response["Error"]["Message"].endswith( + e.value.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config does not exist.)" ) @@ -273,6 +273,6 @@ def test_notebook_instance_lifecycle_config(): NotebookInstanceLifecycleConfigName=name, ) assert \ - e.exception.response["Error"]["Message"].endswith( + e.value.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config does not exist.)" ) diff --git a/tests/test_secretsmanager/test_list_secrets.py b/tests/test_secretsmanager/test_list_secrets.py index 826e09de7..324ab1838 100644 --- a/tests/test_secretsmanager/test_list_secrets.py +++ b/tests/test_secretsmanager/test_list_secrets.py @@ -123,7 +123,7 @@ def test_with_all_filter(): secrets = conn.list_secrets(Filters=[{"Key": "all", "Values": ["foo"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert secret_names == ["foo", "bar", "baz", "qux", "multi"] + assert sorted(secret_names) == ['bar', 'baz', 'foo', 'multi', 'qux'] @mock_secretsmanager @@ -133,8 +133,8 @@ def test_with_no_filter_key(): with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Values": ["foo"]}]) - ire.exception.response["Error"]["Code"].should.equal("InvalidParameterException") - ire.exception.response["Error"]["Message"].should.equal("Invalid filter key") + ire.value.response["Error"]["Code"].should.equal("InvalidParameterException") + ire.value.response["Error"]["Message"].should.equal("Invalid filter key") @mock_secretsmanager @@ -146,8 +146,8 @@ def test_with_no_filter_values(): with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Key": "description"}]) - ire.exception.response["Error"]["Code"].should.equal("InvalidParameterException") - ire.exception.response["Error"]["Message"].should.equal( + ire.value.response["Error"]["Code"].should.equal("InvalidParameterException") + ire.value.response["Error"]["Message"].should.equal( "Invalid filter values for key: description" ) @@ -159,8 +159,8 @@ def test_with_invalid_filter_key(): with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Key": "invalid", "Values": ["foo"]}]) - ire.exception.response["Error"]["Code"].should.equal("ValidationException") - ire.exception.response["Error"]["Message"].should.equal( + ire.value.response["Error"]["Code"].should.equal("ValidationException") + ire.value.response["Error"]["Message"].should.equal( "1 validation error detected: Value 'invalid' at 'filters.1.member.key' failed to satisfy constraint: Member " "must satisfy enum value set: [all, name, tag-key, description, tag-value]" ) diff --git a/tests/test_secretsmanager/test_secretsmanager.py b/tests/test_secretsmanager/test_secretsmanager.py index 301ceb081..14d30bf36 100644 --- a/tests/test_secretsmanager/test_secretsmanager.py +++ b/tests/test_secretsmanager/test_secretsmanager.py @@ -58,7 +58,7 @@ def test_get_secret_that_does_not_exist(): assert \ "Secrets Manager can't find the specified secret." == \ - cm.exception.response["Error"]["Message"] + cm.value.response["Error"]["Message"] @mock_secretsmanager @@ -73,7 +73,7 @@ def test_get_secret_that_does_not_match(): assert \ "Secrets Manager can't find the specified secret." == \ - cm.exception.response["Error"]["Message"] + cm.value.response["Error"]["Message"] @mock_secretsmanager @@ -99,7 +99,7 @@ def test_get_secret_that_has_no_value(): assert \ "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT" == \ - cm.exception.response["Error"] + cm.value.response["Error"]["Message"] @mock_secretsmanager @@ -110,16 +110,14 @@ def test_get_secret_version_that_does_not_exist(): secret_arn = result["ARN"] missing_version_id = "00000000-0000-0000-0000-000000000000" - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: conn.get_secret_value(SecretId=secret_arn, VersionId=missing_version_id) - assert_equal( + assert \ ( "An error occurred (ResourceNotFoundException) when calling the GetSecretValue operation: Secrets " "Manager can't find the specified secret value for VersionId: 00000000-0000-0000-0000-000000000000" - ), - cm.exception.response["Error"]["Message"], - ) + ) == cm.value.response["Error"]["Message"] @mock_secretsmanager @@ -702,8 +700,8 @@ def test_put_secret_binary_requires_either_string_or_binary(): with pytest.raises(ClientError) as ire: conn.put_secret_value(SecretId=DEFAULT_SECRET_NAME) - ire.exception.response["Error"]["Code"].should.equal("InvalidRequestException") - ire.exception.response["Error"]["Message"].should.equal( + ire.value.response["Error"]["Code"].should.equal("InvalidRequestException") + ire.value.response["Error"]["Message"].should.equal( "You must provide either SecretString or SecretBinary." ) @@ -883,7 +881,7 @@ def test_update_secret_which_does_not_exit(): assert \ "Secrets Manager can't find the specified secret." == \ - cm.exception.response["Error"]["Message"] + cm.value.response["Error"]["Message"] @mock_secretsmanager @@ -900,7 +898,7 @@ def test_update_secret_marked_as_deleted(): assert ( "because it was marked for deletion." - in cm.exception.response["Error"]["Message"] + in cm.value.response["Error"]["Message"] ) diff --git a/tests/test_secretsmanager/test_server.py b/tests/test_secretsmanager/test_server.py index da41eb5fb..1d3c9d218 100644 --- a/tests/test_secretsmanager/test_server.py +++ b/tests/test_secretsmanager/test_server.py @@ -89,10 +89,9 @@ def test_get_secret_that_has_no_value(): ) json_data = json.loads(get_secret.data.decode("utf-8")) - assert ( - json_data["message"] - == "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT" - ) + assert \ + json_data["message"] == \ + "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT" assert json_data["__type"] == "ResourceNotFoundException" diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py index f0af73fd3..dee28210c 100644 --- a/tests/test_ses/test_ses_boto3.py +++ b/tests/test_ses/test_ses_boto3.py @@ -311,7 +311,7 @@ def test_create_configuration_set(): }, ) - ex.exception.response["Error"]["Code"].should.equal("ConfigurationSetDoesNotExist") + ex.value.response["Error"]["Code"].should.equal("ConfigurationSetDoesNotExist") with pytest.raises(ClientError) as ex: conn.create_configuration_set_event_destination( @@ -326,7 +326,7 @@ def test_create_configuration_set(): }, ) - ex.exception.response["Error"]["Code"].should.equal("EventDestinationAlreadyExists") + ex.value.response["Error"]["Code"].should.equal("EventDestinationAlreadyExists") @mock_ses @@ -339,7 +339,7 @@ def test_create_receipt_rule_set(): with pytest.raises(ClientError) as ex: conn.create_receipt_rule_set(RuleSetName="testRuleSet") - ex.exception.response["Error"]["Code"].should.equal("RuleSetNameAlreadyExists") + ex.value.response["Error"]["Code"].should.equal("RuleSetNameAlreadyExists") @mock_ses @@ -407,7 +407,7 @@ def test_create_receipt_rule(): }, ) - ex.exception.response["Error"]["Code"].should.equal("RuleAlreadyExists") + ex.value.response["Error"]["Code"].should.equal("RuleAlreadyExists") with pytest.raises(ClientError) as ex: conn.create_receipt_rule( @@ -438,7 +438,7 @@ def test_create_receipt_rule(): }, ) - ex.exception.response["Error"]["Code"].should.equal("RuleSetDoesNotExist") + ex.value.response["Error"]["Code"].should.equal("RuleSetDoesNotExist") @mock_ses @@ -467,7 +467,7 @@ def test_create_ses_template(): } ) - ex.exception.response["Error"]["Code"].should.equal("TemplateNameAlreadyExists") + ex.value.response["Error"]["Code"].should.equal("TemplateNameAlreadyExists") # get a template which is already added result = conn.get_template(TemplateName="MyTemplate") @@ -478,7 +478,7 @@ def test_create_ses_template(): with pytest.raises(ClientError) as ex: conn.get_template(TemplateName="MyFakeTemplate") - ex.exception.response["Error"]["Code"].should.equal("TemplateDoesNotExist") + ex.value.response["Error"]["Code"].should.equal("TemplateDoesNotExist") result = conn.list_templates() result["TemplatesMetadata"][0]["Name"].should.equal("MyTemplate") diff --git a/tests/test_sns/test_publishing_boto3.py b/tests/test_sns/test_publishing_boto3.py index 07bf04b11..797ccdaba 100644 --- a/tests/test_sns/test_publishing_boto3.py +++ b/tests/test_sns/test_publishing_boto3.py @@ -235,14 +235,14 @@ def test_publish_bad_sms(): # Test invalid number with pytest.raises(ClientError) as cm: client.publish(PhoneNumber="NAA+15551234567", Message="my message") - cm.exception.response["Error"]["Code"].should.equal("InvalidParameter") - cm.exception.response["Error"]["Message"].should.contain("not meet the E164") + cm.value.response["Error"]["Code"].should.equal("InvalidParameter") + cm.value.response["Error"]["Message"].should.contain("not meet the E164") # Test to long ASCII message with pytest.raises(ClientError) as cm: client.publish(PhoneNumber="+15551234567", Message="a" * 1601) - cm.exception.response["Error"]["Code"].should.equal("InvalidParameter") - cm.exception.response["Error"]["Message"].should.contain("must be less than 1600") + cm.value.response["Error"]["Code"].should.equal("InvalidParameter") + cm.value.response["Error"]["Message"].should.contain("must be less than 1600") @mock_sqs diff --git a/tests/test_sqs/test_sqs.py b/tests/test_sqs/test_sqs.py index b0a91bbde..57dd97ac3 100644 --- a/tests/test_sqs/test_sqs.py +++ b/tests/test_sqs/test_sqs.py @@ -221,7 +221,7 @@ def test_get_nonexistent_queue(): sqs = boto3.resource("sqs", region_name="us-east-1") with pytest.raises(ClientError) as err: sqs.get_queue_by_name(QueueName="non-existing-queue") - ex = err.exception + ex = err.value ex.operation_name.should.equal("GetQueueUrl") ex.response["Error"]["Code"].should.equal("AWS.SimpleQueueService.NonExistentQueue") ex.response["Error"]["Message"].should.equal( @@ -230,7 +230,7 @@ def test_get_nonexistent_queue(): with pytest.raises(ClientError) as err: sqs.Queue("http://whatever-incorrect-queue-address").load() - ex = err.exception + ex = err.value ex.operation_name.should.equal("GetQueueAttributes") ex.response["Error"]["Code"].should.equal("AWS.SimpleQueueService.NonExistentQueue") @@ -377,7 +377,7 @@ def test_message_with_attributes_invalid_datatype(): } }, ) - ex = e.exception + ex = e.value ex.response["Error"]["Code"].should.equal("MessageAttributesInvalid") ex.response["Error"]["Message"].should.equal( "The message attribute 'timestamp' has an invalid message attribute type, the set of supported type " @@ -1658,7 +1658,7 @@ def test_add_permission_errors(): AWSAccountIds=["111111111111"], Actions=["ReceiveMessage", "SendMessage"], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AddPermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterValue") @@ -1673,7 +1673,7 @@ def test_add_permission_errors(): AWSAccountIds=["111111111111"], Actions=["RemovePermission"], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AddPermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterValue") @@ -1689,7 +1689,7 @@ def test_add_permission_errors(): AWSAccountIds=["111111111111"], Actions=[], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AddPermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("MissingParameter") @@ -1704,7 +1704,7 @@ def test_add_permission_errors(): AWSAccountIds=[], Actions=["ReceiveMessage"], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AddPermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterValue") @@ -1728,7 +1728,7 @@ def test_add_permission_errors(): "SendMessage", ], ) - ex = e.exception + ex = e.value ex.operation_name.should.equal("AddPermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) ex.response["Error"]["Code"].should.contain("OverLimit") @@ -1745,7 +1745,7 @@ def test_remove_permission_errors(): with pytest.raises(ClientError) as e: client.remove_permission(QueueUrl=queue_url, Label="test") - ex = e.exception + ex = e.value ex.operation_name.should.equal("RemovePermission") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("InvalidParameterValue") @@ -2174,7 +2174,7 @@ def test_send_messages_to_fifo_without_message_group_id(): with pytest.raises(Exception) as e: queue.send_message(MessageBody="message-1") - ex = e.exception + ex = e.value ex.response["Error"]["Code"].should.equal("MissingParameter") ex.response["Error"]["Message"].should.equal( "The request must contain the parameter MessageGroupId." diff --git a/tests/test_ssm/test_ssm_boto3.py b/tests/test_ssm/test_ssm_boto3.py index e3c03203f..1eeec09d0 100644 --- a/tests/test_ssm/test_ssm_boto3.py +++ b/tests/test_ssm/test_ssm_boto3.py @@ -35,10 +35,10 @@ def test_delete_parameter(): def test_delete_nonexistent_parameter(): client = boto3.client("ssm", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.delete_parameter(Name="test_noexist") - ex.exception.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") + ex.value.response["Error"]["Message"].should.equal( "Parameter test_noexist not found." ) @@ -438,17 +438,17 @@ def test_get_parameter_with_version_and_labels(): "arn:aws:ssm:us-east-1:1234567890:parameter/test-2" ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.get_parameter(Name="test-2:2:3", WithDecryption=False) - ex.exception.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") + ex.value.response["Error"]["Message"].should.equal( "Parameter test-2:2:3 not found." ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.get_parameter(Name="test-2:2", WithDecryption=False) - ex.exception.response["Error"]["Code"].should.equal("ParameterNotFound") - ex.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Code"].should.equal("ParameterNotFound") + ex.value.response["Error"]["Message"].should.equal( "Parameter test-2:2 not found." ) @@ -462,9 +462,9 @@ def test_get_parameters_errors(): for name, value in ssm_parameters.items(): client.put_parameter(Name=name, Value=value, Type="String") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_parameters(Names=list(ssm_parameters.keys())) - ex = e.exception + ex = e.value ex.operation_name.should.equal("GetParameters") ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) ex.response["Error"]["Code"].should.contain("ValidationException") diff --git a/tests/test_stepfunctions/test_stepfunctions.py b/tests/test_stepfunctions/test_stepfunctions.py index 1a946e8e3..d5eb76ae7 100644 --- a/tests/test_stepfunctions/test_stepfunctions.py +++ b/tests/test_stepfunctions/test_stepfunctions.py @@ -544,11 +544,11 @@ def test_state_machine_start_execution_fails_on_duplicate_execution_name(): stateMachineArn=sm["stateMachineArn"], name="execution_name" ) # - with pytest.raises(ClientError) as exc: + with pytest.raises(ClientError) as ex: _ = client.start_execution( stateMachineArn=sm["stateMachineArn"], name="execution_name" ) - exc.exception.response["Error"]["Message"].should.equal( + ex.value.response["Error"]["Message"].should.equal( "Execution Already Exists: '" + execution_one["executionArn"] + "'" ) diff --git a/tests/test_sts/test_sts.py b/tests/test_sts/test_sts.py index 34b71c358..098da5881 100644 --- a/tests/test_sts/test_sts.py +++ b/tests/test_sts/test_sts.py @@ -357,9 +357,9 @@ def test_federation_token_with_too_long_policy(): json_policy = json.dumps(policy) assert len(json_policy) > MAX_FEDERATION_TOKEN_POLICY_LENGTH - with pytest.raises(ClientError) as exc: + with pytest.raises(ClientError) as ex: cli.get_federation_token(Name="foo", DurationSeconds=3600, Policy=json_policy) - exc.exception.response["Error"]["Code"].should.equal("ValidationError") - exc.exception.response["Error"]["Message"].should.contain( + ex.value.response["Error"]["Code"].should.equal("ValidationError") + ex.value.response["Error"]["Message"].should.contain( str(MAX_FEDERATION_TOKEN_POLICY_LENGTH) )