diff --git a/requirements-tests.txt b/requirements-tests.txt index eaa8454c7..c19f35c7d 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,4 +1,4 @@ -nose +pytest sure==1.4.11 freezegun -parameterized>=0.7.0 \ No newline at end of file +parameterized>=0.7.0 diff --git a/setup.cfg b/setup.cfg index fb04c16a8..3c6e79cf3 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,8 +1,2 @@ -[nosetests] -verbosity=1 -detailed-errors=1 -with-coverage=1 -cover-package=moto - [bdist_wheel] universal=1 diff --git a/tests/__init__.py b/tests/__init__.py index 05b1d476b..01fe5ab1f 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -6,4 +6,3 @@ import logging logging.getLogger("boto").setLevel(logging.CRITICAL) logging.getLogger("boto3").setLevel(logging.CRITICAL) logging.getLogger("botocore").setLevel(logging.CRITICAL) -logging.getLogger("nose").setLevel(logging.CRITICAL) diff --git a/tests/backport_assert_raises.py b/tests/backport_assert_raises.py deleted file mode 100644 index bfed51308..000000000 --- a/tests/backport_assert_raises.py +++ /dev/null @@ -1,41 +0,0 @@ -from __future__ import unicode_literals - -""" -Patch courtesy of: -https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/ -""" - -# code for monkey-patching -import nose.tools - -# let's fix nose.tools.assert_raises (which is really unittest.assertRaises) -# so that it always supports context management - -# in order for these changes to be available to other modules, you'll need -# to guarantee this module is imported by your fixture before either nose or -# unittest are imported - -try: - nose.tools.assert_raises(Exception) -except TypeError: - # this version of assert_raises doesn't support the 1-arg version - class AssertRaisesContext(object): - def __init__(self, expected): - self.expected = expected - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, tb): - self.exception = exc_val - if issubclass(exc_type, self.expected): - return True - nose.tools.assert_equal(exc_type, self.expected) - # if you get to this line, the last assertion must have passed - # suppress the propagation of this exception - return True - - def assert_raises_context(exc_type): - return AssertRaisesContext(exc_type) - - nose.tools.assert_raises = assert_raises_context diff --git a/tests/helpers.py b/tests/helpers.py index ffe27103d..9293bcad9 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals import boto -from nose.plugins.skip import SkipTest +from unittest import SkipTest import six diff --git a/tests/test_acm/__init__.py b/tests/test_acm/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_acm/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_acm/resources/__init__.py b/tests/test_acm/resources/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_acm/resources/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_apigateway/__init__.py b/tests/test_apigateway/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_apigateway/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_apigateway/test_apigateway.py b/tests/test_apigateway/test_apigateway.py index c58d644fa..4a6c3eea3 100644 --- a/tests/test_apigateway/test_apigateway.py +++ b/tests/test_apigateway/test_apigateway.py @@ -11,7 +11,7 @@ from botocore.exceptions import ClientError import responses from moto import mock_apigateway, mock_cognitoidp, settings from moto.core import ACCOUNT_ID -from nose.tools import assert_raises +import pytest @freeze_time("2015-01-01") @@ -90,7 +90,7 @@ def test_create_rest_api_with_policy(): def test_create_rest_api_invalid_apikeysource(): client = boto3.client("apigateway", region_name="us-west-2") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_rest_api( name="my_api", description="this is my api", @@ -126,7 +126,7 @@ def test_create_rest_api_valid_apikeysources(): def test_create_rest_api_invalid_endpointconfiguration(): client = boto3.client("apigateway", region_name="us-west-2") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_rest_api( name="my_api", description="this is my api", @@ -194,7 +194,7 @@ def test_create_resource__validate_name(): valid_names = ["users", "{user_id}", "{proxy+}", "user_09", "good-dog"] # All invalid names should throw an exception for name in invalid_names: - with assert_raises(ClientError) as ex: + 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( @@ -1194,7 +1194,7 @@ def test_create_deployment_requires_REST_methods(): response = client.create_rest_api(name="my_api", description="this is my api") api_id = response["id"] - with assert_raises(ClientError) as ex: + 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( @@ -1217,7 +1217,7 @@ def test_create_deployment_requires_REST_method_integrations(): restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE" ) - with assert_raises(ClientError) as ex: + 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( @@ -1273,7 +1273,7 @@ def test_put_integration_response_requires_responseTemplate(): integrationHttpMethod="POST", ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration_response( restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" ) @@ -1314,7 +1314,7 @@ def test_put_integration_response_with_response_template(): integrationHttpMethod="POST", ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration_response( restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200" ) @@ -1372,7 +1372,7 @@ def test_put_integration_validation(): for type in types_requiring_integration_method: # Ensure that integrations of these types fail if no integrationHttpMethod is provided - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1428,7 +1428,7 @@ def test_put_integration_validation(): ) for type in ["AWS_PROXY"]: # Ensure that aws_proxy does not support S3 - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1446,7 +1446,7 @@ def test_put_integration_validation(): ) for type in aws_types: # Ensure that the Role ARN is for the current account - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1462,7 +1462,7 @@ def test_put_integration_validation(): ) for type in ["AWS"]: # Ensure that the Role ARN is specified for aws integrations - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1477,7 +1477,7 @@ def test_put_integration_validation(): ) for type in http_types: # Ensure that the URI is valid HTTP - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1492,7 +1492,7 @@ def test_put_integration_validation(): ) for type in aws_types: # Ensure that the URI is an ARN - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1507,7 +1507,7 @@ def test_put_integration_validation(): ) for type in aws_types: # Ensure that the URI is a valid ARN - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.put_integration( restApiId=api_id, resourceId=root_id, @@ -1632,7 +1632,7 @@ def test_create_domain_names(): response["domainName"].should.equal(domain_name) response["certificateName"].should.equal(test_certificate_name) # without domain name it should throw BadRequestException - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_domain_name(domainName="") ex.exception.response["Error"]["Message"].should.equal("No Domain Name specified") @@ -1666,7 +1666,7 @@ def test_get_domain_name(): client = boto3.client("apigateway", region_name="us-west-2") domain_name = "testDomain" # quering an invalid domain name which is not present - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.get_domain_name(domainName=domain_name) ex.exception.response["Error"]["Message"].should.equal( @@ -1701,7 +1701,7 @@ def test_create_model(): response["description"].should.equal(description) # with an invalid rest_api_id it should throw NotFoundException - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_model( restApiId=dummy_rest_api_id, name=model_name, @@ -1713,7 +1713,7 @@ def test_create_model(): ) ex.exception.response["Error"]["Code"].should.equal("NotFoundException") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_model( restApiId=rest_api_id, name="", @@ -1770,7 +1770,7 @@ def test_get_model_by_name(): result["name"] = model_name result["description"] = description - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.get_model(restApiId=dummy_rest_api_id, modelName=model_name) ex.exception.response["Error"]["Message"].should.equal( "Invalid Rest API Id specified" @@ -1784,7 +1784,7 @@ def test_get_model_with_invalid_name(): response = client.create_rest_api(name="my_api", description="this is my api") rest_api_id = response["id"] # test with an invalid model name - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.get_model(restApiId=rest_api_id, modelName="fake") ex.exception.response["Error"]["Message"].should.equal( "Invalid Model Name specified" @@ -1868,7 +1868,7 @@ def test_create_api_headers(): payload = {"value": apikey_value, "name": apikey_name} client.create_api_key(**payload) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_api_key(**payload) ex.exception.response["Error"]["Code"].should.equal("ConflictException") if not settings.TEST_SERVER_MODE: @@ -1939,7 +1939,7 @@ def test_usage_plans(): len(response["items"]).should.equal(0) # # Try to get info about a non existing usage - with assert_raises(ClientError) as ex: + 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( @@ -2030,7 +2030,7 @@ def test_usage_plan_keys(): len(response["items"]).should.equal(0) # Try to get info about a non existing api key - with assert_raises(ClientError) as ex: + 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( @@ -2038,7 +2038,7 @@ def test_usage_plan_keys(): ) # Try to get info about an existing api key that has not jet added to a valid usage plan - with assert_raises(ClientError) as ex: + 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( @@ -2046,7 +2046,7 @@ def test_usage_plan_keys(): ) # Try to get info about an existing api key that has not jet added to a valid usage plan - with assert_raises(ClientError) as ex: + 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( diff --git a/tests/test_applicationautoscaling/test_applicationautoscaling.py b/tests/test_applicationautoscaling/test_applicationautoscaling.py index 9b1c0b678..f362cc2c1 100644 --- a/tests/test_applicationautoscaling/test_applicationautoscaling.py +++ b/tests/test_applicationautoscaling/test_applicationautoscaling.py @@ -1,10 +1,10 @@ from __future__ import unicode_literals -import botocore + import boto3 +import botocore +import pytest import sure # noqa -from nose.tools import assert_raises from moto import mock_applicationautoscaling, mock_ecs -from moto.applicationautoscaling.exceptions import AWSValidationException DEFAULT_REGION = "us-east-1" DEFAULT_ECS_CLUSTER = "default" @@ -334,7 +334,7 @@ def test_put_scaling_policy(): }, } - with assert_raises(client.exceptions.ValidationException) as e: + with pytest.raises(client.exceptions.ValidationException) as e: client.put_scaling_policy( PolicyName=policy_name, ServiceNamespace=namespace, @@ -443,7 +443,7 @@ def test_delete_scaling_policies(): }, } - with assert_raises(client.exceptions.ValidationException) as e: + with pytest.raises(client.exceptions.ValidationException) as e: client.delete_scaling_policy( PolicyName=policy_name, ServiceNamespace=namespace, @@ -507,7 +507,7 @@ def test_deregister_scalable_target(): response = client.describe_scalable_targets(ServiceNamespace=namespace) len(response["ScalableTargets"]).should.equal(0) - with assert_raises(client.exceptions.ValidationException) as e: + with pytest.raises(client.exceptions.ValidationException) as e: client.deregister_scalable_target( ServiceNamespace=namespace, ResourceId=resource_id, diff --git a/tests/test_applicationautoscaling/test_validation.py b/tests/test_applicationautoscaling/test_validation.py index 02281ab05..c77b64fc8 100644 --- a/tests/test_applicationautoscaling/test_validation.py +++ b/tests/test_applicationautoscaling/test_validation.py @@ -4,7 +4,7 @@ from moto import mock_applicationautoscaling, mock_ecs from moto.applicationautoscaling import models from moto.applicationautoscaling.exceptions import AWSValidationException from botocore.exceptions import ParamValidationError -from nose.tools import assert_raises +import pytest import sure # noqa from botocore.exceptions import ClientError from parameterized import parameterized @@ -25,21 +25,21 @@ DEFAULT_ROLE_ARN = "test:arn" @mock_applicationautoscaling def test_describe_scalable_targets_no_params_should_raise_param_validation_errors(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): client.describe_scalable_targets() @mock_applicationautoscaling def test_register_scalable_target_no_params_should_raise_param_validation_errors(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): client.register_scalable_target() @mock_applicationautoscaling def test_register_scalable_target_with_none_service_namespace_should_raise_param_validation_errors(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): register_scalable_target(client, ServiceNamespace=None) @@ -47,7 +47,7 @@ def test_register_scalable_target_with_none_service_namespace_should_raise_param def test_describe_scalable_targets_with_invalid_scalable_dimension_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: response = client.describe_scalable_targets( ServiceNamespace=DEFAULT_SERVICE_NAMESPACE, ScalableDimension="foo", ) @@ -62,7 +62,7 @@ def test_describe_scalable_targets_with_invalid_scalable_dimension_should_return def test_describe_scalable_targets_with_invalid_service_namespace_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: response = client.describe_scalable_targets( ServiceNamespace="foo", ScalableDimension=DEFAULT_SCALABLE_DIMENSION, ) @@ -77,7 +77,7 @@ def test_describe_scalable_targets_with_invalid_service_namespace_should_return_ def test_describe_scalable_targets_with_multiple_invalid_parameters_should_return_validation_exception(): client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: response = client.describe_scalable_targets( ServiceNamespace="foo", ScalableDimension="bar", ) @@ -94,7 +94,7 @@ def test_register_scalable_target_ecs_with_non_existent_service_should_return_va client = boto3.client("application-autoscaling", region_name=DEFAULT_REGION) resource_id = "service/{}/foo".format(DEFAULT_ECS_CLUSTER) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: register_scalable_target(client, ServiceNamespace="ecs", ResourceId=resource_id) err.response["Error"]["Code"].should.equal("ValidationException") err.response["Error"]["Message"].should.equal( @@ -116,7 +116,7 @@ def test_target_params_are_valid_success(namespace, r_id, dimension, expected): expected ) else: - with assert_raises(AWSValidationException): + with pytest.raises(AWSValidationException): models._target_params_are_valid(namespace, r_id, dimension) diff --git a/tests/test_athena/__init__.py b/tests/test_athena/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_athena/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_athena/test_athena.py b/tests/test_athena/test_athena.py index 805a653e3..98e1dc4b9 100644 --- a/tests/test_athena/test_athena.py +++ b/tests/test_athena/test_athena.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest import boto3 import sure # noqa @@ -104,7 +104,7 @@ def test_start_query_execution(): def test_start_query_validate_workgroup(): client = boto3.client("athena", region_name="us-east-1") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.start_query_execution( QueryString="query1", QueryExecutionContext={"Database": "string"}, diff --git a/tests/test_autoscaling/__init__.py b/tests/test_autoscaling/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_autoscaling/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_autoscaling/test_autoscaling.py b/tests/test_autoscaling/test_autoscaling.py index 1e7121381..9e51c4b12 100644 --- a/tests/test_autoscaling/test_autoscaling.py +++ b/tests/test_autoscaling/test_autoscaling.py @@ -8,7 +8,7 @@ from boto.ec2.autoscale import Tag import boto.ec2.elb import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import ( mock_autoscaling, @@ -21,7 +21,7 @@ from moto import ( ) from tests.helpers import requires_boto_gte -from utils import ( +from .utils import ( setup_networking, setup_networking_deprecated, setup_instance_with_networking, @@ -781,7 +781,7 @@ def test_create_autoscaling_group_from_invalid_instance_id(): 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", InstanceId=invalid_instance_id, diff --git a/tests/test_autoscaling/test_autoscaling_cloudformation.py b/tests/test_autoscaling/test_autoscaling_cloudformation.py index 240ba66e0..24a5b5628 100644 --- a/tests/test_autoscaling/test_autoscaling_cloudformation.py +++ b/tests/test_autoscaling/test_autoscaling_cloudformation.py @@ -7,7 +7,7 @@ from moto import ( mock_ec2, ) -from utils import setup_networking +from .utils import setup_networking @mock_autoscaling diff --git a/tests/test_autoscaling/test_elbv2.py b/tests/test_autoscaling/test_elbv2.py index a3d3dba9f..d3b1cc5f8 100644 --- a/tests/test_autoscaling/test_elbv2.py +++ b/tests/test_autoscaling/test_elbv2.py @@ -4,7 +4,7 @@ import boto3 import sure # noqa from moto import mock_autoscaling, mock_ec2, mock_elbv2 -from utils import setup_networking +from .utils import setup_networking @mock_elbv2 diff --git a/tests/test_autoscaling/test_policies.py b/tests/test_autoscaling/test_policies.py index f44938eea..284fe267a 100644 --- a/tests/test_autoscaling/test_policies.py +++ b/tests/test_autoscaling/test_policies.py @@ -7,7 +7,7 @@ import sure # noqa from moto import mock_autoscaling_deprecated -from utils import setup_networking_deprecated +from .utils import setup_networking_deprecated def setup_autoscale_group(): diff --git a/tests/test_awslambda/__init__.py b/tests/test_awslambda/__init__.py index e69de29bb..08a1c1568 100644 --- a/tests/test_awslambda/__init__.py +++ b/tests/test_awslambda/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_awslambda/test_awslambda_cloudformation.py b/tests/test_awslambda/test_awslambda_cloudformation.py index c3061ff3a..f87918328 100644 --- a/tests/test_awslambda/test_awslambda_cloudformation.py +++ b/tests/test_awslambda/test_awslambda_cloudformation.py @@ -4,7 +4,7 @@ import sure # noqa import zipfile from botocore.exceptions import ClientError from moto import mock_cloudformation, mock_iam, mock_lambda, mock_s3, mock_sqs -from nose.tools import assert_raises +import pytest from string import Template from uuid import uuid4 @@ -109,7 +109,7 @@ def test_lambda_can_be_deleted_by_cloudformation(): # Delete Stack cf.delete_stack(StackName=stack["StackId"]) # Verify function was deleted - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: lmbda.get_function(FunctionName=created_fn_name) e.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") diff --git a/tests/test_awslambda/test_lambda.py b/tests/test_awslambda/test_lambda.py index f7e7b3c7e..2de95cb3c 100644 --- a/tests/test_awslambda/test_lambda.py +++ b/tests/test_awslambda/test_lambda.py @@ -24,7 +24,7 @@ from moto import ( mock_sqs, ) from moto.sts.models import ACCOUNT_ID -from nose.tools import assert_raises +import pytest from botocore.exceptions import ClientError _lambda_region = "us-west-2" @@ -497,7 +497,7 @@ def test_get_function(): ) # Test get function when can't find function name - with assert_raises(conn.exceptions.ResourceNotFoundException): + with pytest.raises(conn.exceptions.ResourceNotFoundException): conn.get_function(FunctionName="junk", Qualifier="$LATEST") @@ -1800,7 +1800,7 @@ def test_get_function_concurrency(): def create_invalid_lambda(role): conn = boto3.client("lambda", _lambda_region) zip_content = get_test_zip_file1() - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: conn.create_function( FunctionName="testFunction", Runtime="python2.7", diff --git a/tests/test_batch/__init__.py b/tests/test_batch/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_batch/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_batch/test_batch.py b/tests/test_batch/test_batch.py index 566be6aca..511042d1f 100644 --- a/tests/test_batch/test_batch.py +++ b/tests/test_batch/test_batch.py @@ -7,10 +7,6 @@ from botocore.exceptions import ClientError import sure # noqa from moto import mock_batch, mock_iam, mock_ec2, mock_ecs, mock_logs -import functools -import nose - - DEFAULT_REGION = "eu-central-1" diff --git a/tests/test_batch/test_batch_cloudformation.py b/tests/test_batch/test_batch_cloudformation.py index cc51b79f3..7935f3fe9 100644 --- a/tests/test_batch/test_batch_cloudformation.py +++ b/tests/test_batch/test_batch_cloudformation.py @@ -14,7 +14,6 @@ from moto import ( mock_cloudformation, ) import functools -import nose import json DEFAULT_REGION = "eu-central-1" diff --git a/tests/test_cloudformation/test_cloudformation_stack_crud.py b/tests/test_cloudformation/test_cloudformation_stack_crud.py index d7e26e85d..6baae83bc 100644 --- a/tests/test_cloudformation/test_cloudformation_stack_crud.py +++ b/tests/test_cloudformation/test_cloudformation_stack_crud.py @@ -12,9 +12,7 @@ import boto.cloudformation from boto.exception import BotoServerError import sure # noqa -# Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest from moto.core import ACCOUNT_ID from moto import ( @@ -319,7 +317,7 @@ def test_delete_stack_by_id(): conn.describe_stacks().should.have.length_of(1) conn.delete_stack(stack_id) conn.describe_stacks().should.have.length_of(0) - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.describe_stacks("test_stack") conn.describe_stacks(stack_id).should.have.length_of(1) @@ -338,7 +336,7 @@ def test_delete_stack_with_resource_missing_delete_attr(): @mock_cloudformation_deprecated def test_bad_describe_stack(): conn = boto.connect_cloudformation() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.describe_stacks("bad_stack") @@ -519,7 +517,7 @@ def test_update_stack_when_rolled_back(): stack_id ].status = "ROLLBACK_COMPLETE" - with assert_raises(BotoServerError) as err: + with pytest.raises(BotoServerError) as err: conn.update_stack("test_stack", dummy_template_json) ex = err.exception diff --git a/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py b/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py index 65469f1b3..86b6f1a94 100644 --- a/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py +++ b/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py @@ -9,8 +9,7 @@ import boto3 from botocore.exceptions import ClientError import sure # noqa -# Ensure 'assert_raises' context manager support for Python 2.6 -from nose.tools import assert_raises +import pytest from moto import mock_cloudformation, mock_s3, mock_sqs, mock_ec2 from moto.core import ACCOUNT_ID @@ -548,7 +547,7 @@ def test_boto3_list_stack_set_operations(): @mock_cloudformation def test_boto3_bad_list_stack_resources(): cf_conn = boto3.client("cloudformation", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): cf_conn.list_stack_resources(StackName="test_stack_set") @@ -1180,7 +1179,7 @@ def test_describe_updated_stack(): @mock_cloudformation def test_bad_describe_stack(): cf_conn = boto3.client("cloudformation", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): cf_conn.describe_stacks(StackName="non_existent_stack") @@ -1332,7 +1331,7 @@ def test_delete_stack_with_export(): def test_export_names_must_be_unique(): cf = boto3.resource("cloudformation", region_name="us-east-1") cf.create_stack(StackName="test_stack", TemplateBody=dummy_output_template_json) - with assert_raises(ClientError): + with pytest.raises(ClientError): cf.create_stack(StackName="test_stack", TemplateBody=dummy_output_template_json) @@ -1373,7 +1372,7 @@ def test_boto3_create_duplicate_stack(): StackName="test_stack", TemplateBody=dummy_template_json, ) - with assert_raises(ClientError): + with pytest.raises(ClientError): cf_conn.create_stack( StackName="test_stack", TemplateBody=dummy_template_json, ) diff --git a/tests/test_cloudformation/test_validate.py b/tests/test_cloudformation/test_validate.py index ea14fceea..a4c65a4c7 100644 --- a/tests/test_cloudformation/test_validate.py +++ b/tests/test_cloudformation/test_validate.py @@ -3,7 +3,6 @@ import json import yaml import os import boto3 -from nose.tools import raises import botocore import sure # noqa diff --git a/tests/test_cloudwatch/__init__.py b/tests/test_cloudwatch/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_cloudwatch/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_cloudwatch/test_cloudwatch_boto3.py b/tests/test_cloudwatch/test_cloudwatch_boto3.py index 9c4757d60..c62f31459 100644 --- a/tests/test_cloudwatch/test_cloudwatch_boto3.py +++ b/tests/test_cloudwatch/test_cloudwatch_boto3.py @@ -4,7 +4,7 @@ import boto3 from botocore.exceptions import ClientError from datetime import datetime, timedelta from freezegun import freeze_time -from nose.tools import assert_raises +import pytest from uuid import uuid4 import pytz import sure # noqa @@ -111,7 +111,7 @@ def test_delete_invalid_alarm(): ) # trying to delete an alarm which is not created along with valid alarm. - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: cloudwatch.delete_alarms(AlarmNames=["InvalidAlarmName", "testalarm1"]) e.exception.response["Error"]["Code"].should.equal("ResourceNotFound") @@ -120,7 +120,7 @@ def test_delete_invalid_alarm(): len(resp["MetricAlarms"]).should.equal(1) # test to check if the error raises if only one invalid alarm is tried to delete. - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: cloudwatch.delete_alarms(AlarmNames=["InvalidAlarmName"]) e.exception.response["Error"]["Code"].should.equal("ResourceNotFound") @@ -423,7 +423,7 @@ def test_list_metrics_paginated(): # Verify that only a single page of metrics is returned cloudwatch.list_metrics()["Metrics"].should.be.empty # Verify we can't pass a random NextToken - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: cloudwatch.list_metrics(NextToken=str(uuid4())) e.exception.response["Error"]["Message"].should.equal( "Request parameter NextToken is invalid" @@ -452,7 +452,7 @@ def test_list_metrics_paginated(): len(third_page["Metrics"]).should.equal(100) third_page.shouldnt.contain("NextToken") # Verify that we can't reuse an existing token - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: cloudwatch.list_metrics(NextToken=first_page["NextToken"]) e.exception.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 69021372a..7a5867d44 100644 --- a/tests/test_codecommit/test_codecommit.py +++ b/tests/test_codecommit/test_codecommit.py @@ -4,7 +4,7 @@ import sure # noqa from moto import mock_codecommit from moto.core import ACCOUNT_ID from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest @mock_codecommit @@ -81,7 +81,7 @@ def test_create_repository_repository_name_exists(): client.create_repository(repositoryName="repository_two") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_repository( repositoryName="repository_two", repositoryDescription="description repo two", @@ -99,7 +99,7 @@ def test_create_repository_repository_name_exists(): def test_create_repository_invalid_repository_name(): client = boto3.client("codecommit", region_name="eu-central-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_repository(repositoryName="in_123_valid_@#$_characters") ex = e.exception ex.operation_name.should.equal("CreateRepository") @@ -156,7 +156,7 @@ def test_get_repository(): client = boto3.client("codecommit", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_repository(repositoryName=repository_name) ex = e.exception ex.operation_name.should.equal("GetRepository") @@ -171,7 +171,7 @@ def test_get_repository(): def test_get_repository_invalid_repository_name(): client = boto3.client("codecommit", region_name="eu-central-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_repository(repositoryName="repository_one-@#@") ex = e.exception ex.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400) @@ -207,7 +207,7 @@ def test_delete_repository(): def test_delete_repository_invalid_repository_name(): client = boto3.client("codecommit", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_repository(repositoryName="_rep@ository_one") ex = e.exception ex.operation_name.should.equal("DeleteRepository") diff --git a/tests/test_codepipeline/test_codepipeline.py b/tests/test_codepipeline/test_codepipeline.py index a40efa05c..ac72f9981 100644 --- a/tests/test_codepipeline/test_codepipeline.py +++ b/tests/test_codepipeline/test_codepipeline.py @@ -4,7 +4,7 @@ from datetime import datetime import boto3 import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_codepipeline, mock_iam @@ -77,7 +77,7 @@ def test_create_pipeline_errors(): client_iam = boto3.client("iam", region_name="us-east-1") create_basic_codepipeline(client, "test-pipeline") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: create_basic_codepipeline(client, "test-pipeline") ex = e.exception ex.operation_name.should.equal("CreatePipeline") @@ -87,7 +87,7 @@ def test_create_pipeline_errors(): "A pipeline with the name 'test-pipeline' already exists in account '123456789012'" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_pipeline( pipeline={ "name": "invalid-pipeline", @@ -139,7 +139,7 @@ def test_create_pipeline_errors(): ), )["Role"]["Arn"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_pipeline( pipeline={ "name": "invalid-pipeline", @@ -175,7 +175,7 @@ def test_create_pipeline_errors(): "CodePipeline is not authorized to perform AssumeRole on role arn:aws:iam::123456789012:role/wrong-role" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_pipeline( pipeline={ "name": "invalid-pipeline", @@ -282,7 +282,7 @@ def test_get_pipeline(): def test_get_pipeline_errors(): client = boto3.client("codepipeline", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_pipeline(name="not-existing") ex = e.exception ex.operation_name.should.equal("GetPipeline") @@ -410,7 +410,7 @@ def test_update_pipeline(): def test_update_pipeline_errors(): client = boto3.client("codepipeline", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.update_pipeline( pipeline={ "name": "not-existing", @@ -517,7 +517,7 @@ def test_list_tags_for_resource(): def test_list_tags_for_resource_errors(): client = boto3.client("codepipeline", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_tags_for_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing" ) @@ -555,7 +555,7 @@ def test_tag_resource_errors(): name = "test-pipeline" create_basic_codepipeline(client, name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.tag_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing", tags=[{"key": "key-2", "value": "value-2"}], @@ -568,7 +568,7 @@ def test_tag_resource_errors(): "The account with id '123456789012' does not include a pipeline with the name 'not-existing'" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.tag_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:{}".format(name), tags=[{"key": "aws:key", "value": "value"}], @@ -583,7 +583,7 @@ def test_tag_resource_errors(): "msg=[Caller is an end user and not allowed to mutate system tags]" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.tag_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:{}".format(name), tags=[ @@ -634,7 +634,7 @@ def test_untag_resource(): def test_untag_resource_errors(): client = boto3.client("codepipeline", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.untag_resource( resourceArn="arn:aws:codepipeline:us-east-1:123456789012:not-existing", tagKeys=["key"], diff --git a/tests/test_cognitoidentity/__init__.py b/tests/test_cognitoidentity/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_cognitoidentity/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_cognitoidentity/test_cognitoidentity.py b/tests/test_cognitoidentity/test_cognitoidentity.py index 164cb023c..a15903329 100644 --- a/tests/test_cognitoidentity/test_cognitoidentity.py +++ b/tests/test_cognitoidentity/test_cognitoidentity.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import boto3 import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_cognitoidentity from moto.cognitoidentity.utils import get_random_identity_id @@ -75,7 +75,7 @@ def test_describe_identity_pool(): def test_describe_identity_pool_with_invalid_id_raises_error(): conn = boto3.client("cognito-identity", "us-west-2") - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: conn.describe_identity_pool(IdentityPoolId="us-west-2_non-existent") cm.exception.operation_name.should.equal("DescribeIdentityPool") diff --git a/tests/test_cognitoidp/__init__.py b/tests/test_cognitoidp/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_cognitoidp/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_cognitoidp/test_cognitoidp.py b/tests/test_cognitoidp/test_cognitoidp.py index a5212b82e..bbd8d5a39 100644 --- a/tests/test_cognitoidp/test_cognitoidp.py +++ b/tests/test_cognitoidp/test_cognitoidp.py @@ -17,7 +17,7 @@ import boto3 import sure # noqa from botocore.exceptions import ClientError from jose import jws, jwk, jwt -from nose.tools import assert_raises +import pytest from moto import mock_cognitoidp, settings from moto.cognitoidp.utils import create_id @@ -603,7 +603,7 @@ def test_update_identity_provider_no_user_pool(): new_value = str(uuid.uuid4()) - with assert_raises(conn.exceptions.ResourceNotFoundException) as cm: + with pytest.raises(conn.exceptions.ResourceNotFoundException) as cm: conn.update_identity_provider( UserPoolId="foo", ProviderName="bar", ProviderDetails={"thing": new_value} ) @@ -623,7 +623,7 @@ def test_update_identity_provider_no_identity_provider(): new_value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] - with assert_raises(conn.exceptions.ResourceNotFoundException) as cm: + with pytest.raises(conn.exceptions.ResourceNotFoundException) as cm: conn.update_identity_provider( UserPoolId=user_pool_id, ProviderName="foo", @@ -699,7 +699,7 @@ def test_create_group_with_duplicate_name_raises_error(): conn.create_group(GroupName=group_name, UserPoolId=user_pool_id) - with assert_raises(ClientError) as cm: + 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") @@ -747,7 +747,7 @@ def test_delete_group(): result = conn.delete_group(GroupName=group_name, UserPoolId=user_pool_id) list(result.keys()).should.equal(["ResponseMetadata"]) # No response expected - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: conn.get_group(GroupName=group_name, UserPoolId=user_pool_id) cm.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") @@ -1565,7 +1565,7 @@ def test_resource_server(): res["ResourceServer"]["Name"].should.equal(name) res["ResourceServer"]["Scopes"].should.equal(scopes) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_resource_server( UserPoolId=user_pool_id, Identifier=identifier, Name=name, Scopes=scopes ) diff --git a/tests/test_config/__init__.py b/tests/test_config/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_config/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index 344622221..716792863 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -5,8 +5,8 @@ from datetime import datetime, timedelta import boto3 from botocore.exceptions import ClientError -from nose import SkipTest -from nose.tools import assert_raises +from unittest import SkipTest +import pytest from moto import mock_s3 from moto.config import mock_config @@ -20,7 +20,7 @@ def test_put_configuration_recorder(): client = boto3.client("config", region_name="us-west-2") # Try without a name supplied: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_recorder(ConfigurationRecorder={"roleARN": "somearn"}) assert ( ce.exception.response["Error"]["Code"] @@ -29,7 +29,7 @@ def test_put_configuration_recorder(): assert "is not valid, blank string." in ce.exception.response["Error"]["Message"] # Try with a really long name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_recorder( ConfigurationRecorder={"name": "a" * 257, "roleARN": "somearn"} ) @@ -68,7 +68,7 @@ def test_put_configuration_recorder(): ] for bg in bad_groups: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_recorder( ConfigurationRecorder={ "name": "default", @@ -85,7 +85,7 @@ def test_put_configuration_recorder(): ) # With an invalid Resource Type: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_recorder( ConfigurationRecorder={ "name": "default", @@ -166,7 +166,7 @@ def test_put_configuration_recorder(): assert not result[0]["recordingGroup"].get("resourceTypes") # Can currently only have exactly 1 Config Recorder in an account/region: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_recorder( ConfigurationRecorder={ "name": "someotherrecorder", @@ -192,7 +192,7 @@ def test_put_configuration_aggregator(): client = boto3.client("config", region_name="us-west-2") # With too many aggregation sources: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -213,7 +213,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # With an invalid region config (no regions defined): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -229,7 +229,7 @@ def test_put_configuration_aggregator(): ) assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", OrganizationAggregationSource={ @@ -243,7 +243,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" # With both region flags defined: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -260,7 +260,7 @@ def test_put_configuration_aggregator(): ) assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", OrganizationAggregationSource={ @@ -276,7 +276,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" # Name too long: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="a" * 257, AccountAggregationSources=[ @@ -287,7 +287,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Too many tags (>50): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -304,7 +304,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Tag key is too big (>128 chars): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -319,7 +319,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Tag value is too big (>256 chars): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -334,7 +334,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Duplicate Tags: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -346,7 +346,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "InvalidInput" # Invalid characters in the tag key: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -361,7 +361,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # If it contains both the AccountAggregationSources and the OrganizationAggregationSource - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator( ConfigurationAggregatorName="testing", AccountAggregationSources=[ @@ -379,7 +379,7 @@ def test_put_configuration_aggregator(): assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" # If it contains neither: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_configuration_aggregator(ConfigurationAggregatorName="testing") assert ( "AccountAggregationSource or the OrganizationAggregationSource" @@ -466,7 +466,7 @@ def test_describe_configuration_aggregators(): ) # Describe with an incorrect name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_aggregators( ConfigurationAggregatorNames=["DoesNotExist"] ) @@ -480,7 +480,7 @@ def test_describe_configuration_aggregators(): ) # Error describe with more than 1 item in the list: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_aggregators( ConfigurationAggregatorNames=["testing0", "DoesNotExist"] ) @@ -551,7 +551,7 @@ def test_describe_configuration_aggregators(): ) # Test with an invalid filter: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_aggregators(NextToken="WRONG") assert ( "The nextToken provided is invalid" == ce.exception.response["Error"]["Message"] @@ -564,7 +564,7 @@ def test_put_aggregation_authorization(): client = boto3.client("config", region_name="us-west-2") # Too many tags (>50): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_aggregation_authorization( AuthorizedAccountId="012345678910", AuthorizedAwsRegion="us-west-2", @@ -579,7 +579,7 @@ def test_put_aggregation_authorization(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Tag key is too big (>128 chars): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_aggregation_authorization( AuthorizedAccountId="012345678910", AuthorizedAwsRegion="us-west-2", @@ -592,7 +592,7 @@ def test_put_aggregation_authorization(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Tag value is too big (>256 chars): - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_aggregation_authorization( AuthorizedAccountId="012345678910", AuthorizedAwsRegion="us-west-2", @@ -605,7 +605,7 @@ def test_put_aggregation_authorization(): assert ce.exception.response["Error"]["Code"] == "ValidationException" # Duplicate Tags: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_aggregation_authorization( AuthorizedAccountId="012345678910", AuthorizedAwsRegion="us-west-2", @@ -615,7 +615,7 @@ def test_put_aggregation_authorization(): assert ce.exception.response["Error"]["Code"] == "InvalidInput" # Invalid characters in the tag key: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_aggregation_authorization( AuthorizedAccountId="012345678910", AuthorizedAwsRegion="us-west-2", @@ -708,7 +708,7 @@ def test_describe_aggregation_authorizations(): ] == ["{}".format(str(x) * 12) for x in range(8, 10)] # Test with an invalid filter: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_aggregation_authorizations(NextToken="WRONG") assert ( "The nextToken provided is invalid" == ce.exception.response["Error"]["Message"] @@ -751,7 +751,7 @@ def test_delete_configuration_aggregator(): client.delete_configuration_aggregator(ConfigurationAggregatorName="testing") # And again to confirm that it's deleted: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.delete_configuration_aggregator(ConfigurationAggregatorName="testing") assert ( "The configuration aggregator does not exist." @@ -796,7 +796,7 @@ def test_describe_configurations(): ) # Specify an incorrect name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_recorders(ConfigurationRecorderNames=["wrong"]) assert ( ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" @@ -804,7 +804,7 @@ def test_describe_configurations(): assert "wrong" in ce.exception.response["Error"]["Message"] # And with both a good and wrong name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_recorders( ConfigurationRecorderNames=["testrecorder", "wrong"] ) @@ -819,7 +819,7 @@ def test_delivery_channels(): client = boto3.client("config", region_name="us-west-2") # Try without a config recorder: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={}) assert ( ce.exception.response["Error"]["Code"] @@ -845,7 +845,7 @@ def test_delivery_channels(): ) # Try without a name supplied: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={}) assert ( ce.exception.response["Error"]["Code"] == "InvalidDeliveryChannelNameException" @@ -853,7 +853,7 @@ def test_delivery_channels(): assert "is not valid, blank string." in ce.exception.response["Error"]["Message"] # Try with a really long name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={"name": "a" * 257}) assert ce.exception.response["Error"]["Code"] == "ValidationException" assert ( @@ -862,7 +862,7 @@ def test_delivery_channels(): ) # Without specifying a bucket name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel(DeliveryChannel={"name": "testchannel"}) assert ce.exception.response["Error"]["Code"] == "NoSuchBucketException" assert ( @@ -870,7 +870,7 @@ def test_delivery_channels(): == "Cannot find a S3 bucket with an empty bucket name." ) - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel( DeliveryChannel={"name": "testchannel", "s3BucketName": ""} ) @@ -881,7 +881,7 @@ def test_delivery_channels(): ) # With an empty string for the S3 key prefix: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel( DeliveryChannel={ "name": "testchannel", @@ -893,7 +893,7 @@ def test_delivery_channels(): assert "empty s3 key prefix." in ce.exception.response["Error"]["Message"] # With an empty string for the SNS ARN: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel( DeliveryChannel={ "name": "testchannel", @@ -905,7 +905,7 @@ def test_delivery_channels(): assert "The sns topic arn" in ce.exception.response["Error"]["Message"] # With an invalid delivery frequency: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel( DeliveryChannel={ "name": "testchannel", @@ -950,7 +950,7 @@ def test_delivery_channels(): ) # Can only have 1: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_delivery_channel( DeliveryChannel={"name": "testchannel2", "s3BucketName": "somebucket"} ) @@ -1015,13 +1015,13 @@ def test_describe_delivery_channels(): ) # Specify an incorrect name: - with assert_raises(ClientError) as ce: + 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"] # And with both a good and wrong name: - with assert_raises(ClientError) as ce: + 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"] @@ -1032,7 +1032,7 @@ def test_start_configuration_recorder(): client = boto3.client("config", region_name="us-west-2") # Without a config recorder: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.start_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" @@ -1052,7 +1052,7 @@ def test_start_configuration_recorder(): ) # Without a delivery channel: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.start_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( ce.exception.response["Error"]["Code"] == "NoAvailableDeliveryChannelException" @@ -1090,7 +1090,7 @@ def test_stop_configuration_recorder(): client = boto3.client("config", region_name="us-west-2") # Without a config recorder: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.stop_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" @@ -1180,7 +1180,7 @@ def test_describe_configuration_recorder_status(): assert not result[0]["recording"] # Invalid name: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.describe_configuration_recorder_status( ConfigurationRecorderNames=["testrecorder", "wrong"] ) @@ -1211,7 +1211,7 @@ def test_delete_configuration_recorder(): client.delete_configuration_recorder(ConfigurationRecorderName="testrecorder") # Try again -- it should be deleted: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.delete_configuration_recorder(ConfigurationRecorderName="testrecorder") assert ( ce.exception.response["Error"]["Code"] == "NoSuchConfigurationRecorderException" @@ -1240,7 +1240,7 @@ def test_delete_delivery_channel(): client.start_configuration_recorder(ConfigurationRecorderName="testrecorder") # With the recorder enabled: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.delete_delivery_channel(DeliveryChannelName="testchannel") assert ( ce.exception.response["Error"]["Code"] @@ -1258,7 +1258,7 @@ def test_delete_delivery_channel(): client.delete_delivery_channel(DeliveryChannelName="testchannel") # Verify: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.delete_delivery_channel(DeliveryChannelName="testchannel") assert ce.exception.response["Error"]["Code"] == "NoSuchDeliveryChannelException" @@ -1341,12 +1341,12 @@ def test_list_discovered_resource(): )["resourceIdentifiers"] # Test with an invalid page num > 100: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.list_discovered_resources(resourceType="AWS::S3::Bucket", limit=101) assert "101" in ce.exception.response["Error"]["Message"] # Test by supplying both resourceName and also resourceIds: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.list_discovered_resources( resourceType="AWS::S3::Bucket", resourceName="whats", @@ -1359,7 +1359,7 @@ def test_list_discovered_resource(): # More than 20 resourceIds: resource_ids = ["{}".format(x) for x in range(0, 21)] - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.list_discovered_resources( resourceType="AWS::S3::Bucket", resourceIds=resource_ids ) @@ -1378,7 +1378,7 @@ def test_list_aggregate_discovered_resource(): client = boto3.client("config", region_name="us-west-2") # Without an aggregator: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.list_aggregate_discovered_resources( ConfigurationAggregatorName="lolno", ResourceType="AWS::S3::Bucket" ) @@ -1504,7 +1504,7 @@ def test_list_aggregate_discovered_resource(): )["ResourceIdentifiers"] # Test with an invalid page num > 100: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.list_aggregate_discovered_resources( ConfigurationAggregatorName="testing", ResourceType="AWS::S3::Bucket", @@ -1522,7 +1522,7 @@ def test_get_resource_config_history(): client = boto3.client("config", region_name="us-west-2") # With an invalid resource type: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_resource_config_history( resourceType="NOT::A::RESOURCE", resourceId="notcreatedyet" ) @@ -1533,7 +1533,7 @@ def test_get_resource_config_history(): } # With nothing created yet: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_resource_config_history( resourceType="AWS::S3::Bucket", resourceId="notcreatedyet" ) @@ -1565,7 +1565,7 @@ def test_get_resource_config_history(): Bucket="eu-bucket", CreateBucketConfiguration={"LocationConstraint": "eu-west-1"}, ) - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_resource_config_history( resourceType="AWS::S3::Bucket", resourceId="eu-bucket" ) @@ -1581,7 +1581,7 @@ def test_batch_get_resource_config(): client = boto3.client("config", region_name="us-west-2") # With more than 100 resourceKeys: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.batch_get_resource_config( resourceKeys=[ {"resourceType": "AWS::S3::Bucket", "resourceId": "someBucket"} @@ -1653,7 +1653,7 @@ def test_batch_get_aggregate_resource_config(): "ResourceType": "NOT::A::RESOURCE", "ResourceId": "nope", } - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.batch_get_aggregate_resource_config( ConfigurationAggregatorName="lolno", ResourceIdentifiers=[bad_ri] ) @@ -1673,7 +1673,7 @@ def test_batch_get_aggregate_resource_config(): ) # With more than 100 items: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.batch_get_aggregate_resource_config( ConfigurationAggregatorName="testing", ResourceIdentifiers=[bad_ri] * 101 ) @@ -1814,7 +1814,7 @@ def test_put_evaluations(): client = boto3.client("config", region_name="us-west-2") # Try without Evaluations supplied: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_evaluations(Evaluations=[], ResultToken="test", TestMode=True) assert ce.exception.response["Error"]["Code"] == "InvalidParameterValueException" assert ( @@ -1823,7 +1823,7 @@ def test_put_evaluations(): ) # Try without a ResultToken supplied: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_evaluations( Evaluations=[ { @@ -1842,7 +1842,7 @@ def test_put_evaluations(): raise SkipTest("Does not work in server mode due to error in Workzeug") else: # Try without TestMode supplied: - with assert_raises(NotImplementedError): + with pytest.raises(NotImplementedError): client.put_evaluations( Evaluations=[ { @@ -1913,7 +1913,7 @@ def test_put_organization_conformance_pack_errors(): client = boto3.client("config", region_name="us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.put_organization_conformance_pack( DeliveryS3Bucket="awsconfigconforms-test-bucket", OrganizationConformancePackName="test-pack", @@ -1927,7 +1927,7 @@ def test_put_organization_conformance_pack_errors(): ex.response["Error"]["Message"].should.equal("Template body is invalid") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.put_organization_conformance_pack( DeliveryS3Bucket="awsconfigconforms-test-bucket", OrganizationConformancePackName="test-pack", @@ -1979,7 +1979,7 @@ def test_describe_organization_conformance_packs_errors(): client = boto3.client("config", region_name="us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.describe_organization_conformance_packs( OrganizationConformancePackNames=["not-existing"] ) @@ -2055,7 +2055,7 @@ def test_describe_organization_conformance_pack_statuses_errors(): client = boto3.client("config", region_name="us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.describe_organization_conformance_pack_statuses( OrganizationConformancePackNames=["not-existing"] ) @@ -2127,7 +2127,7 @@ def test_get_organization_conformance_pack_detailed_status_errors(): client = boto3.client("config", region_name="us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_organization_conformance_pack_detailed_status( OrganizationConformancePackName="not-existing" ) @@ -2171,7 +2171,7 @@ def test_delete_organization_conformance_pack_errors(): client = boto3.client("config", region_name="us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_organization_conformance_pack( OrganizationConformancePackName="not-existing" ) diff --git a/tests/test_core/__init__.py b/tests/test_core/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_core/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_core/test_auth.py b/tests/test_core/test_auth.py index b391d82c8..67c3b67a2 100644 --- a/tests/test_core/test_auth.py +++ b/tests/test_core/test_auth.py @@ -4,9 +4,7 @@ import boto3 import sure # noqa from botocore.exceptions import ClientError -# Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest from moto import mock_iam, mock_ec2, mock_s3, mock_sts, mock_elbv2, mock_rds2 from moto.core import set_initial_no_auth_action_count @@ -179,7 +177,7 @@ def test_invalid_client_token_id(): aws_access_key_id="invalid", aws_secret_access_key="invalid", ) - with assert_raises(ClientError) as ex: + 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) @@ -197,7 +195,7 @@ def test_auth_failure(): aws_access_key_id="invalid", aws_secret_access_key="invalid", ) - with assert_raises(ClientError) as ex: + 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) @@ -216,7 +214,7 @@ def test_signature_does_not_match(): aws_access_key_id=access_key["AccessKeyId"], aws_secret_access_key="invalid", ) - with assert_raises(ClientError) as ex: + 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) @@ -235,7 +233,7 @@ def test_auth_failure_with_valid_access_key_id(): aws_access_key_id=access_key["AccessKeyId"], aws_secret_access_key="invalid", ) - with assert_raises(ClientError) as ex: + 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) @@ -255,7 +253,7 @@ def test_access_denied_with_no_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) @@ -321,7 +319,7 @@ def test_access_denied_for_run_instances(): 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.run_instances(MaxCount=1, MinCount=1) ex.exception.response["Error"]["Code"].should.equal("AccessDenied") ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) @@ -352,7 +350,7 @@ def test_access_denied_with_denying_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.create_vpc(CidrBlock="10.0.0.0/16") ex.exception.response["Error"]["Code"].should.equal("AccessDenied") ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) @@ -452,7 +450,7 @@ def test_s3_access_denied_with_denying_attached_group_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.list_buckets() ex.exception.response["Error"]["Code"].should.equal("AccessDenied") ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) @@ -486,7 +484,7 @@ def test_s3_access_denied_with_denying_inline_group_policy(): aws_secret_access_key=access_key["SecretAccessKey"], ) client.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as ex: + 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) @@ -532,7 +530,7 @@ def test_access_denied_with_many_irrelevant_policies(): 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.create_key_pair(KeyName="TestKey") ex.exception.response["Error"]["Code"].should.equal("AccessDenied") ex.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(403) @@ -631,7 +629,7 @@ def test_access_denied_with_temporary_credentials(): aws_secret_access_key=credentials["SecretAccessKey"], aws_session_token=credentials["SessionToken"], ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_db_instance( DBInstanceIdentifier="test-db-instance", DBInstanceClass="db.t3", @@ -678,7 +676,7 @@ def test_s3_invalid_access_key_id(): aws_access_key_id="invalid", aws_secret_access_key="invalid", ) - with assert_raises(ClientError) as ex: + 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) @@ -700,7 +698,7 @@ def test_s3_signature_does_not_match(): aws_secret_access_key="invalid", ) client.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as ex: + 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) @@ -736,7 +734,7 @@ def test_s3_access_denied_not_action(): aws_secret_access_key=access_key["SecretAccessKey"], ) client.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as ex: + 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) @@ -776,7 +774,7 @@ def test_s3_invalid_token_with_temporary_credentials(): aws_session_token="invalid", ) client.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as ex: + 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) diff --git a/tests/test_core/test_decorator_calls.py b/tests/test_core/test_decorator_calls.py index 408ca6819..5e04f075c 100644 --- a/tests/test_core/test_decorator_calls.py +++ b/tests/test_core/test_decorator_calls.py @@ -4,8 +4,7 @@ from boto.exception import EC2ResponseError import sure # noqa import unittest -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest from moto import mock_ec2_deprecated, mock_s3_deprecated @@ -27,21 +26,21 @@ def test_basic_decorator(): def test_context_manager(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError): + with pytest.raises(EC2ResponseError): conn.get_all_instances() with mock_ec2_deprecated(): conn = boto.connect_ec2("the_key", "the_secret") list(conn.get_all_instances()).should.equal([]) - with assert_raises(EC2ResponseError): + with pytest.raises(EC2ResponseError): conn = boto.connect_ec2("the_key", "the_secret") conn.get_all_instances() def test_decorator_start_and_stop(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError): + with pytest.raises(EC2ResponseError): conn.get_all_instances() mock = mock_ec2_deprecated() @@ -50,7 +49,7 @@ def test_decorator_start_and_stop(): list(conn.get_all_instances()).should.equal([]) mock.stop() - with assert_raises(EC2ResponseError): + with pytest.raises(EC2ResponseError): conn.get_all_instances() diff --git a/tests/test_core/test_instance_metadata.py b/tests/test_core/test_instance_metadata.py index d30138d5d..9870f0df5 100644 --- a/tests/test_core/test_instance_metadata.py +++ b/tests/test_core/test_instance_metadata.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals import sure # noqa -from nose.tools import assert_raises +import pytest import requests from moto import mock_ec2, settings diff --git a/tests/test_core/test_moto_api.py b/tests/test_core/test_moto_api.py index 6482d903e..648510475 100644 --- a/tests/test_core/test_moto_api.py +++ b/tests/test_core/test_moto_api.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals import sure # noqa -from nose.tools import assert_raises +import pytest import requests import boto3 diff --git a/tests/test_datapipeline/__init__.py b/tests/test_datapipeline/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_datapipeline/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_datasync/test_datasync.py b/tests/test_datasync/test_datasync.py index e3ea87675..d8d919f13 100644 --- a/tests/test_datasync/test_datasync.py +++ b/tests/test_datasync/test_datasync.py @@ -4,11 +4,11 @@ import boto import boto3 from botocore.exceptions import ClientError from moto import mock_datasync -from nose.tools import assert_raises +import pytest def create_locations(client, create_smb=False, create_s3=False): - """ + """ Convenience function for creating locations. Locations must exist before tasks can be created. """ @@ -101,7 +101,7 @@ def test_describe_location_wrong(): Password="", AgentArns=agent_arns, ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_location_s3(LocationArn=response["LocationArn"]) @@ -159,11 +159,11 @@ def test_create_task_fail(): """ Test that Locations must exist before a Task can be created """ client = boto3.client("datasync", region_name="us-east-1") locations = create_locations(client, create_smb=True, create_s3=True) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.create_task( SourceLocationArn="1", DestinationLocationArn=locations["s3_arn"] ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.create_task( SourceLocationArn=locations["smb_arn"], DestinationLocationArn="2" ) @@ -220,7 +220,7 @@ def test_describe_task(): def test_describe_task_not_exist(): client = boto3.client("datasync", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.describe_task(TaskArn="abc") @@ -328,7 +328,7 @@ def test_start_task_execution_twice(): assert "TaskExecutionArn" in response task_execution_arn = response["TaskExecutionArn"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.start_task_execution(TaskArn=task_arn) @@ -392,7 +392,7 @@ def test_describe_task_execution(): def test_describe_task_execution_not_exist(): client = boto3.client("datasync", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.describe_task_execution(TaskExecutionArn="abc") diff --git a/tests/test_dynamodb/__init__.py b/tests/test_dynamodb/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_dynamodb/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_dynamodb/test_dynamodb.py b/tests/test_dynamodb/test_dynamodb.py index 931e57e06..3e1092025 100644 --- a/tests/test_dynamodb/test_dynamodb.py +++ b/tests/test_dynamodb/test_dynamodb.py @@ -4,8 +4,7 @@ import boto import boto.dynamodb import sure # noqa import requests -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest from moto import mock_dynamodb, mock_dynamodb_deprecated from moto.dynamodb import dynamodb_backend @@ -38,7 +37,7 @@ def test_list_tables_layer_1(): @mock_dynamodb_deprecated def test_describe_missing_table(): conn = boto.connect_dynamodb("the_key", "the_secret") - with assert_raises(DynamoDBResponseError): + with pytest.raises(DynamoDBResponseError): conn.describe_table("messages") diff --git a/tests/test_dynamodb2/__init__.py b/tests/test_dynamodb2/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_dynamodb2/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_dynamodb2/test_dynamodb.py b/tests/test_dynamodb2/test_dynamodb.py index 41baddc79..6704bbcc7 100644 --- a/tests/test_dynamodb2/test_dynamodb.py +++ b/tests/test_dynamodb2/test_dynamodb.py @@ -17,7 +17,7 @@ from tests.helpers import requires_boto_gte import moto.dynamodb2.comparisons import moto.dynamodb2.models -from nose.tools import assert_raises +import pytest try: import boto.dynamodb2 @@ -72,7 +72,7 @@ def test_describe_missing_table(): conn = boto.dynamodb2.connect_to_region( "us-west-2", aws_access_key_id="ak", aws_secret_access_key="sk" ) - with assert_raises(JSONResponseError): + with pytest.raises(JSONResponseError): conn.describe_table("messages") @@ -201,7 +201,7 @@ def test_item_add_empty_string_exception(): ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.put_item( TableName=name, Item={ @@ -248,7 +248,7 @@ def test_update_item_with_empty_string_exception(): }, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.update_item( TableName=name, Key={"forum_name": {"S": "LOLCat Forum"}}, @@ -1354,7 +1354,7 @@ def test_put_empty_item(): ) table = dynamodb.Table("test") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: table.put_item(Item={}) ex.exception.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key structure_id in the item" @@ -1373,7 +1373,7 @@ def test_put_item_nonexisting_hash_key(): ) table = dynamodb.Table("test") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: table.put_item(Item={"a_terribly_misguided_id_attribute": "abcdef"}) ex.exception.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key structure_id in the item" @@ -1398,7 +1398,7 @@ def test_put_item_nonexisting_range_key(): ) table = dynamodb.Table("test") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: table.put_item(Item={"structure_id": "abcdef"}) ex.exception.response["Error"]["Message"].should.equal( "One or more parameter values were invalid: Missing the key added_at in the item" @@ -1980,7 +1980,7 @@ def test_delete_item(): assert response["Count"] == 2 # Test ReturnValues validation - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: table.delete_item( Key={"client": "client1", "app": "app1"}, ReturnValues="ALL_NEW" ) @@ -2085,7 +2085,7 @@ def test_describe_continuous_backups_errors(): client = boto3.client("dynamodb", region_name="us-east-1") # when - with assert_raises(Exception) as e: + with pytest.raises(Exception) as e: client.describe_continuous_backups(TableName="not-existing-table") # then @@ -2171,7 +2171,7 @@ def test_update_continuous_backups_errors(): client = boto3.client("dynamodb", region_name="us-east-1") # when - with assert_raises(Exception) as e: + with pytest.raises(Exception) as e: client.update_continuous_backups( TableName="not-existing-table", PointInTimeRecoverySpecification={"PointInTimeRecoveryEnabled": True}, @@ -2291,7 +2291,7 @@ def test_update_item_on_map(): ExpressionAttributeValues={":tb": "new_value"}, ) # Running this against AWS DDB gives an exception so make sure it also fails.: - with assert_raises(client.exceptions.ClientError): + with pytest.raises(client.exceptions.ClientError): # botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem # operation: The document path provided in the update expression is invalid for update table.update_item( @@ -2321,7 +2321,7 @@ def test_update_item_on_map(): ) # Test nested value for a nonexistent attribute throws a ClientError. - with assert_raises(client.exceptions.ClientError): + with pytest.raises(client.exceptions.ClientError): table.update_item( Key={"forum_name": "the-key", "subject": "123"}, UpdateExpression="SET nonexistent.#nested = :tb", @@ -2409,7 +2409,7 @@ def test_update_return_attributes(): r = update("col1", "val5", "NONE") assert r["Attributes"] == {} - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: r = update("col1", "val6", "WRONG") @@ -2438,7 +2438,7 @@ def test_put_return_attributes(): ) assert r["Attributes"] == {"id": {"S": "foo"}, "col1": {"S": "val1"}} - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.put_item( TableName="moto-test", Item={"id": {"S": "foo"}, "col1": {"S": "val3"}}, @@ -2675,7 +2675,7 @@ def test_condition_expressions(): }, ) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.put_item( TableName="test1", Item={ @@ -2691,7 +2691,7 @@ def test_condition_expressions(): }, ) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.put_item( TableName="test1", Item={ @@ -2707,7 +2707,7 @@ def test_condition_expressions(): }, ) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.put_item( TableName="test1", Item={ @@ -2735,7 +2735,7 @@ def test_condition_expressions(): ExpressionAttributeValues={":match": {"S": "match"}}, ) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.update_item( TableName="test1", Key={"client": {"S": "client1"}, "app": {"S": "app1"}}, @@ -2745,7 +2745,7 @@ def test_condition_expressions(): ExpressionAttributeNames={"#existing": "existing", "#match": "match"}, ) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.delete_item( TableName="test1", Key={"client": {"S": "client1"}, "app": {"S": "app1"}}, @@ -2830,7 +2830,7 @@ def test_condition_expression__attr_doesnt_exist(): update_if_attr_doesnt_exist() # Second time should fail - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): update_if_attr_doesnt_exist() @@ -2870,7 +2870,7 @@ def test_condition_expression__and_order(): # ensure that the RHS of the AND expression is not evaluated if the LHS # returns true (as it would result an error) - with assert_raises(client.exceptions.ConditionalCheckFailedException): + with pytest.raises(client.exceptions.ConditionalCheckFailedException): client.update_item( TableName="test", Key={"forum_name": {"S": "the-key"}}, @@ -2966,7 +2966,7 @@ def test_scan_by_non_exists_index(): ], ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.scan(TableName="test", IndexName="non_exists_index") ex.exception.response["Error"]["Code"].should.equal("ValidationException") @@ -3001,7 +3001,7 @@ def test_query_by_non_exists_index(): ], ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.query( TableName="test", IndexName="non_exists_index", @@ -3041,7 +3041,7 @@ def test_batch_items_returns_all(): @mock_dynamodb2 def test_batch_items_throws_exception_when_requesting_100_items_for_single_table(): dynamodb = _create_user_table() - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.batch_get_item( RequestItems={ "users": { @@ -3063,7 +3063,7 @@ def test_batch_items_throws_exception_when_requesting_100_items_for_single_table @mock_dynamodb2 def test_batch_items_throws_exception_when_requesting_100_items_across_all_tables(): dynamodb = _create_user_table() - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.batch_get_item( RequestItems={ "users": { @@ -3160,7 +3160,7 @@ def test_batch_items_with_basic_projection_expression_and_attr_expression_names( @mock_dynamodb2 def test_batch_items_should_throw_exception_for_duplicate_request(): client = _create_user_table() - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.batch_get_item( RequestItems={ "users": { @@ -3186,7 +3186,7 @@ def test_index_with_unknown_attributes_should_fail(): "Some index key attributes are not defined in AttributeDefinitions." ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.create_table( AttributeDefinitions=[ {"AttributeName": "customer_nr", "AttributeType": "S"}, @@ -3366,7 +3366,7 @@ def test_update_list_index__set_index_of_a_string(): client.put_item( TableName=table_name, Item={"id": {"S": "foo2"}, "itemstr": {"S": "somestring"}} ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.update_item( TableName=table_name, Key={"id": {"S": "foo2"}}, @@ -3615,7 +3615,7 @@ def test_item_size_is_under_400KB(): def assert_failure_due_to_item_size(func, **kwargs): - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: func(**kwargs) ex.exception.response["Error"]["Code"].should.equal("ValidationException") ex.exception.response["Error"]["Message"].should.equal( @@ -3624,7 +3624,7 @@ def assert_failure_due_to_item_size(func, **kwargs): def assert_failure_due_to_item_size_to_update(func, **kwargs): - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: func(**kwargs) ex.exception.response["Error"]["Code"].should.equal("ValidationException") ex.exception.response["Error"]["Message"].should.equal( @@ -3654,7 +3654,7 @@ def test_hash_key_cannot_use_begins_with_operations(): batch.put_item(Item=item) table = dynamodb.Table("test-table") - with assert_raises(ClientError) as ex: + 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( @@ -4047,7 +4047,7 @@ def test_update_catches_invalid_list_append_operation(): ) # Update item using invalid list_append expression - with assert_raises(ParamValidationError) as ex: + with pytest.raises(ParamValidationError) as ex: client.update_item( TableName="TestTable", Key={"SHA256": {"S": "sha-of-file"}}, @@ -4166,7 +4166,7 @@ def test_query_catches_when_no_filters(): ) table = dynamo.Table("origin-rbu-dev") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: table.query(TableName="original-rbu-dev") ex.exception.response["Error"]["Code"].should.equal("ValidationException") @@ -4197,7 +4197,7 @@ def test_invalid_transact_get_items(): client = boto3.client("dynamodb", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.transact_get_items( TransactItems=[ {"Get": {"Key": {"id": {"S": "1"}}, "TableName": "test1"}} @@ -4211,7 +4211,7 @@ def test_invalid_transact_get_items(): re.I, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.transact_get_items( TransactItems=[ {"Get": {"Key": {"id": {"S": "1"},}, "TableName": "test1"}}, @@ -4491,7 +4491,7 @@ def test_transact_write_items_put_conditional_expressions(): TableName="test-table", Item={"id": {"S": "foo2"},}, ) # Put multiple items - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.transact_write_items( TransactItems=[ { @@ -4581,7 +4581,7 @@ def test_transact_write_items_conditioncheck_fails(): ) # Try to put an email address, but verify whether it exists # ConditionCheck should fail - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.transact_write_items( TransactItems=[ { @@ -4687,7 +4687,7 @@ def test_transact_write_items_delete_with_failed_condition_expression(): ) # Try to delete an item that does not have an email address # ConditionCheck should fail - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.transact_write_items( TransactItems=[ { @@ -4758,7 +4758,7 @@ def test_transact_write_items_update_with_failed_condition_expression(): ) # Try to update an item that does not have an email address # ConditionCheck should fail - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.transact_write_items( TransactItems=[ { @@ -5318,7 +5318,7 @@ def test_transact_write_items_fails_with_transaction_canceled_exception(): # Insert one item dynamodb.put_item(TableName="test-table", Item={"id": {"S": "foo"}}) # Update two items, the one that exists and another that doesn't - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: dynamodb.transact_write_items( TransactItems=[ { 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 12e75a73e..e50cd45c1 100644 --- a/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py +++ b/tests/test_dynamodb2/test_dynamodb_table_with_range_key.py @@ -8,7 +8,7 @@ from boto3.dynamodb.conditions import Key from botocore.exceptions import ClientError import sure # noqa from freezegun import freeze_time -from nose.tools import assert_raises +import pytest from moto import mock_dynamodb2, mock_dynamodb2_deprecated from boto.exception import JSONResponseError @@ -1353,7 +1353,7 @@ def test_update_item_with_expression(): def assert_failure_due_to_key_not_in_schema(func, **kwargs): - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: func(**kwargs) ex.exception.response["Error"]["Code"].should.equal("ValidationException") ex.exception.response["Error"]["Message"].should.equal( diff --git a/tests/test_dynamodbstreams/__init__.py b/tests/test_dynamodbstreams/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_dynamodbstreams/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_dynamodbstreams/test_dynamodbstreams.py b/tests/test_dynamodbstreams/test_dynamodbstreams.py index 6f66e304d..70efc5289 100644 --- a/tests/test_dynamodbstreams/test_dynamodbstreams.py +++ b/tests/test_dynamodbstreams/test_dynamodbstreams.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals, print_function -from nose.tools import assert_raises +import pytest import boto3 from moto import mock_dynamodb2, mock_dynamodbstreams @@ -224,7 +224,7 @@ class TestEdges: assert "LatestStreamLabel" in resp["TableDescription"] # now try to enable it again - with assert_raises(conn.exceptions.ResourceInUseException): + with pytest.raises(conn.exceptions.ResourceInUseException): resp = conn.update_table( TableName="test-streams", StreamSpecification={ diff --git a/tests/test_ec2/test_amis.py b/tests/test_ec2/test_amis.py index 5b26acf6f..b23eae4ab 100644 --- a/tests/test_ec2/test_amis.py +++ b/tests/test_ec2/test_amis.py @@ -7,7 +7,7 @@ from boto.exception import EC2ResponseError from botocore.exceptions import ClientError # Ensure 'assert_raises' context manager support for Python 2.6 -from nose.tools import assert_raises +import pytest import sure # noqa from moto import mock_ec2_deprecated, mock_ec2 @@ -27,7 +27,7 @@ def test_ami_create_and_delete(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: image_id = conn.create_image( instance.id, "test-ami", "this is a test ami", dry_run=True ) @@ -76,7 +76,7 @@ def test_ami_create_and_delete(): root_mapping.should_not.be.none # Deregister - with assert_raises(EC2ResponseError) as ex: + 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) @@ -87,7 +87,7 @@ def test_ami_create_and_delete(): success = conn.deregister_image(image_id) success.should.be.true - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.deregister_image(image_id) cm.exception.code.should.equal("InvalidAMIID.NotFound") cm.exception.status.should.equal(400) @@ -112,7 +112,7 @@ def test_ami_copy(): # Boto returns a 'CopyImage' object with an image_id attribute here. Use # the image_id to fetch the full info. - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: copy_image_ref = conn.copy_image( source_image.region.name, source_image.id, @@ -152,7 +152,7 @@ def test_ami_copy(): ) # Copy from non-existent source ID. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.copy_image( source_image.region.name, "ami-abcd1234", @@ -164,7 +164,7 @@ def test_ami_copy(): cm.exception.request_id.should_not.be.none # Copy from non-existent source region. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: invalid_region = ( "us-east-1" if (source_image.region.name != "us-east-1") else "us-west-1" ) @@ -208,7 +208,7 @@ def test_ami_tagging(): conn.create_image(instance.id, "test-ami", "this is a test ami") image = conn.get_all_images()[0] - with assert_raises(EC2ResponseError) as ex: + 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) @@ -233,7 +233,7 @@ def test_ami_create_from_missing_instance(): conn = boto.connect_ec2("the_key", "the_secret") args = ["i-abcdefg", "test-ami", "this is a test ami"] - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.create_image(*args) cm.exception.code.should.equal("InvalidInstanceID.NotFound") cm.exception.status.should.equal(400) @@ -353,7 +353,7 @@ def test_ami_filtering_via_tag(): def test_getting_missing_ami(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.get_image("ami-missing") cm.exception.code.should.equal("InvalidAMIID.NotFound") cm.exception.status.should.equal(400) @@ -364,7 +364,7 @@ def test_getting_missing_ami(): def test_getting_malformed_ami(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.get_image("foo-missing") cm.exception.code.should.equal("InvalidAMIID.Malformed") cm.exception.status.should.equal(400) @@ -399,7 +399,7 @@ def test_ami_attribute_group_permissions(): } # Add 'all' group and confirm - with assert_raises(EC2ResponseError) as ex: + 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) @@ -678,7 +678,7 @@ def test_ami_attribute_error_cases(): image = conn.get_image(image_id) # Error: Add with group != 'all' - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( image.id, attribute="launchPermission", operation="add", groups="everyone" ) @@ -687,7 +687,7 @@ def test_ami_attribute_error_cases(): cm.exception.request_id.should_not.be.none # Error: Add with user ID that isn't an integer. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( image.id, attribute="launchPermission", @@ -699,7 +699,7 @@ def test_ami_attribute_error_cases(): cm.exception.request_id.should_not.be.none # Error: Add with user ID that is > length 12. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( image.id, attribute="launchPermission", @@ -711,7 +711,7 @@ def test_ami_attribute_error_cases(): cm.exception.request_id.should_not.be.none # Error: Add with user ID that is < length 12. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( image.id, attribute="launchPermission", @@ -724,7 +724,7 @@ def test_ami_attribute_error_cases(): # Error: Add with one invalid user ID among other valid IDs, ensure no # partial changes. - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( image.id, attribute="launchPermission", @@ -739,7 +739,7 @@ def test_ami_attribute_error_cases(): attributes.attrs.should.have.length_of(0) # Error: Add with invalid image ID - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( "ami-abcd1234", attribute="launchPermission", operation="add", groups="all" ) @@ -748,7 +748,7 @@ def test_ami_attribute_error_cases(): cm.exception.request_id.should_not.be.none # Error: Remove with invalid image ID - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_image_attribute( "ami-abcd1234", attribute="launchPermission", @@ -765,11 +765,11 @@ def test_ami_describe_non_existent(): ec2 = boto3.resource("ec2", region_name="us-west-1") # Valid pattern but non-existent id img = ec2.Image("ami-abcd1234") - with assert_raises(ClientError): + with pytest.raises(ClientError): img.load() # Invalid ami pattern img = ec2.Image("not_an_ami_id") - with assert_raises(ClientError): + with pytest.raises(ClientError): img.load() diff --git a/tests/test_ec2/test_customer_gateways.py b/tests/test_ec2/test_customer_gateways.py index a676a2b5d..8d94a9a94 100644 --- a/tests/test_ec2/test_customer_gateways.py +++ b/tests/test_ec2/test_customer_gateways.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals import boto import sure # noqa -from nose.tools import assert_raises -from nose.tools import assert_false +import pytest from boto.exception import EC2ResponseError from moto import mock_ec2_deprecated @@ -45,5 +44,5 @@ def test_delete_customer_gateways(): @mock_ec2_deprecated def test_delete_customer_gateways_bad_id(): conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.delete_customer_gateway("cgw-0123abcd") diff --git a/tests/test_ec2/test_dhcp_options.py b/tests/test_ec2/test_dhcp_options.py index 4aaceaa07..c04faa85d 100644 --- a/tests/test_ec2/test_dhcp_options.py +++ b/tests/test_ec2/test_dhcp_options.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto3 import boto @@ -33,7 +32,7 @@ def test_dhcp_options_associate_invalid_dhcp_id(): conn = boto.connect_vpc("the_key", "the_secret") vpc = conn.create_vpc("10.0.0.0/16") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -46,7 +45,7 @@ def test_dhcp_options_associate_invalid_vpc_id(): conn = boto.connect_vpc("the_key", "the_secret") dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -64,7 +63,7 @@ def test_dhcp_options_delete_with_vpc(): rval = conn.associate_dhcp_options(dhcp_options_id, vpc.id) rval.should.be.equal(True) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -72,7 +71,7 @@ def test_dhcp_options_delete_with_vpc(): vpc.delete() - with assert_raises(EC2ResponseError) as cm: + 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) @@ -100,13 +99,13 @@ def test_create_dhcp_options_invalid_options(): conn = boto.connect_vpc("the_key", "the_secret") servers = ["f", "f", "f", "f", "f"] - with assert_raises(EC2ResponseError) as cm: + 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 - with assert_raises(EC2ResponseError) as cm: + 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) @@ -131,7 +130,7 @@ def test_describe_dhcp_options_invalid_id(): """get error on invalid dhcp_option_id lookup""" conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -149,7 +148,7 @@ def test_delete_dhcp_options(): conn.delete_dhcp_options(dhcp_option.id) # .should.be.equal(True) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -162,7 +161,7 @@ def test_delete_dhcp_options_invalid_id(): conn.create_dhcp_options() - with assert_raises(EC2ResponseError) as cm: + 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) @@ -175,7 +174,7 @@ def test_delete_dhcp_options_malformed_id(): conn.create_dhcp_options() - with assert_raises(EC2ResponseError) as cm: + 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) diff --git a/tests/test_ec2/test_elastic_block_store.py b/tests/test_ec2/test_elastic_block_store.py index 2a5dfbf2a..846d1bacc 100644 --- a/tests/test_ec2/test_elastic_block_store.py +++ b/tests/test_ec2/test_elastic_block_store.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest from moto.ec2 import ec2_backends import boto @@ -31,7 +30,7 @@ def test_create_and_delete_volume(): volume = current_volume[0] - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: volume.delete(dry_run=True) ex.exception.error_code.should.equal("DryRunOperation") ex.exception.status.should.equal(400) @@ -46,7 +45,7 @@ def test_create_and_delete_volume(): my_volume.should.have.length_of(0) # Deleting something that was already deleted should throw an error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: volume.delete() cm.exception.code.should.equal("InvalidVolume.NotFound") cm.exception.status.should.equal(400) @@ -95,7 +94,7 @@ def test_delete_attached_volume(): @mock_ec2_deprecated def test_create_encrypted_volume_dryrun(): conn = boto.ec2.connect_to_region("us-east-1") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -109,7 +108,7 @@ def test_create_encrypted_volume(): conn = boto.ec2.connect_to_region("us-east-1") volume = conn.create_volume(80, "us-east-1a", encrypted=True) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -134,7 +133,7 @@ def test_filter_volume_by_id(): vol2 = conn.get_all_volumes(volume_ids=[volume1.id, volume2.id]) vol2.should.have.length_of(2) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -259,7 +258,7 @@ def test_volume_attach_and_detach(): volume.update() volume.volume_state().should.equal("available") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -275,7 +274,7 @@ def test_volume_attach_and_detach(): volume.attach_data.instance_id.should.equal(instance.id) - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: volume.detach(dry_run=True) ex.exception.error_code.should.equal("DryRunOperation") ex.exception.status.should.equal(400) @@ -288,19 +287,19 @@ def test_volume_attach_and_detach(): volume.update() volume.volume_state().should.equal("available") - with assert_raises(EC2ResponseError) as cm1: + 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 - with assert_raises(EC2ResponseError) as cm2: + 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 - with assert_raises(EC2ResponseError) as cm3: + 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) @@ -312,7 +311,7 @@ def test_create_snapshot(): conn = boto.ec2.connect_to_region("us-east-1") volume = conn.create_volume(80, "us-east-1a") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -340,7 +339,7 @@ def test_create_snapshot(): conn.get_all_snapshots().should.have.length_of(num_snapshots) # Deleting something that was already deleted should throw an error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: snapshot.delete() cm.exception.code.should.equal("InvalidSnapshot.NotFound") cm.exception.status.should.equal(400) @@ -382,7 +381,7 @@ def test_filter_snapshot_by_id(): s.volume_id.should.be.within([volume2.id, volume3.id]) s.region.name.should.equal(conn.region.name) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -484,7 +483,7 @@ def test_snapshot_attribute(): # Add 'all' group and confirm - with assert_raises(EC2ResponseError) as ex: + 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) @@ -506,7 +505,7 @@ def test_snapshot_attribute(): ) # Remove 'all' group and confirm - with assert_raises(EC2ResponseError) as ex: + 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) @@ -527,7 +526,7 @@ def test_snapshot_attribute(): ).should_not.throw(EC2ResponseError) # Error: Add with group != 'all' - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_snapshot_attribute( snapshot.id, attribute="createVolumePermission", @@ -539,7 +538,7 @@ def test_snapshot_attribute(): cm.exception.request_id.should_not.be.none # Error: Add with invalid snapshot ID - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_snapshot_attribute( "snapshot-abcd1234", attribute="createVolumePermission", @@ -551,7 +550,7 @@ def test_snapshot_attribute(): cm.exception.request_id.should_not.be.none # Error: Remove with invalid snapshot ID - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.modify_snapshot_attribute( "snapshot-abcd1234", attribute="createVolumePermission", @@ -740,7 +739,7 @@ def test_create_volume_from_snapshot(): volume = conn.create_volume(80, "us-east-1a") snapshot = volume.create_snapshot("a test snapshot") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -786,7 +785,7 @@ def test_modify_attribute_blockDeviceMapping(): instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: instance.modify_attribute( "blockDeviceMapping", {"/dev/sda1": True}, dry_run=True ) @@ -809,7 +808,7 @@ def test_volume_tag_escaping(): vol = conn.create_volume(10, "us-east-1a") snapshot = conn.create_snapshot(vol.id, "Desc") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -879,25 +878,25 @@ def test_copy_snapshot(): getattr(source, attrib).should.equal(getattr(dest, attrib)) # Copy from non-existent source ID. - with assert_raises(ClientError) as cm: + 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( - "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.exception.response["Error"]["Code"].should.equal("InvalidVolume.NotFound") + cm.exception.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) # Copy from non-existent source region. - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: copy_snapshot_response = dest_ec2_client.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.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) @mock_ec2 diff --git a/tests/test_ec2/test_elastic_ip_addresses.py b/tests/test_ec2/test_elastic_ip_addresses.py index baecb94d6..e9a247ea7 100644 --- a/tests/test_ec2/test_elastic_ip_addresses.py +++ b/tests/test_ec2/test_elastic_ip_addresses.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto import boto3 @@ -21,7 +20,7 @@ def test_eip_allocate_classic(): """Allocate/release Classic EIP""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -35,7 +34,7 @@ def test_eip_allocate_classic(): standard.instance_id.should.be.none standard.domain.should.be.equal("standard") - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: standard.release(dry_run=True) ex.exception.error_code.should.equal("DryRunOperation") ex.exception.status.should.equal(400) @@ -52,7 +51,7 @@ def test_eip_allocate_vpc(): """Allocate/release VPC EIP""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -84,7 +83,7 @@ def test_eip_allocate_invalid_domain(): """Allocate EIP invalid domain""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.allocate_address(domain="bogus") cm.exception.code.should.equal("InvalidParameterValue") cm.exception.status.should.equal(400) @@ -102,13 +101,13 @@ def test_eip_associate_classic(): eip = conn.allocate_address() eip.instance_id.should.be.none - with assert_raises(EC2ResponseError) as cm: + 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 - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: conn.associate_address( instance_id=instance.id, public_ip=eip.public_ip, dry_run=True ) @@ -123,7 +122,7 @@ def test_eip_associate_classic(): eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] eip.instance_id.should.be.equal(instance.id) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -153,7 +152,7 @@ def test_eip_associate_vpc(): eip = conn.allocate_address(domain="vpc") eip.instance_id.should.be.none - with assert_raises(EC2ResponseError) as cm: + 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) @@ -169,7 +168,7 @@ def test_eip_associate_vpc(): eip.instance_id.should.be.equal("") eip.association_id.should.be.none - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: eip.release(dry_run=True) ex.exception.error_code.should.equal("DryRunOperation") ex.exception.status.should.equal(400) @@ -241,7 +240,7 @@ def test_eip_associate_network_interface(): eip = conn.allocate_address(domain="vpc") eip.network_interface_id.should.be.none - with assert_raises(EC2ResponseError) as cm: + 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) @@ -276,7 +275,7 @@ def test_eip_reassociate(): conn.associate_address(instance_id=instance1.id, public_ip=eip.public_ip) # Different ID detects resource association - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.associate_address( instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=False ) @@ -312,7 +311,7 @@ def test_eip_reassociate_nic(): conn.associate_address(network_interface_id=eni1.id, public_ip=eip.public_ip) # Different ID detects resource association - with assert_raises(EC2ResponseError) as cm: + 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) @@ -336,7 +335,7 @@ def test_eip_associate_invalid_args(): eip = conn.allocate_address() - with assert_raises(EC2ResponseError) as cm: + 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) @@ -350,7 +349,7 @@ def test_eip_disassociate_bogus_association(): """Disassociate bogus EIP""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -362,7 +361,7 @@ def test_eip_release_bogus_eip(): """Release bogus EIP""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -374,7 +373,7 @@ def test_eip_disassociate_arg_error(): """Invalid arguments disassociate address""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.disassociate_address() cm.exception.code.should.equal("MissingParameter") cm.exception.status.should.equal(400) @@ -386,7 +385,7 @@ def test_eip_release_arg_error(): """Invalid arguments release address""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.release_address() cm.exception.code.should.equal("MissingParameter") cm.exception.status.should.equal(400) @@ -438,7 +437,7 @@ def test_eip_describe_none(): """Error when search for bogus IP""" conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) diff --git a/tests/test_ec2/test_elastic_network_interfaces.py b/tests/test_ec2/test_elastic_network_interfaces.py index e7fd878a6..259885ee0 100644 --- a/tests/test_ec2/test_elastic_network_interfaces.py +++ b/tests/test_ec2/test_elastic_network_interfaces.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto3 from botocore.exceptions import ClientError @@ -21,7 +20,7 @@ def test_elastic_network_interfaces(): vpc = conn.create_vpc("10.0.0.0/16") subnet = conn.create_subnet(vpc.id, "10.0.0.0/18") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -38,7 +37,7 @@ def test_elastic_network_interfaces(): eni.private_ip_addresses.should.have.length_of(1) eni.private_ip_addresses[0].private_ip_address.startswith("10.").should.be.true - with assert_raises(EC2ResponseError) as ex: + 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) @@ -51,7 +50,7 @@ def test_elastic_network_interfaces(): all_enis = conn.get_all_network_interfaces() all_enis.should.have.length_of(0) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -62,7 +61,7 @@ def test_elastic_network_interfaces(): def test_elastic_network_interfaces_subnet_validation(): conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -133,7 +132,7 @@ def test_elastic_network_interfaces_modify_attribute(): eni.groups.should.have.length_of(1) eni.groups[0].id.should.equal(security_group1.id) - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: conn.modify_network_interface_attribute( eni.id, "groupset", [security_group2.id], dry_run=True ) @@ -228,7 +227,7 @@ def test_elastic_network_interfaces_get_by_tag_name(): SubnetId=subnet.id, PrivateIpAddress="10.0.10.5" ) - with assert_raises(ClientError) as ex: + 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) diff --git a/tests/test_ec2/test_flow_logs.py b/tests/test_ec2/test_flow_logs.py index 044e6c31d..1dba572d3 100644 --- a/tests/test_ec2/test_flow_logs.py +++ b/tests/test_ec2/test_flow_logs.py @@ -1,7 +1,6 @@ from __future__ import unicode_literals -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest import boto3 @@ -36,7 +35,7 @@ def test_create_flow_logs_s3(): CreateBucketConfiguration={"LocationConstraint": "us-west-1"}, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -87,7 +86,7 @@ def test_create_flow_logs_cloud_watch(): vpc = client.create_vpc(CidrBlock="10.0.0.0/16")["Vpc"] logs_client.create_log_group(logGroupName="test-group") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -243,7 +242,7 @@ def test_delete_flow_logs_delete_many(): def test_delete_flow_logs_non_existing(): client = boto3.client("ec2", region_name="us-west-1") - with assert_raises(ClientError) as ex: + 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) @@ -251,7 +250,7 @@ def test_delete_flow_logs_non_existing(): "These flow log ids in the input list are not found: [TotalCount: 1] fl-1a2b3c4d" ) - with assert_raises(ClientError) as ex: + 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) @@ -304,7 +303,7 @@ def test_create_flow_logs_invalid_parameters(): CreateBucketConfiguration={"LocationConstraint": "us-west-1"}, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -319,7 +318,7 @@ def test_create_flow_logs_invalid_parameters(): "Invalid Flow Log Max Aggregation Interval" ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -332,7 +331,7 @@ def test_create_flow_logs_invalid_parameters(): "LogDestination can't be empty if LogGroupName is not provided." ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -346,7 +345,7 @@ def test_create_flow_logs_invalid_parameters(): "LogDestination type must be cloud-watch-logs if LogGroupName is provided." ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -368,7 +367,7 @@ def test_create_flow_logs_invalid_parameters(): )["FlowLogIds"] response.should.have.length_of(1) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], @@ -391,7 +390,7 @@ def test_create_flow_logs_invalid_parameters(): )["FlowLogIds"] response.should.have.length_of(1) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.create_flow_logs( ResourceType="VPC", ResourceIds=[vpc["VpcId"]], diff --git a/tests/test_ec2/test_general.py b/tests/test_ec2/test_general.py index 7b8f3bd53..b6e75ea6a 100644 --- a/tests/test_ec2/test_general.py +++ b/tests/test_ec2/test_general.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto import boto3 @@ -25,7 +24,7 @@ def test_console_output(): def test_console_output_without_instance(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index d7a2ff3f3..b770862e2 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -3,8 +3,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 from botocore.exceptions import ClientError -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import base64 import ipaddress @@ -52,7 +51,7 @@ def test_add_servers(): def test_instance_launch_and_terminate(): conn = boto.ec2.connect_to_region("us-east-1") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -87,7 +86,7 @@ def test_instance_launch_and_terminate(): volume.attach_data.instance_id.should.equal(instance.id) volume.status.should.equal("in-use") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -290,7 +289,7 @@ def test_get_instances_by_id(): instance_ids.should.equal([instance1.id, instance2.id]) # Call get_all_instances with a bad id should raise an error - with assert_raises(EC2ResponseError) as cm: + 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) @@ -743,7 +742,7 @@ def test_instance_start_and_stop(): instance_ids = [instance.id for instance in instances] - with assert_raises(EC2ResponseError) as ex: + 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) @@ -756,7 +755,7 @@ def test_instance_start_and_stop(): for instance in stopped_instances: instance.state.should.equal("stopping") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -774,7 +773,7 @@ def test_instance_reboot(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: instance.reboot(dry_run=True) ex.exception.error_code.should.equal("DryRunOperation") ex.exception.status.should.equal(400) @@ -792,7 +791,7 @@ def test_instance_attribute_instance_type(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + 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) @@ -820,7 +819,7 @@ def test_modify_instance_attribute_security_groups(): "test security group 2", "this is a test security group 2" ).id - with assert_raises(EC2ResponseError) as ex: + 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) @@ -843,7 +842,7 @@ def test_instance_attribute_user_data(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + 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) @@ -873,7 +872,7 @@ def test_instance_attribute_source_dest_check(): # Set to false (note: Boto converts bool to string, eg 'false') - with assert_raises(EC2ResponseError) as ex: + 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) @@ -919,7 +918,7 @@ def test_user_data_with_run_instance(): def test_run_instance_with_security_group_name(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -1196,7 +1195,7 @@ def test_instance_with_nic_attach_detach(): set([group.id for group in eni.groups]).should.equal(set([security_group2.id])) # Attach - with assert_raises(EC2ResponseError) as ex: + 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) @@ -1223,7 +1222,7 @@ def test_instance_with_nic_attach_detach(): ) # Detach - with assert_raises(EC2ResponseError) as ex: + 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) @@ -1242,7 +1241,7 @@ def test_instance_with_nic_attach_detach(): set([group.id for group in eni.groups]).should.equal(set([security_group2.id])) # Detach with invalid attachment ID - with assert_raises(EC2ResponseError) as cm: + 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) @@ -1410,7 +1409,7 @@ def test_describe_instance_status_with_instance_filter_deprecated(): all_status[0].id.should.equal(instance.id) # Call get_all_instance_status with a bad id should raise an error - with assert_raises(EC2ResponseError) as cm: + 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) @@ -1537,7 +1536,7 @@ def test_get_instance_by_security_group(): security_group = conn.create_security_group("test", "test") - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: conn.modify_instance_attribute( instance.id, "groupSet", [security_group.id], dry_run=True ) @@ -1661,7 +1660,7 @@ def test_describe_instance_attribute(): ] for invalid_instance_attribute in invalid_instance_attributes: - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: client.describe_instance_attribute( InstanceId=instance_id, Attribute=invalid_instance_attribute ) diff --git a/tests/test_ec2/test_internet_gateways.py b/tests/test_ec2/test_internet_gateways.py index 2319bf062..cfa8bafe9 100644 --- a/tests/test_ec2/test_internet_gateways.py +++ b/tests/test_ec2/test_internet_gateways.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import re @@ -28,7 +27,7 @@ def test_igw_create(): conn.get_all_internet_gateways().should.have.length_of(0) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -51,7 +50,7 @@ def test_igw_attach(): igw = conn.create_internet_gateway() vpc = conn.create_vpc(VPC_CIDR) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -71,7 +70,7 @@ def test_igw_attach_bad_vpc(): conn = boto.connect_vpc("the_key", "the_secret") igw = conn.create_internet_gateway() - with assert_raises(EC2ResponseError) as cm: + 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) @@ -87,7 +86,7 @@ def test_igw_attach_twice(): vpc2 = conn.create_vpc(VPC_CIDR) conn.attach_internet_gateway(igw.id, vpc1.id) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -102,7 +101,7 @@ def test_igw_detach(): vpc = conn.create_vpc(VPC_CIDR) conn.attach_internet_gateway(igw.id, vpc.id) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -124,7 +123,7 @@ def test_igw_detach_wrong_vpc(): vpc2 = conn.create_vpc(VPC_CIDR) conn.attach_internet_gateway(igw.id, vpc1.id) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -139,7 +138,7 @@ def test_igw_detach_invalid_vpc(): vpc = conn.create_vpc(VPC_CIDR) conn.attach_internet_gateway(igw.id, vpc.id) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -153,7 +152,7 @@ def test_igw_detach_unattached(): igw = conn.create_internet_gateway() vpc = conn.create_vpc(VPC_CIDR) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -169,7 +168,7 @@ def test_igw_delete(): igw = conn.create_internet_gateway() conn.get_all_internet_gateways().should.have.length_of(1) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -189,7 +188,7 @@ def test_igw_delete_attached(): vpc = conn.create_vpc(VPC_CIDR) conn.attach_internet_gateway(igw.id, vpc.id) - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.delete_internet_gateway(igw.id) cm.exception.code.should.equal("DependencyViolation") cm.exception.status.should.equal(400) @@ -209,7 +208,7 @@ def test_igw_desribe(): def test_igw_describe_bad_id(): """ internet gateway fail to fetch by bad id """ conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) diff --git a/tests/test_ec2/test_key_pairs.py b/tests/test_ec2/test_key_pairs.py index 09982ac7a..022b4ceeb 100644 --- a/tests/test_ec2/test_key_pairs.py +++ b/tests/test_ec2/test_key_pairs.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto import sure # noqa @@ -56,7 +55,7 @@ def test_key_pairs_empty(): def test_key_pairs_invalid_id(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -67,7 +66,7 @@ def test_key_pairs_invalid_id(): def test_key_pairs_create(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -110,7 +109,7 @@ def test_key_pairs_create_exist(): conn.create_key_pair("foo") assert len(conn.get_all_key_pairs()) == 1 - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.create_key_pair("foo") cm.exception.code.should.equal("InvalidKeyPair.Duplicate") cm.exception.status.should.equal(400) @@ -130,7 +129,7 @@ def test_key_pairs_delete_exist(): conn = boto.connect_ec2("the_key", "the_secret") conn.create_key_pair("foo") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -147,7 +146,7 @@ def test_key_pairs_delete_exist(): def test_key_pairs_import(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -176,7 +175,7 @@ def test_key_pairs_import_exist(): assert kp.name == "foo" assert len(conn.get_all_key_pairs()) == 1 - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.create_key_pair("foo") cm.exception.code.should.equal("InvalidKeyPair.Duplicate") cm.exception.status.should.equal(400) @@ -187,19 +186,19 @@ def test_key_pairs_import_exist(): def test_key_pairs_invalid(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + 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") - with assert_raises(EC2ResponseError) as ex: + 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") - with assert_raises(EC2ResponseError) as ex: + 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) diff --git a/tests/test_ec2/test_launch_templates.py b/tests/test_ec2/test_launch_templates.py index 4c37818d1..0bcf188ce 100644 --- a/tests/test_ec2/test_launch_templates.py +++ b/tests/test_ec2/test_launch_templates.py @@ -1,7 +1,7 @@ import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from botocore.client import ClientError from moto import mock_ec2 @@ -30,7 +30,7 @@ def test_launch_template_create(): lt["DefaultVersionNumber"].should.equal(1) lt["LatestVersionNumber"].should.equal(1) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: cli.create_launch_template( LaunchTemplateName="test-template", LaunchTemplateData={ diff --git a/tests/test_ec2/test_network_acls.py b/tests/test_ec2/test_network_acls.py index c20bf75c6..1bb058733 100644 --- a/tests/test_ec2/test_network_acls.py +++ b/tests/test_ec2/test_network_acls.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals import boto import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from botocore.exceptions import ClientError from moto import mock_ec2_deprecated, mock_ec2 @@ -261,7 +261,7 @@ def test_duplicate_network_acl_entry(): RuleNumber=rule_number, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: default_network_acl.create_entry( CidrBlock="10.0.0.0/0", Egress=egress, diff --git a/tests/test_ec2/test_route_tables.py b/tests/test_ec2/test_route_tables.py index a652bd1cf..4ebfeb737 100644 --- a/tests/test_ec2/test_route_tables.py +++ b/tests/test_ec2/test_route_tables.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest import boto import boto3 @@ -61,7 +60,7 @@ def test_route_tables_additional(): local_route.state.should.equal("active") local_route.destination_cidr_block.should.equal(vpc.cidr_block) - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.delete_vpc(vpc.id) cm.exception.code.should.equal("DependencyViolation") cm.exception.status.should.equal(400) @@ -72,7 +71,7 @@ def test_route_tables_additional(): all_route_tables = conn.get_all_route_tables(filters={"vpc-id": vpc.id}) all_route_tables.should.have.length_of(1) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -197,7 +196,7 @@ def test_route_table_associations(): association_id_idempotent.should.equal(association_id) # Error: Attempt delete associated route table. - with assert_raises(EC2ResponseError) as cm: + 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) @@ -211,21 +210,21 @@ def test_route_table_associations(): route_table.associations.should.have.length_of(0) # Error: Disassociate with invalid association ID - with assert_raises(EC2ResponseError) as cm: + 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 # Error: Associate with invalid subnet ID - with assert_raises(EC2ResponseError) as cm: + 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 # Error: Associate with invalid route table ID - with assert_raises(EC2ResponseError) as cm: + 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) @@ -293,7 +292,7 @@ def test_route_table_replace_route_table_association(): association_id_idempotent.should.equal(association_id2) # Error: Replace association with invalid association ID - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.replace_route_table_association_with_assoc( "rtbassoc-1234abcd", route_table1.id ) @@ -302,7 +301,7 @@ def test_route_table_replace_route_table_association(): cm.exception.request_id.should_not.be.none # Error: Replace association with invalid route table ID - with assert_raises(EC2ResponseError) as cm: + 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) @@ -389,7 +388,7 @@ def test_routes_additional(): ] new_routes.should.have.length_of(0) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -442,7 +441,7 @@ def test_routes_replace(): target_route.state.should.equal("active") target_route.destination_cidr_block.should.equal(ROUTE_CIDR) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -571,7 +570,7 @@ def test_create_route_with_invalid_destination_cidr_block_parameter(): internet_gateway.reload() destination_cidr_block = "1000.1.0.0/20" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: route = route_table.create_route( DestinationCidrBlock=destination_cidr_block, GatewayId=internet_gateway.id ) diff --git a/tests/test_ec2/test_security_groups.py b/tests/test_ec2/test_security_groups.py index 10885df18..9f8c1aecd 100644 --- a/tests/test_ec2/test_security_groups.py +++ b/tests/test_ec2/test_security_groups.py @@ -4,8 +4,7 @@ import copy import json # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest import boto3 import boto @@ -20,7 +19,7 @@ from moto import mock_ec2, mock_ec2_deprecated def test_create_and_describe_security_group(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: security_group = conn.create_security_group( "test security group", "this is a test security group", dry_run=True ) @@ -38,7 +37,7 @@ def test_create_and_describe_security_group(): security_group.description.should.equal("this is a test security group") # Trying to create another group with the same name should throw an error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.create_security_group( "test security group", "this is a test security group" ) @@ -57,7 +56,7 @@ def test_create_and_describe_security_group(): def test_create_security_group_without_description_raises_error(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -87,7 +86,7 @@ def test_create_and_describe_vpc_security_group(): # Trying to create another group with the same name in the same VPC should # throw an error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.create_security_group( "test security group", "this is a test security group", vpc_id ) @@ -146,14 +145,14 @@ def test_deleting_security_groups(): conn.get_all_security_groups().should.have.length_of(4) # Deleting a group that doesn't exist should throw an error - with assert_raises(EC2ResponseError) as cm: + 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 # Delete by name - with assert_raises(EC2ResponseError) as ex: + 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) @@ -184,7 +183,7 @@ def test_authorize_ip_range_and_revoke(): conn = boto.connect_ec2("the_key", "the_secret") security_group = conn.create_security_group("test", "test") - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: success = security_group.authorize( ip_protocol="tcp", from_port="22", @@ -208,7 +207,7 @@ def test_authorize_ip_range_and_revoke(): security_group.rules[0].grants[0].cidr_ip.should.equal("123.123.123.123/32") # Wrong Cidr should throw error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: security_group.revoke( ip_protocol="tcp", from_port="22", @@ -220,7 +219,7 @@ def test_authorize_ip_range_and_revoke(): cm.exception.request_id.should_not.be.none # Actually revoke - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: security_group.revoke( ip_protocol="tcp", from_port="22", @@ -246,7 +245,7 @@ def test_authorize_ip_range_and_revoke(): "testegress", "testegress", vpc_id="vpc-3432589" ) - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: success = conn.authorize_security_group_egress( egress_security_group.id, "tcp", @@ -285,7 +284,7 @@ def test_authorize_ip_range_and_revoke(): ).should.throw(EC2ResponseError) # Actually revoke - with assert_raises(EC2ResponseError) as ex: + with pytest.raises(EC2ResponseError) as ex: conn.revoke_security_group_egress( egress_security_group.id, "tcp", @@ -335,7 +334,7 @@ def test_authorize_other_group_and_revoke(): security_group.rules[0].grants[0].group_id.should.equal(other_security_group.id) # Wrong source group should throw error - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: security_group.revoke( ip_protocol="tcp", from_port="22", to_port="2222", src_group=wrong_group ) @@ -440,7 +439,7 @@ def test_get_all_security_groups(): resp.should.have.length_of(1) resp[0].id.should.equal(sg1.id) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -469,7 +468,7 @@ def test_get_all_security_groups(): def test_authorize_bad_cidr_throws_invalid_parameter_value(): conn = boto.connect_ec2("the_key", "the_secret") security_group = conn.create_security_group("test", "test") - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: security_group.authorize( ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123" ) @@ -485,7 +484,7 @@ def test_security_group_tagging(): sg = conn.create_security_group("test-sg", "Test SG", vpc.id) - with assert_raises(EC2ResponseError) as ex: + 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) @@ -534,7 +533,7 @@ def test_sec_group_rule_limit(): other_sg = ec2_conn.create_security_group("test_2", "test_other") # INGRESS - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", @@ -556,13 +555,13 @@ def test_sec_group_rule_limit(): ) success.should.be.true # verify that we cannot authorize past the limit for a CIDR IP - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: 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") # verify that we cannot authorize past the limit for a different sec group - with assert_raises(EC2ResponseError) as cm: + 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 ) @@ -581,13 +580,13 @@ def test_sec_group_rule_limit(): group_id=sg.id, ip_protocol="-1", cidr_ip="{0}.0.0.0/0".format(i) ) # verify that we cannot authorize past the limit for a CIDR IP - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: 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") # verify that we cannot authorize past the limit for a different sec group - with assert_raises(EC2ResponseError) as cm: + 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 ) @@ -605,7 +604,7 @@ def test_sec_group_rule_limit_vpc(): other_sg = ec2_conn.create_security_group("test_2", "test", vpc_id=vpc.id) # INGRESS - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: ec2_conn.authorize_security_group( group_id=sg.id, ip_protocol="-1", @@ -627,13 +626,13 @@ def test_sec_group_rule_limit_vpc(): ) # verify that we cannot authorize past the limit for a CIDR IP success.should.be.true - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: 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") # verify that we cannot authorize past the limit for a different sec group - with assert_raises(EC2ResponseError) as cm: + 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 ) @@ -652,13 +651,13 @@ def test_sec_group_rule_limit_vpc(): group_id=sg.id, ip_protocol="-1", cidr_ip="{0}.0.0.0/0".format(i) ) # verify that we cannot authorize past the limit for a CIDR IP - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: 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") # verify that we cannot authorize past the limit for a different sec group - with assert_raises(EC2ResponseError) as cm: + 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 ) @@ -689,7 +688,7 @@ def test_add_same_rule_twice_throws_error(): ] sg.authorize_ingress(IpPermissions=ip_permissions) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: sg.authorize_ingress(IpPermissions=ip_permissions) @@ -761,7 +760,7 @@ def test_security_group_tagging_boto3(): sg = conn.create_security_group(GroupName="test-sg", Description="Test SG") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_tags( Resources=[sg["GroupId"]], Tags=[{"Key": "Test", "Value": "Tag"}], @@ -926,7 +925,7 @@ def test_get_all_security_groups_filter_with_same_vpc_id(): ) security_groups.should.have.length_of(1) - with assert_raises(EC2ResponseError) as cm: + 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) diff --git a/tests/test_ec2/test_spot_instances.py b/tests/test_ec2/test_spot_instances.py index 5eb5a6e48..c7b965918 100644 --- a/tests/test_ec2/test_spot_instances.py +++ b/tests/test_ec2/test_spot_instances.py @@ -1,5 +1,5 @@ from __future__ import unicode_literals -from nose.tools import assert_raises +import pytest import datetime import boto @@ -31,7 +31,7 @@ def test_request_spot_instances(): start = iso_8601_datetime_with_milliseconds(start_dt) end = iso_8601_datetime_with_milliseconds(end_dt) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: request = conn.request_spot_instances( SpotPrice="0.5", InstanceCount=1, @@ -155,7 +155,7 @@ def test_cancel_spot_instance_request(): requests = conn.get_all_spot_instance_requests() requests.should.have.length_of(1) - with assert_raises(EC2ResponseError) as ex: + 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) diff --git a/tests/test_ec2/test_subnets.py b/tests/test_ec2/test_subnets.py index 416235f43..1d44999ae 100644 --- a/tests/test_ec2/test_subnets.py +++ b/tests/test_ec2/test_subnets.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest import boto3 import boto @@ -30,7 +29,7 @@ def test_subnets(): all_subnets = conn.get_all_subnets() all_subnets.should.have.length_of(0 + len(ec2.get_all_zones())) - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.delete_subnet(subnet.id) cm.exception.code.should.equal("InvalidSubnetID.NotFound") cm.exception.status.should.equal(400) @@ -41,7 +40,7 @@ def test_subnets(): def test_subnet_create_vpc_validation(): conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -202,7 +201,7 @@ def test_modify_subnet_attribute_validation(): VpcId=vpc.id, CidrBlock="10.0.0.0/24", AvailabilityZone="us-west-1a" ) - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): client.modify_subnet_attribute( SubnetId=subnet.id, MapPublicIpOnLaunch={"Value": "invalid"} ) @@ -228,7 +227,7 @@ def test_subnet_get_by_id(): subnetA.id.should.be.within(subnets_by_id) subnetB1.id.should.be.within(subnets_by_id) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -386,7 +385,7 @@ def test_create_subnet_with_invalid_availability_zone(): vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16") subnet_availability_zone = "asfasfas" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: subnet = client.create_subnet( VpcId=vpc.id, CidrBlock="10.0.0.0/24", @@ -409,7 +408,7 @@ def test_create_subnet_with_invalid_cidr_range(): vpc.is_default.shouldnt.be.ok subnet_cidr_block = "10.1.0.0/20" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) str(ex.exception).should.equal( "An error occurred (InvalidSubnet.Range) when calling the CreateSubnet " @@ -444,7 +443,7 @@ def test_create_subnet_with_invalid_cidr_block_parameter(): vpc.is_default.shouldnt.be.ok subnet_cidr_block = "1000.1.0.0/20" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block) str(ex.exception).should.equal( "An error occurred (InvalidParameterValue) when calling the CreateSubnet " @@ -503,7 +502,7 @@ def test_create_subnets_with_overlapping_cidr_blocks(): vpc.is_default.shouldnt.be.ok subnet_cidr_block = "10.0.0.0/24" - with assert_raises(ClientError) as ex: + 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( diff --git a/tests/test_ec2/test_tags.py b/tests/test_ec2/test_tags.py index 8480f8bc0..918b02623 100644 --- a/tests/test_ec2/test_tags.py +++ b/tests/test_ec2/test_tags.py @@ -1,5 +1,5 @@ from __future__ import unicode_literals -from nose.tools import assert_raises +import pytest import itertools @@ -11,7 +11,7 @@ from boto.ec2.instance import Reservation import sure # noqa from moto import mock_ec2_deprecated, mock_ec2 -from nose.tools import assert_raises +import pytest @mock_ec2_deprecated @@ -20,7 +20,7 @@ def test_add_tag(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as ex: + 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) @@ -51,7 +51,7 @@ def test_remove_tag(): tag.name.should.equal("a key") tag.value.should.equal("some value") - with assert_raises(EC2ResponseError) as ex: + 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) @@ -106,7 +106,7 @@ def test_create_tags(): "blank key": "", } - with assert_raises(EC2ResponseError) as ex: + 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) @@ -131,14 +131,14 @@ def test_tag_limit_exceeded(): for i in range(51): tag_dict["{0:02d}".format(i + 1)] = "" - with assert_raises(EC2ResponseError) as cm: + 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 instance.add_tag("a key", "a value") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -157,7 +157,7 @@ def test_invalid_parameter_tag_null(): reservation = conn.run_instances("ami-1234abcd") instance = reservation.instances[0] - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: instance.add_tag("a key", None) cm.exception.code.should.equal("InvalidParameterValue") cm.exception.status.should.equal(400) @@ -167,13 +167,13 @@ def test_invalid_parameter_tag_null(): @mock_ec2_deprecated def test_invalid_id(): conn = boto.connect_ec2("the_key", "the_secret") - with assert_raises(EC2ResponseError) as cm: + 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 - with assert_raises(EC2ResponseError) as cm: + 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) @@ -449,7 +449,7 @@ def test_create_tag_empty_resource(): # create ec2 client in us-west-1 client = boto3.client("ec2", region_name="us-west-1") # create tag with empty resource - with assert_raises(ClientError) as ex: + 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( @@ -462,7 +462,7 @@ def test_delete_tag_empty_resource(): # create ec2 client in us-west-1 client = boto3.client("ec2", region_name="us-west-1") # delete tag with empty resource - with assert_raises(ClientError) as ex: + 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( diff --git a/tests/test_ec2/test_vpc_peering.py b/tests/test_ec2/test_vpc_peering.py index b535518de..f852ab3ca 100644 --- a/tests/test_ec2/test_vpc_peering.py +++ b/tests/test_ec2/test_vpc_peering.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises -from nose.tools import assert_raises +import pytest from moto.ec2.exceptions import EC2ClientError from botocore.exceptions import ClientError @@ -49,7 +48,7 @@ def test_vpc_peering_connections_accept(): vpc_pcx = conn.accept_vpc_peering_connection(vpc_pcx.id) vpc_pcx._status.code.should.equal("active") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -69,7 +68,7 @@ def test_vpc_peering_connections_reject(): verdict = conn.reject_vpc_peering_connection(vpc_pcx.id) verdict.should.equal(True) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -93,7 +92,7 @@ def test_vpc_peering_connections_delete(): all_vpc_pcxs.should.have.length_of(1) all_vpc_pcxs[0]._status.code.should.equal("deleted") - with assert_raises(EC2ResponseError) as cm: + 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) @@ -129,7 +128,7 @@ def test_vpc_peering_connections_cross_region_fail(): ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1") vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16") # create peering wrong region with no vpc - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: ec2_usw1.create_vpc_peering_connection( VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-2" ) @@ -253,7 +252,7 @@ def test_vpc_peering_connections_cross_region_accept_wrong_region(): # accept wrong peering from us-west-1 which will raise error ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1") ec2_usw1 = boto3.client("ec2", region_name="us-west-1") - with assert_raises(ClientError) as cm: + 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") exp_msg = ( @@ -278,7 +277,7 @@ def test_vpc_peering_connections_cross_region_reject_wrong_region(): # reject wrong peering from us-west-1 which will raise error ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1") ec2_usw1 = boto3.client("ec2", region_name="us-west-1") - with assert_raises(ClientError) as cm: + 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") exp_msg = ( diff --git a/tests/test_ec2/test_vpcs.py b/tests/test_ec2/test_vpcs.py index 8ad85072c..32e59a91b 100644 --- a/tests/test_ec2/test_vpcs.py +++ b/tests/test_ec2/test_vpcs.py @@ -1,8 +1,7 @@ from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa -from nose.tools import assert_raises +import pytest from moto.ec2.exceptions import EC2ClientError from botocore.exceptions import ClientError @@ -31,7 +30,7 @@ def test_vpcs(): all_vpcs = conn.get_all_vpcs() all_vpcs.should.have.length_of(1) - with assert_raises(EC2ResponseError) as cm: + with pytest.raises(EC2ResponseError) as cm: conn.delete_vpc("vpc-1234abcd") cm.exception.code.should.equal("InvalidVpcID.NotFound") cm.exception.status.should.equal(400) @@ -114,7 +113,7 @@ def test_vpc_get_by_id(): vpc1.id.should.be.within(vpc_ids) vpc2.id.should.be.within(vpc_ids) - with assert_raises(EC2ResponseError) as cm: + 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) @@ -402,7 +401,7 @@ def test_associate_vpc_ipv4_cidr_block(): ) # Check error on adding 6th association. - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: response = ec2.meta.client.associate_vpc_cidr_block( VpcId=vpc.id, CidrBlock="10.10.50.0/22" ) @@ -447,7 +446,7 @@ def test_disassociate_vpc_ipv4_cidr_block(): ) # Error attempting to delete a non-existent CIDR_BLOCK association - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: response = ec2.meta.client.disassociate_vpc_cidr_block( AssociationId="vpc-cidr-assoc-BORING123" ) @@ -469,7 +468,7 @@ def test_disassociate_vpc_ipv4_cidr_block(): {}, )["AssociationId"] - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: response = ec2.meta.client.disassociate_vpc_cidr_block( AssociationId=vpc_base_cidr_assoc_id ) @@ -549,7 +548,7 @@ def test_vpc_associate_ipv6_cidr_block(): ipv6_cidr_block_association_set["AssociationId"].should.contain("vpc-cidr-assoc") # Test Fail on adding 2nd IPV6 association - AWS only allows 1 at this time! - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: response = ec2.meta.client.associate_vpc_cidr_block( VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True ) @@ -657,7 +656,7 @@ def test_create_vpc_with_invalid_cidr_block_parameter(): ec2 = boto3.resource("ec2", region_name="us-west-1") vpc_cidr_block = "1000.1.0.0/20" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block) str(ex.exception).should.equal( "An error occurred (InvalidParameterValue) when calling the CreateVpc " @@ -672,7 +671,7 @@ def test_create_vpc_with_invalid_cidr_range(): ec2 = boto3.resource("ec2", region_name="us-west-1") vpc_cidr_block = "10.1.0.0/29" - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block) str(ex.exception).should.equal( "An error occurred (InvalidVpc.Range) when calling the CreateVpc " diff --git a/tests/test_ec2/test_vpn_connections.py b/tests/test_ec2/test_vpn_connections.py index 4360c8b2e..ca8897417 100644 --- a/tests/test_ec2/test_vpn_connections.py +++ b/tests/test_ec2/test_vpn_connections.py @@ -1,11 +1,11 @@ from __future__ import unicode_literals + import boto import boto3 -from nose.tools import assert_raises +import pytest import sure # noqa from boto.exception import EC2ResponseError - -from moto import mock_ec2_deprecated, mock_ec2 +from moto import mock_ec2, mock_ec2_deprecated @mock_ec2_deprecated @@ -35,7 +35,7 @@ def test_delete_vpn_connections(): @mock_ec2_deprecated def test_delete_vpn_connections_bad_id(): conn = boto.connect_vpc("the_key", "the_secret") - with assert_raises(EC2ResponseError): + with pytest.raises(EC2ResponseError): conn.delete_vpn_connection("vpn-0123abcd") diff --git a/tests/test_ecr/__init__.py b/tests/test_ecr/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_ecr/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_ecr/test_ecr_boto3.py b/tests/test_ecr/test_ecr_boto3.py index fd678f661..e44307bee 100644 --- a/tests/test_ecr/test_ecr_boto3.py +++ b/tests/test_ecr/test_ecr_boto3.py @@ -15,7 +15,7 @@ from botocore.exceptions import ClientError, ParamValidationError from dateutil.tz import tzlocal from moto import mock_ecr -from nose import SkipTest +from unittest import SkipTest def _create_image_digest(contents=None): diff --git a/tests/test_ecs/__init__.py b/tests/test_ecs/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_ecs/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_ecs/test_ecs_boto3.py b/tests/test_ecs/test_ecs_boto3.py index 2ef801807..afec17da2 100644 --- a/tests/test_ecs/test_ecs_boto3.py +++ b/tests/test_ecs/test_ecs_boto3.py @@ -10,7 +10,7 @@ from uuid import UUID from moto import mock_ecs from moto import mock_ec2 -from nose.tools import assert_raises +import pytest @mock_ecs @@ -860,7 +860,7 @@ def test_deregister_container_instance(): containerInstances=[container_instance_id], startedBy="moto", ) - with assert_raises(Exception) as e: + with pytest.raises(Exception) as e: ecs_client.deregister_container_instance( cluster=test_cluster_name, containerInstance=container_instance_id ).should.have.raised(Exception) @@ -952,7 +952,7 @@ def test_describe_container_instances(): instance.keys().should.contain("pendingTasksCount") instance["registeredAt"].should.be.a("datetime.datetime") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: ecs_client.describe_container_instances( cluster=test_cluster_name, containerInstances=[] ) diff --git a/tests/test_elb/__init__.py b/tests/test_elb/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_elb/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_elb/test_elb.py b/tests/test_elb/test_elb.py index 1583ea544..dd51e8f60 100644 --- a/tests/test_elb/test_elb.py +++ b/tests/test_elb/test_elb.py @@ -11,7 +11,7 @@ from boto.ec2.elb.attributes import ( ) from botocore.exceptions import ClientError from boto.exception import BotoServerError -from nose.tools import assert_raises +import pytest import sure # noqa from moto import mock_elb, mock_ec2, mock_elb_deprecated, mock_ec2_deprecated @@ -123,7 +123,7 @@ def test_create_and_delete_boto3_support(): def test_create_load_balancer_with_no_listeners_defined(): client = boto3.client("elb", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_load_balancer( LoadBalancerName="my-lb", Listeners=[], @@ -180,7 +180,7 @@ def test_apply_security_groups_to_load_balancer(): assert balancer["SecurityGroups"] == [security_group.id] # Using a not-real security group raises an error - with assert_raises(ClientError) as error: + with pytest.raises(ClientError) as error: response = client.apply_security_groups_to_load_balancer( LoadBalancerName="my-lb", SecurityGroups=["not-really-a-security-group"] ) @@ -255,7 +255,7 @@ def test_create_and_delete_listener_boto3_support(): balancer["ListenerDescriptions"][1]["Listener"]["InstancePort"].should.equal(8443) # Creating this listener with an conflicting definition throws error - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_load_balancer_listeners( LoadBalancerName="my-lb", Listeners=[ diff --git a/tests/test_elbv2/__init__.py b/tests/test_elbv2/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_elbv2/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_elbv2/test_elbv2.py b/tests/test_elbv2/test_elbv2.py index 5ab85284d..6ff48095d 100644 --- a/tests/test_elbv2/test_elbv2.py +++ b/tests/test_elbv2/test_elbv2.py @@ -4,7 +4,7 @@ import os import boto3 import botocore from botocore.exceptions import ClientError, ParamValidationError -from nose.tools import assert_raises +import pytest import sure # noqa from moto import mock_elbv2, mock_ec2, mock_acm @@ -96,9 +96,9 @@ def test_describe_load_balancers(): response = conn.describe_load_balancers(Names=["my-lb"]) response.get("LoadBalancers")[0].get("LoadBalancerName").should.equal("my-lb") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_load_balancers(LoadBalancerArns=["not-a/real/arn"]) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_load_balancers(Names=["nope"]) @@ -132,7 +132,7 @@ def test_add_remove_tags(): lbs.should.have.length_of(1) lb = lbs[0] - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.add_tags(ResourceArns=["missing-arn"], Tags=[{"Key": "a", "Value": "b"}]) conn.add_tags( @@ -274,7 +274,7 @@ def test_create_target_group_and_listeners(): load_balancer_arn = response.get("LoadBalancers")[0].get("LoadBalancerArn") # Can't create a target group with an invalid protocol - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_target_group( Name="a-target", Protocol="HTTP", @@ -389,7 +389,7 @@ def test_create_target_group_and_listeners(): # Try to delete the target group and it fails because there's a # listener referencing it - with assert_raises(ClientError) as e: + 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( @@ -477,7 +477,7 @@ def test_create_invalid_target_group(): # Fail to create target group with name which length is 33 long_name = "A" * 33 - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_target_group( Name=long_name, Protocol="HTTP", @@ -495,7 +495,7 @@ def test_create_invalid_target_group(): invalid_names = ["-name", "name-", "-name-", "example.com", "test@test", "Na--me"] for name in invalid_names: - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_target_group( Name=name, Protocol="HTTP", @@ -941,7 +941,7 @@ def test_handle_listener_rules(): load_balancer_arn = response.get("LoadBalancers")[0].get("LoadBalancerArn") # Can't create a target group with an invalid protocol - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_target_group( Name="a-target", Protocol="HTTP", @@ -1032,7 +1032,7 @@ def test_handle_listener_rules(): ) # test for PriorityInUse - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=priority, @@ -1079,11 +1079,11 @@ def test_handle_listener_rules(): ) # test for invalid describe rule request - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_rules() - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_rules(RuleArns=[]) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_rules( ListenerArn=http_listener_arn, RuleArns=[first_rule["RuleArn"]] ) @@ -1125,7 +1125,7 @@ def test_handle_listener_rules(): } ] ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.set_rule_priorities( RulePriorities=[ {"RuleArn": first_rule["RuleArn"], "Priority": 999}, @@ -1141,7 +1141,7 @@ def test_handle_listener_rules(): # test for invalid action type safe_priority = 2 - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=safe_priority, @@ -1160,7 +1160,7 @@ def test_handle_listener_rules(): # test for invalid action type safe_priority = 2 invalid_target_group_arn = target_group.get("TargetGroupArn") + "x" - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=safe_priority, @@ -1173,7 +1173,7 @@ def test_handle_listener_rules(): # test for invalid condition field_name safe_priority = 2 - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=safe_priority, @@ -1188,7 +1188,7 @@ def test_handle_listener_rules(): # test for emptry condition value safe_priority = 2 - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=safe_priority, @@ -1203,7 +1203,7 @@ def test_handle_listener_rules(): # test for multiple condition value safe_priority = 2 - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_rule( ListenerArn=http_listener_arn, Priority=safe_priority, @@ -1260,7 +1260,7 @@ def test_describe_invalid_target_group(): ) # Check error raises correctly - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.describe_target_groups(Names=["invalid"]) @@ -1358,7 +1358,7 @@ def test_set_ip_address_type(): arn = response["LoadBalancers"][0]["LoadBalancerArn"] # Internal LBs cant be dualstack yet - with assert_raises(ClientError): + with pytest.raises(ClientError): client.set_ip_address_type(LoadBalancerArn=arn, IpAddressType="dualstack") # Create internet facing one @@ -1410,7 +1410,7 @@ def test_set_security_groups(): resp = client.describe_load_balancers(LoadBalancerArns=[arn]) len(resp["LoadBalancers"][0]["SecurityGroups"]).should.equal(2) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.set_security_groups(LoadBalancerArn=arn, SecurityGroups=["non_existent"]) @@ -1451,11 +1451,11 @@ def test_set_subnets(): len(resp["LoadBalancers"][0]["AvailabilityZones"]).should.equal(3) # Only 1 AZ - with assert_raises(ClientError): + with pytest.raises(ClientError): client.set_subnets(LoadBalancerArn=arn, Subnets=[subnet1.id]) # Multiple subnets in same AZ - with assert_raises(ClientError): + with pytest.raises(ClientError): client.set_subnets( LoadBalancerArn=arn, Subnets=[subnet1.id, subnet2.id, subnet2.id] ) @@ -1644,7 +1644,7 @@ def test_modify_listener_http_to_https(): listener.certificate.should.equal(yahoo_arn) # No default cert - with assert_raises(ClientError): + with pytest.raises(ClientError): client.modify_listener( ListenerArn=listener_arn, Port=443, @@ -1655,7 +1655,7 @@ def test_modify_listener_http_to_https(): ) # Bad cert - with assert_raises(ClientError): + with pytest.raises(ClientError): client.modify_listener( ListenerArn=listener_arn, Port=443, @@ -1884,7 +1884,7 @@ def test_fixed_response_action_listener_rule_validates_status_code(): "MessageBody": "This page does not exist", }, } - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): conn.create_listener( LoadBalancerArn=load_balancer_arn, Protocol="HTTP", @@ -1934,7 +1934,7 @@ def test_fixed_response_action_listener_rule_validates_status_code(): "MessageBody": "This page does not exist", }, } - with assert_raises(ParamValidationError): + with pytest.raises(ParamValidationError): conn.create_listener( LoadBalancerArn=load_balancer_arn, Protocol="HTTP", @@ -1951,7 +1951,7 @@ def test_fixed_response_action_listener_rule_validates_status_code(): }, } - with assert_raises(ClientError) as invalid_status_code_exception: + with pytest.raises(ClientError) as invalid_status_code_exception: conn.create_listener( LoadBalancerArn=load_balancer_arn, Protocol="HTTP", @@ -1998,7 +1998,7 @@ def test_fixed_response_action_listener_rule_validates_content_type(): "StatusCode": "200", }, } - with assert_raises(ClientError) as invalid_content_type_exception: + with pytest.raises(ClientError) as invalid_content_type_exception: conn.create_listener( LoadBalancerArn=load_balancer_arn, Protocol="HTTP", diff --git a/tests/test_emr/__init__.py b/tests/test_emr/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_emr/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_emr/test_emr_boto3.py b/tests/test_emr/test_emr_boto3.py index af6939f80..a3308e3fe 100644 --- a/tests/test_emr/test_emr_boto3.py +++ b/tests/test_emr/test_emr_boto3.py @@ -9,7 +9,7 @@ import pytz import six import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_emr @@ -395,7 +395,7 @@ def test_run_job_flow(): @mock_emr def test_run_job_flow_with_invalid_params(): client = boto3.client("emr", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: # cannot set both AmiVersion and ReleaseLabel args = deepcopy(run_job_flow_args) args["AmiVersion"] = "2.4" @@ -592,7 +592,7 @@ def _patch_cluster_id_placeholder_in_autoscaling_policy( def test_run_job_flow_with_custom_ami(): client = boto3.client("emr", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: # CustomAmiId available in Amazon EMR 5.7.0 and later args = deepcopy(run_job_flow_args) args["CustomAmiId"] = "MyEmrCustomId" @@ -601,7 +601,7 @@ def test_run_job_flow_with_custom_ami(): ex.exception.response["Error"]["Code"].should.equal("ValidationException") ex.exception.response["Error"]["Message"].should.equal("Custom AMI is not allowed") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: args = deepcopy(run_job_flow_args) args["CustomAmiId"] = "MyEmrCustomId" args["AmiVersion"] = "3.8.1" @@ -611,7 +611,7 @@ def test_run_job_flow_with_custom_ami(): "Custom AMI is not supported in this version of EMR" ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: # AMI version and release label exception raises before CustomAmi exception args = deepcopy(run_job_flow_args) args["CustomAmiId"] = "MyEmrCustomId" diff --git a/tests/test_events/__init__.py b/tests/test_events/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_events/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_events/test_events.py b/tests/test_events/test_events.py index b65171603..4b5bbd4cb 100644 --- a/tests/test_events/test_events.py +++ b/tests/test_events/test_events.py @@ -6,7 +6,7 @@ import boto3 import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto.core import ACCOUNT_ID from moto.core.exceptions import JsonRESTError @@ -331,7 +331,7 @@ def test_put_events(): response["FailedEntryCount"].should.equal(0) response["Entries"].should.have.length_of(1) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.put_events(Entries=[event] * 20) diff --git a/tests/test_glacier/__init__.py b/tests/test_glacier/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_glacier/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_glue/test_datacatalog.py b/tests/test_glue/test_datacatalog.py index bc68b48f6..ac63932ef 100644 --- a/tests/test_glue/test_datacatalog.py +++ b/tests/test_glue/test_datacatalog.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals import sure # noqa import re -from nose.tools import assert_raises +import pytest import boto3 from botocore.client import ClientError @@ -32,7 +32,7 @@ def test_create_database_already_exists(): database_name = "cantcreatethisdatabasetwice" helpers.create_database(client, database_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.create_database(client, database_name) exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") @@ -43,7 +43,7 @@ def test_get_database_not_exits(): client = boto3.client("glue", region_name="us-east-1") database_name = "nosuchdatabase" - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_database(client, database_name) exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -102,7 +102,7 @@ def test_create_table_already_exists(): table_name = "cantcreatethistabletwice" helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.create_table(client, database_name, table_name) exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") @@ -192,7 +192,7 @@ def test_get_table_version_not_found(): helpers.create_database(client, database_name) helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_table_version(client, database_name, "myfirsttable", "20") exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -207,7 +207,7 @@ def test_get_table_version_invalid_input(): helpers.create_database(client, database_name) helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + 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") @@ -219,7 +219,7 @@ def test_get_table_not_exits(): database_name = "myspecialdatabase" helpers.create_database(client, database_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, "myfirsttable") exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -233,7 +233,7 @@ def test_get_table_when_database_not_exits(): client = boto3.client("glue", region_name="us-east-1") database_name = "nosuchdatabase" - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, "myfirsttable") exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -256,7 +256,7 @@ def test_delete_table(): result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) # confirm table is deleted - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, table_name) exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -281,7 +281,7 @@ def test_batch_delete_table(): result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) # confirm table is deleted - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_table(client, database_name, table_name) exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -350,7 +350,7 @@ def test_create_partition_already_exist(): helpers.create_partition(client, database_name, table_name, values=values) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.create_partition(client, database_name, table_name, values=values) exc.exception.response["Error"]["Code"].should.equal("AlreadyExistsException") @@ -366,7 +366,7 @@ def test_get_partition_not_found(): helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_partition(client, database_name, table_name, values) exc.exception.response["Error"]["Code"].should.equal("EntityNotFoundException") @@ -542,7 +542,7 @@ def test_update_partition_not_found_moving(): helpers.create_database(client, database_name) helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.update_partition( client, database_name, @@ -565,7 +565,7 @@ def test_update_partition_not_found_change_in_place(): helpers.create_database(client, database_name) helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.update_partition( client, database_name, table_name, old_values=values, values=values ) @@ -588,7 +588,7 @@ def test_update_partition_cannot_overwrite(): helpers.create_partition(client, database_name, table_name, values=values[0]) helpers.create_partition(client, database_name, table_name, values=values[1]) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.update_partition( client, database_name, table_name, old_values=values[0], values=values[1] ) @@ -648,7 +648,7 @@ def test_update_partition_move(): columns=[{"Name": "country", "Type": "string"}], ) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: helpers.get_partition(client, database_name, table_name, values) # Old partition shouldn't exist anymore @@ -697,7 +697,7 @@ def test_delete_partition_bad_partition(): helpers.create_database(client, database_name) helpers.create_table(client, database_name, table_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: client.delete_partition( DatabaseName=database_name, TableName=table_name, PartitionValues=values ) diff --git a/tests/test_iam/__init__.py b/tests/test_iam/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_iam/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_iam/test_iam.py b/tests/test_iam/test_iam.py index 7db2f0162..d63e1777f 100644 --- a/tests/test_iam/test_iam.py +++ b/tests/test_iam/test_iam.py @@ -13,8 +13,7 @@ from moto import mock_config, mock_iam, mock_iam_deprecated, settings from moto.core import ACCOUNT_ID from moto.iam.models import aws_managed_policies from moto.backends import get_backend -from nose.tools import assert_raises, assert_equals -from nose.tools import raises +import pytest from datetime import datetime from tests.helpers import requires_boto_gte @@ -93,7 +92,7 @@ def test_get_all_server_certs(): def test_get_server_cert_doesnt_exist(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_server_certificate("NonExistant") @@ -128,14 +127,14 @@ def test_delete_server_cert(): conn.upload_server_cert("certname", "certbody", "privatekey") conn.get_server_certificate("certname") conn.delete_server_cert("certname") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_server_certificate("certname") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.delete_server_cert("certname") @mock_iam_deprecated() -@raises(BotoServerError) +@pytest.mark.xfail(raises=BotoServerError) def test_get_role__should_throw__when_role_does_not_exist(): conn = boto.connect_iam() @@ -143,7 +142,7 @@ def test_get_role__should_throw__when_role_does_not_exist(): @mock_iam_deprecated() -@raises(BotoServerError) +@pytest.mark.xfail(raises=BotoServerError) def test_get_instance_profile__should_throw__when_instance_profile_does_not_exist(): conn = boto.connect_iam() @@ -181,7 +180,7 @@ def test_create_role_and_instance_profile(): def test_create_instance_profile_should_throw_when_name_is_not_unique(): conn = boto3.client("iam", region_name="us-east-1") conn.create_instance_profile(InstanceProfileName="unique-instance-profile") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_instance_profile(InstanceProfileName="unique-instance-profile") @@ -214,13 +213,13 @@ def test_delete_instance_profile(): conn.add_role_to_instance_profile( InstanceProfileName="my-profile", RoleName="my-role" ) - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_instance_profile(InstanceProfileName="my-profile") conn.remove_role_from_instance_profile( InstanceProfileName="my-profile", RoleName="my-role" ) conn.delete_instance_profile(InstanceProfileName="my-profile") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): profile = conn.get_instance_profile(InstanceProfileName="my-profile") @@ -253,7 +252,7 @@ def test_update_login_profile(): def test_delete_role(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.delete_role(RoleName="my-role") # Test deletion failure with a managed policy @@ -264,12 +263,12 @@ def test_delete_role(): PolicyName="my-managed-policy", PolicyDocument=MOCK_POLICY ) conn.attach_role_policy(PolicyArn=response["Policy"]["Arn"], RoleName="my-role") - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_role(RoleName="my-role") conn.detach_role_policy(PolicyArn=response["Policy"]["Arn"], RoleName="my-role") conn.delete_policy(PolicyArn=response["Policy"]["Arn"]) conn.delete_role(RoleName="my-role") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_role(RoleName="my-role") # Test deletion failure with an inline policy @@ -279,11 +278,11 @@ def test_delete_role(): conn.put_role_policy( RoleName="my-role", PolicyName="my-role-policy", PolicyDocument=MOCK_POLICY ) - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_role(RoleName="my-role") conn.delete_role_policy(RoleName="my-role", PolicyName="my-role-policy") conn.delete_role(RoleName="my-role") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_role(RoleName="my-role") # Test deletion failure with attachment to an instance profile @@ -294,13 +293,13 @@ def test_delete_role(): conn.add_role_to_instance_profile( InstanceProfileName="my-profile", RoleName="my-role" ) - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_role(RoleName="my-role") conn.remove_role_from_instance_profile( InstanceProfileName="my-profile", RoleName="my-role" ) conn.delete_role(RoleName="my-role") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_role(RoleName="my-role") # Test deletion with no conflicts @@ -308,7 +307,7 @@ def test_delete_role(): RoleName="my-role", AssumeRolePolicyDocument="some policy", Path="/my-path/" ) conn.delete_role(RoleName="my-role") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_role(RoleName="my-role") @@ -389,7 +388,7 @@ def test_list_role_policies(): role.policy_names.should.have.length_of(1) role.policy_names[0].should.equal("test policy 2") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.delete_role_policy("my-role", "test policy") @@ -412,7 +411,7 @@ def test_get_role_policy(): conn.create_role( RoleName="my-role", AssumeRolePolicyDocument="some policy", Path="my-path" ) - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_role_policy(RoleName="my-role", PolicyName="does-not-exist") @@ -442,7 +441,7 @@ def test_create_policy_already_exists(): response = conn.create_policy( PolicyName="TestCreatePolicy", PolicyDocument=MOCK_POLICY ) - with assert_raises(conn.exceptions.EntityAlreadyExistsException) as ex: + with pytest.raises(conn.exceptions.EntityAlreadyExistsException) as ex: response = conn.create_policy( PolicyName="TestCreatePolicy", PolicyDocument=MOCK_POLICY ) @@ -467,7 +466,7 @@ def test_delete_policy(): @mock_iam def test_create_policy_versions(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_policy_version( PolicyArn="arn:aws:iam::{}:policy/TestCreatePolicyVersion".format( ACCOUNT_ID @@ -508,7 +507,7 @@ def test_create_many_policy_versions(): ), PolicyDocument=MOCK_POLICY, ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_policy_version( PolicyArn="arn:aws:iam::{}:policy/TestCreateManyPolicyVersions".format( ACCOUNT_ID @@ -639,7 +638,7 @@ def test_get_policy_version(): PolicyArn="arn:aws:iam::{}:policy/TestGetPolicyVersion".format(ACCOUNT_ID), PolicyDocument=MOCK_POLICY, ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.get_policy_version( PolicyArn="arn:aws:iam::{}:policy/TestGetPolicyVersion".format(ACCOUNT_ID), VersionId="v2-does-not-exist", @@ -661,7 +660,7 @@ def test_get_aws_managed_policy_version(): managed_policy_version_create_date = datetime.strptime( "2015-04-09T15:03:43+00:00", "%Y-%m-%dT%H:%M:%S+00:00" ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.get_policy_version( PolicyArn=managed_policy_arn, VersionId="v2-does-not-exist" ) @@ -679,7 +678,7 @@ def test_get_aws_managed_policy_v4_version(): managed_policy_version_create_date = datetime.strptime( "2018-10-08T21:33:45+00:00", "%Y-%m-%dT%H:%M:%S+00:00" ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.get_policy_version( PolicyArn=managed_policy_arn, VersionId="v2-does-not-exist" ) @@ -693,7 +692,7 @@ def test_get_aws_managed_policy_v4_version(): @mock_iam def test_list_policy_versions(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): versions = conn.list_policy_versions( PolicyArn="arn:aws:iam::{}:policy/TestListPolicyVersions".format(ACCOUNT_ID) ) @@ -729,7 +728,7 @@ def test_delete_policy_version(): PolicyArn="arn:aws:iam::{}:policy/TestDeletePolicyVersion".format(ACCOUNT_ID), PolicyDocument=MOCK_POLICY, ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_policy_version( PolicyArn="arn:aws:iam::{}:policy/TestDeletePolicyVersion".format( ACCOUNT_ID @@ -754,7 +753,7 @@ def test_delete_default_policy_version(): PolicyArn="arn:aws:iam::{}:policy/TestDeletePolicyVersion".format(ACCOUNT_ID), PolicyDocument=MOCK_POLICY_2, ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_policy_version( PolicyArn="arn:aws:iam::{}:policy/TestDeletePolicyVersion".format( ACCOUNT_ID @@ -767,14 +766,14 @@ def test_delete_default_policy_version(): def test_create_user(): conn = boto.connect_iam() conn.create_user("my-user") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.create_user("my-user") @mock_iam_deprecated() def test_get_user(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_user("my-user") conn.create_user("my-user") conn.get_user("my-user") @@ -783,13 +782,13 @@ def test_get_user(): @mock_iam() def test_update_user(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.update_user(UserName="my-user") conn.create_user(UserName="my-user") conn.update_user(UserName="my-user", NewPath="/new-path/", NewUserName="new-user") response = conn.get_user(UserName="new-user") response["User"].get("Path").should.equal("/new-path/") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_user(UserName="my-user") @@ -846,11 +845,11 @@ def test_user_policies(): @mock_iam_deprecated() def test_create_login_profile(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.create_login_profile("my-user", "my-pass") conn.create_user("my-user") conn.create_login_profile("my-user", "my-pass") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.create_login_profile("my-user", "my-pass") @@ -858,7 +857,7 @@ def test_create_login_profile(): def test_delete_login_profile(): conn = boto.connect_iam() conn.create_user("my-user") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.delete_login_profile("my-user") conn.create_login_profile("my-user", "my-pass") conn.delete_login_profile("my-user") @@ -867,7 +866,7 @@ def test_delete_login_profile(): @mock_iam def test_create_access_key(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_access_key(UserName="my-user") conn.create_user(UserName="my-user") access_key = conn.create_access_key(UserName="my-user")["AccessKey"] @@ -899,22 +898,19 @@ def test_get_all_access_keys(): conn = boto.connect_iam() conn.create_user("my-user") response = conn.get_all_access_keys("my-user") - assert_equals( + assert \ response["list_access_keys_response"]["list_access_keys_result"][ "access_key_metadata" - ], - [], - ) + ] == [] conn.create_access_key("my-user") response = conn.get_all_access_keys("my-user") - assert_equals( + assert \ sorted( response["list_access_keys_response"]["list_access_keys_result"][ "access_key_metadata" ][0].keys() - ), - sorted(["status", "create_date", "user_name", "access_key_id"]), - ) + ) == \ + sorted(["status", "create_date", "user_name", "access_key_id"]) @mock_iam @@ -922,13 +918,12 @@ def test_list_access_keys(): conn = boto3.client("iam", region_name="us-east-1") conn.create_user(UserName="my-user") response = conn.list_access_keys(UserName="my-user") - assert_equals(response["AccessKeyMetadata"], []) + assert response["AccessKeyMetadata"] == [] access_key = conn.create_access_key(UserName="my-user")["AccessKey"] response = conn.list_access_keys(UserName="my-user") - assert_equals( - sorted(response["AccessKeyMetadata"][0].keys()), - sorted(["Status", "CreateDate", "UserName", "AccessKeyId"]), - ) + assert \ + sorted(response["AccessKeyMetadata"][0].keys()) == \ + sorted(["Status", "CreateDate", "UserName", "AccessKeyId"] conn = boto3.client( "iam", region_name="us-east-1", @@ -936,10 +931,9 @@ def test_list_access_keys(): aws_secret_access_key=access_key["SecretAccessKey"], ) response = conn.list_access_keys() - assert_equals( - sorted(response["AccessKeyMetadata"][0].keys()), - sorted(["Status", "CreateDate", "UserName", "AccessKeyId"]), - ) + assert \ + sorted(response["AccessKeyMetadata"][0].keys()) == \ + sorted(["Status", "CreateDate", "UserName", "AccessKeyId"]) @mock_iam_deprecated() @@ -1188,7 +1182,7 @@ def test_enable_virtual_mfa_device(): @mock_iam_deprecated() def test_delete_user_deprecated(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.delete_user("my-user") conn.create_user("my-user") conn.delete_user("my-user") @@ -1197,7 +1191,7 @@ def test_delete_user_deprecated(): @mock_iam() def test_delete_user(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.delete_user(UserName="my-user") # Test deletion failure with a managed policy @@ -1206,12 +1200,12 @@ def test_delete_user(): PolicyName="my-managed-policy", PolicyDocument=MOCK_POLICY ) conn.attach_user_policy(PolicyArn=response["Policy"]["Arn"], UserName="my-user") - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_user(UserName="my-user") conn.detach_user_policy(PolicyArn=response["Policy"]["Arn"], UserName="my-user") conn.delete_policy(PolicyArn=response["Policy"]["Arn"]) conn.delete_user(UserName="my-user") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_user(UserName="my-user") # Test deletion failure with an inline policy @@ -1219,17 +1213,17 @@ def test_delete_user(): conn.put_user_policy( UserName="my-user", PolicyName="my-user-policy", PolicyDocument=MOCK_POLICY ) - with assert_raises(conn.exceptions.DeleteConflictException): + with pytest.raises(conn.exceptions.DeleteConflictException): conn.delete_user(UserName="my-user") conn.delete_user_policy(UserName="my-user", PolicyName="my-user-policy") conn.delete_user(UserName="my-user") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_user(UserName="my-user") # Test deletion with no conflicts conn.create_user(UserName="my-user") conn.delete_user(UserName="my-user") - with assert_raises(conn.exceptions.NoSuchEntityException): + with pytest.raises(conn.exceptions.NoSuchEntityException): conn.get_user(UserName="my-user") @@ -1259,7 +1253,7 @@ def test_boto3_generate_credential_report(): def test_get_credential_report(): conn = boto.connect_iam() conn.create_user("my-user") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_credential_report() result = conn.generate_credential_report() while ( @@ -1282,7 +1276,7 @@ def test_get_credential_report(): def test_boto3_get_credential_report(): conn = boto3.client("iam", region_name="us-east-1") conn.create_user(UserName="my-user") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.get_credential_report() result = conn.generate_credential_report() while result["State"] != "COMPLETE": @@ -1306,7 +1300,7 @@ def test_boto3_get_credential_report_content(): if not settings.TEST_SERVER_MODE: iam_backend = get_backend("iam")["global"] iam_backend.users[username].access_keys[1].last_used = timestamp - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.get_credential_report() result = conn.generate_credential_report() while result["State"] != "COMPLETE": @@ -1336,7 +1330,7 @@ def test_get_access_key_last_used_when_used(): client = iam.meta.client username = "test-user" iam.create_user(UserName=username) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.get_access_key_last_used(AccessKeyId="non-existent-key-id") create_key_response = client.create_access_key(UserName=username)["AccessKey"] # Set last used date using the IAM backend. Moto currently does not have a mechanism for tracking usage of access keys @@ -1448,12 +1442,12 @@ def test_managed_policy(): "attached_policies" ].should.have.length_of(1) - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.detach_role_policy( "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceRole", role_name ) - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.detach_role_policy("arn:aws:iam::aws:policy/Nonexistent", role_name) @@ -1461,13 +1455,13 @@ def test_managed_policy(): def test_boto3_create_login_profile(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_login_profile(UserName="my-user", Password="Password") conn.create_user(UserName="my-user") conn.create_login_profile(UserName="my-user", Password="Password") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_login_profile(UserName="my-user", Password="Password") @@ -1506,7 +1500,7 @@ def test_update_access_key(): client = iam.meta.client username = "test-user" iam.create_user(UserName=username) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.update_access_key( UserName=username, AccessKeyId="non-existent-key", Status="Inactive" ) @@ -1527,7 +1521,7 @@ def test_get_access_key_last_used_when_unused(): client = iam.meta.client username = "test-user" iam.create_user(UserName=username) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.get_access_key_last_used(AccessKeyId="non-existent-key-id") create_key_response = client.create_access_key(UserName=username)["AccessKey"] resp = client.get_access_key_last_used( @@ -1566,7 +1560,7 @@ def test_get_ssh_public_key(): iam.create_user(UserName=username) public_key = MOCK_CERT - with assert_raises(ClientError): + with pytest.raises(ClientError): client.get_ssh_public_key( UserName=username, SSHPublicKeyId="xxnon-existent-keyxx", Encoding="SSH" ) @@ -1607,7 +1601,7 @@ def test_update_ssh_public_key(): iam.create_user(UserName=username) public_key = MOCK_CERT - with assert_raises(ClientError): + with pytest.raises(ClientError): client.update_ssh_public_key( UserName=username, SSHPublicKeyId="xxnon-existent-keyxx", Status="Inactive" ) @@ -1634,7 +1628,7 @@ def test_delete_ssh_public_key(): iam.create_user(UserName=username) public_key = MOCK_CERT - with assert_raises(ClientError): + with pytest.raises(ClientError): client.delete_ssh_public_key( UserName=username, SSHPublicKeyId="xxnon-existent-keyxx" ) @@ -1827,14 +1821,14 @@ def test_signing_certs(): assert resp["CertificateId"] # Upload a the cert with an invalid body: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.upload_signing_certificate( UserName="testing", CertificateBody="notacert" ) assert ce.exception.response["Error"]["Code"] == "MalformedCertificate" # Upload with an invalid user: - with assert_raises(ClientError): + with pytest.raises(ClientError): client.upload_signing_certificate( UserName="notauser", CertificateBody=MOCK_CERT ) @@ -1844,12 +1838,12 @@ def test_signing_certs(): UserName="testing", CertificateId=cert_id, Status="Inactive" ) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.update_signing_certificate( UserName="notauser", CertificateId=cert_id, Status="Inactive" ) - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.update_signing_certificate( UserName="testing", CertificateId="x" * 32, Status="Inactive" ) @@ -1864,13 +1858,13 @@ def test_signing_certs(): assert resp[0]["CertificateBody"] == MOCK_CERT assert resp[0]["Status"] == "Inactive" # Changed with the update call above. - with assert_raises(ClientError): + with pytest.raises(ClientError): client.list_signing_certificates(UserName="notauser") # Delete: client.delete_signing_certificate(UserName="testing", CertificateId=cert_id) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.delete_signing_certificate(UserName="notauser", CertificateId=cert_id) @@ -1921,7 +1915,7 @@ def test_delete_saml_provider(): conn.create_user(UserName="testing") cert_id = "123456789012345678901234" - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.delete_signing_certificate(UserName="testing", CertificateId=cert_id) assert ce.exception.response["Error"][ @@ -1982,7 +1976,7 @@ def test_create_role_with_tags(): # Test creating tags with invalid values: # With more than 50 tags: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: too_many_tags = list( map(lambda x: {"Key": str(x), "Value": str(x)}, range(0, 51)) ) @@ -1995,7 +1989,7 @@ def test_create_role_with_tags(): ) # With a duplicate tag: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.create_role( RoleName="my-role3", AssumeRolePolicyDocument="{}", @@ -2007,7 +2001,7 @@ def test_create_role_with_tags(): ) # Duplicate tag with different casing: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.create_role( RoleName="my-role3", AssumeRolePolicyDocument="{}", @@ -2019,7 +2013,7 @@ def test_create_role_with_tags(): ) # With a really big key: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.create_role( RoleName="my-role3", AssumeRolePolicyDocument="{}", @@ -2031,7 +2025,7 @@ def test_create_role_with_tags(): ) # With a really big value: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.create_role( RoleName="my-role3", AssumeRolePolicyDocument="{}", @@ -2043,7 +2037,7 @@ def test_create_role_with_tags(): ) # With an invalid character: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.create_role( RoleName="my-role3", AssumeRolePolicyDocument="{}", @@ -2125,7 +2119,7 @@ def test_tag_role(): # Test creating tags with invalid values: # With more than 50 tags: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: too_many_tags = list( map(lambda x: {"Key": str(x), "Value": str(x)}, range(0, 51)) ) @@ -2136,7 +2130,7 @@ def test_tag_role(): ) # With a duplicate tag: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.tag_role( RoleName="my-role", Tags=[{"Key": "0", "Value": ""}, {"Key": "0", "Value": ""}], @@ -2147,7 +2141,7 @@ def test_tag_role(): ) # Duplicate tag with different casing: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.tag_role( RoleName="my-role", Tags=[{"Key": "a", "Value": ""}, {"Key": "A", "Value": ""}], @@ -2158,7 +2152,7 @@ def test_tag_role(): ) # With a really big key: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.tag_role(RoleName="my-role", Tags=[{"Key": "0" * 129, "Value": ""}]) assert ( "Member must have length less than or equal to 128." @@ -2166,7 +2160,7 @@ def test_tag_role(): ) # With a really big value: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.tag_role(RoleName="my-role", Tags=[{"Key": "0", "Value": "0" * 257}]) assert ( "Member must have length less than or equal to 256." @@ -2174,7 +2168,7 @@ def test_tag_role(): ) # With an invalid character: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: conn.tag_role(RoleName="my-role", Tags=[{"Key": "NOWAY!", "Value": ""}]) assert ( "Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+" @@ -2182,7 +2176,7 @@ def test_tag_role(): ) # With a role that doesn't exist: - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.tag_role(RoleName="notarole", Tags=[{"Key": "some", "Value": "value"}]) @@ -2214,7 +2208,7 @@ def test_untag_role(): # Test removing tags with invalid values: # With more than 50 tags: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: 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." @@ -2223,7 +2217,7 @@ def test_untag_role(): assert "tagKeys" in ce.exception.response["Error"]["Message"] # With a really big key: - with assert_raises(ClientError) as ce: + 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." @@ -2232,7 +2226,7 @@ def test_untag_role(): assert "tagKeys" in ce.exception.response["Error"]["Message"] # With an invalid character: - with assert_raises(ClientError) as ce: + 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}_.:/=+\\-@]+" @@ -2241,7 +2235,7 @@ def test_untag_role(): assert "tagKeys" in ce.exception.response["Error"]["Message"] # With a role that doesn't exist: - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.untag_role(RoleName="notarole", TagKeys=["somevalue"]) @@ -2249,7 +2243,7 @@ def test_untag_role(): def test_update_role_description(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_role(RoleName="my-role") conn.create_role( @@ -2264,7 +2258,7 @@ def test_update_role_description(): def test_update_role(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_role(RoleName="my-role") conn.create_role( @@ -2278,7 +2272,7 @@ def test_update_role(): def test_update_role(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_role(RoleName="my-role") conn.create_role( @@ -2292,7 +2286,7 @@ def test_update_role(): def test_update_role_defaults(): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.delete_role(RoleName="my-role") conn.create_role( @@ -2436,12 +2430,12 @@ def test_create_role_with_permissions_boundary(): invalid_boundary_arn = "arn:aws:iam::123456789:not_a_boundary" - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.put_role_permissions_boundary( RoleName="my-role", PermissionsBoundary=invalid_boundary_arn ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_role( RoleName="bad-boundary", AssumeRolePolicyDocument="some policy", @@ -2461,7 +2455,7 @@ def test_create_role_with_same_name_should_fail(): RoleName=test_role_name, AssumeRolePolicyDocument="policy", Description="test" ) # Create the role again, and verify that it fails - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: iam.create_role( RoleName=test_role_name, AssumeRolePolicyDocument="policy", @@ -2479,7 +2473,7 @@ def test_create_policy_with_same_name_should_fail(): test_policy_name = str(uuid4()) policy = iam.create_policy(PolicyName=test_policy_name, PolicyDocument=MOCK_POLICY) # Create the role again, and verify that it fails - with assert_raises(ClientError) as err: + 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( diff --git a/tests/test_iam/test_iam_cloudformation.py b/tests/test_iam/test_iam_cloudformation.py index aa063273f..737e76323 100644 --- a/tests/test_iam/test_iam_cloudformation.py +++ b/tests/test_iam/test_iam_cloudformation.py @@ -2,7 +2,7 @@ import boto3 import yaml import sure # noqa -from nose.tools import assert_raises +import pytest from botocore.exceptions import ClientError from moto import mock_iam, mock_cloudformation, mock_s3, mock_sts @@ -111,7 +111,7 @@ Resources: cf_client.update_stack(StackName=stack_name, TemplateBody=template) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: iam_client.get_user(UserName=original_user_name) e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") @@ -175,7 +175,7 @@ Resources: second_user_name.should.equal(second_provisioned_user["PhysicalResourceId"]) iam_client.get_user(UserName=second_user_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: iam_client.get_user(UserName=first_user_name) e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") @@ -205,7 +205,7 @@ Resources: cf_client.delete_stack(StackName=stack_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: user = iam_client.get_user(UserName=user_name) e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") @@ -235,7 +235,7 @@ Resources: cf_client.delete_stack(StackName=stack_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: user = iam_client.get_user(UserName=user_name) e.exception.response["Error"]["Code"].should.equal("NoSuchEntity") diff --git a/tests/test_iam/test_iam_groups.py b/tests/test_iam/test_iam_groups.py index 64d838e2b..a6bb5f4c0 100644 --- a/tests/test_iam/test_iam_groups.py +++ b/tests/test_iam/test_iam_groups.py @@ -6,7 +6,7 @@ import boto import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from boto.exception import BotoServerError from botocore.exceptions import ClientError from moto import mock_iam, mock_iam_deprecated @@ -29,7 +29,7 @@ MOCK_POLICY = """ def test_create_group(): conn = boto.connect_iam() conn.create_group("my-group") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.create_group("my-group") @@ -38,7 +38,7 @@ def test_get_group(): conn = boto.connect_iam() conn.create_group("my-group") conn.get_group("my-group") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_group("not-group") @@ -77,10 +77,10 @@ def test_get_all_groups(): @mock_iam_deprecated() def test_add_user_to_group(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.add_user_to_group("my-group", "my-user") conn.create_group("my-group") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.add_user_to_group("my-group", "my-user") conn.create_user("my-user") conn.add_user_to_group("my-group", "my-user") @@ -89,11 +89,11 @@ def test_add_user_to_group(): @mock_iam_deprecated() def test_remove_user_from_group(): conn = boto.connect_iam() - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.remove_user_from_group("my-group", "my-user") conn.create_group("my-group") conn.create_user("my-user") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.remove_user_from_group("my-group", "my-user") conn.add_user_to_group("my-group", "my-user") conn.remove_user_from_group("my-group", "my-user") @@ -150,7 +150,7 @@ def test_attach_group_policies(): def test_get_group_policy(): conn = boto.connect_iam() conn.create_group("my-group") - with assert_raises(BotoServerError): + with pytest.raises(BotoServerError): conn.get_group_policy("my-group", "my-policy") conn.put_group_policy("my-group", "my-policy", MOCK_POLICY) diff --git a/tests/test_iam/test_iam_policies.py b/tests/test_iam/test_iam_policies.py index 6348b0cba..dae533827 100644 --- a/tests/test_iam/test_iam_policies.py +++ b/tests/test_iam/test_iam_policies.py @@ -2,7 +2,7 @@ import json import boto3 from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_iam @@ -1624,7 +1624,7 @@ def test_create_policy_with_valid_policy_documents(): @mock_iam def check_create_policy_with_invalid_policy_document(test_case): conn = boto3.client("iam", region_name="us-east-1") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_policy( PolicyName="TestCreatePolicy", PolicyDocument=json.dumps(test_case["document"]), diff --git a/tests/test_iot/__init__.py b/tests/test_iot/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_iot/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_iot/test_iot.py b/tests/test_iot/test_iot.py index e80a12a0f..44b365182 100644 --- a/tests/test_iot/test_iot.py +++ b/tests/test_iot/test_iot.py @@ -6,7 +6,7 @@ import boto3 from moto import mock_iot from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest def generate_thing_group_tree(iot_client, tree_dict, _parent=None): @@ -643,7 +643,7 @@ def test_delete_policy_validation(): client.create_policy(policyName=policy_name, policyDocument=doc) client.attach_principal_policy(policyName=policy_name, principal=cert_arn) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_policy(policyName=policy_name) e.exception.response["Error"]["Message"].should.contain( "The policy cannot be deleted as the policy is attached to one or more principals (name=%s)" @@ -684,7 +684,7 @@ def test_delete_certificate_validation(): client.create_thing(thingName=thing_name) client.attach_thing_principal(thingName=thing_name, principal=cert_arn) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) e.exception.response["Error"]["Message"].should.contain( "Certificate must be deactivated (not ACTIVE) before deletion." @@ -693,7 +693,7 @@ def test_delete_certificate_validation(): res.should.have.key("certificates").which.should.have.length_of(1) client.update_certificate(certificateId=cert_id, newStatus="REVOKED") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) e.exception.response["Error"]["Message"].should.contain( "Things must be detached before deletion (arn: %s)" % cert_arn @@ -702,7 +702,7 @@ def test_delete_certificate_validation(): res.should.have.key("certificates").which.should.have.length_of(1) client.detach_thing_principal(thingName=thing_name, principal=cert_arn) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_certificate(certificateId=cert_id) e.exception.response["Error"]["Message"].should.contain( "Certificate policies must be detached before deletion (arn: %s)" % cert_arn @@ -798,7 +798,7 @@ def test_principal_policy(): res.should.have.key("policies").which.should.have.length_of(0) res = client.list_policy_principals(policyName=policy_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.detach_policy(policyName=policy_name, target=cert_arn) e.exception.response["Error"]["Code"].should.equal("ResourceNotFoundException") diff --git a/tests/test_iotdata/__init__.py b/tests/test_iotdata/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_iotdata/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_iotdata/test_iotdata.py b/tests/test_iotdata/test_iotdata.py index ac0a04244..caebdbde8 100644 --- a/tests/test_iotdata/test_iotdata.py +++ b/tests/test_iotdata/test_iotdata.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import json import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from botocore.exceptions import ClientError from moto import mock_iotdata, mock_iot @@ -17,7 +17,7 @@ def test_basic(): raw_payload = b'{"state": {"desired": {"led": "on"}}}' iot_client.create_thing(thingName=name) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.get_thing_shadow(thingName=name) res = client.update_thing_shadow(thingName=name, payload=raw_payload) @@ -42,7 +42,7 @@ def test_basic(): payload.should.have.key("timestamp") client.delete_thing_shadow(thingName=name) - with assert_raises(ClientError): + with pytest.raises(ClientError): client.get_thing_shadow(thingName=name) @@ -99,7 +99,7 @@ def test_update(): payload.should.have.key("timestamp") raw_payload = b'{"state": {"desired": {"led": "on"}}, "version": 1}' - with assert_raises(ClientError) as ex: + 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") diff --git a/tests/test_kinesis/__init__.py b/tests/test_kinesis/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_kinesis/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_kinesisvideo/__init__.py b/tests/test_kinesisvideo/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_kinesisvideo/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_kinesisvideo/test_kinesisvideo.py b/tests/test_kinesisvideo/test_kinesisvideo.py index de3d9ebbb..abd63bbda 100644 --- a/tests/test_kinesisvideo/test_kinesisvideo.py +++ b/tests/test_kinesisvideo/test_kinesisvideo.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from moto import mock_kinesisvideo from botocore.exceptions import ClientError import json @@ -28,7 +28,7 @@ def test_create_stream_with_same_name(): client.create_stream(StreamName=stream_name, DeviceName=device_name) # cannot create with same stream name - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_stream(StreamName=stream_name, DeviceName=device_name) @@ -43,7 +43,7 @@ def test_describe_stream(): stream_arn = res["StreamARN"] # cannot create with existing stream name - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_stream(StreamName=stream_name, DeviceName=device_name) # stream can be described with name @@ -69,7 +69,7 @@ def test_describe_stream_with_name_not_exist(): stream_name_not_exist = "not-exist-stream" # cannot describe with not exist stream name - with assert_raises(ClientError): + with pytest.raises(ClientError): client.describe_stream(StreamName=stream_name_not_exist) @@ -123,7 +123,7 @@ def test_delete_stream_with_arn_not_exist(): # cannot delete with not exist stream stream_arn_not_exist = stream_2_arn - with assert_raises(ClientError): + with pytest.raises(ClientError): client.delete_stream(StreamARN=stream_arn_not_exist) diff --git a/tests/test_kinesisvideoarchivedmedia/__init__.py b/tests/test_kinesisvideoarchivedmedia/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_kinesisvideoarchivedmedia/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_kms/__init__.py b/tests/test_kms/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_kms/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_kms/test_kms.py b/tests/test_kms/test_kms.py index a04a24a82..64c70078e 100644 --- a/tests/test_kms/test_kms.py +++ b/tests/test_kms/test_kms.py @@ -9,7 +9,7 @@ import six import sure # noqa from boto.exception import JSONResponseError from boto.kms.exceptions import AlreadyExistsException, NotFoundException -from nose.tools import assert_raises +import pytest from parameterized import parameterized from moto.core.exceptions import JsonRESTError from moto.kms.models import KmsBackend @@ -192,10 +192,10 @@ def test_generate_data_key(): response = conn.generate_data_key(key_id=key_id, number_of_bytes=32) # CiphertextBlob must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(response["CiphertextBlob"], validate=True) # Plaintext must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(response["Plaintext"], validate=True) response["KeyId"].should.equal(key_arn) @@ -364,7 +364,7 @@ def test__create_alias__raises_if_reserved_alias(): ] for alias_name in reserved_aliases: - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) ex = err.exception @@ -392,7 +392,7 @@ def test__create_alias__raises_if_wrong_prefix(): create_resp = kms.create_key() key_id = create_resp["KeyMetadata"]["KeyId"] - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.create_alias("wrongprefix/my-alias", key_id) ex = err.exception @@ -415,7 +415,7 @@ def test__create_alias__raises_if_duplicate(): kms.create_alias(alias, key_id) - with assert_raises(AlreadyExistsException) as err: + with pytest.raises(AlreadyExistsException) as err: kms.create_alias(alias, key_id) ex = err.exception @@ -450,7 +450,7 @@ def test__create_alias__raises_if_alias_has_restricted_characters(): ] for alias_name in alias_names_with_restricted_characters: - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) ex = err.exception ex.body["__type"].should.equal("ValidationException") @@ -480,7 +480,7 @@ def test__create_alias__raises_if_alias_has_colon_character(): alias_names_with_restricted_characters = ["alias/my:alias"] for alias_name in alias_names_with_restricted_characters: - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.create_alias(alias_name, key_id) ex = err.exception ex.body["__type"].should.equal("ValidationException") @@ -514,7 +514,7 @@ def test__create_alias__raises_if_target_key_id_is_existing_alias(): kms.create_alias(alias, key_id) - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.create_alias(alias, alias) ex = err.exception @@ -554,7 +554,7 @@ def test__delete_alias(): def test__delete_alias__raises_if_wrong_prefix(): kms = boto.connect_kms() - with assert_raises(JSONResponseError) as err: + with pytest.raises(JSONResponseError) as err: kms.delete_alias("wrongprefix/my-alias") ex = err.exception @@ -572,7 +572,7 @@ def test__delete_alias__raises_if_alias_is_not_found(): kms = boto.kms.connect_to_region(region) alias_name = "alias/unexisting-alias" - with assert_raises(NotFoundException) as err: + with pytest.raises(NotFoundException) as err: kms.delete_alias(alias_name) expected_message_match = r"Alias arn:aws:kms:{region}:[0-9]{{12}}:{alias_name} is not found.".format( diff --git a/tests/test_kms/test_kms_boto3.py b/tests/test_kms/test_kms_boto3.py index c125c0557..53f284575 100644 --- a/tests/test_kms/test_kms_boto3.py +++ b/tests/test_kms/test_kms_boto3.py @@ -10,7 +10,7 @@ import botocore.exceptions import six import sure # noqa from freezegun import freeze_time -from nose.tools import assert_raises +import pytest from parameterized import parameterized from moto import mock_kms @@ -132,7 +132,7 @@ def test_describe_key_via_alias_invalid_alias(key_id): client = boto3.client("kms", region_name="us-east-1") client.create_key(Description="key") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.describe_key(KeyId=key_id) @@ -147,10 +147,10 @@ def test_generate_data_key(): response = kms.generate_data_key(KeyId=key_id, NumberOfBytes=32) # CiphertextBlob must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(response["CiphertextBlob"], validate=True) # Plaintext must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(response["Plaintext"], validate=True) response["KeyId"].should.equal(key_arn) @@ -169,7 +169,7 @@ def test_encrypt(plaintext): response["CiphertextBlob"].should_not.equal(plaintext) # CiphertextBlob must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(response["CiphertextBlob"], validate=True) response["KeyId"].should.equal(key_arn) @@ -188,13 +188,13 @@ def test_decrypt(plaintext): client.create_key(Description="key") # CiphertextBlob must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(encrypt_response["CiphertextBlob"], validate=True) decrypt_response = client.decrypt(CiphertextBlob=encrypt_response["CiphertextBlob"]) # Plaintext must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(decrypt_response["Plaintext"], validate=True) decrypt_response["Plaintext"].should.equal(_get_encoded_value(plaintext)) @@ -216,7 +216,7 @@ def test_decrypt(plaintext): def test_invalid_key_ids(key_id): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.generate_data_key(KeyId=key_id, NumberOfBytes=5) @@ -403,7 +403,7 @@ def test_generate_data_key_invalid_size_params(kwargs): client = boto3.client("kms", region_name="us-east-1") key = client.create_key(Description="generate-data-key-size") - with assert_raises( + with pytest.raises( (botocore.exceptions.ClientError, botocore.exceptions.ParamValidationError) ) as err: client.generate_data_key(KeyId=key["KeyMetadata"]["KeyId"], **kwargs) @@ -423,7 +423,7 @@ def test_generate_data_key_invalid_size_params(kwargs): def test_generate_data_key_invalid_key(key_id): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.generate_data_key(KeyId=key_id, KeySpec="AES_256") @@ -485,7 +485,7 @@ def test_re_encrypt_decrypt(plaintext): ) # CiphertextBlob must NOT be base64-encoded - with assert_raises(Exception): + with pytest.raises(Exception): base64.b64decode(re_encrypt_response["CiphertextBlob"], validate=True) re_encrypt_response["SourceKeyId"].should.equal(key_1_arn) @@ -517,7 +517,7 @@ def test_re_encrypt_to_invalid_destination(): encrypt_response = client.encrypt(KeyId=key_id, Plaintext=b"some plaintext") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.re_encrypt( CiphertextBlob=encrypt_response["CiphertextBlob"], DestinationKeyId="alias/DoesNotExist", @@ -548,7 +548,7 @@ def test_generate_random(number_of_bytes): def test_generate_random_invalid_number_of_bytes(number_of_bytes, error_type): client = boto3.client("kms", region_name="us-west-2") - with assert_raises(error_type): + with pytest.raises(error_type): client.generate_random(NumberOfBytes=number_of_bytes) @@ -556,7 +556,7 @@ def test_generate_random_invalid_number_of_bytes(number_of_bytes, error_type): def test_enable_key_rotation_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.enable_key_rotation(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -564,7 +564,7 @@ def test_enable_key_rotation_key_not_found(): def test_disable_key_rotation_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.disable_key_rotation(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -572,7 +572,7 @@ def test_disable_key_rotation_key_not_found(): def test_enable_key_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.enable_key(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -580,7 +580,7 @@ def test_enable_key_key_not_found(): def test_disable_key_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.disable_key(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -588,7 +588,7 @@ def test_disable_key_key_not_found(): def test_cancel_key_deletion_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.cancel_key_deletion(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -596,7 +596,7 @@ def test_cancel_key_deletion_key_not_found(): def test_schedule_key_deletion_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.schedule_key_deletion(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -604,7 +604,7 @@ def test_schedule_key_deletion_key_not_found(): def test_get_key_rotation_status_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.get_key_rotation_status(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -612,7 +612,7 @@ def test_get_key_rotation_status_key_not_found(): def test_get_key_policy_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.get_key_policy( KeyId="12366f9b-1230-123d-123e-123e6ae60c02", PolicyName="default" ) @@ -622,7 +622,7 @@ def test_get_key_policy_key_not_found(): def test_list_key_policies_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.list_key_policies(KeyId="12366f9b-1230-123d-123e-123e6ae60c02") @@ -630,7 +630,7 @@ def test_list_key_policies_key_not_found(): def test_put_key_policy_key_not_found(): client = boto3.client("kms", region_name="us-east-1") - with assert_raises(client.exceptions.NotFoundException): + with pytest.raises(client.exceptions.NotFoundException): client.put_key_policy( KeyId="00000000-0000-0000-0000-000000000000", PolicyName="default", diff --git a/tests/test_kms/test_utils.py b/tests/test_kms/test_utils.py index 4446635f3..fa402b6b9 100644 --- a/tests/test_kms/test_utils.py +++ b/tests/test_kms/test_utils.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals import sure # noqa -from nose.tools import assert_raises +import pytest from parameterized import parameterized from moto.kms.exceptions import ( @@ -123,7 +123,7 @@ def test_encrypt_decrypt_cycle(encryption_context): def test_encrypt_unknown_key_id(): - with assert_raises(NotFoundException): + with pytest.raises(NotFoundException): encrypt( master_keys={}, key_id="anything", @@ -136,7 +136,7 @@ def test_decrypt_invalid_ciphertext_format(): master_key = Key("nop", "nop", "nop", "nop", "nop") master_key_map = {master_key.id: master_key} - with assert_raises(InvalidCiphertextException): + with pytest.raises(InvalidCiphertextException): decrypt(master_keys=master_key_map, ciphertext_blob=b"", encryption_context={}) @@ -148,7 +148,7 @@ def test_decrypt_unknwown_key_id(): b"some ciphertext" ) - with assert_raises(AccessDeniedException): + with pytest.raises(AccessDeniedException): decrypt(master_keys={}, ciphertext_blob=ciphertext_blob, encryption_context={}) @@ -161,7 +161,7 @@ def test_decrypt_invalid_ciphertext(): b"some ciphertext" ) - with assert_raises(InvalidCiphertextException): + with pytest.raises(InvalidCiphertextException): decrypt( master_keys=master_key_map, ciphertext_blob=ciphertext_blob, @@ -181,7 +181,7 @@ def test_decrypt_invalid_encryption_context(): encryption_context={"some": "encryption", "context": "here"}, ) - with assert_raises(InvalidCiphertextException): + with pytest.raises(InvalidCiphertextException): decrypt( master_keys=master_key_map, ciphertext_blob=ciphertext_blob, diff --git a/tests/test_logs/__init__.py b/tests/test_logs/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_logs/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_logs/test_logs.py b/tests/test_logs/test_logs.py index 648d561aa..f693aeb1e 100644 --- a/tests/test_logs/test_logs.py +++ b/tests/test_logs/test_logs.py @@ -5,8 +5,8 @@ import six from botocore.exceptions import ClientError from moto import mock_logs, settings -from nose.tools import assert_raises -from nose import SkipTest +import pytest +from unittest import SkipTest _logs_region = "us-east-1" if settings.TEST_SERVER_MODE else "us-west-2" @@ -28,13 +28,13 @@ def test_exceptions(): log_group_name = "dummy" log_stream_name = "dummp-stream" conn.create_log_group(logGroupName=log_group_name) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_log_group(logGroupName=log_group_name) # descrine_log_groups is not implemented yet conn.create_log_stream(logGroupName=log_group_name, logStreamName=log_stream_name) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.create_log_stream( logGroupName=log_group_name, logStreamName=log_stream_name ) @@ -45,7 +45,7 @@ def test_exceptions(): logEvents=[{"timestamp": 0, "message": "line"}], ) - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.put_log_events( logGroupName=log_group_name, logStreamName="invalid-stream", @@ -117,7 +117,7 @@ def test_filter_logs_raises_if_filter_pattern(): conn.put_log_events( logGroupName=log_group_name, logStreamName=log_stream_name, logEvents=messages ) - with assert_raises(NotImplementedError): + with pytest.raises(NotImplementedError): conn.filter_log_events( logGroupName=log_group_name, logStreamNames=[log_stream_name], @@ -332,7 +332,7 @@ def test_get_log_events_errors(): client.create_log_group(logGroupName=log_group_name) client.create_log_stream(logGroupName=log_group_name, logStreamName=log_stream_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_log_events( logGroupName=log_group_name, logStreamName=log_stream_name, @@ -346,7 +346,7 @@ def test_get_log_events_errors(): "The specified nextToken is invalid." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_log_events( logGroupName=log_group_name, logStreamName=log_stream_name, @@ -447,7 +447,7 @@ def test_describe_subscription_filters_errors(): client = boto3.client("logs", "us-east-1") # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.describe_subscription_filters(logGroupName="not-existing-log-group",) # then diff --git a/tests/test_managedblockchain/test_managedblockchain_proposalvotes.py b/tests/test_managedblockchain/test_managedblockchain_proposalvotes.py index eda728398..e8f4043d5 100644 --- a/tests/test_managedblockchain/test_managedblockchain_proposalvotes.py +++ b/tests/test_managedblockchain/test_managedblockchain_proposalvotes.py @@ -5,7 +5,7 @@ import os import boto3 import sure # noqa from freezegun import freeze_time -from nose import SkipTest +from unittest import SkipTest from moto import mock_managedblockchain, settings from . import helpers diff --git a/tests/test_opsworks/__init__.py b/tests/test_opsworks/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_opsworks/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_organizations/test_organizations_boto3.py b/tests/test_organizations/test_organizations_boto3.py index 65f964082..1d2ef3715 100644 --- a/tests/test_organizations/test_organizations_boto3.py +++ b/tests/test_organizations/test_organizations_boto3.py @@ -7,7 +7,7 @@ import json import six import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_organizations from moto.core import ACCOUNT_ID @@ -61,7 +61,7 @@ def test_describe_organization(): @mock_organizations def test_describe_organization_exception(): client = boto3.client("organizations", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_organization() ex = e.exception ex.operation_name.should.equal("DescribeOrganization") @@ -110,7 +110,7 @@ def test_describe_organizational_unit(): def test_describe_organizational_unit_exception(): client = boto3.client("organizations", region_name="us-east-1") org = client.create_organization(FeatureSet="ALL")["Organization"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_organizational_unit( OrganizationalUnitId=utils.make_random_root_id() ) @@ -139,7 +139,7 @@ def test_list_organizational_units_for_parent(): @mock_organizations def test_list_organizational_units_for_parent_exception(): client = boto3.client("organizations", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_organizational_units_for_parent( ParentId=utils.make_random_root_id() ) @@ -193,7 +193,7 @@ def test_describe_account(): @mock_organizations def test_describe_account_exception(): client = boto3.client("organizations", region_name="us-east-1") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_account(AccountId=utils.make_random_account_id()) ex = e.exception ex.operation_name.should.equal("DescribeAccount") @@ -335,7 +335,7 @@ def test_list_children_exception(): client = boto3.client("organizations", region_name="us-east-1") org = client.create_organization(FeatureSet="ALL")["Organization"] root_id = client.list_roots()["Roots"][0]["Id"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_children( ParentId=utils.make_random_root_id(), ChildType="ACCOUNT" ) @@ -343,7 +343,7 @@ def test_list_children_exception(): ex.operation_name.should.equal("ListChildren") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("ParentNotFoundException") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_children(ParentId=root_id, ChildType="BLEE") ex = e.exception ex.operation_name.should.equal("ListChildren") @@ -387,7 +387,7 @@ def test_create_policy_errors(): # invalid policy type # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_policy( Content=json.dumps(policy_doc01), Description="moto", @@ -427,13 +427,13 @@ def test_describe_policy_exception(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL")["Organization"] policy_id = "p-47fhe9s3" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_policy(PolicyId=policy_id) ex = e.exception ex.operation_name.should.equal("DescribePolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.describe_policy(PolicyId="meaninglessstring") ex = e.exception ex.operation_name.should.equal("DescribePolicy") @@ -626,7 +626,7 @@ def test_delete_policy_exception(): client = boto3.client("organizations", region_name="us-east-1") org = client.create_organization(FeatureSet="ALL")["Organization"] non_existent_policy_id = utils.make_random_policy_id() - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.delete_policy(PolicyId=non_existent_policy_id) ex = e.exception ex.operation_name.should.equal("DeletePolicy") @@ -642,7 +642,7 @@ def test_delete_policy_exception(): )["Policy"]["PolicySummary"]["Id"] root_id = client.list_roots()["Roots"][0]["Id"] client.attach_policy(PolicyId=policy_id, TargetId=root_id) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.delete_policy(PolicyId=policy_id) ex = e.exception ex.operation_name.should.equal("DeletePolicy") @@ -663,7 +663,7 @@ def test_attach_policy_exception(): Name="MockServiceControlPolicy", Type="SERVICE_CONTROL_POLICY", )["Policy"]["PolicySummary"]["Id"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=root_id) ex = e.exception ex.operation_name.should.equal("AttachPolicy") @@ -671,7 +671,7 @@ def test_attach_policy_exception(): ex.response["Error"]["Message"].should.contain( "OrganizationalUnitNotFoundException" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=ou_id) ex = e.exception ex.operation_name.should.equal("AttachPolicy") @@ -679,7 +679,7 @@ def test_attach_policy_exception(): ex.response["Error"]["Message"].should.contain( "OrganizationalUnitNotFoundException" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.attach_policy(PolicyId=policy_id, TargetId=account_id) ex = e.exception ex.operation_name.should.equal("AttachPolicy") @@ -688,7 +688,7 @@ def test_attach_policy_exception(): ex.response["Error"]["Message"].should.equal( "You specified an account that doesn't exist." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.attach_policy( PolicyId=policy_id, TargetId="meaninglessstring" ) @@ -729,7 +729,7 @@ def test_update_policy_exception(): client = boto3.client("organizations", region_name="us-east-1") org = client.create_organization(FeatureSet="ALL")["Organization"] non_existent_policy_id = utils.make_random_policy_id() - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.update_policy(PolicyId=non_existent_policy_id) ex = e.exception ex.operation_name.should.equal("UpdatePolicy") @@ -791,7 +791,7 @@ def test_list_policies_for_target_exception(): root_id = client.list_roots()["Roots"][0]["Id"] ou_id = "ou-gi99-i7r8eh2i2" account_id = "126644886543" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_policies_for_target( TargetId=ou_id, Filter="SERVICE_CONTROL_POLICY" ) @@ -801,7 +801,7 @@ def test_list_policies_for_target_exception(): ex.response["Error"]["Message"].should.contain( "OrganizationalUnitNotFoundException" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_policies_for_target( TargetId=account_id, Filter="SERVICE_CONTROL_POLICY" ) @@ -812,7 +812,7 @@ def test_list_policies_for_target_exception(): ex.response["Error"]["Message"].should.equal( "You specified an account that doesn't exist." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_policies_for_target( TargetId="meaninglessstring", Filter="SERVICE_CONTROL_POLICY" ) @@ -824,7 +824,7 @@ def test_list_policies_for_target_exception(): # not existing root # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_policies_for_target( TargetId="r-0000", Filter="SERVICE_CONTROL_POLICY" ) @@ -840,7 +840,7 @@ def test_list_policies_for_target_exception(): # invalid policy type # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_policies_for_target(TargetId=root_id, Filter="MOTO") # then @@ -887,13 +887,13 @@ def test_list_targets_for_policy_exception(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL")["Organization"] policy_id = "p-47fhe9s3" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_targets_for_policy(PolicyId=policy_id) ex = e.exception ex.operation_name.should.equal("ListTargetsForPolicy") ex.response["Error"]["Code"].should.equal("400") ex.response["Error"]["Message"].should.contain("PolicyNotFoundException") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: response = client.list_targets_for_policy(PolicyId="meaninglessstring") ex = e.exception ex.operation_name.should.equal("ListTargetsForPolicy") @@ -929,7 +929,7 @@ def test_tag_resource_errors(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.tag_resource( ResourceId="000000000000", Tags=[{"Key": "key", "Value": "value"},], ) @@ -961,7 +961,7 @@ def test_list_tags_for_resource_errors(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_tags_for_resource(ResourceId="000000000000") ex = e.exception ex.operation_name.should.equal("ListTagsForResource") @@ -998,7 +998,7 @@ def test_untag_resource_errors(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.untag_resource(ResourceId="000000000000", TagKeys=["key"]) ex = e.exception ex.operation_name.should.equal("UntagResource") @@ -1035,7 +1035,7 @@ def test_update_organizational_unit_duplicate_error(): response = client.create_organizational_unit(ParentId=root_id, Name=ou_name) validate_organizational_unit(org, response) response["OrganizationalUnit"]["Name"].should.equal(ou_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.update_organizational_unit( OrganizationalUnitId=response["OrganizationalUnit"]["Id"], Name=ou_name ) @@ -1081,7 +1081,7 @@ def test_enable_aws_service_access(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.enable_aws_service_access(ServicePrincipal="moto.amazonaws.com") ex = e.exception ex.operation_name.should.equal("EnableAWSServiceAccess") @@ -1142,7 +1142,7 @@ def test_disable_aws_service_access_errors(): client = boto3.client("organizations", region_name="us-east-1") client.create_organization(FeatureSet="ALL") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.disable_aws_service_access(ServicePrincipal="moto.amazonaws.com") ex = e.exception ex.operation_name.should.equal("DisableAWSServiceAccess") @@ -1199,7 +1199,7 @@ def test_register_delegated_administrator_errors(): # register master Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_delegated_administrator( AccountId=ACCOUNT_ID, ServicePrincipal="ssm.amazonaws.com" ) @@ -1215,7 +1215,7 @@ def test_register_delegated_administrator_errors(): # register not existing Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_delegated_administrator( AccountId="000000000000", ServicePrincipal="ssm.amazonaws.com" ) @@ -1231,7 +1231,7 @@ def test_register_delegated_administrator_errors(): # register not supported service # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_delegated_administrator( AccountId=account_id, ServicePrincipal="moto.amazonaws.com" ) @@ -1247,7 +1247,7 @@ def test_register_delegated_administrator_errors(): # register service again # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.register_delegated_administrator( AccountId=account_id, ServicePrincipal="ssm.amazonaws.com" ) @@ -1319,7 +1319,7 @@ def test_list_delegated_administrators_erros(): # list not supported service # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_delegated_administrators(ServicePrincipal="moto.amazonaws.com") # then @@ -1365,7 +1365,7 @@ def test_list_delegated_services_for_account_erros(): # list services for not existing Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_delegated_services_for_account(AccountId="000000000000") # then @@ -1379,7 +1379,7 @@ def test_list_delegated_services_for_account_erros(): # list services for not registered Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.list_delegated_services_for_account(AccountId=ACCOUNT_ID) # then @@ -1425,7 +1425,7 @@ def test_deregister_delegated_administrator_erros(): # deregister master Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.deregister_delegated_administrator( AccountId=ACCOUNT_ID, ServicePrincipal="ssm.amazonaws.com" ) @@ -1441,7 +1441,7 @@ def test_deregister_delegated_administrator_erros(): # deregister not existing Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.deregister_delegated_administrator( AccountId="000000000000", ServicePrincipal="ssm.amazonaws.com" ) @@ -1457,7 +1457,7 @@ def test_deregister_delegated_administrator_erros(): # deregister not registered Account # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.deregister_delegated_administrator( AccountId=account_id, ServicePrincipal="ssm.amazonaws.com" ) @@ -1478,7 +1478,7 @@ def test_deregister_delegated_administrator_erros(): # deregister not registered service # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.deregister_delegated_administrator( AccountId=account_id, ServicePrincipal="guardduty.amazonaws.com" ) @@ -1529,7 +1529,7 @@ def test_enable_policy_type_errors(): # not existing root # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.enable_policy_type( RootId="r-0000", PolicyType="AISERVICES_OPT_OUT_POLICY" ) @@ -1545,7 +1545,7 @@ def test_enable_policy_type_errors(): # enable policy again ('SERVICE_CONTROL_POLICY' is enabled by default) # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.enable_policy_type(RootId=root_id, PolicyType="SERVICE_CONTROL_POLICY") # then @@ -1559,7 +1559,7 @@ def test_enable_policy_type_errors(): # invalid policy type # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.enable_policy_type(RootId=root_id, PolicyType="MOTO") # then @@ -1604,7 +1604,7 @@ def test_disable_policy_type_errors(): # not existing root # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.disable_policy_type( RootId="r-0000", PolicyType="AISERVICES_OPT_OUT_POLICY" ) @@ -1620,7 +1620,7 @@ def test_disable_policy_type_errors(): # disable not enabled policy # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.disable_policy_type( RootId=root_id, PolicyType="AISERVICES_OPT_OUT_POLICY" ) @@ -1636,7 +1636,7 @@ def test_disable_policy_type_errors(): # invalid policy type # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.disable_policy_type(RootId=root_id, PolicyType="MOTO") # then diff --git a/tests/test_packages/__init__.py b/tests/test_packages/__init__.py index 05b1d476b..01fe5ab1f 100644 --- a/tests/test_packages/__init__.py +++ b/tests/test_packages/__init__.py @@ -6,4 +6,3 @@ import logging logging.getLogger("boto").setLevel(logging.CRITICAL) logging.getLogger("boto3").setLevel(logging.CRITICAL) logging.getLogger("botocore").setLevel(logging.CRITICAL) -logging.getLogger("nose").setLevel(logging.CRITICAL) diff --git a/tests/test_polly/__init__.py b/tests/test_polly/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_polly/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_polly/test_polly.py b/tests/test_polly/test_polly.py index 5428cdeb7..6c99d0538 100644 --- a/tests/test_polly/test_polly.py +++ b/tests/test_polly/test_polly.py @@ -3,19 +3,19 @@ from __future__ import unicode_literals from botocore.exceptions import ClientError import boto3 import sure # noqa -from nose.tools import assert_raises +import pytest from moto import mock_polly # Polly only available in a few regions DEFAULT_REGION = "eu-west-1" LEXICON_XML = """ - W3C diff --git a/tests/test_ram/test_ram.py b/tests/test_ram/test_ram.py index 624221929..dbc57a2c0 100644 --- a/tests/test_ram/test_ram.py +++ b/tests/test_ram/test_ram.py @@ -4,7 +4,7 @@ from datetime import datetime import boto3 import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_ram, mock_organizations from moto.core import ACCOUNT_ID @@ -65,7 +65,7 @@ def test_create_resource_share_errors(): # invalid ARN # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_resource_share(name="test", resourceArns=["inalid-arn"]) ex = e.exception ex.operation_name.should.equal("CreateResourceShare") @@ -78,7 +78,7 @@ def test_create_resource_share_errors(): # valid ARN, but not shareable resource type # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_resource_share( name="test", resourceArns=["arn:aws:iam::{}:role/test".format(ACCOUNT_ID)] ) @@ -92,7 +92,7 @@ def test_create_resource_share_errors(): # invalid principal ID # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_resource_share( name="test", principals=["invalid"], @@ -162,7 +162,7 @@ def test_create_resource_share_with_organization_errors(): # unknown Organization # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_resource_share( name="test", principals=[ @@ -184,7 +184,7 @@ def test_create_resource_share_with_organization_errors(): # unknown OU # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.create_resource_share( name="test", principals=[ @@ -236,7 +236,7 @@ def test_get_resource_shares_errors(): # invalid resource owner # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.get_resource_shares(resourceOwner="invalid") ex = e.exception ex.operation_name.should.equal("GetResourceShares") @@ -282,7 +282,7 @@ def test_update_resource_share_errors(): # invalid resource owner # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.update_resource_share( resourceShareArn="arn:aws:ram:us-east-1:{}:resource-share/not-existing".format( ACCOUNT_ID @@ -328,7 +328,7 @@ def test_delete_resource_share_errors(): # invalid resource owner # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.delete_resource_share( resourceShareArn="arn:aws:ram:us-east-1:{}:resource-share/not-existing".format( ACCOUNT_ID @@ -368,7 +368,7 @@ def test_enable_sharing_with_aws_organization_errors(): # no Organization defined # when - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.enable_sharing_with_aws_organization() ex = e.exception ex.operation_name.should.equal("EnableSharingWithAwsOrganization") diff --git a/tests/test_rds/__init__.py b/tests/test_rds/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_rds/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_rds2/__init__.py b/tests/test_rds2/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_rds2/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_redshift/__init__.py b/tests/test_redshift/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_redshift/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_route53/__init__.py b/tests/test_route53/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_route53/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_route53/test_route53.py b/tests/test_route53/test_route53.py index 8c036441c..68436a40e 100644 --- a/tests/test_route53/test_route53.py +++ b/tests/test_route53/test_route53.py @@ -10,7 +10,7 @@ import sure # noqa import uuid import botocore -from nose.tools import assert_raises +import pytest from moto import mock_route53, mock_route53_deprecated @@ -855,7 +855,7 @@ def test_change_resource_record_invalid(): ], } - with assert_raises(botocore.exceptions.ClientError): + with pytest.raises(botocore.exceptions.ClientError): conn.change_resource_record_sets( HostedZoneId=hosted_zone_id, ChangeBatch=invalid_a_record_payload ) @@ -878,7 +878,7 @@ def test_change_resource_record_invalid(): ], } - with assert_raises(botocore.exceptions.ClientError): + with pytest.raises(botocore.exceptions.ClientError): conn.change_resource_record_sets( HostedZoneId=hosted_zone_id, ChangeBatch=invalid_cname_record_payload ) diff --git a/tests/test_s3/test_s3.py b/tests/test_s3/test_s3.py index d8f08e9ef..933d02c6d 100644 --- a/tests/test_s3/test_s3.py +++ b/tests/test_s3/test_s3.py @@ -27,10 +27,9 @@ from freezegun import freeze_time from parameterized import parameterized import six import requests -import tests.backport_assert_raises # noqa from moto.s3.responses import DEFAULT_REGION_NAME -from nose import SkipTest -from nose.tools import assert_raises +from unittest import SkipTest +import pytest import sure # noqa @@ -523,7 +522,7 @@ def test_create_existing_bucket(): "Trying to create a bucket that already exists should raise an Error" conn = boto.s3.connect_to_region("us-west-2") conn.create_bucket("foobar", location="us-west-2") - with assert_raises(S3CreateError): + with pytest.raises(S3CreateError): conn.create_bucket("foobar", location="us-west-2") @@ -665,7 +664,7 @@ def test_delete_keys_invalid(): @mock_s3 def test_boto3_delete_empty_keys_list(): - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: boto3.client("s3").delete_objects(Bucket="foobar", Delete={"Objects": []}) assert err.exception.response["Error"]["Code"] == "MalformedXML" @@ -1015,7 +1014,7 @@ def test_s3_object_in_public_bucket(): bucket.put_object(ACL="private", Body=b"ABCD", Key="file.txt") - with assert_raises(ClientError) as exc: + 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") @@ -1089,7 +1088,7 @@ def test_s3_object_in_private_bucket(): s3_anonymous = boto3.resource("s3") s3_anonymous.meta.client.meta.events.register("choose-signer.s3.*", disable_signing) - with assert_raises(ClientError) as exc: + 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") @@ -1181,7 +1180,7 @@ if not settings.TEST_SERVER_MODE: bucket_name = "asdfasdfsdfdsfasda" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.create_bucket(Bucket=bucket_name) e.exception.response["Error"]["Message"].should.equal( "The unspecified location constraint is incompatible for the region specific endpoint this request was sent to." @@ -1200,12 +1199,12 @@ if not settings.TEST_SERVER_MODE: client = boto3.client("s3control", region_name="us-west-2") # With an invalid account ID: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId="111111111111") assert ce.exception.response["Error"]["Code"] == "AccessDenied" # Without one defined: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId=ACCOUNT_ID) assert ( ce.exception.response["Error"]["Code"] @@ -1213,7 +1212,7 @@ if not settings.TEST_SERVER_MODE: ) # Put a with an invalid account ID: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_public_access_block( AccountId="111111111111", PublicAccessBlockConfiguration={"BlockPublicAcls": True}, @@ -1221,7 +1220,7 @@ if not settings.TEST_SERVER_MODE: assert ce.exception.response["Error"]["Code"] == "AccessDenied" # Put with an invalid PAB: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_public_access_block( AccountId=ACCOUNT_ID, PublicAccessBlockConfiguration={} ) @@ -1255,7 +1254,7 @@ if not settings.TEST_SERVER_MODE: } # Delete with an invalid account ID: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.delete_public_access_block(AccountId="111111111111") assert ce.exception.response["Error"]["Code"] == "AccessDenied" @@ -1263,7 +1262,7 @@ if not settings.TEST_SERVER_MODE: client.delete_public_access_block(AccountId=ACCOUNT_ID) # Confirm that it's deleted: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_public_access_block(AccountId=ACCOUNT_ID) assert ( ce.exception.response["Error"]["Code"] @@ -1462,7 +1461,7 @@ if not settings.TEST_SERVER_MODE: ) # Without a PAB in place: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: config_client.get_resource_config_history( resourceType="AWS::S3::AccountPublicAccessBlock", resourceId=ACCOUNT_ID ) @@ -1633,7 +1632,7 @@ def test_policy(): } ) - with assert_raises(S3ResponseError) as err: + with pytest.raises(S3ResponseError) as err: bucket.get_policy() ex = err.exception @@ -1654,7 +1653,7 @@ def test_policy(): bucket.delete_policy() - with assert_raises(S3ResponseError) as err: + with pytest.raises(S3ResponseError) as err: bucket.get_policy() @@ -1976,7 +1975,7 @@ def test_bucket_create_duplicate(): s3.create_bucket( Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "us-west-2"} ) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.create_bucket( Bucket="blah", CreateBucketConfiguration={"LocationConstraint": "us-west-2"} ) @@ -1986,7 +1985,7 @@ def test_bucket_create_duplicate(): @mock_s3 def test_bucket_create_force_us_east_1(): s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.create_bucket( Bucket="blah", CreateBucketConfiguration={"LocationConstraint": DEFAULT_REGION_NAME}, @@ -2011,7 +2010,7 @@ def test_boto3_bucket_create_eu_central(): @mock_s3 def test_bucket_create_empty_bucket_configuration_should_return_malformed_xml_error(): s3 = boto3.resource("s3", region_name="us-east-1") - with assert_raises(ClientError) as e: + 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) @@ -2028,7 +2027,7 @@ def test_boto3_head_object(): Bucket="blah", Key="hello.txt" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.Object("blah", "hello2.txt").meta.client.head_object( Bucket="blah", Key="hello_bad.txt" ) @@ -2077,7 +2076,7 @@ def test_boto3_get_object(): Bucket="blah", Key="hello.txt" ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.Object("blah", "hello2.txt").get() e.exception.response["Error"]["Code"].should.equal("NoSuchKey") @@ -2104,7 +2103,7 @@ def test_boto3_get_missing_object_with_part_number(): s3 = boto3.resource("s3", region_name=DEFAULT_REGION_NAME) s3.create_bucket(Bucket="blah") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.Object("blah", "hello.txt").meta.client.head_object( Bucket="blah", Key="hello.txt", PartNumber=123 ) @@ -2176,7 +2175,7 @@ def test_boto3_copy_object_with_versioning(): obj3_version_new.should_not.equal(obj2_version_new) # Copy file that doesn't exist - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.copy_object( CopySource={"Bucket": "blah", "Key": "test4", "VersionId": obj2_version}, Bucket="blah", @@ -2212,7 +2211,7 @@ def test_s3_abort_multipart_data_with_invalid_upload_and_key(): client.create_bucket(Bucket="blah") - with assert_raises(Exception) as err: + with pytest.raises(Exception) as err: client.abort_multipart_upload( Bucket="blah", Key="foobar", UploadId="dummy_upload_id" ) @@ -2360,7 +2359,7 @@ def test_boto3_get_object_if_modified_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, @@ -2438,7 +2437,7 @@ def test_boto3_head_object_if_modified_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, @@ -2633,7 +2632,7 @@ def test_boto3_put_bucket_tagging(): resp["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) # With duplicate tag keys: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: resp = s3.put_bucket_tagging( Bucket=bucket_name, Tagging={ @@ -2650,7 +2649,7 @@ def test_boto3_put_bucket_tagging(): ) # Cannot put tags that are "system" tags - i.e. tags that start with "aws:" - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: s3.put_bucket_tagging( Bucket=bucket_name, Tagging={"TagSet": [{"Key": "aws:sometag", "Value": "nope"}]}, @@ -2691,7 +2690,7 @@ def test_boto3_get_bucket_tagging(): # With no tags: s3.put_bucket_tagging(Bucket=bucket_name, Tagging={"TagSet": []}) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.get_bucket_tagging(Bucket=bucket_name) e = err.exception @@ -2718,7 +2717,7 @@ def test_boto3_delete_bucket_tagging(): resp = s3.delete_bucket_tagging(Bucket=bucket_name) resp["ResponseMetadata"]["HTTPStatusCode"].should.equal(204) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.get_bucket_tagging(Bucket=bucket_name) e = err.exception @@ -2756,7 +2755,7 @@ def test_boto3_put_bucket_cors(): resp["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_cors( Bucket=bucket_name, CORSConfiguration={ @@ -2771,14 +2770,14 @@ def test_boto3_put_bucket_cors(): "Found unsupported HTTP method in CORS config. " "Unsupported method is NOTREAL" ) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_cors(Bucket=bucket_name, CORSConfiguration={"CORSRules": []}) e = err.exception e.response["Error"]["Code"].should.equal("MalformedXML") # And 101: many_rules = [{"AllowedOrigins": ["*"], "AllowedMethods": ["GET"]}] * 101 - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_cors( Bucket=bucket_name, CORSConfiguration={"CORSRules": many_rules} ) @@ -2793,7 +2792,7 @@ def test_boto3_get_bucket_cors(): s3.create_bucket(Bucket=bucket_name) # Without CORS: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.get_bucket_cors(Bucket=bucket_name) e = err.exception @@ -2843,7 +2842,7 @@ def test_boto3_delete_bucket_cors(): resp["ResponseMetadata"]["HTTPStatusCode"].should.equal(204) # Verify deletion: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.get_bucket_cors(Bucket=bucket_name) e = err.exception @@ -2906,7 +2905,7 @@ def test_put_bucket_acl_body(): assert len(result["Grants"]) == 1 # With no owner: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_acl( Bucket="bucket", AccessControlPolicy={ @@ -2924,7 +2923,7 @@ def test_put_bucket_acl_body(): assert err.exception.response["Error"]["Code"] == "MalformedACLError" # With incorrect permission: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_acl( Bucket="bucket", AccessControlPolicy={ @@ -3185,7 +3184,7 @@ def test_put_bucket_notification_errors(): # With incorrect ARNs: for tech, arn in [("Queue", "sqs"), ("Topic", "sns"), ("LambdaFunction", "lambda")]: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_notification_configuration( Bucket="bucket", NotificationConfiguration={ @@ -3206,7 +3205,7 @@ def test_put_bucket_notification_errors(): ) # Region not the same as the bucket: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_notification_configuration( Bucket="bucket", NotificationConfiguration={ @@ -3226,7 +3225,7 @@ def test_put_bucket_notification_errors(): ) # Invalid event name: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_notification_configuration( Bucket="bucket", NotificationConfiguration={ @@ -3263,7 +3262,7 @@ def test_boto3_put_bucket_logging(): assert not result.get("LoggingEnabled") # A log-bucket that doesn't exist: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_logging( Bucket=bucket_name, BucketLoggingStatus={ @@ -3273,7 +3272,7 @@ def test_boto3_put_bucket_logging(): assert err.exception.response["Error"]["Code"] == "InvalidTargetBucketForLogging" # A log-bucket that's missing the proper ACLs for LogDelivery: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_logging( Bucket=bucket_name, BucketLoggingStatus={ @@ -3314,7 +3313,7 @@ def test_boto3_put_bucket_logging(): ) # A log-bucket that's in the wrong region: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_logging( Bucket=bucket_name, BucketLoggingStatus={ @@ -3402,7 +3401,7 @@ def test_boto3_put_bucket_logging(): assert len(result["LoggingEnabled"]["TargetGrants"]) == 1 # With an invalid grant: - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_bucket_logging( Bucket=bucket_name, BucketLoggingStatus={ @@ -3431,7 +3430,7 @@ def test_boto3_put_object_tagging(): key = "key-with-tags" s3.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_object_tagging( Bucket=bucket_name, Key=key, @@ -3479,7 +3478,7 @@ def test_boto3_put_object_tagging_on_earliest_version(): bucket_versioning.enable() bucket_versioning.status.should.equal("Enabled") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_object_tagging( Bucket=bucket_name, Key=key, @@ -3547,7 +3546,7 @@ def test_boto3_put_object_tagging_on_both_version(): bucket_versioning.enable() bucket_versioning.status.should.equal("Enabled") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_object_tagging( Bucket=bucket_name, Key=key, @@ -3772,7 +3771,7 @@ def test_boto3_delete_markers(): s3.delete_objects(Bucket=bucket_name, Delete={"Objects": [{"Key": key}]}) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=key) e.exception.response["Error"]["Code"].should.equal("NoSuchKey") @@ -3820,7 +3819,7 @@ def test_boto3_multiple_delete_markers(): response = s3.list_object_versions(Bucket=bucket_name) response["DeleteMarkers"].should.have.length_of(2) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=key) e.response["Error"]["Code"].should.equal("404") @@ -3892,7 +3891,7 @@ TEST_XML = """\ @mock_s3 def test_boto3_bucket_name_too_long(): s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.create_bucket(Bucket="x" * 64) exc.exception.response["Error"]["Code"].should.equal("InvalidBucketName") @@ -3900,7 +3899,7 @@ def test_boto3_bucket_name_too_long(): @mock_s3 def test_boto3_bucket_name_too_short(): s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.create_bucket(Bucket="x" * 2) exc.exception.response["Error"]["Code"].should.equal("InvalidBucketName") @@ -3972,7 +3971,7 @@ def test_accelerate_configuration_status_validation(): bucket_name = "some_bucket" s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) s3.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.put_bucket_accelerate_configuration( Bucket=bucket_name, AccelerateConfiguration={"Status": "bad_status"} ) @@ -3984,7 +3983,7 @@ def test_accelerate_configuration_is_not_supported_when_bucket_name_has_dots(): bucket_name = "some.bucket.with.dots" s3 = boto3.client("s3", region_name=DEFAULT_REGION_NAME) s3.create_bucket(Bucket=bucket_name) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.put_bucket_accelerate_configuration( Bucket=bucket_name, AccelerateConfiguration={"Status": "Enabled"} ) @@ -4028,11 +4027,11 @@ def test_leading_slashes_not_removed(bucket_name): s3.put_object(Bucket=bucket_name, Key=uploaded_key, Body=b"Some body") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=invalid_key_1) e.exception.response["Error"]["Code"].should.equal("NoSuchKey") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=invalid_key_2) e.exception.response["Error"]["Code"].should.equal("NoSuchKey") @@ -4052,7 +4051,7 @@ def test_delete_objects_with_url_encoded_key(key): s3.put_object(Bucket=bucket_name, Key=key, Body=body) def assert_deleted(): - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: s3.get_object(Bucket=bucket_name, Key=key) e.exception.response["Error"]["Code"].should.equal("NoSuchKey") @@ -4073,7 +4072,7 @@ def test_public_access_block(): client.create_bucket(Bucket="mybucket") # Try to get the public access block (should not exist by default) - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_public_access_block(Bucket="mybucket") assert ( @@ -4123,7 +4122,7 @@ def test_public_access_block(): } # Test with a blank PublicAccessBlockConfiguration: - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.put_public_access_block( Bucket="mybucket", PublicAccessBlockConfiguration={} ) @@ -4156,7 +4155,7 @@ def test_public_access_block(): # Delete: client.delete_public_access_block(Bucket="mybucket") - with assert_raises(ClientError) as ce: + with pytest.raises(ClientError) as ce: client.get_public_access_block(Bucket="mybucket") assert ( ce.exception.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration" @@ -4301,7 +4300,7 @@ def test_list_config_discovered_resources(): ) # With an invalid page: - with assert_raises(InvalidNextTokenException) as inte: + 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 @@ -4761,7 +4760,7 @@ def test_encryption(): conn = boto3.client("s3", region_name="us-east-1") conn.create_bucket(Bucket="mybucket") - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: conn.get_bucket_encryption(Bucket="mybucket") sse_config = { @@ -4784,7 +4783,7 @@ def test_encryption(): assert resp["ServerSideEncryptionConfiguration"] == sse_config conn.delete_bucket_encryption(Bucket="mybucket") - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: conn.get_bucket_encryption(Bucket="mybucket") @@ -4799,7 +4798,7 @@ def test_presigned_url_restrict_parameters(): s3 = boto3.client("s3", region_name="us-east-1") # Create a pre-signed url with some metadata. - with assert_raises(botocore.exceptions.ParamValidationError) as err: + with pytest.raises(botocore.exceptions.ParamValidationError) as err: s3.generate_presigned_url( ClientMethod="put_object", Params={"Bucket": bucket, "Key": key, "Unknown": "metadata"}, diff --git a/tests/test_s3/test_s3_lifecycle.py b/tests/test_s3/test_s3_lifecycle.py index 0a2e66b5c..da9ffbca4 100644 --- a/tests/test_s3/test_s3_lifecycle.py +++ b/tests/test_s3/test_s3_lifecycle.py @@ -8,7 +8,7 @@ from boto.s3.lifecycle import Lifecycle, Transition, Expiration, Rule import sure # noqa from botocore.exceptions import ClientError from datetime import datetime -from nose.tools import assert_raises +import pytest from moto import mock_s3_deprecated, mock_s3 @@ -56,7 +56,7 @@ def test_lifecycle_with_filters(): assert result["Rules"][0]["Filter"]["Prefix"] == "" assert not result["Rules"][0]["Filter"].get("And") assert not result["Rules"][0]["Filter"].get("Tag") - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # Without any prefixes and an empty filter (this is by default a prefix for the whole bucket): @@ -75,12 +75,12 @@ def test_lifecycle_with_filters(): ) result = client.get_bucket_lifecycle_configuration(Bucket="bucket") assert len(result["Rules"]) == 1 - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # If we remove the filter -- and don't specify a Prefix, then this is bad: lfc["Rules"][0].pop("Filter") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -93,12 +93,12 @@ def test_lifecycle_with_filters(): ) result = client.get_bucket_lifecycle_configuration(Bucket="bucket") assert len(result["Rules"]) == 1 - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Filter"]["Prefix"] assert not result["Rules"][0]["Filter"].get("And") assert result["Rules"][0]["Filter"]["Tag"]["Key"] == "mytag" assert result["Rules"][0]["Filter"]["Tag"]["Value"] == "mytagvalue" - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # With And (single tag): @@ -118,7 +118,7 @@ def test_lifecycle_with_filters(): assert len(result["Rules"][0]["Filter"]["And"]["Tags"]) == 1 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Key"] == "mytag" assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue" - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # With multiple And tags: @@ -141,7 +141,7 @@ def test_lifecycle_with_filters(): assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue" assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Key"] == "mytag2" assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Value"] == "mytagvalue2" - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # And filter without Prefix but multiple Tags: @@ -156,26 +156,26 @@ def test_lifecycle_with_filters(): ) result = client.get_bucket_lifecycle_configuration(Bucket="bucket") assert len(result["Rules"]) == 1 - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Filter"]["And"]["Prefix"] assert len(result["Rules"][0]["Filter"]["And"]["Tags"]) == 2 assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Key"] == "mytag" assert result["Rules"][0]["Filter"]["And"]["Tags"][0]["Value"] == "mytagvalue" assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Key"] == "mytag2" assert result["Rules"][0]["Filter"]["And"]["Tags"][1]["Value"] == "mytagvalue2" - with assert_raises(KeyError): + with pytest.raises(KeyError): assert result["Rules"][0]["Prefix"] # Can't have both filter and prefix: lfc["Rules"][0]["Prefix"] = "" - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) assert err.exception.response["Error"]["Code"] == "MalformedXML" lfc["Rules"][0]["Prefix"] = "some/path" - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -196,7 +196,7 @@ def test_lifecycle_with_filters(): "Prefix": "some/prefix", "Tag": {"Key": "mytag", "Value": "mytagvalue"}, } - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -212,7 +212,7 @@ def test_lifecycle_with_filters(): ], }, } - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -279,7 +279,7 @@ def test_lifecycle_with_eodm(): # With failure: lfc["Rules"][0]["Expiration"]["Days"] = 7 - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -287,7 +287,7 @@ def test_lifecycle_with_eodm(): del lfc["Rules"][0]["Expiration"]["Days"] lfc["Rules"][0]["Expiration"]["Date"] = datetime(2015, 1, 1) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -383,7 +383,7 @@ def test_lifecycle_with_nvt(): # With failures for missing children: del lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) @@ -391,7 +391,7 @@ def test_lifecycle_with_nvt(): lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["NoncurrentDays"] = 30 del lfc["Rules"][0]["NoncurrentVersionTransitions"][0]["StorageClass"] - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: client.put_bucket_lifecycle_configuration( Bucket="bucket", LifecycleConfiguration=lfc ) diff --git a/tests/test_s3/test_s3_storageclass.py b/tests/test_s3/test_s3_storageclass.py index a89b4a896..0e8152b03 100644 --- a/tests/test_s3/test_s3_storageclass.py +++ b/tests/test_s3/test_s3_storageclass.py @@ -4,7 +4,7 @@ import boto3 import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_s3 @@ -105,7 +105,7 @@ def test_s3_invalid_copied_storage_class(): ) # Try to copy an object with an invalid storage class - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.copy_object( CopySource={"Bucket": "Bucket", "Key": "First_Object"}, Bucket="Bucket2", @@ -128,7 +128,7 @@ def test_s3_invalid_storage_class(): ) # Try to add an object with an invalid storage class - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: s3.put_object( Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="STANDARDD" ) @@ -166,7 +166,7 @@ def test_s3_copy_object_error_for_glacier_storage_class_not_restored(): Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="GLACIER" ) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.copy_object( CopySource={"Bucket": "Bucket", "Key": "First_Object"}, Bucket="Bucket", @@ -187,7 +187,7 @@ def test_s3_copy_object_error_for_deep_archive_storage_class_not_restored(): Bucket="Bucket", Key="First_Object", Body="Body", StorageClass="DEEP_ARCHIVE" ) - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: s3.copy_object( CopySource={"Bucket": "Bucket", "Key": "First_Object"}, Bucket="Bucket", diff --git a/tests/test_s3bucket_path/__init__.py b/tests/test_s3bucket_path/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_s3bucket_path/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_sagemaker/test_sagemaker_endpoint.py b/tests/test_sagemaker/test_sagemaker_endpoint.py index b048439ff..0d21ad1ef 100644 --- a/tests/test_sagemaker/test_sagemaker_endpoint.py +++ b/tests/test_sagemaker/test_sagemaker_endpoint.py @@ -3,12 +3,12 @@ from __future__ import unicode_literals import datetime import boto3 -from botocore.exceptions import ClientError, ParamValidationError +from botocore.exceptions import ClientError import sure # noqa from moto import mock_sagemaker from moto.sts.models import ACCOUNT_ID -from nose.tools import assert_true, assert_equal, assert_raises +import pytest TEST_REGION_NAME = "us-east-1" FAKE_ROLE_ARN = "arn:aws:iam::{}:role/FakeRole".format(ACCOUNT_ID) @@ -33,14 +33,12 @@ def test_create_endpoint_config(): ] endpoint_config_name = "MyEndpointConfig" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) - assert_true( - e.exception.response["Error"]["Message"].startswith("Could not find model") - ) + assert e.exception.response["Error"]["Message"].startswith("Could not find model") _create_model(sagemaker, model_name) resp = sagemaker.create_endpoint_config( @@ -88,22 +86,13 @@ def test_delete_endpoint_config(): ) resp = sagemaker.delete_endpoint_config(EndpointConfigName=endpoint_config_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.describe_endpoint_config(EndpointConfigName=endpoint_config_name) - assert_true( - e.exception.response["Error"]["Message"].startswith( - "Could not find endpoint configuration" - ) - ) + assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint configuration") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.delete_endpoint_config(EndpointConfigName=endpoint_config_name) - assert_true( - e.exception.response["Error"]["Message"].startswith( - "Could not find endpoint configuration" - ) - ) - pass + assert e.exception.response["Error"]["Message"].startswith( "Could not find endpoint configuration") @mock_sagemaker @@ -124,16 +113,16 @@ def test_create_endpoint_invalid_instance_type(): ] endpoint_config_name = "MyEndpointConfig" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.create_endpoint_config( EndpointConfigName=endpoint_config_name, ProductionVariants=production_variants, ) - assert_equal(e.exception.response["Error"]["Code"], "ValidationException") + assert e.exception.response["Error"]["Code"] == "ValidationException" expected_message = "Value '{}' at 'instanceType' failed to satisfy constraint: Member must satisfy enum value set: [".format( instance_type ) - assert_true(expected_message in e.exception.response["Error"]["Message"]) + assert expected_message in e.exception.response["Error"]["Message"] @mock_sagemaker @@ -141,15 +130,11 @@ def test_create_endpoint(): sagemaker = boto3.client("sagemaker", region_name=TEST_REGION_NAME) endpoint_name = "MyEndpoint" - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.create_endpoint( EndpointName=endpoint_name, EndpointConfigName="NonexistentEndpointConfig" ) - assert_true( - e.exception.response["Error"]["Message"].startswith( - "Could not find endpoint configuration" - ) - ) + assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint configuration") model_name = "MyModel" _create_model(sagemaker, model_name) @@ -173,12 +158,12 @@ def test_create_endpoint(): resp["EndpointName"].should.equal(endpoint_name) resp["EndpointConfigName"].should.equal(endpoint_config_name) resp["EndpointStatus"].should.equal("InService") - assert_true(isinstance(resp["CreationTime"], datetime.datetime)) - assert_true(isinstance(resp["LastModifiedTime"], datetime.datetime)) + assert isinstance(resp["CreationTime"], datetime.datetime) + assert isinstance(resp["LastModifiedTime"], datetime.datetime) resp["ProductionVariants"][0]["VariantName"].should.equal("MyProductionVariant") resp = sagemaker.list_tags(ResourceArn=resp["EndpointArn"]) - assert_equal(resp["Tags"], GENERIC_TAGS_PARAM) + assert resp["Tags"] == GENERIC_TAGS_PARAM @mock_sagemaker @@ -195,17 +180,13 @@ def test_delete_endpoint(): _create_endpoint(sagemaker, endpoint_name, endpoint_config_name) sagemaker.delete_endpoint(EndpointName=endpoint_name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.describe_endpoint(EndpointName=endpoint_name) - assert_true( - e.exception.response["Error"]["Message"].startswith("Could not find endpoint") - ) + assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.delete_endpoint(EndpointName=endpoint_name) - assert_true( - e.exception.response["Error"]["Message"].startswith("Could not find endpoint") - ) + assert e.exception.response["Error"]["Message"].startswith("Could not find endpoint") def _create_model(boto_client, model_name): @@ -217,7 +198,7 @@ def _create_model(boto_client, model_name): }, ExecutionRoleArn=FAKE_ROLE_ARN, ) - assert_equal(resp["ResponseMetadata"]["HTTPStatusCode"], 200) + assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200 def _create_endpoint_config(boto_client, endpoint_config_name, model_name): diff --git a/tests/test_sagemaker/test_sagemaker_models.py b/tests/test_sagemaker/test_sagemaker_models.py index 4139ca575..1f2f4440d 100644 --- a/tests/test_sagemaker/test_sagemaker_models.py +++ b/tests/test_sagemaker/test_sagemaker_models.py @@ -2,9 +2,8 @@ from __future__ import unicode_literals import boto3 -import tests.backport_assert_raises # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_sagemaker import sure # noqa @@ -76,7 +75,7 @@ def test_delete_model(): @mock_sagemaker def test_delete_model_not_found(): - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: boto3.client("sagemaker", region_name="us-east-1").delete_model( ModelName="blah" ) diff --git a/tests/test_sagemaker/test_sagemaker_notebooks.py b/tests/test_sagemaker/test_sagemaker_notebooks.py index c04618c77..9f6a2be39 100644 --- a/tests/test_sagemaker/test_sagemaker_notebooks.py +++ b/tests/test_sagemaker/test_sagemaker_notebooks.py @@ -8,7 +8,7 @@ import sure # noqa from moto import mock_sagemaker from moto.sts.models import ACCOUNT_ID -from nose.tools import assert_true, assert_equal, assert_raises +import pytest TEST_REGION_NAME = "us-east-1" FAKE_SUBNET_ID = "subnet-012345678" @@ -41,26 +41,25 @@ def test_create_notebook_instance_minimal_params(): "RoleArn": FAKE_ROLE_ARN, } resp = sagemaker.create_notebook_instance(**args) - assert_true(resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker")) - assert_true(resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"])) + assert resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"]) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_true(resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker")) - assert_true(resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"])) - assert_equal(resp["NotebookInstanceName"], NAME_PARAM) - assert_equal(resp["NotebookInstanceStatus"], "InService") - assert_equal( - resp["Url"], "{}.notebook.{}.sagemaker.aws".format(NAME_PARAM, TEST_REGION_NAME) - ) - assert_equal(resp["InstanceType"], INSTANCE_TYPE_PARAM) - assert_equal(resp["RoleArn"], FAKE_ROLE_ARN) - assert_true(isinstance(resp["LastModifiedTime"], datetime.datetime)) - assert_true(isinstance(resp["CreationTime"], datetime.datetime)) - assert_equal(resp["DirectInternetAccess"], "Enabled") - assert_equal(resp["VolumeSizeInGB"], 5) + assert resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"]) + assert resp["NotebookInstanceName"] == NAME_PARAM + assert resp["NotebookInstanceStatus"] == "InService" + assert resp["Url"] == \ + "{}.notebook.{}.sagemaker.aws".format(NAME_PARAM, TEST_REGION_NAME) + assert resp["InstanceType"] == INSTANCE_TYPE_PARAM + assert resp["RoleArn"] == FAKE_ROLE_ARN + assert isinstance(resp["LastModifiedTime"], datetime.datetime) + assert isinstance(resp["CreationTime"], datetime.datetime) + assert resp["DirectInternetAccess"] == "Enabled" + assert resp["VolumeSizeInGB"] == 5 -# assert_equal(resp["RootAccess"], True) # ToDo: Not sure if this defaults... +# assert resp["RootAccess"] == True # ToDo: Not sure if this defaults... @mock_sagemaker @@ -92,36 +91,34 @@ def test_create_notebook_instance_params(): "RootAccess": ROOT_ACCESS_PARAM, } resp = sagemaker.create_notebook_instance(**args) - assert_true(resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker")) - assert_true(resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"])) + assert resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"]) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_true(resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker")) - assert_true(resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"])) - assert_equal(resp["NotebookInstanceName"], NAME_PARAM) - assert_equal(resp["NotebookInstanceStatus"], "InService") - assert_equal( - resp["Url"], "{}.notebook.{}.sagemaker.aws".format(NAME_PARAM, TEST_REGION_NAME) - ) - assert_equal(resp["InstanceType"], INSTANCE_TYPE_PARAM) - assert_equal(resp["RoleArn"], FAKE_ROLE_ARN) - assert_true(isinstance(resp["LastModifiedTime"], datetime.datetime)) - assert_true(isinstance(resp["CreationTime"], datetime.datetime)) - assert_equal(resp["DirectInternetAccess"], "Enabled") - assert_equal(resp["VolumeSizeInGB"], VOLUME_SIZE_IN_GB_PARAM) - # assert_equal(resp["RootAccess"], True) # ToDo: Not sure if this defaults... - assert_equal(resp["SubnetId"], FAKE_SUBNET_ID) - assert_equal(resp["SecurityGroups"], FAKE_SECURITY_GROUP_IDS) - assert_equal(resp["KmsKeyId"], FAKE_KMS_KEY_ID) - assert_equal( - resp["NotebookInstanceLifecycleConfigName"], FAKE_LIFECYCLE_CONFIG_NAME - ) - assert_equal(resp["AcceleratorTypes"], ACCELERATOR_TYPES_PARAM) - assert_equal(resp["DefaultCodeRepository"], FAKE_DEFAULT_CODE_REPO) - assert_equal(resp["AdditionalCodeRepositories"], FAKE_ADDL_CODE_REPOS) + assert resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"]) + assert resp["NotebookInstanceName"] == NAME_PARAM + assert resp["NotebookInstanceStatus"] == "InService" + assert resp["Url"] == \ + "{}.notebook.{}.sagemaker.aws".format(NAME_PARAM, TEST_REGION_NAME) + assert resp["InstanceType"] == INSTANCE_TYPE_PARAM + assert resp["RoleArn"] == FAKE_ROLE_ARN + assert isinstance(resp["LastModifiedTime"], datetime.datetime) + assert isinstance(resp["CreationTime"], datetime.datetime) + assert resp["DirectInternetAccess"] == "Enabled" + assert resp["VolumeSizeInGB"] == VOLUME_SIZE_IN_GB_PARAM + # assert resp["RootAccess"] == True # ToDo: Not sure if this defaults... + assert resp["SubnetId"] == FAKE_SUBNET_ID + assert resp["SecurityGroups"] == FAKE_SECURITY_GROUP_IDS + assert resp["KmsKeyId"] == FAKE_KMS_KEY_ID + assert resp["NotebookInstanceLifecycleConfigName"] == \ + FAKE_LIFECYCLE_CONFIG_NAME + assert resp["AcceleratorTypes"] == ACCELERATOR_TYPES_PARAM + assert resp["DefaultCodeRepository"] == FAKE_DEFAULT_CODE_REPO + assert resp["AdditionalCodeRepositories"] == FAKE_ADDL_CODE_REPOS resp = sagemaker.list_tags(ResourceArn=resp["NotebookInstanceArn"]) - assert_equal(resp["Tags"], GENERIC_TAGS_PARAM) + assert resp["Tags"] == GENERIC_TAGS_PARAM @mock_sagemaker @@ -136,14 +133,11 @@ def test_create_notebook_instance_bad_volume_size(): "RoleArn": FAKE_ROLE_ARN, "VolumeSizeInGB": vol_size, } - with assert_raises(ParamValidationError) as ex: - resp = sagemaker.create_notebook_instance(**args) - assert_equal( - ex.exception.args[0], - "Parameter validation failed:\nInvalid range for parameter VolumeSizeInGB, value: {}, valid range: 5-inf".format( - vol_size - ), - ) + with pytest.raises(ParamValidationError) as ex: + sagemaker.create_notebook_instance(**args) + assert \ + ex.exception.args[0] == \ + "Parameter validation failed:\nInvalid range for parameter VolumeSizeInGB, value: {}, valid range: 5-inf".format(vol_size) @mock_sagemaker @@ -157,14 +151,14 @@ def test_create_notebook_instance_invalid_instance_type(): "InstanceType": instance_type, "RoleArn": FAKE_ROLE_ARN, } - with assert_raises(ClientError) as ex: - resp = sagemaker.create_notebook_instance(**args) - assert_equal(ex.exception.response["Error"]["Code"], "ValidationException") + with pytest.raises(ClientError) as ex: + sagemaker.create_notebook_instance(**args) + assert ex.exception.response["Error"]["Code"] == "ValidationException" expected_message = "Value '{}' at 'instanceType' failed to satisfy constraint: Member must satisfy enum value set: [".format( instance_type ) - assert_true(expected_message in ex.exception.response["Error"]["Message"]) + assert expected_message in ex.exception.response["Error"]["Message"] @mock_sagemaker @@ -180,51 +174,49 @@ def test_notebook_instance_lifecycle(): "RoleArn": FAKE_ROLE_ARN, } resp = sagemaker.create_notebook_instance(**args) - assert_true(resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker")) - assert_true(resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"])) + assert resp["NotebookInstanceArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceArn"].endswith(args["NotebookInstanceName"]) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) notebook_instance_arn = resp["NotebookInstanceArn"] - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: sagemaker.delete_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_equal(ex.exception.response["Error"]["Code"], "ValidationException") + assert ex.exception.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_true(expected_message in ex.exception.response["Error"]["Message"]) + assert expected_message in ex.exception.response["Error"]["Message"] sagemaker.stop_notebook_instance(NotebookInstanceName=NAME_PARAM) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_equal(resp["NotebookInstanceStatus"], "Stopped") + assert resp["NotebookInstanceStatus"] == "Stopped" sagemaker.start_notebook_instance(NotebookInstanceName=NAME_PARAM) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_equal(resp["NotebookInstanceStatus"], "InService") + assert resp["NotebookInstanceStatus"] == "InService" sagemaker.stop_notebook_instance(NotebookInstanceName=NAME_PARAM) resp = sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_equal(resp["NotebookInstanceStatus"], "Stopped") + assert resp["NotebookInstanceStatus"] == "Stopped" sagemaker.delete_notebook_instance(NotebookInstanceName=NAME_PARAM) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: sagemaker.describe_notebook_instance(NotebookInstanceName=NAME_PARAM) - assert_equal(ex.exception.response["Error"]["Message"], "RecordNotFound") + assert ex.exception.response["Error"]["Message"] == "RecordNotFound" @mock_sagemaker def test_describe_nonexistent_model(): sagemaker = boto3.client("sagemaker", region_name=TEST_REGION_NAME) - with assert_raises(ClientError) as e: - resp = sagemaker.describe_model(ModelName="Nonexistent") - assert_true( - e.exception.response["Error"]["Message"].startswith("Could not find model") - ) + with pytest.raises(ClientError) as e: + sagemaker.describe_model(ModelName="Nonexistent") + assert e.exception.response["Error"]["Message"].startswith("Could not find model") @mock_sagemaker @@ -237,56 +229,50 @@ def test_notebook_instance_lifecycle_config(): resp = sagemaker.create_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, OnCreate=on_create, OnStart=on_start ) - assert_true( - resp["NotebookInstanceLifecycleConfigArn"].startswith("arn:aws:sagemaker") - ) - assert_true(resp["NotebookInstanceLifecycleConfigArn"].endswith(name)) + assert resp["NotebookInstanceLifecycleConfigArn"].startswith("arn:aws:sagemaker") + assert resp["NotebookInstanceLifecycleConfigArn"].endswith(name) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: resp = sagemaker.create_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, OnCreate=on_create, OnStart=on_start, ) - assert_true( + assert \ e.exception.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config already exists.)" ) - ) resp = sagemaker.describe_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, ) - assert_equal(resp["NotebookInstanceLifecycleConfigName"], name) - assert_true( + assert resp["NotebookInstanceLifecycleConfigName"] == name + assert \ resp["NotebookInstanceLifecycleConfigArn"].startswith("arn:aws:sagemaker") - ) - assert_true(resp["NotebookInstanceLifecycleConfigArn"].endswith(name)) - assert_equal(resp["OnStart"], on_start) - assert_equal(resp["OnCreate"], on_create) - assert_true(isinstance(resp["LastModifiedTime"], datetime.datetime)) - assert_true(isinstance(resp["CreationTime"], datetime.datetime)) + assert resp["NotebookInstanceLifecycleConfigArn"].endswith(name) + assert resp["OnStart"] == on_start + assert resp["OnCreate"] == on_create + assert isinstance(resp["LastModifiedTime"], datetime.datetime) + assert isinstance(resp["CreationTime"], datetime.datetime) sagemaker.delete_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.describe_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, ) - assert_true( + assert \ e.exception.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config does not exist.)" ) - ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: sagemaker.delete_notebook_instance_lifecycle_config( NotebookInstanceLifecycleConfigName=name, ) - assert_true( + assert \ e.exception.response["Error"]["Message"].endswith( "Notebook Instance Lifecycle Config does not exist.)" ) - ) diff --git a/tests/test_sagemaker/test_sagemaker_training.py b/tests/test_sagemaker/test_sagemaker_training.py index feaf9f713..8f1dda9fe 100644 --- a/tests/test_sagemaker/test_sagemaker_training.py +++ b/tests/test_sagemaker/test_sagemaker_training.py @@ -7,7 +7,6 @@ import sure # noqa from moto import mock_sagemaker from moto.sts.models import ACCOUNT_ID -from nose.tools import assert_true, assert_equal, assert_raises, assert_regexp_matches FAKE_ROLE_ARN = "arn:aws:iam::{}:role/FakeRole".format(ACCOUNT_ID) TEST_REGION_NAME = "us-east-1" @@ -82,46 +81,41 @@ def test_create_training_job(): resp["TrainingJobArn"].should.match( r"^arn:aws:sagemaker:.*:.*:training-job/{}$".format(training_job_name) ) - assert_true( - resp["ModelArtifacts"]["S3ModelArtifacts"].startswith( + assert resp["ModelArtifacts"]["S3ModelArtifacts"].startswith( params["OutputDataConfig"]["S3OutputPath"] ) - ) - assert_true(training_job_name in (resp["ModelArtifacts"]["S3ModelArtifacts"])) - assert_true( + assert training_job_name in (resp["ModelArtifacts"]["S3ModelArtifacts"]) + assert \ resp["ModelArtifacts"]["S3ModelArtifacts"].endswith("output/model.tar.gz") - ) - assert_equal(resp["TrainingJobStatus"], "Completed") - assert_equal(resp["SecondaryStatus"], "Completed") - assert_equal(resp["HyperParameters"], params["HyperParameters"]) - assert_equal( - resp["AlgorithmSpecification"]["TrainingImage"], - params["AlgorithmSpecification"]["TrainingImage"], - ) - assert_equal( - resp["AlgorithmSpecification"]["TrainingInputMode"], - params["AlgorithmSpecification"]["TrainingInputMode"], - ) - assert_true("MetricDefinitions" in resp["AlgorithmSpecification"]) - assert_true("Name" in resp["AlgorithmSpecification"]["MetricDefinitions"][0]) - assert_true("Regex" in resp["AlgorithmSpecification"]["MetricDefinitions"][0]) - assert_equal(resp["RoleArn"], FAKE_ROLE_ARN) - assert_equal(resp["InputDataConfig"], params["InputDataConfig"]) - assert_equal(resp["OutputDataConfig"], params["OutputDataConfig"]) - assert_equal(resp["ResourceConfig"], params["ResourceConfig"]) - assert_equal(resp["StoppingCondition"], params["StoppingCondition"]) - assert_true(isinstance(resp["CreationTime"], datetime.datetime)) - assert_true(isinstance(resp["TrainingStartTime"], datetime.datetime)) - assert_true(isinstance(resp["TrainingEndTime"], datetime.datetime)) - assert_true(isinstance(resp["LastModifiedTime"], datetime.datetime)) - assert_true("SecondaryStatusTransitions" in resp) - assert_true("Status" in resp["SecondaryStatusTransitions"][0]) - assert_true("StartTime" in resp["SecondaryStatusTransitions"][0]) - assert_true("EndTime" in resp["SecondaryStatusTransitions"][0]) - assert_true("StatusMessage" in resp["SecondaryStatusTransitions"][0]) - assert_true("FinalMetricDataList" in resp) - assert_true("MetricName" in resp["FinalMetricDataList"][0]) - assert_true("Value" in resp["FinalMetricDataList"][0]) - assert_true("Timestamp" in resp["FinalMetricDataList"][0]) + assert resp["TrainingJobStatus"] == "Completed" + assert resp["SecondaryStatus"] == "Completed" + assert resp["HyperParameters"] == params["HyperParameters"] + assert \ + resp["AlgorithmSpecification"]["TrainingImage"] == \ + params["AlgorithmSpecification"]["TrainingImage"] + assert \ + resp["AlgorithmSpecification"]["TrainingInputMode"] == \ + params["AlgorithmSpecification"]["TrainingInputMode"] + assert "MetricDefinitions" in resp["AlgorithmSpecification"] + assert "Name" in resp["AlgorithmSpecification"]["MetricDefinitions"][0] + assert "Regex" in resp["AlgorithmSpecification"]["MetricDefinitions"][0] + assert resp["RoleArn"] == FAKE_ROLE_ARN + assert resp["InputDataConfig"] == params["InputDataConfig"] + assert resp["OutputDataConfig"] == params["OutputDataConfig"] + assert resp["ResourceConfig"] == params["ResourceConfig"] + assert resp["StoppingCondition"] == params["StoppingCondition"] + assert isinstance(resp["CreationTime"], datetime.datetime) + assert isinstance(resp["TrainingStartTime"], datetime.datetime) + assert isinstance(resp["TrainingEndTime"], datetime.datetime) + assert isinstance(resp["LastModifiedTime"], datetime.datetime) + assert "SecondaryStatusTransitions" in resp + assert "Status" in resp["SecondaryStatusTransitions"][0] + assert "StartTime" in resp["SecondaryStatusTransitions"][0] + assert "EndTime" in resp["SecondaryStatusTransitions"][0] + assert "StatusMessage" in resp["SecondaryStatusTransitions"][0] + assert "FinalMetricDataList" in resp + assert "MetricName" in resp["FinalMetricDataList"][0] + assert "Value" in resp["FinalMetricDataList"][0] + assert "Timestamp" in resp["FinalMetricDataList"][0] pass diff --git a/tests/test_secretsmanager/__init__.py b/tests/test_secretsmanager/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_secretsmanager/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_secretsmanager/test_list_secrets.py b/tests/test_secretsmanager/test_list_secrets.py index 5470e3e12..826e09de7 100644 --- a/tests/test_secretsmanager/test_list_secrets.py +++ b/tests/test_secretsmanager/test_list_secrets.py @@ -6,12 +6,7 @@ import boto3 from moto import mock_secretsmanager from botocore.exceptions import ClientError import sure # noqa -from nose.tools import assert_raises - -try: - from nose.tools import assert_items_equal -except ImportError: - from nose.tools import assert_count_equal as assert_items_equal +import pytest def boto_client(): @@ -24,7 +19,7 @@ def test_empty(): secrets = conn.list_secrets() - assert_items_equal(secrets["SecretList"], []) + assert secrets["SecretList"] == [] @mock_secretsmanager @@ -60,7 +55,7 @@ def test_with_name_filter(): secrets = conn.list_secrets(Filters=[{"Key": "name", "Values": ["foo"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -75,7 +70,7 @@ def test_with_tag_key_filter(): secrets = conn.list_secrets(Filters=[{"Key": "tag-key", "Values": ["baz"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -90,7 +85,7 @@ def test_with_tag_value_filter(): secrets = conn.list_secrets(Filters=[{"Key": "tag-value", "Values": ["baz"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -103,7 +98,7 @@ def test_with_description_filter(): secrets = conn.list_secrets(Filters=[{"Key": "description", "Values": ["baz"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -128,14 +123,14 @@ 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_items_equal(secret_names, ["foo", "bar", "baz", "qux", "multi"]) + assert secret_names == ["foo", "bar", "baz", "qux", "multi"] @mock_secretsmanager def test_with_no_filter_key(): conn = boto_client() - with assert_raises(ClientError) as ire: + with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Values": ["foo"]}]) ire.exception.response["Error"]["Code"].should.equal("InvalidParameterException") @@ -148,7 +143,7 @@ def test_with_no_filter_values(): conn.create_secret(Name="foo", SecretString="secret", Description="hello") - with assert_raises(ClientError) as ire: + with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Key": "description"}]) ire.exception.response["Error"]["Code"].should.equal("InvalidParameterException") @@ -161,7 +156,7 @@ def test_with_no_filter_values(): def test_with_invalid_filter_key(): conn = boto_client() - with assert_raises(ClientError) as ire: + with pytest.raises(ClientError) as ire: conn.list_secrets(Filters=[{"Key": "invalid", "Values": ["foo"]}]) ire.exception.response["Error"]["Code"].should.equal("ValidationException") @@ -190,7 +185,7 @@ def test_with_duplicate_filter_keys(): ) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -220,7 +215,7 @@ def test_with_multiple_filters(): ) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo"]) + assert secret_names == ["foo"] @mock_secretsmanager @@ -234,7 +229,7 @@ def test_with_filter_with_multiple_values(): secrets = conn.list_secrets(Filters=[{"Key": "name", "Values": ["foo", "bar"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo", "bar"]) + assert secret_names == ["foo", "bar"] @mock_secretsmanager @@ -250,4 +245,4 @@ def test_with_filter_with_value_with_multiple_words(): secrets = conn.list_secrets(Filters=[{"Key": "description", "Values": ["one two"]}]) secret_names = list(map(lambda s: s["Name"], secrets["SecretList"])) - assert_items_equal(secret_names, ["foo", "bar"]) + assert secret_names == ["foo", "bar"] diff --git a/tests/test_secretsmanager/test_secretsmanager.py b/tests/test_secretsmanager/test_secretsmanager.py index 68a7e6742..301ceb081 100644 --- a/tests/test_secretsmanager/test_secretsmanager.py +++ b/tests/test_secretsmanager/test_secretsmanager.py @@ -9,7 +9,7 @@ import string import pytz from datetime import datetime import sure # noqa -from nose.tools import assert_raises, assert_equal +import pytest from six import b DEFAULT_SECRET_NAME = "test-secret" @@ -53,13 +53,12 @@ def test_get_secret_value_binary(): def test_get_secret_that_does_not_exist(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: result = conn.get_secret_value(SecretId="i-dont-exist") - assert_equal( - "Secrets Manager can't find the specified secret.", - cm.exception.response["Error"]["Message"], - ) + assert \ + "Secrets Manager can't find the specified secret." == \ + cm.exception.response["Error"]["Message"] @mock_secretsmanager @@ -69,13 +68,12 @@ def test_get_secret_that_does_not_match(): Name="java-util-test-password", SecretString="foosecret" ) - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: result = conn.get_secret_value(SecretId="i-dont-match") - assert_equal( - "Secrets Manager can't find the specified secret.", - cm.exception.response["Error"]["Message"], - ) + assert \ + "Secrets Manager can't find the specified secret." == \ + cm.exception.response["Error"]["Message"] @mock_secretsmanager @@ -86,7 +84,7 @@ def test_get_secret_value_that_is_marked_deleted(): conn.delete_secret(SecretId="test-secret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.get_secret_value(SecretId="test-secret") @@ -96,13 +94,12 @@ def test_get_secret_that_has_no_value(): create_secret = conn.create_secret(Name="java-util-test-password") - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: result = conn.get_secret_value(SecretId="java-util-test-password") - assert_equal( - "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT", - cm.exception.response["Error"]["Message"], - ) + assert \ + "Secrets Manager can't find the specified secret value for staging label: AWSCURRENT" == \ + cm.exception.response["Error"] @mock_secretsmanager @@ -227,7 +224,7 @@ def test_delete_secret_force(): assert result["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert result["Name"] == "test-secret" - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.get_secret_value(SecretId="test-secret") @@ -245,7 +242,7 @@ def test_delete_secret_force_with_arn(): assert result["DeletionDate"] > datetime.fromtimestamp(1, pytz.utc) assert result["Name"] == "test-secret" - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.get_secret_value(SecretId="test-secret") @@ -253,7 +250,7 @@ def test_delete_secret_force_with_arn(): def test_delete_secret_that_does_not_exist(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.delete_secret( SecretId="i-dont-exist", ForceDeleteWithoutRecovery=True ) @@ -265,7 +262,7 @@ def test_delete_secret_fails_with_both_force_delete_flag_and_recovery_window_fla conn.create_secret(Name="test-secret", SecretString="foosecret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.delete_secret( SecretId="test-secret", RecoveryWindowInDays=1, @@ -279,7 +276,7 @@ def test_delete_secret_recovery_window_too_short(): conn.create_secret(Name="test-secret", SecretString="foosecret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.delete_secret(SecretId="test-secret", RecoveryWindowInDays=6) @@ -289,7 +286,7 @@ def test_delete_secret_recovery_window_too_long(): conn.create_secret(Name="test-secret", SecretString="foosecret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.delete_secret(SecretId="test-secret", RecoveryWindowInDays=31) @@ -301,7 +298,7 @@ def test_delete_secret_that_is_marked_deleted(): deleted_secret = conn.delete_secret(SecretId="test-secret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.delete_secret(SecretId="test-secret") @@ -339,7 +336,7 @@ def test_get_random_exclude_lowercase(): conn = boto3.client("secretsmanager", region_name="us-west-2") random_password = conn.get_random_password(PasswordLength=55, ExcludeLowercase=True) - assert any(c.islower() for c in random_password["RandomPassword"]) == False + assert not any(c.islower() for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -347,7 +344,7 @@ def test_get_random_exclude_uppercase(): conn = boto3.client("secretsmanager", region_name="us-west-2") random_password = conn.get_random_password(PasswordLength=55, ExcludeUppercase=True) - assert any(c.isupper() for c in random_password["RandomPassword"]) == False + assert not any(c.isupper() for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -357,7 +354,7 @@ def test_get_random_exclude_characters_and_symbols(): random_password = conn.get_random_password( PasswordLength=20, ExcludeCharacters="xyzDje@?!." ) - assert any(c in "xyzDje@?!." for c in random_password["RandomPassword"]) == False + assert not any(c in "xyzDje@?!." for c in random_password["RandomPassword"]) assert len(random_password["RandomPassword"]) == 20 @@ -366,7 +363,7 @@ def test_get_random_exclude_numbers(): conn = boto3.client("secretsmanager", region_name="us-west-2") random_password = conn.get_random_password(PasswordLength=100, ExcludeNumbers=True) - assert any(c.isdigit() for c in random_password["RandomPassword"]) == False + assert not any(c.isdigit() for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -376,9 +373,7 @@ def test_get_random_exclude_punctuation(): random_password = conn.get_random_password( PasswordLength=100, ExcludePunctuation=True ) - assert ( - any(c in string.punctuation for c in random_password["RandomPassword"]) == False - ) + assert not any(c in string.punctuation for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -386,7 +381,7 @@ def test_get_random_include_space_false(): conn = boto3.client("secretsmanager", region_name="us-west-2") random_password = conn.get_random_password(PasswordLength=300) - assert any(c.isspace() for c in random_password["RandomPassword"]) == False + assert not any(c.isspace() for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -394,7 +389,7 @@ def test_get_random_include_space_true(): conn = boto3.client("secretsmanager", region_name="us-west-2") random_password = conn.get_random_password(PasswordLength=4, IncludeSpace=True) - assert any(c.isspace() for c in random_password["RandomPassword"]) == True + assert any(c.isspace() for c in random_password["RandomPassword"]) @mock_secretsmanager @@ -404,25 +399,17 @@ def test_get_random_require_each_included_type(): random_password = conn.get_random_password( PasswordLength=4, RequireEachIncludedType=True ) - assert ( - any(c in string.punctuation for c in random_password["RandomPassword"]) == True - ) - assert ( - any(c in string.ascii_lowercase for c in random_password["RandomPassword"]) - == True - ) - assert ( - any(c in string.ascii_uppercase for c in random_password["RandomPassword"]) - == True - ) - assert any(c in string.digits for c in random_password["RandomPassword"]) == True + assert any(c in string.punctuation for c in random_password["RandomPassword"]) + assert any(c in string.ascii_lowercase for c in random_password["RandomPassword"]) + assert any(c in string.ascii_uppercase for c in random_password["RandomPassword"]) + assert any(c in string.digits for c in random_password["RandomPassword"]) @mock_secretsmanager def test_get_random_too_short_password(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError): + with pytest.raises(ClientError): random_password = conn.get_random_password(PasswordLength=3) @@ -430,7 +417,7 @@ def test_get_random_too_short_password(): def test_get_random_too_long_password(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(Exception): + with pytest.raises(Exception): random_password = conn.get_random_password(PasswordLength=5555) @@ -468,7 +455,7 @@ def test_describe_secret_with_arn(): def test_describe_secret_that_does_not_exist(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.get_secret_value(SecretId="i-dont-exist") @@ -477,7 +464,7 @@ def test_describe_secret_that_does_not_match(): conn = boto3.client("secretsmanager", region_name="us-west-2") conn.create_secret(Name="test-secret", SecretString="foosecret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.get_secret_value(SecretId="i-dont-match") @@ -515,7 +502,7 @@ def test_restore_secret_that_is_not_deleted(): def test_restore_secret_that_does_not_exist(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.restore_secret(SecretId="i-dont-exist") @@ -566,7 +553,7 @@ def test_rotate_secret_that_is_marked_deleted(): conn.delete_secret(SecretId="test-secret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret(SecretId="test-secret") @@ -574,7 +561,7 @@ def test_rotate_secret_that_is_marked_deleted(): def test_rotate_secret_that_does_not_exist(): conn = boto3.client("secretsmanager", "us-west-2") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret(SecretId="i-dont-exist") @@ -583,7 +570,7 @@ def test_rotate_secret_that_does_not_match(): conn = boto3.client("secretsmanager", region_name="us-west-2") conn.create_secret(Name="test-secret", SecretString="foosecret") - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret(SecretId="i-dont-match") @@ -603,7 +590,7 @@ def test_rotate_secret_client_request_token_too_long(): client_request_token = ( "ED9F8B6C-85B7-446A-B7E4-38F2A3BEB13C-" "ED9F8B6C-85B7-446A-B7E4-38F2A3BEB13C" ) - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret( SecretId=DEFAULT_SECRET_NAME, ClientRequestToken=client_request_token ) @@ -615,7 +602,7 @@ def test_rotate_secret_rotation_lambda_arn_too_long(): conn.create_secret(Name=DEFAULT_SECRET_NAME, SecretString="foosecret") rotation_lambda_arn = "85B7-446A-B7E4" * 147 # == 2058 characters - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret( SecretId=DEFAULT_SECRET_NAME, RotationLambdaARN=rotation_lambda_arn ) @@ -635,7 +622,7 @@ def test_rotate_secret_rotation_period_too_long(): conn.create_secret(Name=DEFAULT_SECRET_NAME, SecretString="foosecret") rotation_rules = {"AutomaticallyAfterDays": 1001} - with assert_raises(ClientError): + with pytest.raises(ClientError): result = conn.rotate_secret( SecretId=DEFAULT_SECRET_NAME, RotationRules=rotation_rules ) @@ -712,7 +699,7 @@ def test_create_and_put_secret_binary_value_puts_new_secret(): @mock_secretsmanager def test_put_secret_binary_requires_either_string_or_binary(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError) as ire: + with pytest.raises(ClientError) as ire: conn.put_secret_value(SecretId=DEFAULT_SECRET_NAME) ire.exception.response["Error"]["Code"].should.equal("InvalidRequestException") @@ -889,15 +876,14 @@ def test_update_secret_with_tags_and_description(): def test_update_secret_which_does_not_exit(): conn = boto3.client("secretsmanager", region_name="us-west-2") - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: updated_secret = conn.update_secret( SecretId="test-secret", SecretString="barsecret" ) - assert_equal( - "Secrets Manager can't find the specified secret.", - cm.exception.response["Error"]["Message"], - ) + assert \ + "Secrets Manager can't find the specified secret." == \ + cm.exception.response["Error"]["Message"] @mock_secretsmanager @@ -907,7 +893,7 @@ def test_update_secret_marked_as_deleted(): created_secret = conn.create_secret(Name="test-secret", SecretString="foosecret") deleted_secret = conn.delete_secret(SecretId="test-secret") - with assert_raises(ClientError) as cm: + with pytest.raises(ClientError) as cm: updated_secret = conn.update_secret( SecretId="test-secret", SecretString="barsecret" ) diff --git a/tests/test_ses/__init__.py b/tests/test_ses/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_ses/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_ses/test_ses_boto3.py b/tests/test_ses/test_ses_boto3.py index efd4b980c..f0af73fd3 100644 --- a/tests/test_ses/test_ses_boto3.py +++ b/tests/test_ses/test_ses_boto3.py @@ -4,7 +4,7 @@ import boto3 from botocore.exceptions import ClientError from six.moves.email_mime_multipart import MIMEMultipart from six.moves.email_mime_text import MIMEText -from nose.tools import assert_raises +import pytest import sure # noqa @@ -298,7 +298,7 @@ def test_create_configuration_set(): }, ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_configuration_set_event_destination( ConfigurationSetName="failtest", EventDestination={ @@ -313,7 +313,7 @@ def test_create_configuration_set(): ex.exception.response["Error"]["Code"].should.equal("ConfigurationSetDoesNotExist") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_configuration_set_event_destination( ConfigurationSetName="test", EventDestination={ @@ -336,7 +336,7 @@ def test_create_receipt_rule_set(): result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_receipt_rule_set(RuleSetName="testRuleSet") ex.exception.response["Error"]["Code"].should.equal("RuleSetNameAlreadyExists") @@ -378,7 +378,7 @@ def test_create_receipt_rule(): result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_receipt_rule( RuleSetName=rule_set_name, Rule={ @@ -409,7 +409,7 @@ def test_create_receipt_rule(): ex.exception.response["Error"]["Code"].should.equal("RuleAlreadyExists") - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_receipt_rule( RuleSetName="InvalidRuleSetaName", Rule={ @@ -455,7 +455,7 @@ def test_create_ses_template(): "

Your favorite animal is {{favoriteanimal}}.

", } ) - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.create_template( Template={ "TemplateName": "MyTemplate", @@ -475,7 +475,7 @@ def test_create_ses_template(): result["Template"]["SubjectPart"].should.equal("Greetings, {{name}}!") # get a template which is not present - with assert_raises(ClientError) as ex: + with pytest.raises(ClientError) as ex: conn.get_template(TemplateName="MyFakeTemplate") ex.exception.response["Error"]["Code"].should.equal("TemplateDoesNotExist") diff --git a/tests/test_ses/test_ses_sns_boto3.py b/tests/test_ses/test_ses_sns_boto3.py index 43d4000bf..2a165080e 100644 --- a/tests/test_ses/test_ses_sns_boto3.py +++ b/tests/test_ses/test_ses_sns_boto3.py @@ -7,7 +7,6 @@ from six.moves.email_mime_multipart import MIMEMultipart from six.moves.email_mime_text import MIMEText import sure # noqa -from nose import tools from moto import mock_ses, mock_sns, mock_sqs from moto.ses.models import SESFeedback from moto.core import ACCOUNT_ID diff --git a/tests/test_sns/__init__.py b/tests/test_sns/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_sns/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_sns/test_publishing_boto3.py b/tests/test_sns/test_publishing_boto3.py index 63c409302..07bf04b11 100644 --- a/tests/test_sns/test_publishing_boto3.py +++ b/tests/test_sns/test_publishing_boto3.py @@ -10,7 +10,7 @@ import sure # noqa import responses from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_sns, mock_sqs, settings from moto.core import ACCOUNT_ID from moto.sns import sns_backend @@ -233,13 +233,13 @@ def test_publish_bad_sms(): client = boto3.client("sns", region_name="us-east-1") # Test invalid number - with assert_raises(ClientError) as cm: + 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") # Test to long ASCII message - with assert_raises(ClientError) as cm: + 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") @@ -387,7 +387,7 @@ def test_publish_message_too_long(): sns = boto3.resource("sns", region_name="us-east-1") topic = sns.create_topic(Name="some-topic") - with assert_raises(ClientError): + with pytest.raises(ClientError): topic.publish(Message="".join(["." for i in range(0, 262145)])) # message short enough - does not raise an error diff --git a/tests/test_sns/test_subscriptions_boto3.py b/tests/test_sns/test_subscriptions_boto3.py index c15658dca..b476cd86d 100644 --- a/tests/test_sns/test_subscriptions_boto3.py +++ b/tests/test_sns/test_subscriptions_boto3.py @@ -5,7 +5,7 @@ import json import sure # noqa from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_sns, mock_sqs from moto.sns.models import ( @@ -293,7 +293,7 @@ def test_creating_subscription_with_attributes(): subscriptions.should.have.length_of(0) # invalid attr name - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.subscribe( TopicArn=topic_arn, Protocol="http", @@ -387,17 +387,17 @@ def test_set_subscription_attributes(): attrs["Attributes"]["FilterPolicy"].should.equal(filter_policy) # not existing subscription - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.set_subscription_attributes( SubscriptionArn="invalid", AttributeName="RawMessageDelivery", AttributeValue="true", ) - with assert_raises(ClientError): + with pytest.raises(ClientError): attrs = conn.get_subscription_attributes(SubscriptionArn="invalid") # invalid attr name - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.set_subscription_attributes( SubscriptionArn=subscription_arn, AttributeName="InvalidName", @@ -502,7 +502,7 @@ def test_check_opted_out_invalid(): conn = boto3.client("sns", region_name="us-east-1") # Invalid phone number - with assert_raises(ClientError): + with pytest.raises(ClientError): conn.check_if_phone_number_is_opted_out(phoneNumber="+44742LALALA") diff --git a/tests/test_sqs/__init__.py b/tests/test_sqs/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_sqs/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_sqs/test_sqs.py b/tests/test_sqs/test_sqs.py index b974e04f6..b0a91bbde 100644 --- a/tests/test_sqs/test_sqs.py +++ b/tests/test_sqs/test_sqs.py @@ -11,14 +11,13 @@ import boto3 import botocore.exceptions import six import sure # noqa -import tests.backport_assert_raises # noqa from boto.exception import SQSError from boto.sqs.message import Message, RawMessage from botocore.exceptions import ClientError from freezegun import freeze_time from moto import mock_sqs, mock_sqs_deprecated, mock_lambda, mock_logs, settings -from nose import SkipTest -from nose.tools import assert_raises +from unittest import SkipTest +import pytest from tests.helpers import requires_boto_gte from tests.test_awslambda.test_lambda import get_test_zip_file1, get_role_name from moto.core import ACCOUNT_ID @@ -220,7 +219,7 @@ def test_get_queue_url_errors(): @mock_sqs def test_get_nonexistent_queue(): sqs = boto3.resource("sqs", region_name="us-east-1") - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: sqs.get_queue_by_name(QueueName="non-existing-queue") ex = err.exception ex.operation_name.should.equal("GetQueueUrl") @@ -229,7 +228,7 @@ def test_get_nonexistent_queue(): "The specified queue non-existing-queue does not exist for this wsdl version." ) - with assert_raises(ClientError) as err: + with pytest.raises(ClientError) as err: sqs.Queue("http://whatever-incorrect-queue-address").load() ex = err.exception ex.operation_name.should.equal("GetQueueAttributes") @@ -368,7 +367,7 @@ def test_message_with_attributes_invalid_datatype(): sqs = boto3.resource("sqs", region_name="us-east-1") queue = sqs.create_queue(QueueName="blah") - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: queue.send_message( MessageBody="derp", MessageAttributes={ @@ -491,7 +490,7 @@ def test_delete_queue(): queue.delete() conn.list_queues().get("QueueUrls").should.equal(None) - with assert_raises(botocore.exceptions.ClientError): + with pytest.raises(botocore.exceptions.ClientError): queue.delete() @@ -758,10 +757,10 @@ def test_max_number_of_messages_invalid_param(): sqs = boto3.resource("sqs", region_name="us-east-1") queue = sqs.create_queue(QueueName="test-queue") - with assert_raises(ClientError): + with pytest.raises(ClientError): queue.receive_messages(MaxNumberOfMessages=11) - with assert_raises(ClientError): + with pytest.raises(ClientError): queue.receive_messages(MaxNumberOfMessages=0) # no error but also no messages returned @@ -773,10 +772,10 @@ def test_wait_time_seconds_invalid_param(): sqs = boto3.resource("sqs", region_name="us-east-1") queue = sqs.create_queue(QueueName="test-queue") - with assert_raises(ClientError): + with pytest.raises(ClientError): queue.receive_messages(WaitTimeSeconds=-1) - with assert_raises(ClientError): + with pytest.raises(ClientError): queue.receive_messages(WaitTimeSeconds=21) # no error but also no messages returned @@ -1652,7 +1651,7 @@ def test_add_permission_errors(): Actions=["ReceiveMessage"], ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.add_permission( QueueUrl=queue_url, Label="test", @@ -1667,7 +1666,7 @@ def test_add_permission_errors(): "Value test for parameter Label is invalid. " "Reason: Already exists." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.add_permission( QueueUrl=queue_url, Label="test-2", @@ -1683,7 +1682,7 @@ def test_add_permission_errors(): "Reason: Only the queue owner is allowed to invoke this action." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.add_permission( QueueUrl=queue_url, Label="test-2", @@ -1698,7 +1697,7 @@ def test_add_permission_errors(): "The request must contain the parameter Actions." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.add_permission( QueueUrl=queue_url, Label="test-2", @@ -1713,7 +1712,7 @@ def test_add_permission_errors(): "Value [] for parameter PrincipalId is invalid. Reason: Unable to verify." ) - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.add_permission( QueueUrl=queue_url, Label="test-2", @@ -1744,7 +1743,7 @@ def test_remove_permission_errors(): response = client.create_queue(QueueName="test-queue") queue_url = response["QueueUrl"] - with assert_raises(ClientError) as e: + with pytest.raises(ClientError) as e: client.remove_permission(QueueUrl=queue_url, Label="test") ex = e.exception ex.operation_name.should.equal("RemovePermission") @@ -1876,7 +1875,7 @@ def test_create_fifo_queue_with_dlq(): ) # Cant have fifo queue with non fifo DLQ - with assert_raises(ClientError): + with pytest.raises(ClientError): sqs.create_queue( QueueName="test-queue2.fifo", Attributes={ @@ -1970,7 +1969,7 @@ def test_redrive_policy_available(): assert json.loads(attributes["RedrivePolicy"]) == redrive_policy # Cant have redrive policy without maxReceiveCount - with assert_raises(ClientError): + with pytest.raises(ClientError): sqs.create_queue( QueueName="test-queue2", Attributes={ @@ -1988,7 +1987,7 @@ def test_redrive_policy_non_existent_queue(): "maxReceiveCount": 1, } - with assert_raises(ClientError): + with pytest.raises(ClientError): sqs.create_queue( QueueName="test-queue", Attributes={"RedrivePolicy": json.dumps(redrive_policy)}, @@ -2173,7 +2172,7 @@ def test_send_messages_to_fifo_without_message_group_id(): Attributes={"FifoQueue": "true", "ContentBasedDeduplication": "true"}, ) - with assert_raises(Exception) as e: + with pytest.raises(Exception) as e: queue.send_message(MessageBody="message-1") ex = e.exception ex.response["Error"]["Code"].should.equal("MissingParameter") diff --git a/tests/test_ssm/__init__.py b/tests/test_ssm/__init__.py index e69de29bb..08a1c1568 100644 --- a/tests/test_ssm/__init__.py +++ b/tests/test_ssm/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_ssm/test_ssm_boto3.py b/tests/test_ssm/test_ssm_boto3.py index c590e75b7..e3c03203f 100644 --- a/tests/test_ssm/test_ssm_boto3.py +++ b/tests/test_ssm/test_ssm_boto3.py @@ -9,7 +9,7 @@ import datetime import uuid from botocore.exceptions import ClientError, ParamValidationError -from nose.tools import assert_raises +import pytest from moto import mock_ec2, mock_ssm @@ -1671,7 +1671,7 @@ def test_list_commands(): cmd["InstanceIds"].should.contain("i-123456") # test the error case for an invalid command id - with assert_raises(ClientError): + with pytest.raises(ClientError): response = client.list_commands(CommandId=str(uuid.uuid4())) @@ -1703,13 +1703,13 @@ def test_get_command_invocation(): invocation_response["InstanceId"].should.equal(instance_id) # test the error case for an invalid instance id - with assert_raises(ClientError): + with pytest.raises(ClientError): invocation_response = client.get_command_invocation( CommandId=cmd_id, InstanceId="i-FAKE" ) # test the error case for an invalid plugin name - with assert_raises(ClientError): + with pytest.raises(ClientError): invocation_response = client.get_command_invocation( CommandId=cmd_id, InstanceId=instance_id, PluginName="FAKE" ) diff --git a/tests/test_stepfunctions/__init__.py b/tests/test_stepfunctions/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_stepfunctions/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_stepfunctions/test_stepfunctions.py b/tests/test_stepfunctions/test_stepfunctions.py index dd11e7961..1a946e8e3 100644 --- a/tests/test_stepfunctions/test_stepfunctions.py +++ b/tests/test_stepfunctions/test_stepfunctions.py @@ -6,7 +6,7 @@ import sure # noqa from datetime import datetime from botocore.exceptions import ClientError -from nose.tools import assert_raises +import pytest from moto import mock_cloudformation, mock_sts, mock_stepfunctions from moto.core import ACCOUNT_ID @@ -134,7 +134,7 @@ def test_state_machine_creation_fails_with_invalid_names(): # for invalid_name in invalid_names: - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_state_machine( name=invalid_name, definition=str(simple_definition), @@ -147,7 +147,7 @@ def test_state_machine_creation_requires_valid_role_arn(): client = boto3.client("stepfunctions", region_name=region) name = "example_step_function" # - with assert_raises(ClientError): + with pytest.raises(ClientError): client.create_state_machine( name=name, definition=str(simple_definition), @@ -291,7 +291,7 @@ def test_state_machine_creation_can_be_described(): def test_state_machine_throws_error_when_describing_unknown_machine(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): unknown_state_machine = ( "arn:aws:states:" + region @@ -307,7 +307,7 @@ def test_state_machine_throws_error_when_describing_unknown_machine(): def test_state_machine_throws_error_when_describing_bad_arn(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): client.describe_state_machine(stateMachineArn="bad") @@ -316,7 +316,7 @@ def test_state_machine_throws_error_when_describing_bad_arn(): def test_state_machine_throws_error_when_describing_machine_in_different_account(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): unknown_state_machine = ( "arn:aws:states:" + region + ":000000000000:stateMachine:unknown" ) @@ -504,7 +504,7 @@ def test_state_machine_start_execution(): def test_state_machine_start_execution_bad_arn_raises_exception(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): client.start_execution(stateMachineArn="bad") @@ -544,7 +544,7 @@ def test_state_machine_start_execution_fails_on_duplicate_execution_name(): stateMachineArn=sm["stateMachineArn"], name="execution_name" ) # - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: _ = client.start_execution( stateMachineArn=sm["stateMachineArn"], name="execution_name" ) @@ -588,9 +588,9 @@ def test_state_machine_start_execution_with_invalid_input(): sm = client.create_state_machine( name="name", definition=str(simple_definition), roleArn=_get_default_role() ) - with assert_raises(ClientError): + with pytest.raises(ClientError): _ = client.start_execution(stateMachineArn=sm["stateMachineArn"], input="") - with assert_raises(ClientError): + with pytest.raises(ClientError): _ = client.start_execution(stateMachineArn=sm["stateMachineArn"], input="{") @@ -744,7 +744,7 @@ def test_state_machine_describe_execution_with_custom_input(): def test_execution_throws_error_when_describing_unknown_execution(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): unknown_execution = ( "arn:aws:states:" + region + ":" + _get_account_id() + ":execution:unknown" ) @@ -775,7 +775,7 @@ def test_state_machine_can_be_described_by_execution(): def test_state_machine_throws_error_when_describing_unknown_execution(): client = boto3.client("stepfunctions", region_name=region) # - with assert_raises(ClientError): + with pytest.raises(ClientError): unknown_execution = ( "arn:aws:states:" + region + ":" + _get_account_id() + ":execution:unknown" ) diff --git a/tests/test_sts/__init__.py b/tests/test_sts/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_sts/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tests/test_sts/test_sts.py b/tests/test_sts/test_sts.py index efc04beb4..34b71c358 100644 --- a/tests/test_sts/test_sts.py +++ b/tests/test_sts/test_sts.py @@ -6,7 +6,7 @@ import boto import boto3 from botocore.client import ClientError from freezegun import freeze_time -from nose.tools import assert_raises +import pytest import sure # noqa @@ -357,7 +357,7 @@ def test_federation_token_with_too_long_policy(): json_policy = json.dumps(policy) assert len(json_policy) > MAX_FEDERATION_TOKEN_POLICY_LENGTH - with assert_raises(ClientError) as exc: + with pytest.raises(ClientError) as exc: 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( diff --git a/tests/test_swf/models/test_domain.py b/tests/test_swf/models/test_domain.py index 32940753f..9e7579ddd 100644 --- a/tests/test_swf/models/test_domain.py +++ b/tests/test_swf/models/test_domain.py @@ -4,9 +4,6 @@ import sure # noqa from moto.swf.exceptions import SWFUnknownResourceFault from moto.swf.models import Domain -# Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa - # Fake WorkflowExecution for tests purposes WorkflowExecution = namedtuple( "WorkflowExecution", ["workflow_id", "run_id", "execution_status", "open"] diff --git a/tests/test_swf/responses/test_workflow_executions.py b/tests/test_swf/responses/test_workflow_executions.py index bec352ce8..2832abf75 100644 --- a/tests/test_swf/responses/test_workflow_executions.py +++ b/tests/test_swf/responses/test_workflow_executions.py @@ -4,9 +4,6 @@ from datetime import datetime, timedelta import sure # noqa -# Ensure 'assert_raises' context manager support for Python 2.6 -import tests.backport_assert_raises # noqa - from moto import mock_swf_deprecated from moto.core.utils import unix_time diff --git a/tests/test_xray/__init__.py b/tests/test_xray/__init__.py new file mode 100644 index 000000000..08a1c1568 --- /dev/null +++ b/tests/test_xray/__init__.py @@ -0,0 +1 @@ +# This file is intentionally left blank. diff --git a/tox.ini b/tox.ini index 9dacca18c..f77df29b3 100644 --- a/tox.ini +++ b/tox.ini @@ -12,7 +12,7 @@ deps = -r{toxinidir}/requirements-dev.txt commands = {envpython} setup.py test - nosetests {posargs} + pytest -v {posargs} [flake8] ignore = W503,W605,E128,E501,E203,E266,E501,E231