This commit is contained in:
Bert Blommers 2020-03-30 13:42:00 +01:00
parent 3ece2dabff
commit 888e0c31a0
7 changed files with 96 additions and 140 deletions

View File

@ -1,11 +1,4 @@
from __future__ import unicode_literals
import logging
# logging.getLogger('boto').setLevel(logging.CRITICAL)
__title__ = "moto"
__version__ = "1.3.15.dev"
from .acm import mock_acm # noqa
from .apigateway import mock_apigateway, mock_apigateway_deprecated # noqa
@ -28,7 +21,7 @@ from .datasync import mock_datasync # noqa
from .dynamodb import mock_dynamodb, mock_dynamodb_deprecated # noqa
from .dynamodb2 import mock_dynamodb2, mock_dynamodb2_deprecated # noqa
from .dynamodbstreams import mock_dynamodbstreams # noqa
from .eb import mock_eb # flake8: noqa
from .eb import mock_eb # noqa
from .ec2 import mock_ec2, mock_ec2_deprecated # noqa
from .ec2_instance_connect import mock_ec2_instance_connect # noqa
from .ecr import mock_ecr, mock_ecr_deprecated # noqa
@ -65,6 +58,12 @@ from .sts import mock_sts, mock_sts_deprecated # noqa
from .swf import mock_swf, mock_swf_deprecated # noqa
from .xray import XRaySegment, mock_xray, mock_xray_client # noqa
# import logging
# logging.getLogger('boto').setLevel(logging.CRITICAL)
__title__ = "moto"
__version__ = "1.3.15.dev"
try:
# Need to monkey-patch botocore requests back to underlying urllib3 classes

View File

@ -331,10 +331,7 @@ def py2_strip_unicode_keys(blob):
def tags_from_query_string(
querystring_dict,
prefix="Tag",
key_suffix="Key",
value_suffix="Value"
querystring_dict, prefix="Tag", key_suffix="Key", value_suffix="Value"
):
response_values = {}
for key, value in querystring_dict.items():
@ -342,18 +339,14 @@ def tags_from_query_string(
tag_index = key.replace(prefix + ".", "").replace("." + key_suffix, "")
tag_key = querystring_dict.get(
"{prefix}.{index}.{key_suffix}".format(
prefix=prefix,
index=tag_index,
key_suffix=key_suffix,
))[0]
prefix=prefix, index=tag_index, key_suffix=key_suffix,
)
)[0]
tag_value_key = "{prefix}.{index}.{value_suffix}".format(
prefix=prefix,
index=tag_index,
value_suffix=value_suffix,
prefix=prefix, index=tag_index, value_suffix=value_suffix,
)
if tag_value_key in querystring_dict:
response_values[tag_key] = querystring_dict.get(tag_value_key)[
0]
response_values[tag_key] = querystring_dict.get(tag_value_key)[0]
else:
response_values[tag_key] = None
return response_values

View File

@ -4,10 +4,12 @@ from moto.core.exceptions import RESTError
class InvalidParameterValueError(RESTError):
def __init__(self, message):
super(InvalidParameterValueError, self).__init__(
"InvalidParameterValue", message)
"InvalidParameterValue", message
)
class ResourceNotFoundException(RESTError):
def __init__(self, message):
super(ResourceNotFoundException, self).__init__(
"ResourceNotFoundException", message)
"ResourceNotFoundException", message
)

View File

@ -8,13 +8,11 @@ from .exceptions import InvalidParameterValueError
class FakeEnvironment(BaseModel):
def __init__(
self,
application,
environment_name,
solution_stack_name,
tags,
self, application, environment_name, solution_stack_name, tags,
):
self.application = weakref.proxy(application) # weakref to break circular dependencies
self.application = weakref.proxy(
application
) # weakref to break circular dependencies
self.environment_name = environment_name
self.solution_stack_name = solution_stack_name
self.tags = tags
@ -25,17 +23,19 @@ class FakeEnvironment(BaseModel):
@property
def environment_arn(self):
return 'arn:aws:elasticbeanstalk:{region}:{account_id}:' \
'environment/{application_name}/{environment_name}'.format(
return (
"arn:aws:elasticbeanstalk:{region}:{account_id}:"
"environment/{application_name}/{environment_name}".format(
region=self.region,
account_id='123456789012',
account_id="123456789012",
application_name=self.application_name,
environment_name=self.environment_name,
)
)
@property
def platform_arn(self):
return 'TODO' # TODO
return "TODO" # TODO
@property
def region(self):
@ -49,10 +49,7 @@ class FakeApplication(BaseModel):
self.environments = dict()
def create_environment(
self,
environment_name,
solution_stack_name,
tags,
self, environment_name, solution_stack_name, tags,
):
if environment_name in self.environments:
raise InvalidParameterValueError
@ -89,13 +86,11 @@ class EBBackend(BaseBackend):
raise InvalidParameterValueError(
"Application {} already exists.".format(application_name)
)
new_app = FakeApplication(
backend=self,
application_name=application_name,
)
new_app = FakeApplication(backend=self, application_name=application_name,)
self.applications[application_name] = new_app
return new_app
eb_backends = dict((region.name, EBBackend(region.name))
for region in boto.beanstalk.regions())
eb_backends = dict(
(region.name, EBBackend(region.name)) for region in boto.beanstalk.regions()
)

View File

@ -14,42 +14,34 @@ class EBResponse(BaseResponse):
def create_application(self):
app = self.backend.create_application(
application_name=self._get_param('ApplicationName'),
application_name=self._get_param("ApplicationName"),
)
template = self.response_template(EB_CREATE_APPLICATION)
return template.render(
region_name=self.backend.region,
application=app,
)
return template.render(region_name=self.backend.region, application=app,)
def describe_applications(self):
template = self.response_template(EB_DESCRIBE_APPLICATIONS)
return template.render(
applications=self.backend.applications.values(),
)
return template.render(applications=self.backend.applications.values(),)
def create_environment(self):
application_name = self._get_param('ApplicationName')
application_name = self._get_param("ApplicationName")
try:
app = self.backend.applications[application_name]
except KeyError:
raise InvalidParameterValueError(
"No Application named \'{}\' found.".format(application_name)
"No Application named '{}' found.".format(application_name)
)
tags = tags_from_query_string(self.querystring, prefix="Tags.member")
env = app.create_environment(
environment_name=self._get_param('EnvironmentName'),
solution_stack_name=self._get_param('SolutionStackName'),
environment_name=self._get_param("EnvironmentName"),
solution_stack_name=self._get_param("SolutionStackName"),
tags=tags,
)
template = self.response_template(EB_CREATE_ENVIRONMENT)
return template.render(
environment=env,
region=self.backend.region,
)
return template.render(environment=env, region=self.backend.region,)
def describe_environments(self):
envs = []
@ -59,9 +51,7 @@ class EBResponse(BaseResponse):
envs.append(env)
template = self.response_template(EB_DESCRIBE_ENVIRONMENTS)
return template.render(
environments=envs,
)
return template.render(environments=envs,)
@staticmethod
def list_available_solution_stacks():
@ -75,39 +65,38 @@ class EBResponse(BaseResponse):
raise KeyError()
def update_tags_for_resource(self):
resource_arn = self._get_param('ResourceArn')
resource_arn = self._get_param("ResourceArn")
try:
res = self._find_environment_by_arn(resource_arn)
except KeyError:
raise ResourceNotFoundException(
"Resource not found for ARN \'{}\'.".format(resource_arn)
"Resource not found for ARN '{}'.".format(resource_arn)
)
tags_to_add = tags_from_query_string(self.querystring, prefix="TagsToAdd.member")
tags_to_add = tags_from_query_string(
self.querystring, prefix="TagsToAdd.member"
)
for key, value in tags_to_add.items():
res.tags[key] = value
tags_to_remove = self._get_multi_param('TagsToRemove.member')
tags_to_remove = self._get_multi_param("TagsToRemove.member")
for key in tags_to_remove:
del res.tags[key]
return EB_UPDATE_TAGS_FOR_RESOURCE
def list_tags_for_resource(self):
resource_arn = self._get_param('ResourceArn')
resource_arn = self._get_param("ResourceArn")
try:
res = self._find_environment_by_arn(resource_arn)
except KeyError:
raise ResourceNotFoundException(
"Resource not found for ARN \'{}\'.".format(resource_arn)
"Resource not found for ARN '{}'.".format(resource_arn)
)
tags = res.tags
template = self.response_template(EB_LIST_TAGS_FOR_RESOURCE)
return template.render(
tags=tags,
arn=resource_arn,
)
return template.render(tags=tags, arn=resource_arn,)
EB_CREATE_APPLICATION = """

View File

@ -7,5 +7,5 @@ url_bases = [
]
url_paths = {
'{0}/$': EBResponse.dispatch,
"{0}/$": EBResponse.dispatch,
}

View File

@ -8,114 +8,94 @@ from moto import mock_eb
@mock_eb
def test_create_application():
# Create Elastic Beanstalk Application
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
app = conn.create_application(
ApplicationName="myapp",
)
app['Application']['ApplicationName'].should.equal("myapp")
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
app = conn.create_application(ApplicationName="myapp",)
app["Application"]["ApplicationName"].should.equal("myapp")
@mock_eb
def test_create_application_dup():
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn.create_application(
ApplicationName="myapp",
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
conn.create_application(ApplicationName="myapp",)
conn.create_application.when.called_with(ApplicationName="myapp",).should.throw(
ClientError
)
conn.create_application.when.called_with(
ApplicationName="myapp",
).should.throw(ClientError)
@mock_eb
def test_describe_applications():
# Create Elastic Beanstalk Application
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn.create_application(
ApplicationName="myapp",
)
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
conn.create_application(ApplicationName="myapp",)
apps = conn.describe_applications()
len(apps['Applications']).should.equal(1)
apps['Applications'][0]['ApplicationName'].should.equal('myapp')
len(apps["Applications"]).should.equal(1)
apps["Applications"][0]["ApplicationName"].should.equal("myapp")
@mock_eb
def test_create_environment():
# Create Elastic Beanstalk Environment
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
app = conn.create_application(
ApplicationName="myapp",
)
env = conn.create_environment(
ApplicationName="myapp",
EnvironmentName="myenv",
)
env['EnvironmentName'].should.equal("myenv")
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
app = conn.create_application(ApplicationName="myapp",)
env = conn.create_environment(ApplicationName="myapp", EnvironmentName="myenv",)
env["EnvironmentName"].should.equal("myenv")
@mock_eb
def test_describe_environments():
# List Elastic Beanstalk Envs
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn.create_application(
ApplicationName="myapp",
)
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
conn.create_application(ApplicationName="myapp",)
conn.create_environment(
ApplicationName="myapp",
EnvironmentName="myenv",
ApplicationName="myapp", EnvironmentName="myenv",
)
envs = conn.describe_environments()
envs = envs['Environments']
envs = envs["Environments"]
len(envs).should.equal(1)
envs[0]['ApplicationName'].should.equal('myapp')
envs[0]['EnvironmentName'].should.equal('myenv')
envs[0]["ApplicationName"].should.equal("myapp")
envs[0]["EnvironmentName"].should.equal("myenv")
def tags_dict_to_list(tag_dict):
tag_list = []
for key, value in tag_dict.items():
tag_list.append({'Key': key, 'Value': value})
tag_list.append({"Key": key, "Value": value})
return tag_list
def tags_list_to_dict(tag_list):
tag_dict = {}
for tag in tag_list:
tag_dict[tag['Key']] = tag['Value']
tag_dict[tag["Key"]] = tag["Value"]
return tag_dict
@mock_eb
def test_create_environment_tags():
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn.create_application(
ApplicationName="myapp",
)
env_tags = {'initial key': 'initial value'}
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
conn.create_application(ApplicationName="myapp",)
env_tags = {"initial key": "initial value"}
env = conn.create_environment(
ApplicationName="myapp",
EnvironmentName="myenv",
Tags=tags_dict_to_list(env_tags),
)
tags = conn.list_tags_for_resource(
ResourceArn=env['EnvironmentArn'],
)
tags['ResourceArn'].should.equal(env['EnvironmentArn'])
tags_list_to_dict(tags['ResourceTags']).should.equal(env_tags)
tags = conn.list_tags_for_resource(ResourceArn=env["EnvironmentArn"],)
tags["ResourceArn"].should.equal(env["EnvironmentArn"])
tags_list_to_dict(tags["ResourceTags"]).should.equal(env_tags)
@mock_eb
def test_update_tags():
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn.create_application(
ApplicationName="myapp",
)
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
conn.create_application(ApplicationName="myapp",)
env_tags = {
'initial key': 'initial value',
'to remove': 'delete me',
'to update': 'original',
"initial key": "initial value",
"to remove": "delete me",
"to update": "original",
}
env = conn.create_environment(
ApplicationName="myapp",
@ -124,29 +104,27 @@ def test_update_tags():
)
extra_env_tags = {
'to update': 'new',
'extra key': 'extra value',
"to update": "new",
"extra key": "extra value",
}
conn.update_tags_for_resource(
ResourceArn=env['EnvironmentArn'],
ResourceArn=env["EnvironmentArn"],
TagsToAdd=tags_dict_to_list(extra_env_tags),
TagsToRemove=['to remove'],
TagsToRemove=["to remove"],
)
total_env_tags = env_tags.copy()
total_env_tags.update(extra_env_tags)
del total_env_tags['to remove']
del total_env_tags["to remove"]
tags = conn.list_tags_for_resource(
ResourceArn=env['EnvironmentArn'],
)
tags['ResourceArn'].should.equal(env['EnvironmentArn'])
tags_list_to_dict(tags['ResourceTags']).should.equal(total_env_tags)
tags = conn.list_tags_for_resource(ResourceArn=env["EnvironmentArn"],)
tags["ResourceArn"].should.equal(env["EnvironmentArn"])
tags_list_to_dict(tags["ResourceTags"]).should.equal(total_env_tags)
@mock_eb
def test_list_available_solution_stacks():
conn = boto3.client('elasticbeanstalk', region_name='us-east-1')
conn = boto3.client("elasticbeanstalk", region_name="us-east-1")
stacks = conn.list_available_solution_stacks()
len(stacks['SolutionStacks']).should.be.greater_than(0)
len(stacks['SolutionStacks']).should.be.equal(len(stacks['SolutionStackDetails']))
len(stacks["SolutionStacks"]).should.be.greater_than(0)
len(stacks["SolutionStacks"]).should.be.equal(len(stacks["SolutionStackDetails"]))