Merge remote-tracking branch 'nielslaukens/feature/mock_eb' into feature/mock_eb

This commit is contained in:
Bert Blommers 2020-03-30 13:38:56 +01:00
commit 3ece2dabff
9 changed files with 1745 additions and 7 deletions

View File

@ -1,4 +1,11 @@
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
@ -21,6 +28,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 .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
@ -57,12 +65,6 @@ 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

@ -328,3 +328,32 @@ def py2_strip_unicode_keys(blob):
blob = new_set
return blob
def tags_from_query_string(
querystring_dict,
prefix="Tag",
key_suffix="Key",
value_suffix="Value"
):
response_values = {}
for key, value in querystring_dict.items():
if key.startswith(prefix) and key.endswith(key_suffix):
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]
tag_value_key = "{prefix}.{index}.{value_suffix}".format(
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]
else:
response_values[tag_key] = None
return response_values

4
moto/eb/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from .models import eb_backends
from moto.core.models import base_decorator
mock_eb = base_decorator(eb_backends)

13
moto/eb/exceptions.py Normal file
View File

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

101
moto/eb/models.py Normal file
View File

@ -0,0 +1,101 @@
import weakref
import boto.beanstalk
from moto.core import BaseBackend, BaseModel
from .exceptions import InvalidParameterValueError
class FakeEnvironment(BaseModel):
def __init__(
self,
application,
environment_name,
solution_stack_name,
tags,
):
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
@property
def application_name(self):
return self.application.application_name
@property
def environment_arn(self):
return 'arn:aws:elasticbeanstalk:{region}:{account_id}:' \
'environment/{application_name}/{environment_name}'.format(
region=self.region,
account_id='123456789012',
application_name=self.application_name,
environment_name=self.environment_name,
)
@property
def platform_arn(self):
return 'TODO' # TODO
@property
def region(self):
return self.application.region
class FakeApplication(BaseModel):
def __init__(self, backend, application_name):
self.backend = weakref.proxy(backend) # weakref to break cycles
self.application_name = application_name
self.environments = dict()
def create_environment(
self,
environment_name,
solution_stack_name,
tags,
):
if environment_name in self.environments:
raise InvalidParameterValueError
env = FakeEnvironment(
application=self,
environment_name=environment_name,
solution_stack_name=solution_stack_name,
tags=tags,
)
self.environments[environment_name] = env
return env
@property
def region(self):
return self.backend.region
class EBBackend(BaseBackend):
def __init__(self, region):
self.region = region
self.applications = dict()
def reset(self):
# preserve region
region = self.region
self._reset_model_refs()
self.__dict__ = {}
self.__init__(region)
def create_application(self, application_name):
if application_name in self.applications:
raise InvalidParameterValueError(
"Application {} already exists.".format(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())

1425
moto/eb/responses.py Normal file

File diff suppressed because it is too large Load Diff

11
moto/eb/urls.py Normal file
View File

@ -0,0 +1,11 @@
from __future__ import unicode_literals
from .responses import EBResponse
url_bases = [
r"https?://elasticbeanstalk.(?P<region>[a-zA-Z0-9\-_]+).amazonaws.com",
]
url_paths = {
'{0}/$': EBResponse.dispatch,
}

View File

@ -2,7 +2,8 @@ from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.models import validate_resource_ids
from moto.ec2.utils import tags_from_query_string, filters_from_querystring
from moto.ec2.utils import filters_from_querystring
from moto.core.utils import tags_from_query_string
class TagResponse(BaseResponse):

152
tests/test_eb/test_eb.py Normal file
View File

@ -0,0 +1,152 @@
import boto3
import sure # noqa
from botocore.exceptions import ClientError
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")
@mock_eb
def test_create_application_dup():
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)
@mock_eb
def test_describe_applications():
# Create Elastic Beanstalk Application
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')
@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")
@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.create_environment(
ApplicationName="myapp",
EnvironmentName="myenv",
)
envs = conn.describe_environments()
envs = envs['Environments']
len(envs).should.equal(1)
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})
return tag_list
def tags_list_to_dict(tag_list):
tag_dict = {}
for tag in tag_list:
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'}
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)
@mock_eb
def test_update_tags():
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',
}
env = conn.create_environment(
ApplicationName="myapp",
EnvironmentName="myenv",
Tags=tags_dict_to_list(env_tags),
)
extra_env_tags = {
'to update': 'new',
'extra key': 'extra value',
}
conn.update_tags_for_resource(
ResourceArn=env['EnvironmentArn'],
TagsToAdd=tags_dict_to_list(extra_env_tags),
TagsToRemove=['to remove'],
)
total_env_tags = env_tags.copy()
total_env_tags.update(extra_env_tags)
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)
@mock_eb
def test_list_available_solution_stacks():
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']))