Lints.
This commit is contained in:
parent
1433f28846
commit
f37bad0e00
260 changed files with 6363 additions and 3766 deletions
|
|
@ -19,6 +19,7 @@ try:
|
|||
except TypeError:
|
||||
# this version of assert_raises doesn't support the 1-arg version
|
||||
class AssertRaisesContext(object):
|
||||
|
||||
def __init__(self, expected):
|
||||
self.expected = expected
|
||||
|
||||
|
|
|
|||
|
|
@ -8,13 +8,15 @@ def version_tuple(v):
|
|||
return tuple(map(int, (v.split("."))))
|
||||
|
||||
|
||||
# Note: See https://github.com/spulec/moto/issues/201 for why this is a separate method.
|
||||
# Note: See https://github.com/spulec/moto/issues/201 for why this is a
|
||||
# separate method.
|
||||
def skip_test():
|
||||
raise SkipTest
|
||||
|
||||
|
||||
class requires_boto_gte(object):
|
||||
"""Decorator for requiring boto version greater than or equal to 'version'"""
|
||||
|
||||
def __init__(self, version):
|
||||
self.version = version
|
||||
|
||||
|
|
@ -27,6 +29,7 @@ class requires_boto_gte(object):
|
|||
|
||||
|
||||
class disable_on_py3(object):
|
||||
|
||||
def __call__(self, test):
|
||||
if not six.PY3:
|
||||
return test
|
||||
|
|
|
|||
|
|
@ -72,13 +72,15 @@ def test_create_resource():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
root_resource = client.get_resource(
|
||||
restApiId=api_id,
|
||||
resourceId=root_id,
|
||||
)
|
||||
root_resource['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
root_resource['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
root_resource['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
root_resource.should.equal({
|
||||
'path': '/',
|
||||
|
|
@ -97,7 +99,8 @@ def test_create_resource():
|
|||
|
||||
resources = client.get_resources(restApiId=api_id)['items']
|
||||
len(resources).should.equal(2)
|
||||
non_root_resource = [resource for resource in resources if resource['path'] != '/'][0]
|
||||
non_root_resource = [
|
||||
resource for resource in resources if resource['path'] != '/'][0]
|
||||
|
||||
response = client.delete_resource(
|
||||
restApiId=api_id,
|
||||
|
|
@ -117,7 +120,8 @@ def test_child_resource():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
response = client.create_resource(
|
||||
restApiId=api_id,
|
||||
|
|
@ -137,7 +141,8 @@ def test_child_resource():
|
|||
restApiId=api_id,
|
||||
resourceId=tags_id,
|
||||
)
|
||||
child_resource['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
child_resource['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
child_resource['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
child_resource.should.equal({
|
||||
'path': '/users/tags',
|
||||
|
|
@ -159,7 +164,8 @@ def test_create_method():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
client.put_method(
|
||||
restApiId=api_id,
|
||||
|
|
@ -174,7 +180,8 @@ def test_create_method():
|
|||
httpMethod='GET'
|
||||
)
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'httpMethod': 'GET',
|
||||
|
|
@ -193,7 +200,8 @@ def test_create_method_response():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
client.put_method(
|
||||
restApiId=api_id,
|
||||
|
|
@ -214,7 +222,8 @@ def test_create_method_response():
|
|||
httpMethod='GET',
|
||||
statusCode='200',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
|
|
@ -227,7 +236,8 @@ def test_create_method_response():
|
|||
httpMethod='GET',
|
||||
statusCode='200',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
|
|
@ -240,7 +250,8 @@ def test_create_method_response():
|
|||
httpMethod='GET',
|
||||
statusCode='200',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({'ResponseMetadata': {'HTTPStatusCode': 200}})
|
||||
|
||||
|
|
@ -255,7 +266,8 @@ def test_integrations():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
client.put_method(
|
||||
restApiId=api_id,
|
||||
|
|
@ -278,7 +290,8 @@ def test_integrations():
|
|||
type='HTTP',
|
||||
uri='http://httpbin.org/robots.txt',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
|
|
@ -300,7 +313,8 @@ def test_integrations():
|
|||
resourceId=root_id,
|
||||
httpMethod='GET'
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
|
|
@ -321,7 +335,8 @@ def test_integrations():
|
|||
restApiId=api_id,
|
||||
resourceId=root_id,
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response['resourceMethods']['GET']['methodIntegration'].should.equal({
|
||||
'httpMethod': 'GET',
|
||||
|
|
@ -359,7 +374,8 @@ def test_integrations():
|
|||
)
|
||||
|
||||
templates = {
|
||||
# example based on http://docs.aws.amazon.com/apigateway/latest/developerguide/api-as-kinesis-proxy-export-swagger-with-extensions.html
|
||||
# example based on
|
||||
# http://docs.aws.amazon.com/apigateway/latest/developerguide/api-as-kinesis-proxy-export-swagger-with-extensions.html
|
||||
'application/json': "{\n \"StreamName\": \"$input.params('stream-name')\",\n \"Records\": []\n}"
|
||||
}
|
||||
test_uri = 'http://example.com/foobar.txt'
|
||||
|
|
@ -371,7 +387,8 @@ def test_integrations():
|
|||
uri=test_uri,
|
||||
requestTemplates=templates
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response['ResponseMetadata'].should.equal({'HTTPStatusCode': 200})
|
||||
|
||||
|
|
@ -394,7 +411,8 @@ def test_integration_response():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
client.put_method(
|
||||
restApiId=api_id,
|
||||
|
|
@ -425,7 +443,8 @@ def test_integration_response():
|
|||
statusCode='200',
|
||||
selectionPattern='foobar',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'statusCode': '200',
|
||||
|
|
@ -442,7 +461,8 @@ def test_integration_response():
|
|||
httpMethod='GET',
|
||||
statusCode='200',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'statusCode': '200',
|
||||
|
|
@ -458,7 +478,8 @@ def test_integration_response():
|
|||
resourceId=root_id,
|
||||
httpMethod='GET',
|
||||
)
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response['methodIntegration']['integrationResponses'].should.equal({
|
||||
'200': {
|
||||
|
|
@ -506,23 +527,24 @@ def test_update_stage_configuration():
|
|||
restApiId=api_id,
|
||||
deploymentId=deployment_id,
|
||||
)
|
||||
response.pop('createdDate',None) # createdDate is hard to match against, remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# createdDate is hard to match against, remove it
|
||||
response.pop('createdDate', None)
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'id': deployment_id,
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description' : '1.0.1'
|
||||
'description': '1.0.1'
|
||||
})
|
||||
|
||||
response = client.create_deployment(
|
||||
restApiId=api_id,
|
||||
stageName=stage_name,
|
||||
description="1.0.2"
|
||||
)
|
||||
restApiId=api_id,
|
||||
stageName=stage_name,
|
||||
description="1.0.2"
|
||||
)
|
||||
deployment_id2 = response['id']
|
||||
|
||||
|
||||
stage = client.get_stage(
|
||||
restApiId=api_id,
|
||||
stageName=stage_name
|
||||
|
|
@ -531,11 +553,11 @@ def test_update_stage_configuration():
|
|||
stage['deploymentId'].should.equal(deployment_id2)
|
||||
stage.shouldnt.have.key('cacheClusterSize')
|
||||
|
||||
client.update_stage(restApiId=api_id,stageName=stage_name,
|
||||
client.update_stage(restApiId=api_id, stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/cacheClusterEnabled",
|
||||
"op": "replace",
|
||||
"path": "/cacheClusterEnabled",
|
||||
"value": "True"
|
||||
}
|
||||
])
|
||||
|
|
@ -547,11 +569,11 @@ def test_update_stage_configuration():
|
|||
|
||||
stage.should.have.key('cacheClusterSize').which.should.equal("0.5")
|
||||
|
||||
client.update_stage(restApiId=api_id,stageName=stage_name,
|
||||
client.update_stage(restApiId=api_id, stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/cacheClusterSize",
|
||||
"op": "replace",
|
||||
"path": "/cacheClusterSize",
|
||||
"value": "1.6"
|
||||
}
|
||||
])
|
||||
|
|
@ -563,56 +585,55 @@ def test_update_stage_configuration():
|
|||
|
||||
stage.should.have.key('cacheClusterSize').which.should.equal("1.6")
|
||||
|
||||
|
||||
client.update_stage(restApiId=api_id,stageName=stage_name,
|
||||
client.update_stage(restApiId=api_id, stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/deploymentId",
|
||||
"op": "replace",
|
||||
"path": "/deploymentId",
|
||||
"value": deployment_id
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/variables/environment",
|
||||
"value" : "dev"
|
||||
"op": "replace",
|
||||
"path": "/variables/environment",
|
||||
"value": "dev"
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/variables/region",
|
||||
"value" : "eu-west-1"
|
||||
"op": "replace",
|
||||
"path": "/variables/region",
|
||||
"value": "eu-west-1"
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/*/*/caching/dataEncrypted",
|
||||
"value" : "True"
|
||||
"op": "replace",
|
||||
"path": "/*/*/caching/dataEncrypted",
|
||||
"value": "True"
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/cacheClusterEnabled",
|
||||
"value" : "True"
|
||||
"op": "replace",
|
||||
"path": "/cacheClusterEnabled",
|
||||
"value": "True"
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/description",
|
||||
"value" : "stage description update"
|
||||
"op": "replace",
|
||||
"path": "/description",
|
||||
"value": "stage description update"
|
||||
},
|
||||
{
|
||||
"op" : "replace",
|
||||
"path" : "/cacheClusterSize",
|
||||
"value" : "1.6"
|
||||
"op": "replace",
|
||||
"path": "/cacheClusterSize",
|
||||
"value": "1.6"
|
||||
}
|
||||
])
|
||||
|
||||
client.update_stage(restApiId=api_id,stageName=stage_name,
|
||||
client.update_stage(restApiId=api_id, stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op" : "remove",
|
||||
"path" : "/variables/region",
|
||||
"value" : "eu-west-1"
|
||||
"op": "remove",
|
||||
"path": "/variables/region",
|
||||
"value": "eu-west-1"
|
||||
}
|
||||
])
|
||||
|
||||
stage = client.get_stage(restApiId=api_id,stageName=stage_name)
|
||||
stage = client.get_stage(restApiId=api_id, stageName=stage_name)
|
||||
|
||||
stage['description'].should.match('stage description update')
|
||||
stage['cacheClusterSize'].should.equal("1.6")
|
||||
|
|
@ -621,21 +642,23 @@ def test_update_stage_configuration():
|
|||
stage['cacheClusterEnabled'].should.be.true
|
||||
stage['deploymentId'].should.match(deployment_id)
|
||||
stage['methodSettings'].should.have.key('*/*')
|
||||
stage['methodSettings']['*/*'].should.have.key('cacheDataEncrypted').which.should.be.true
|
||||
stage['methodSettings'][
|
||||
'*/*'].should.have.key('cacheDataEncrypted').which.should.be.true
|
||||
|
||||
try:
|
||||
client.update_stage(restApiId=api_id,stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op" : "add",
|
||||
"path" : "/notasetting",
|
||||
"value" : "eu-west-1"
|
||||
}
|
||||
])
|
||||
assert False.should.be.ok #Fail, should not be here
|
||||
client.update_stage(restApiId=api_id, stageName=stage_name,
|
||||
patchOperations=[
|
||||
{
|
||||
"op": "add",
|
||||
"path": "/notasetting",
|
||||
"value": "eu-west-1"
|
||||
}
|
||||
])
|
||||
assert False.should.be.ok # Fail, should not be here
|
||||
except Exception:
|
||||
assert True.should.be.ok
|
||||
|
||||
|
||||
@mock_apigateway
|
||||
def test_non_existent_stage():
|
||||
client = boto3.client('apigateway', region_name='us-west-2')
|
||||
|
|
@ -645,9 +668,8 @@ def test_non_existent_stage():
|
|||
)
|
||||
api_id = response['id']
|
||||
|
||||
|
||||
client.get_stage.when.called_with(restApiId=api_id,stageName='xxx').should.throw(ClientError)
|
||||
|
||||
client.get_stage.when.called_with(
|
||||
restApiId=api_id, stageName='xxx').should.throw(ClientError)
|
||||
|
||||
|
||||
@mock_apigateway
|
||||
|
|
@ -670,13 +692,15 @@ def test_create_stage():
|
|||
restApiId=api_id,
|
||||
deploymentId=deployment_id,
|
||||
)
|
||||
response.pop('createdDate',None) # createdDate is hard to match against, remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# createdDate is hard to match against, remove it
|
||||
response.pop('createdDate', None)
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'id': deployment_id,
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description' : ''
|
||||
'description': ''
|
||||
})
|
||||
|
||||
response = client.create_deployment(
|
||||
|
|
@ -686,34 +710,37 @@ def test_create_stage():
|
|||
|
||||
deployment_id2 = response['id']
|
||||
|
||||
|
||||
response = client.get_deployments(
|
||||
restApiId=api_id,
|
||||
)
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
response['items'][0].pop('createdDate')
|
||||
response['items'][1].pop('createdDate')
|
||||
response['items'][0]['id'].should.match(r"{0}|{1}".format(deployment_id2,deployment_id))
|
||||
response['items'][1]['id'].should.match(r"{0}|{1}".format(deployment_id2,deployment_id))
|
||||
|
||||
response['items'][0]['id'].should.match(
|
||||
r"{0}|{1}".format(deployment_id2, deployment_id))
|
||||
response['items'][1]['id'].should.match(
|
||||
r"{0}|{1}".format(deployment_id2, deployment_id))
|
||||
|
||||
new_stage_name = 'current'
|
||||
response = client.create_stage(restApiId=api_id,stageName=new_stage_name,deploymentId=deployment_id2)
|
||||
response = client.create_stage(
|
||||
restApiId=api_id, stageName=new_stage_name, deploymentId=deployment_id2)
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
response.should.equal({
|
||||
'stageName':new_stage_name,
|
||||
'deploymentId':deployment_id2,
|
||||
'methodSettings':{},
|
||||
'variables':{},
|
||||
'stageName': new_stage_name,
|
||||
'deploymentId': deployment_id2,
|
||||
'methodSettings': {},
|
||||
'variables': {},
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description':'',
|
||||
'cacheClusterEnabled':False
|
||||
'description': '',
|
||||
'cacheClusterEnabled': False
|
||||
})
|
||||
|
||||
stage = client.get_stage(
|
||||
|
|
@ -724,20 +751,21 @@ def test_create_stage():
|
|||
stage['deploymentId'].should.equal(deployment_id2)
|
||||
|
||||
new_stage_name_with_vars = 'stage_with_vars'
|
||||
response = client.create_stage(restApiId=api_id,stageName=new_stage_name_with_vars,deploymentId=deployment_id2,variables={
|
||||
"env" : "dev"
|
||||
response = client.create_stage(restApiId=api_id, stageName=new_stage_name_with_vars, deploymentId=deployment_id2, variables={
|
||||
"env": "dev"
|
||||
})
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
response.should.equal({
|
||||
'stageName':new_stage_name_with_vars,
|
||||
'deploymentId':deployment_id2,
|
||||
'methodSettings':{},
|
||||
'variables':{ "env" : "dev" },
|
||||
'stageName': new_stage_name_with_vars,
|
||||
'deploymentId': deployment_id2,
|
||||
'methodSettings': {},
|
||||
'variables': {"env": "dev"},
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description':'',
|
||||
'description': '',
|
||||
'cacheClusterEnabled': False
|
||||
})
|
||||
|
||||
|
|
@ -750,22 +778,23 @@ def test_create_stage():
|
|||
stage['variables'].should.have.key('env').which.should.match("dev")
|
||||
|
||||
new_stage_name = 'stage_with_vars_and_cache_settings'
|
||||
response = client.create_stage(restApiId=api_id,stageName=new_stage_name,deploymentId=deployment_id2,variables={
|
||||
"env" : "dev"
|
||||
}, cacheClusterEnabled=True,description="hello moto")
|
||||
response = client.create_stage(restApiId=api_id, stageName=new_stage_name, deploymentId=deployment_id2, variables={
|
||||
"env": "dev"
|
||||
}, cacheClusterEnabled=True, description="hello moto")
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
response.should.equal({
|
||||
'stageName':new_stage_name,
|
||||
'deploymentId':deployment_id2,
|
||||
'methodSettings':{},
|
||||
'variables':{ "env" : "dev" },
|
||||
'stageName': new_stage_name,
|
||||
'deploymentId': deployment_id2,
|
||||
'methodSettings': {},
|
||||
'variables': {"env": "dev"},
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description':'hello moto',
|
||||
'description': 'hello moto',
|
||||
'cacheClusterEnabled': True,
|
||||
'cacheClusterSize' : "0.5"
|
||||
'cacheClusterSize': "0.5"
|
||||
})
|
||||
|
||||
stage = client.get_stage(
|
||||
|
|
@ -776,22 +805,23 @@ def test_create_stage():
|
|||
stage['cacheClusterSize'].should.equal("0.5")
|
||||
|
||||
new_stage_name = 'stage_with_vars_and_cache_settings_and_size'
|
||||
response = client.create_stage(restApiId=api_id,stageName=new_stage_name,deploymentId=deployment_id2,variables={
|
||||
"env" : "dev"
|
||||
}, cacheClusterEnabled=True,cacheClusterSize="1.6",description="hello moto")
|
||||
response = client.create_stage(restApiId=api_id, stageName=new_stage_name, deploymentId=deployment_id2, variables={
|
||||
"env": "dev"
|
||||
}, cacheClusterEnabled=True, cacheClusterSize="1.6", description="hello moto")
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
response.should.equal({
|
||||
'stageName':new_stage_name,
|
||||
'deploymentId':deployment_id2,
|
||||
'methodSettings':{},
|
||||
'variables':{ "env" : "dev" },
|
||||
'stageName': new_stage_name,
|
||||
'deploymentId': deployment_id2,
|
||||
'methodSettings': {},
|
||||
'variables': {"env": "dev"},
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description':'hello moto',
|
||||
'description': 'hello moto',
|
||||
'cacheClusterEnabled': True,
|
||||
'cacheClusterSize' : "1.6"
|
||||
'cacheClusterSize': "1.6"
|
||||
})
|
||||
|
||||
stage = client.get_stage(
|
||||
|
|
@ -804,7 +834,6 @@ def test_create_stage():
|
|||
stage['cacheClusterSize'].should.equal("1.6")
|
||||
|
||||
|
||||
|
||||
@mock_apigateway
|
||||
def test_deployment():
|
||||
client = boto3.client('apigateway', region_name='us-west-2')
|
||||
|
|
@ -825,13 +854,15 @@ def test_deployment():
|
|||
restApiId=api_id,
|
||||
deploymentId=deployment_id,
|
||||
)
|
||||
response.pop('createdDate',None) # createdDate is hard to match against, remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# createdDate is hard to match against, remove it
|
||||
response.pop('createdDate', None)
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'id': deployment_id,
|
||||
'ResponseMetadata': {'HTTPStatusCode': 200},
|
||||
'description' : ''
|
||||
'description': ''
|
||||
})
|
||||
|
||||
response = client.get_deployments(
|
||||
|
|
@ -898,7 +929,8 @@ def test_http_proxying_integration():
|
|||
api_id = response['id']
|
||||
|
||||
resources = client.get_resources(restApiId=api_id)
|
||||
root_id = [resource for resource in resources['items'] if resource['path'] == '/'][0]['id']
|
||||
root_id = [resource for resource in resources[
|
||||
'items'] if resource['path'] == '/'][0]['id']
|
||||
|
||||
client.put_method(
|
||||
restApiId=api_id,
|
||||
|
|
@ -928,7 +960,8 @@ def test_http_proxying_integration():
|
|||
stageName=stage_name,
|
||||
)
|
||||
|
||||
deploy_url = "https://{api_id}.execute-api.{region_name}.amazonaws.com/{stage_name}".format(api_id=api_id, region_name=region_name, stage_name=stage_name)
|
||||
deploy_url = "https://{api_id}.execute-api.{region_name}.amazonaws.com/{stage_name}".format(
|
||||
api_id=api_id, region_name=region_name, stage_name=stage_name)
|
||||
|
||||
if not settings.TEST_SERVER_MODE:
|
||||
requests.get(deploy_url).content.should.equal(b"a fake response")
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ from tests.helpers import requires_boto_gte
|
|||
@mock_elb_deprecated
|
||||
def test_create_autoscaling_group():
|
||||
elb_conn = boto.ec2.elb.connect_to_region('us-east-1')
|
||||
elb_conn.create_load_balancer('test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
elb_conn.create_load_balancer(
|
||||
'test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
|
||||
conn = boto.ec2.autoscale.connect_to_region('us-east-1')
|
||||
config = LaunchConfiguration(
|
||||
|
|
@ -45,14 +46,15 @@ def test_create_autoscaling_group():
|
|||
key='test_key',
|
||||
value='test_value',
|
||||
propagate_at_launch=True
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
conn.create_auto_scaling_group(group)
|
||||
|
||||
group = conn.get_all_groups()[0]
|
||||
group.name.should.equal('tester_group')
|
||||
set(group.availability_zones).should.equal(set(['us-east-1c', 'us-east-1b']))
|
||||
set(group.availability_zones).should.equal(
|
||||
set(['us-east-1c', 'us-east-1b']))
|
||||
group.desired_capacity.should.equal(2)
|
||||
group.max_size.should.equal(2)
|
||||
group.min_size.should.equal(2)
|
||||
|
|
@ -64,7 +66,8 @@ def test_create_autoscaling_group():
|
|||
group.health_check_type.should.equal("EC2")
|
||||
list(group.load_balancers).should.equal(["test_lb"])
|
||||
group.placement_group.should.equal("test_placement")
|
||||
list(group.termination_policies).should.equal(["OldestInstance", "NewestInstance"])
|
||||
list(group.termination_policies).should.equal(
|
||||
["OldestInstance", "NewestInstance"])
|
||||
len(list(group.tags)).should.equal(1)
|
||||
tag = list(group.tags)[0]
|
||||
tag.resource_id.should.equal('tester_group')
|
||||
|
|
@ -134,7 +137,8 @@ def test_autoscaling_group_describe_filter():
|
|||
group.name = 'tester_group3'
|
||||
conn.create_auto_scaling_group(group)
|
||||
|
||||
conn.get_all_groups(names=['tester_group', 'tester_group2']).should.have.length_of(2)
|
||||
conn.get_all_groups(
|
||||
names=['tester_group', 'tester_group2']).should.have.length_of(2)
|
||||
conn.get_all_groups().should.have.length_of(3)
|
||||
|
||||
|
||||
|
|
@ -197,16 +201,16 @@ def test_autoscaling_tags_update():
|
|||
conn.create_auto_scaling_group(group)
|
||||
|
||||
conn.create_or_update_tags(tags=[Tag(
|
||||
resource_id='tester_group',
|
||||
key='test_key',
|
||||
value='new_test_value',
|
||||
propagate_at_launch=True
|
||||
), Tag(
|
||||
resource_id='tester_group',
|
||||
key='test_key2',
|
||||
value='test_value2',
|
||||
propagate_at_launch=True
|
||||
)])
|
||||
resource_id='tester_group',
|
||||
key='test_key',
|
||||
value='new_test_value',
|
||||
propagate_at_launch=True
|
||||
), Tag(
|
||||
resource_id='tester_group',
|
||||
key='test_key2',
|
||||
value='test_value2',
|
||||
propagate_at_launch=True
|
||||
)])
|
||||
group = conn.get_all_groups()[0]
|
||||
group.tags.should.have.length_of(2)
|
||||
|
||||
|
|
@ -372,6 +376,7 @@ def test_set_desired_capacity_the_same():
|
|||
instances = list(conn.get_all_autoscaling_instances())
|
||||
instances.should.have.length_of(2)
|
||||
|
||||
|
||||
@mock_autoscaling_deprecated
|
||||
@mock_elb_deprecated
|
||||
def test_autoscaling_group_with_elb():
|
||||
|
|
@ -402,7 +407,8 @@ def test_autoscaling_group_with_elb():
|
|||
group.desired_capacity.should.equal(2)
|
||||
elb.instances.should.have.length_of(2)
|
||||
|
||||
autoscale_instance_ids = set(instance.instance_id for instance in group.instances)
|
||||
autoscale_instance_ids = set(
|
||||
instance.instance_id for instance in group.instances)
|
||||
elb_instace_ids = set(instance.id for instance in elb.instances)
|
||||
autoscale_instance_ids.should.equal(elb_instace_ids)
|
||||
|
||||
|
|
@ -412,7 +418,8 @@ def test_autoscaling_group_with_elb():
|
|||
group.desired_capacity.should.equal(3)
|
||||
elb.instances.should.have.length_of(3)
|
||||
|
||||
autoscale_instance_ids = set(instance.instance_id for instance in group.instances)
|
||||
autoscale_instance_ids = set(
|
||||
instance.instance_id for instance in group.instances)
|
||||
elb_instace_ids = set(instance.id for instance in elb.instances)
|
||||
autoscale_instance_ids.should.equal(elb_instace_ids)
|
||||
|
||||
|
|
@ -429,38 +436,39 @@ Boto3
|
|||
|
||||
@mock_autoscaling
|
||||
def test_create_autoscaling_group_boto3():
|
||||
client = boto3.client('autoscaling', region_name='us-east-1')
|
||||
_ = client.create_launch_configuration(
|
||||
LaunchConfigurationName='test_launch_configuration'
|
||||
)
|
||||
response = client.create_auto_scaling_group(
|
||||
AutoScalingGroupName='test_asg',
|
||||
LaunchConfigurationName='test_launch_configuration',
|
||||
MinSize=0,
|
||||
MaxSize=20,
|
||||
DesiredCapacity=5
|
||||
)
|
||||
response['ResponseMetadata']['HTTPStatusCode'].should.equal(200)
|
||||
client = boto3.client('autoscaling', region_name='us-east-1')
|
||||
_ = client.create_launch_configuration(
|
||||
LaunchConfigurationName='test_launch_configuration'
|
||||
)
|
||||
response = client.create_auto_scaling_group(
|
||||
AutoScalingGroupName='test_asg',
|
||||
LaunchConfigurationName='test_launch_configuration',
|
||||
MinSize=0,
|
||||
MaxSize=20,
|
||||
DesiredCapacity=5
|
||||
)
|
||||
response['ResponseMetadata']['HTTPStatusCode'].should.equal(200)
|
||||
|
||||
|
||||
@mock_autoscaling
|
||||
def test_describe_autoscaling_groups_boto3():
|
||||
client = boto3.client('autoscaling', region_name='us-east-1')
|
||||
_ = client.create_launch_configuration(
|
||||
LaunchConfigurationName='test_launch_configuration'
|
||||
)
|
||||
_ = client.create_auto_scaling_group(
|
||||
AutoScalingGroupName='test_asg',
|
||||
LaunchConfigurationName='test_launch_configuration',
|
||||
MinSize=0,
|
||||
MaxSize=20,
|
||||
DesiredCapacity=5
|
||||
)
|
||||
response = client.describe_auto_scaling_groups(
|
||||
AutoScalingGroupNames=["test_asg"]
|
||||
)
|
||||
response['ResponseMetadata']['HTTPStatusCode'].should.equal(200)
|
||||
response['AutoScalingGroups'][0]['AutoScalingGroupName'].should.equal('test_asg')
|
||||
client = boto3.client('autoscaling', region_name='us-east-1')
|
||||
_ = client.create_launch_configuration(
|
||||
LaunchConfigurationName='test_launch_configuration'
|
||||
)
|
||||
_ = client.create_auto_scaling_group(
|
||||
AutoScalingGroupName='test_asg',
|
||||
LaunchConfigurationName='test_launch_configuration',
|
||||
MinSize=0,
|
||||
MaxSize=20,
|
||||
DesiredCapacity=5
|
||||
)
|
||||
response = client.describe_auto_scaling_groups(
|
||||
AutoScalingGroupNames=["test_asg"]
|
||||
)
|
||||
response['ResponseMetadata']['HTTPStatusCode'].should.equal(200)
|
||||
response['AutoScalingGroups'][0][
|
||||
'AutoScalingGroupName'].should.equal('test_asg')
|
||||
|
||||
|
||||
@mock_autoscaling
|
||||
|
|
@ -509,22 +517,23 @@ def test_autoscaling_taqs_update_boto3():
|
|||
)
|
||||
|
||||
client.create_or_update_tags(Tags=[{
|
||||
"ResourceId": 'test_asg',
|
||||
"Key": 'test_key',
|
||||
"Value": 'updated_test_value',
|
||||
"PropagateAtLaunch": True
|
||||
}, {
|
||||
"ResourceId": 'test_asg',
|
||||
"Key": 'test_key2',
|
||||
"Value": 'test_value2',
|
||||
"PropagateAtLaunch": True
|
||||
}])
|
||||
"ResourceId": 'test_asg',
|
||||
"Key": 'test_key',
|
||||
"Value": 'updated_test_value',
|
||||
"PropagateAtLaunch": True
|
||||
}, {
|
||||
"ResourceId": 'test_asg',
|
||||
"Key": 'test_key2',
|
||||
"Value": 'test_value2',
|
||||
"PropagateAtLaunch": True
|
||||
}])
|
||||
|
||||
response = client.describe_auto_scaling_groups(
|
||||
AutoScalingGroupNames=["test_asg"]
|
||||
)
|
||||
response['AutoScalingGroups'][0]['Tags'].should.have.length_of(2)
|
||||
|
||||
|
||||
@mock_autoscaling
|
||||
def test_autoscaling_describe_policies_boto3():
|
||||
client = boto3.client('autoscaling', region_name='us-east-1')
|
||||
|
|
@ -577,4 +586,5 @@ def test_autoscaling_describe_policies_boto3():
|
|||
PolicyTypes=['SimpleScaling']
|
||||
)
|
||||
response['ScalingPolicies'].should.have.length_of(1)
|
||||
response['ScalingPolicies'][0]['PolicyName'].should.equal('test_policy_down')
|
||||
response['ScalingPolicies'][0][
|
||||
'PolicyName'].should.equal('test_policy_down')
|
||||
|
|
|
|||
|
|
@ -30,10 +30,12 @@ def test_create_launch_configuration():
|
|||
launch_config.image_id.should.equal('ami-abcd1234')
|
||||
launch_config.instance_type.should.equal('t1.micro')
|
||||
launch_config.key_name.should.equal('the_keys')
|
||||
set(launch_config.security_groups).should.equal(set(['default', 'default2']))
|
||||
set(launch_config.security_groups).should.equal(
|
||||
set(['default', 'default2']))
|
||||
launch_config.user_data.should.equal(b"This is some user_data")
|
||||
launch_config.instance_monitoring.enabled.should.equal('true')
|
||||
launch_config.instance_profile_name.should.equal('arn:aws:iam::123456789012:instance-profile/testing')
|
||||
launch_config.instance_profile_name.should.equal(
|
||||
'arn:aws:iam::123456789012:instance-profile/testing')
|
||||
launch_config.spot_price.should.equal(0.1)
|
||||
|
||||
|
||||
|
|
@ -78,16 +80,19 @@ def test_create_launch_configuration_with_block_device_mappings():
|
|||
launch_config.image_id.should.equal('ami-abcd1234')
|
||||
launch_config.instance_type.should.equal('m1.small')
|
||||
launch_config.key_name.should.equal('the_keys')
|
||||
set(launch_config.security_groups).should.equal(set(['default', 'default2']))
|
||||
set(launch_config.security_groups).should.equal(
|
||||
set(['default', 'default2']))
|
||||
launch_config.user_data.should.equal(b"This is some user_data")
|
||||
launch_config.instance_monitoring.enabled.should.equal('true')
|
||||
launch_config.instance_profile_name.should.equal('arn:aws:iam::123456789012:instance-profile/testing')
|
||||
launch_config.instance_profile_name.should.equal(
|
||||
'arn:aws:iam::123456789012:instance-profile/testing')
|
||||
launch_config.spot_price.should.equal(0.1)
|
||||
len(launch_config.block_device_mappings).should.equal(3)
|
||||
|
||||
returned_mapping = launch_config.block_device_mappings
|
||||
|
||||
set(returned_mapping.keys()).should.equal(set(['/dev/xvdb', '/dev/xvdp', '/dev/xvdh']))
|
||||
set(returned_mapping.keys()).should.equal(
|
||||
set(['/dev/xvdb', '/dev/xvdp', '/dev/xvdh']))
|
||||
|
||||
returned_mapping['/dev/xvdh'].iops.should.equal(1000)
|
||||
returned_mapping['/dev/xvdh'].size.should.equal(100)
|
||||
|
|
@ -198,7 +203,8 @@ def test_launch_configuration_describe_filter():
|
|||
config.name = 'tester3'
|
||||
conn.create_launch_configuration(config)
|
||||
|
||||
conn.get_all_launch_configurations(names=['tester', 'tester2']).should.have.length_of(2)
|
||||
conn.get_all_launch_configurations(
|
||||
names=['tester', 'tester2']).should.have.length_of(2)
|
||||
conn.get_all_launch_configurations().should.have.length_of(3)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -73,8 +73,10 @@ def test_invoke_requestresponse_function():
|
|||
Payload=json.dumps(in_data))
|
||||
|
||||
success_result["StatusCode"].should.equal(202)
|
||||
base64.b64decode(success_result["LogResult"]).decode('utf-8').should.equal(json.dumps(in_data))
|
||||
json.loads(success_result["Payload"].read().decode('utf-8')).should.equal(in_data)
|
||||
base64.b64decode(success_result["LogResult"]).decode(
|
||||
'utf-8').should.equal(json.dumps(in_data))
|
||||
json.loads(success_result["Payload"].read().decode(
|
||||
'utf-8')).should.equal(in_data)
|
||||
|
||||
|
||||
@mock_lambda
|
||||
|
|
@ -101,9 +103,11 @@ def test_invoke_event_function():
|
|||
).should.throw(botocore.client.ClientError)
|
||||
|
||||
in_data = {'msg': 'So long and thanks for all the fish'}
|
||||
success_result = conn.invoke(FunctionName='testFunction', InvocationType='Event', Payload=json.dumps(in_data))
|
||||
success_result = conn.invoke(
|
||||
FunctionName='testFunction', InvocationType='Event', Payload=json.dumps(in_data))
|
||||
success_result["StatusCode"].should.equal(202)
|
||||
json.loads(success_result['Payload'].read().decode('utf-8')).should.equal({})
|
||||
json.loads(success_result['Payload'].read().decode(
|
||||
'utf-8')).should.equal({})
|
||||
|
||||
|
||||
@mock_ec2
|
||||
|
|
@ -129,9 +133,11 @@ def test_invoke_function_get_ec2_volume():
|
|||
)
|
||||
|
||||
in_data = {'volume_id': vol.id}
|
||||
result = conn.invoke(FunctionName='testFunction', InvocationType='RequestResponse', Payload=json.dumps(in_data))
|
||||
result = conn.invoke(FunctionName='testFunction',
|
||||
InvocationType='RequestResponse', Payload=json.dumps(in_data))
|
||||
result["StatusCode"].should.equal(202)
|
||||
msg = 'get volume details for %s\nVolume - %s state=%s, size=%s\n%s' % (vol.id, vol.id, vol.state, vol.size, json.dumps(in_data))
|
||||
msg = 'get volume details for %s\nVolume - %s state=%s, size=%s\n%s' % (
|
||||
vol.id, vol.id, vol.state, vol.size, json.dumps(in_data))
|
||||
base64.b64decode(result["LogResult"]).decode('utf-8').should.equal(msg)
|
||||
result['Payload'].read().decode('utf-8').should.equal(msg)
|
||||
|
||||
|
|
@ -189,8 +195,10 @@ def test_create_function_from_aws_bucket():
|
|||
"SubnetIds": ["subnet-123abc"],
|
||||
},
|
||||
)
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None) # Botocore inserts retry attempts not seen in Python27
|
||||
# this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
# Botocore inserts retry attempts not seen in Python27
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
result.pop('LastModified')
|
||||
result.should.equal({
|
||||
'FunctionName': 'testFunction',
|
||||
|
|
@ -231,8 +239,10 @@ def test_create_function_from_zipfile():
|
|||
MemorySize=128,
|
||||
Publish=True,
|
||||
)
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None) # Botocore inserts retry attempts not seen in Python27
|
||||
# this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
# Botocore inserts retry attempts not seen in Python27
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
result.pop('LastModified')
|
||||
|
||||
result.should.equal({
|
||||
|
|
@ -283,8 +293,10 @@ def test_get_function():
|
|||
)
|
||||
|
||||
result = conn.get_function(FunctionName='testFunction')
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None) # Botocore inserts retry attempts not seen in Python27
|
||||
# this is hard to match against, so remove it
|
||||
result['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
# Botocore inserts retry attempts not seen in Python27
|
||||
result['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
result['Configuration'].pop('LastModified')
|
||||
|
||||
result.should.equal({
|
||||
|
|
@ -339,12 +351,15 @@ def test_delete_function():
|
|||
)
|
||||
|
||||
success_result = conn.delete_function(FunctionName='testFunction')
|
||||
success_result['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
success_result['ResponseMetadata'].pop('RetryAttempts', None) # Botocore inserts retry attempts not seen in Python27
|
||||
# this is hard to match against, so remove it
|
||||
success_result['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
# Botocore inserts retry attempts not seen in Python27
|
||||
success_result['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
|
||||
success_result.should.equal({'ResponseMetadata': {'HTTPStatusCode': 204}})
|
||||
|
||||
conn.delete_function.when.called_with(FunctionName='testFunctionThatDoesntExist').should.throw(botocore.client.ClientError)
|
||||
conn.delete_function.when.called_with(
|
||||
FunctionName='testFunctionThatDoesntExist').should.throw(botocore.client.ClientError)
|
||||
|
||||
|
||||
@mock_lambda
|
||||
|
|
@ -407,8 +422,10 @@ def test_list_create_list_get_delete_list():
|
|||
func.should.equal(expected_function_result['Configuration'])
|
||||
|
||||
func = conn.get_function(FunctionName='testFunction')
|
||||
func['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
func['ResponseMetadata'].pop('RetryAttempts', None) # Botocore inserts retry attempts not seen in Python27
|
||||
# this is hard to match against, so remove it
|
||||
func['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
# Botocore inserts retry attempts not seen in Python27
|
||||
func['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
func['Configuration'].pop('LastModified')
|
||||
|
||||
func.should.equal(expected_function_result)
|
||||
|
|
|
|||
|
|
@ -1,201 +1,204 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion" : "2010-09-09",
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
|
||||
"Description" : "AWS CloudFormation Sample Template RDS_MySQL_With_Read_Replica: Sample template showing how to create a highly-available, RDS DBInstance with a read replica. **WARNING** This template creates an Amazon Relational Database Service database instance and Amazon CloudWatch alarms. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
"Description": "AWS CloudFormation Sample Template RDS_MySQL_With_Read_Replica: Sample template showing how to create a highly-available, RDS DBInstance with a read replica. **WARNING** This template creates an Amazon Relational Database Service database instance and Amazon CloudWatch alarms. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
|
||||
"Parameters": {
|
||||
"DBName": {
|
||||
"Default": "MyDatabase",
|
||||
"Description" : "The database name",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "64",
|
||||
"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
"Parameters": {
|
||||
"DBName": {
|
||||
"Default": "MyDatabase",
|
||||
"Description": "The database name",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "64",
|
||||
"AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription": "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBInstanceIdentifier": {
|
||||
"Type": "String"
|
||||
},
|
||||
"DBInstanceIdentifier": {
|
||||
"Type": "String"
|
||||
},
|
||||
|
||||
"DBUser": {
|
||||
"NoEcho": "true",
|
||||
"Description" : "The database admin account username",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "16",
|
||||
"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
"DBUser": {
|
||||
"NoEcho": "true",
|
||||
"Description": "The database admin account username",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "16",
|
||||
"AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription": "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBPassword": {
|
||||
"NoEcho": "true",
|
||||
"Description" : "The database admin account password",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "41",
|
||||
"AllowedPattern" : "[a-zA-Z0-9]+",
|
||||
"ConstraintDescription" : "must contain only alphanumeric characters."
|
||||
},
|
||||
"DBPassword": {
|
||||
"NoEcho": "true",
|
||||
"Description": "The database admin account password",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "41",
|
||||
"AllowedPattern": "[a-zA-Z0-9]+",
|
||||
"ConstraintDescription": "must contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBAllocatedStorage": {
|
||||
"Default": "5",
|
||||
"Description" : "The size of the database (Gb)",
|
||||
"Type": "Number",
|
||||
"MinValue": "5",
|
||||
"MaxValue": "1024",
|
||||
"ConstraintDescription" : "must be between 5 and 1024Gb."
|
||||
},
|
||||
"DBAllocatedStorage": {
|
||||
"Default": "5",
|
||||
"Description": "The size of the database (Gb)",
|
||||
"Type": "Number",
|
||||
"MinValue": "5",
|
||||
"MaxValue": "1024",
|
||||
"ConstraintDescription": "must be between 5 and 1024Gb."
|
||||
},
|
||||
|
||||
"DBInstanceClass": {
|
||||
"Description" : "The database instance type",
|
||||
"Type": "String",
|
||||
"Default": "db.m1.small",
|
||||
"AllowedValues" : [ "db.t1.micro", "db.m1.small", "db.m1.medium", "db.m1.large", "db.m1.xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.m3.medium", "db.m3.large", "db.m3.xlarge", "db.m3.2xlarge", "db.r3.large", "db.r3.xlarge", "db.r3.2xlarge", "db.r3.4xlarge", "db.r3.8xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.cr1.8xlarge"]
|
||||
,
|
||||
"ConstraintDescription" : "must select a valid database instance type."
|
||||
},
|
||||
"DBInstanceClass": {
|
||||
"Description": "The database instance type",
|
||||
"Type": "String",
|
||||
"Default": "db.m1.small",
|
||||
"AllowedValues": ["db.t1.micro", "db.m1.small", "db.m1.medium", "db.m1.large", "db.m1.xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.m3.medium", "db.m3.large", "db.m3.xlarge", "db.m3.2xlarge", "db.r3.large", "db.r3.xlarge", "db.r3.2xlarge", "db.r3.4xlarge", "db.r3.8xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.cr1.8xlarge"],
|
||||
"ConstraintDescription": "must select a valid database instance type."
|
||||
},
|
||||
|
||||
"EC2SecurityGroup": {
|
||||
"Description" : "The EC2 security group that contains instances that need access to the database",
|
||||
"Default": "default",
|
||||
"Type": "String",
|
||||
"AllowedPattern" : "[a-zA-Z0-9\\-]+",
|
||||
"ConstraintDescription" : "must be a valid security group name."
|
||||
},
|
||||
"EC2SecurityGroup": {
|
||||
"Description": "The EC2 security group that contains instances that need access to the database",
|
||||
"Default": "default",
|
||||
"Type": "String",
|
||||
"AllowedPattern": "[a-zA-Z0-9\\-]+",
|
||||
"ConstraintDescription": "must be a valid security group name."
|
||||
},
|
||||
|
||||
"MultiAZ" : {
|
||||
"Description" : "Multi-AZ master database",
|
||||
"Type" : "String",
|
||||
"Default" : "false",
|
||||
"AllowedValues" : [ "true", "false" ],
|
||||
"ConstraintDescription" : "must be true or false."
|
||||
}
|
||||
},
|
||||
|
||||
"Conditions" : {
|
||||
"Is-EC2-VPC" : { "Fn::Or" : [ {"Fn::Equals" : [{"Ref" : "AWS::Region"}, "eu-central-1" ]},
|
||||
{"Fn::Equals" : [{"Ref" : "AWS::Region"}, "cn-north-1" ]}]},
|
||||
"Is-EC2-Classic" : { "Fn::Not" : [{ "Condition" : "Is-EC2-VPC"}]}
|
||||
},
|
||||
|
||||
"Resources" : {
|
||||
"DBParameterGroup": {
|
||||
"Type": "AWS::RDS::DBParameterGroup",
|
||||
"Properties" : {
|
||||
"Description": "DB Parameter Goup",
|
||||
"Family" : "MySQL5.1",
|
||||
"Parameters": {
|
||||
"BACKLOG_QUEUE_LIMIT": "2048"
|
||||
"MultiAZ": {
|
||||
"Description": "Multi-AZ master database",
|
||||
"Type": "String",
|
||||
"Default": "false",
|
||||
"AllowedValues": ["true", "false"],
|
||||
"ConstraintDescription": "must be true or false."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"DBEC2SecurityGroup": {
|
||||
"Type": "AWS::EC2::SecurityGroup",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties" : {
|
||||
"GroupDescription": "Open database for access",
|
||||
"SecurityGroupIngress" : [{
|
||||
"IpProtocol" : "tcp",
|
||||
"FromPort" : "3306",
|
||||
"ToPort" : "3306",
|
||||
"SourceSecurityGroupName" : { "Ref" : "EC2SecurityGroup" }
|
||||
}]
|
||||
}
|
||||
"Conditions": {
|
||||
"Is-EC2-VPC": {"Fn::Or": [{"Fn::Equals": [{"Ref": "AWS::Region"}, "eu-central-1"]},
|
||||
{"Fn::Equals": [{"Ref": "AWS::Region"}, "cn-north-1"]}]},
|
||||
"Is-EC2-Classic": {"Fn::Not": [{"Condition": "Is-EC2-VPC"}]}
|
||||
},
|
||||
|
||||
"DBSecurityGroup": {
|
||||
"Type": "AWS::RDS::DBSecurityGroup",
|
||||
"Condition" : "Is-EC2-Classic",
|
||||
"Properties": {
|
||||
"DBSecurityGroupIngress": [{
|
||||
"EC2SecurityGroupName": { "Ref": "EC2SecurityGroup" }
|
||||
}],
|
||||
"GroupDescription": "database access"
|
||||
}
|
||||
"Resources": {
|
||||
"DBParameterGroup": {
|
||||
"Type": "AWS::RDS::DBParameterGroup",
|
||||
"Properties": {
|
||||
"Description": "DB Parameter Goup",
|
||||
"Family": "MySQL5.1",
|
||||
"Parameters": {
|
||||
"BACKLOG_QUEUE_LIMIT": "2048"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"DBEC2SecurityGroup": {
|
||||
"Type": "AWS::EC2::SecurityGroup",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"GroupDescription": "Open database for access",
|
||||
"SecurityGroupIngress": [{
|
||||
"IpProtocol": "tcp",
|
||||
"FromPort": "3306",
|
||||
"ToPort": "3306",
|
||||
"SourceSecurityGroupName": {"Ref": "EC2SecurityGroup"}
|
||||
}]
|
||||
}
|
||||
},
|
||||
|
||||
"DBSecurityGroup": {
|
||||
"Type": "AWS::RDS::DBSecurityGroup",
|
||||
"Condition": "Is-EC2-Classic",
|
||||
"Properties": {
|
||||
"DBSecurityGroupIngress": [{
|
||||
"EC2SecurityGroupName": {"Ref": "EC2SecurityGroup"}
|
||||
}],
|
||||
"GroupDescription": "database access"
|
||||
}
|
||||
},
|
||||
|
||||
"my_vpc": {
|
||||
"Type": "AWS::EC2::VPC",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.0.0.0/16",
|
||||
}
|
||||
},
|
||||
|
||||
"EC2Subnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"AvailabilityZone": "eu-central-1a",
|
||||
"CidrBlock": "10.0.1.0/24",
|
||||
"VpcId": {"Ref": "my_vpc"}
|
||||
}
|
||||
},
|
||||
|
||||
"DBSubnet": {
|
||||
"Type": "AWS::RDS::DBSubnetGroup",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"DBSubnetGroupDescription": "my db subnet group",
|
||||
"SubnetIds": [{"Ref": "EC2Subnet"}],
|
||||
}
|
||||
},
|
||||
|
||||
"MasterDB": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"DBInstanceIdentifier": {"Ref": "DBInstanceIdentifier"},
|
||||
"DBName": {"Ref": "DBName"},
|
||||
"AllocatedStorage": {"Ref": "DBAllocatedStorage"},
|
||||
"DBInstanceClass": {"Ref": "DBInstanceClass"},
|
||||
"Engine": "MySQL",
|
||||
"DBSubnetGroupName": {"Fn::If": ["Is-EC2-VPC", {"Ref": "DBSubnet"}, {"Ref": "AWS::NoValue"}]},
|
||||
"MasterUsername": {"Ref": "DBUser"},
|
||||
"MasterUserPassword": {"Ref": "DBPassword"},
|
||||
"MultiAZ": {"Ref": "MultiAZ"},
|
||||
"Tags": [{"Key": "Name", "Value": "Master Database"}],
|
||||
"VPCSecurityGroups": {"Fn::If": ["Is-EC2-VPC", [{"Fn::GetAtt": ["DBEC2SecurityGroup", "GroupId"]}], {"Ref": "AWS::NoValue"}]},
|
||||
"DBSecurityGroups": {"Fn::If": ["Is-EC2-Classic", [{"Ref": "DBSecurityGroup"}], {"Ref": "AWS::NoValue"}]}
|
||||
},
|
||||
"DeletionPolicy": "Snapshot"
|
||||
},
|
||||
|
||||
"ReplicaDB": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"SourceDBInstanceIdentifier": {"Ref": "MasterDB"},
|
||||
"DBInstanceClass": {"Ref": "DBInstanceClass"},
|
||||
"Tags": [{"Key": "Name", "Value": "Read Replica Database"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"my_vpc": {
|
||||
"Type" : "AWS::EC2::VPC",
|
||||
"Properties" : {
|
||||
"CidrBlock" : "10.0.0.0/16",
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"EC2Platform": {
|
||||
"Description": "Platform in which this stack is deployed",
|
||||
"Value": {"Fn::If": ["Is-EC2-VPC", "EC2-VPC", "EC2-Classic"]}
|
||||
},
|
||||
|
||||
"EC2Subnet": {
|
||||
"Type" : "AWS::EC2::Subnet",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties" : {
|
||||
"AvailabilityZone" : "eu-central-1a",
|
||||
"CidrBlock" : "10.0.1.0/24",
|
||||
"VpcId" : { "Ref" : "my_vpc" }
|
||||
}
|
||||
},
|
||||
|
||||
"DBSubnet": {
|
||||
"Type": "AWS::RDS::DBSubnetGroup",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"DBSubnetGroupDescription": "my db subnet group",
|
||||
"SubnetIds" : [ { "Ref": "EC2Subnet" } ],
|
||||
}
|
||||
},
|
||||
|
||||
"MasterDB" : {
|
||||
"Type" : "AWS::RDS::DBInstance",
|
||||
"Properties" : {
|
||||
"DBInstanceIdentifier": { "Ref": "DBInstanceIdentifier" },
|
||||
"DBName" : { "Ref" : "DBName" },
|
||||
"AllocatedStorage" : { "Ref" : "DBAllocatedStorage" },
|
||||
"DBInstanceClass" : { "Ref" : "DBInstanceClass" },
|
||||
"Engine" : "MySQL",
|
||||
"DBSubnetGroupName": {"Fn::If": ["Is-EC2-VPC", { "Ref": "DBSubnet" }, { "Ref": "AWS::NoValue" }]},
|
||||
"MasterUsername" : { "Ref" : "DBUser" },
|
||||
"MasterUserPassword" : { "Ref" : "DBPassword" },
|
||||
"MultiAZ" : { "Ref" : "MultiAZ" },
|
||||
"Tags" : [{ "Key" : "Name", "Value" : "Master Database" }],
|
||||
"VPCSecurityGroups": { "Fn::If" : [ "Is-EC2-VPC", [ { "Fn::GetAtt": [ "DBEC2SecurityGroup", "GroupId" ] } ], { "Ref" : "AWS::NoValue"}]},
|
||||
"DBSecurityGroups": { "Fn::If" : [ "Is-EC2-Classic", [ { "Ref": "DBSecurityGroup" } ], { "Ref" : "AWS::NoValue"}]}
|
||||
},
|
||||
"DeletionPolicy" : "Snapshot"
|
||||
},
|
||||
|
||||
"ReplicaDB" : {
|
||||
"Type" : "AWS::RDS::DBInstance",
|
||||
"Properties" : {
|
||||
"SourceDBInstanceIdentifier" : { "Ref" : "MasterDB" },
|
||||
"DBInstanceClass" : { "Ref" : "DBInstanceClass" },
|
||||
"Tags" : [{ "Key" : "Name", "Value" : "Read Replica Database" }]
|
||||
}
|
||||
"MasterJDBCConnectionString": {
|
||||
"Description": "JDBC connection string for the master database",
|
||||
"Value": {"Fn::Join": ["", ["jdbc:mysql://",
|
||||
{"Fn::GetAtt": [
|
||||
"MasterDB", "Endpoint.Address"]},
|
||||
":",
|
||||
{"Fn::GetAtt": [
|
||||
"MasterDB", "Endpoint.Port"]},
|
||||
"/",
|
||||
{"Ref": "DBName"}]]}
|
||||
},
|
||||
"ReplicaJDBCConnectionString": {
|
||||
"Description": "JDBC connection string for the replica database",
|
||||
"Value": {"Fn::Join": ["", ["jdbc:mysql://",
|
||||
{"Fn::GetAtt": [
|
||||
"ReplicaDB", "Endpoint.Address"]},
|
||||
":",
|
||||
{"Fn::GetAtt": [
|
||||
"ReplicaDB", "Endpoint.Port"]},
|
||||
"/",
|
||||
{"Ref": "DBName"}]]}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"Outputs" : {
|
||||
"EC2Platform" : {
|
||||
"Description" : "Platform in which this stack is deployed",
|
||||
"Value" : { "Fn::If" : [ "Is-EC2-VPC", "EC2-VPC", "EC2-Classic" ]}
|
||||
},
|
||||
|
||||
"MasterJDBCConnectionString": {
|
||||
"Description" : "JDBC connection string for the master database",
|
||||
"Value" : { "Fn::Join": [ "", [ "jdbc:mysql://",
|
||||
{ "Fn::GetAtt": [ "MasterDB", "Endpoint.Address" ] },
|
||||
":",
|
||||
{ "Fn::GetAtt": [ "MasterDB", "Endpoint.Port" ] },
|
||||
"/",
|
||||
{ "Ref": "DBName" }]]}
|
||||
},
|
||||
"ReplicaJDBCConnectionString": {
|
||||
"Description" : "JDBC connection string for the replica database",
|
||||
"Value" : { "Fn::Join": [ "", [ "jdbc:mysql://",
|
||||
{ "Fn::GetAtt": [ "ReplicaDB", "Endpoint.Address" ] },
|
||||
":",
|
||||
{ "Fn::GetAtt": [ "ReplicaDB", "Endpoint.Port" ] },
|
||||
"/",
|
||||
{ "Ref": "DBName" }]]}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,190 +1,193 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion" : "2010-09-09",
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
|
||||
"Description" : "AWS CloudFormation Sample Template RDS_MySQL_With_Read_Replica: Sample template showing how to create a highly-available, RDS DBInstance with a read replica. **WARNING** This template creates an Amazon Relational Database Service database instance and Amazon CloudWatch alarms. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
"Description": "AWS CloudFormation Sample Template RDS_MySQL_With_Read_Replica: Sample template showing how to create a highly-available, RDS DBInstance with a read replica. **WARNING** This template creates an Amazon Relational Database Service database instance and Amazon CloudWatch alarms. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
|
||||
"Parameters": {
|
||||
"DBName": {
|
||||
"Default": "MyDatabase",
|
||||
"Description" : "The database name",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "64",
|
||||
"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
|
||||
"Parameters": {
|
||||
"DBName": {
|
||||
"Default": "MyDatabase",
|
||||
"Description": "The database name",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "64",
|
||||
"AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription": "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBInstanceIdentifier": {
|
||||
"Type": "String"
|
||||
},
|
||||
|
||||
"DBUser": {
|
||||
"NoEcho": "true",
|
||||
"Description": "The database admin account username",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "16",
|
||||
"AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription": "must begin with a letter and contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBPassword": {
|
||||
"NoEcho": "true",
|
||||
"Description": "The database admin account password",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "41",
|
||||
"AllowedPattern": "[a-zA-Z0-9]+",
|
||||
"ConstraintDescription": "must contain only alphanumeric characters."
|
||||
},
|
||||
|
||||
"DBAllocatedStorage": {
|
||||
"Default": "5",
|
||||
"Description": "The size of the database (Gb)",
|
||||
"Type": "Number",
|
||||
"MinValue": "5",
|
||||
"MaxValue": "1024",
|
||||
"ConstraintDescription": "must be between 5 and 1024Gb."
|
||||
},
|
||||
|
||||
"DBInstanceClass": {
|
||||
"Description": "The database instance type",
|
||||
"Type": "String",
|
||||
"Default": "db.m1.small",
|
||||
"AllowedValues": ["db.t1.micro", "db.m1.small", "db.m1.medium", "db.m1.large", "db.m1.xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.m3.medium", "db.m3.large", "db.m3.xlarge", "db.m3.2xlarge", "db.r3.large", "db.r3.xlarge", "db.r3.2xlarge", "db.r3.4xlarge", "db.r3.8xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.cr1.8xlarge"],
|
||||
"ConstraintDescription": "must select a valid database instance type."
|
||||
},
|
||||
|
||||
"EC2SecurityGroup": {
|
||||
"Description": "The EC2 security group that contains instances that need access to the database",
|
||||
"Default": "default",
|
||||
"Type": "String",
|
||||
"AllowedPattern": "[a-zA-Z0-9\\-]+",
|
||||
"ConstraintDescription": "must be a valid security group name."
|
||||
},
|
||||
|
||||
"MultiAZ": {
|
||||
"Description": "Multi-AZ master database",
|
||||
"Type": "String",
|
||||
"Default": "false",
|
||||
"AllowedValues": ["true", "false"],
|
||||
"ConstraintDescription": "must be true or false."
|
||||
}
|
||||
},
|
||||
|
||||
"DBInstanceIdentifier": {
|
||||
"Type": "String"
|
||||
"Conditions": {
|
||||
"Is-EC2-VPC": {"Fn::Or": [{"Fn::Equals": [{"Ref": "AWS::Region"}, "eu-central-1"]},
|
||||
{"Fn::Equals": [{"Ref": "AWS::Region"}, "cn-north-1"]}]},
|
||||
"Is-EC2-Classic": {"Fn::Not": [{"Condition": "Is-EC2-VPC"}]}
|
||||
},
|
||||
|
||||
"DBUser": {
|
||||
"NoEcho": "true",
|
||||
"Description" : "The database admin account username",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "16",
|
||||
"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",
|
||||
"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."
|
||||
"Resources": {
|
||||
"DBEC2SecurityGroup": {
|
||||
"Type": "AWS::EC2::SecurityGroup",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"GroupDescription": "Open database for access",
|
||||
"SecurityGroupIngress": [{
|
||||
"IpProtocol": "tcp",
|
||||
"FromPort": "3306",
|
||||
"ToPort": "3306",
|
||||
"SourceSecurityGroupName": {"Ref": "EC2SecurityGroup"}
|
||||
}]
|
||||
}
|
||||
},
|
||||
|
||||
"DBSecurityGroup": {
|
||||
"Type": "AWS::RDS::DBSecurityGroup",
|
||||
"Condition": "Is-EC2-Classic",
|
||||
"Properties": {
|
||||
"DBSecurityGroupIngress": [{
|
||||
"EC2SecurityGroupName": {"Ref": "EC2SecurityGroup"}
|
||||
}],
|
||||
"GroupDescription": "database access"
|
||||
}
|
||||
},
|
||||
|
||||
"my_vpc": {
|
||||
"Type": "AWS::EC2::VPC",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.0.0.0/16",
|
||||
}
|
||||
},
|
||||
|
||||
"EC2Subnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"AvailabilityZone": "eu-central-1a",
|
||||
"CidrBlock": "10.0.1.0/24",
|
||||
"VpcId": {"Ref": "my_vpc"}
|
||||
}
|
||||
},
|
||||
|
||||
"DBSubnet": {
|
||||
"Type": "AWS::RDS::DBSubnetGroup",
|
||||
"Condition": "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"DBSubnetGroupDescription": "my db subnet group",
|
||||
"SubnetIds": [{"Ref": "EC2Subnet"}],
|
||||
}
|
||||
},
|
||||
|
||||
"MasterDB": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"DBInstanceIdentifier": {"Ref": "DBInstanceIdentifier"},
|
||||
"DBName": {"Ref": "DBName"},
|
||||
"AllocatedStorage": {"Ref": "DBAllocatedStorage"},
|
||||
"DBInstanceClass": {"Ref": "DBInstanceClass"},
|
||||
"Engine": "MySQL",
|
||||
"DBSubnetGroupName": {"Fn::If": ["Is-EC2-VPC", {"Ref": "DBSubnet"}, {"Ref": "AWS::NoValue"}]},
|
||||
"MasterUsername": {"Ref": "DBUser"},
|
||||
"MasterUserPassword": {"Ref": "DBPassword"},
|
||||
"MultiAZ": {"Ref": "MultiAZ"},
|
||||
"Tags": [{"Key": "Name", "Value": "Master Database"}],
|
||||
"VPCSecurityGroups": {"Fn::If": ["Is-EC2-VPC", [{"Fn::GetAtt": ["DBEC2SecurityGroup", "GroupId"]}], {"Ref": "AWS::NoValue"}]},
|
||||
"DBSecurityGroups": {"Fn::If": ["Is-EC2-Classic", [{"Ref": "DBSecurityGroup"}], {"Ref": "AWS::NoValue"}]}
|
||||
},
|
||||
"DeletionPolicy": "Snapshot"
|
||||
},
|
||||
|
||||
"ReplicaDB": {
|
||||
"Type": "AWS::RDS::DBInstance",
|
||||
"Properties": {
|
||||
"SourceDBInstanceIdentifier": {"Ref": "MasterDB"},
|
||||
"DBInstanceClass": {"Ref": "DBInstanceClass"},
|
||||
"Tags": [{"Key": "Name", "Value": "Read Replica Database"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"DBPassword": {
|
||||
"NoEcho": "true",
|
||||
"Description" : "The database admin account password",
|
||||
"Type": "String",
|
||||
"MinLength": "1",
|
||||
"MaxLength": "41",
|
||||
"AllowedPattern" : "[a-zA-Z0-9]+",
|
||||
"ConstraintDescription" : "must contain only alphanumeric characters."
|
||||
},
|
||||
"Outputs": {
|
||||
"EC2Platform": {
|
||||
"Description": "Platform in which this stack is deployed",
|
||||
"Value": {"Fn::If": ["Is-EC2-VPC", "EC2-VPC", "EC2-Classic"]}
|
||||
},
|
||||
|
||||
"DBAllocatedStorage": {
|
||||
"Default": "5",
|
||||
"Description" : "The size of the database (Gb)",
|
||||
"Type": "Number",
|
||||
"MinValue": "5",
|
||||
"MaxValue": "1024",
|
||||
"ConstraintDescription" : "must be between 5 and 1024Gb."
|
||||
},
|
||||
|
||||
"DBInstanceClass": {
|
||||
"Description" : "The database instance type",
|
||||
"Type": "String",
|
||||
"Default": "db.m1.small",
|
||||
"AllowedValues" : [ "db.t1.micro", "db.m1.small", "db.m1.medium", "db.m1.large", "db.m1.xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.m3.medium", "db.m3.large", "db.m3.xlarge", "db.m3.2xlarge", "db.r3.large", "db.r3.xlarge", "db.r3.2xlarge", "db.r3.4xlarge", "db.r3.8xlarge", "db.m2.xlarge", "db.m2.2xlarge", "db.m2.4xlarge", "db.cr1.8xlarge"]
|
||||
,
|
||||
"ConstraintDescription" : "must select a valid database instance type."
|
||||
},
|
||||
|
||||
"EC2SecurityGroup": {
|
||||
"Description" : "The EC2 security group that contains instances that need access to the database",
|
||||
"Default": "default",
|
||||
"Type": "String",
|
||||
"AllowedPattern" : "[a-zA-Z0-9\\-]+",
|
||||
"ConstraintDescription" : "must be a valid security group name."
|
||||
},
|
||||
|
||||
"MultiAZ" : {
|
||||
"Description" : "Multi-AZ master database",
|
||||
"Type" : "String",
|
||||
"Default" : "false",
|
||||
"AllowedValues" : [ "true", "false" ],
|
||||
"ConstraintDescription" : "must be true or false."
|
||||
"MasterJDBCConnectionString": {
|
||||
"Description": "JDBC connection string for the master database",
|
||||
"Value": {"Fn::Join": ["", ["jdbc:mysql://",
|
||||
{"Fn::GetAtt": [
|
||||
"MasterDB", "Endpoint.Address"]},
|
||||
":",
|
||||
{"Fn::GetAtt": [
|
||||
"MasterDB", "Endpoint.Port"]},
|
||||
"/",
|
||||
{"Ref": "DBName"}]]}
|
||||
},
|
||||
"ReplicaJDBCConnectionString": {
|
||||
"Description": "JDBC connection string for the replica database",
|
||||
"Value": {"Fn::Join": ["", ["jdbc:mysql://",
|
||||
{"Fn::GetAtt": [
|
||||
"ReplicaDB", "Endpoint.Address"]},
|
||||
":",
|
||||
{"Fn::GetAtt": [
|
||||
"ReplicaDB", "Endpoint.Port"]},
|
||||
"/",
|
||||
{"Ref": "DBName"}]]}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"Conditions" : {
|
||||
"Is-EC2-VPC" : { "Fn::Or" : [ {"Fn::Equals" : [{"Ref" : "AWS::Region"}, "eu-central-1" ]},
|
||||
{"Fn::Equals" : [{"Ref" : "AWS::Region"}, "cn-north-1" ]}]},
|
||||
"Is-EC2-Classic" : { "Fn::Not" : [{ "Condition" : "Is-EC2-VPC"}]}
|
||||
},
|
||||
|
||||
"Resources" : {
|
||||
"DBEC2SecurityGroup": {
|
||||
"Type": "AWS::EC2::SecurityGroup",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties" : {
|
||||
"GroupDescription": "Open database for access",
|
||||
"SecurityGroupIngress" : [{
|
||||
"IpProtocol" : "tcp",
|
||||
"FromPort" : "3306",
|
||||
"ToPort" : "3306",
|
||||
"SourceSecurityGroupName" : { "Ref" : "EC2SecurityGroup" }
|
||||
}]
|
||||
}
|
||||
},
|
||||
|
||||
"DBSecurityGroup": {
|
||||
"Type": "AWS::RDS::DBSecurityGroup",
|
||||
"Condition" : "Is-EC2-Classic",
|
||||
"Properties": {
|
||||
"DBSecurityGroupIngress": [{
|
||||
"EC2SecurityGroupName": { "Ref": "EC2SecurityGroup" }
|
||||
}],
|
||||
"GroupDescription": "database access"
|
||||
}
|
||||
},
|
||||
|
||||
"my_vpc": {
|
||||
"Type" : "AWS::EC2::VPC",
|
||||
"Properties" : {
|
||||
"CidrBlock" : "10.0.0.0/16",
|
||||
}
|
||||
},
|
||||
|
||||
"EC2Subnet": {
|
||||
"Type" : "AWS::EC2::Subnet",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties" : {
|
||||
"AvailabilityZone" : "eu-central-1a",
|
||||
"CidrBlock" : "10.0.1.0/24",
|
||||
"VpcId" : { "Ref" : "my_vpc" }
|
||||
}
|
||||
},
|
||||
|
||||
"DBSubnet": {
|
||||
"Type": "AWS::RDS::DBSubnetGroup",
|
||||
"Condition" : "Is-EC2-VPC",
|
||||
"Properties": {
|
||||
"DBSubnetGroupDescription": "my db subnet group",
|
||||
"SubnetIds" : [ { "Ref": "EC2Subnet" } ],
|
||||
}
|
||||
},
|
||||
|
||||
"MasterDB" : {
|
||||
"Type" : "AWS::RDS::DBInstance",
|
||||
"Properties" : {
|
||||
"DBInstanceIdentifier": { "Ref": "DBInstanceIdentifier" },
|
||||
"DBName" : { "Ref" : "DBName" },
|
||||
"AllocatedStorage" : { "Ref" : "DBAllocatedStorage" },
|
||||
"DBInstanceClass" : { "Ref" : "DBInstanceClass" },
|
||||
"Engine" : "MySQL",
|
||||
"DBSubnetGroupName": {"Fn::If": ["Is-EC2-VPC", { "Ref": "DBSubnet" }, { "Ref": "AWS::NoValue" }]},
|
||||
"MasterUsername" : { "Ref" : "DBUser" },
|
||||
"MasterUserPassword" : { "Ref" : "DBPassword" },
|
||||
"MultiAZ" : { "Ref" : "MultiAZ" },
|
||||
"Tags" : [{ "Key" : "Name", "Value" : "Master Database" }],
|
||||
"VPCSecurityGroups": { "Fn::If" : [ "Is-EC2-VPC", [ { "Fn::GetAtt": [ "DBEC2SecurityGroup", "GroupId" ] } ], { "Ref" : "AWS::NoValue"}]},
|
||||
"DBSecurityGroups": { "Fn::If" : [ "Is-EC2-Classic", [ { "Ref": "DBSecurityGroup" } ], { "Ref" : "AWS::NoValue"}]}
|
||||
},
|
||||
"DeletionPolicy" : "Snapshot"
|
||||
},
|
||||
|
||||
"ReplicaDB" : {
|
||||
"Type" : "AWS::RDS::DBInstance",
|
||||
"Properties" : {
|
||||
"SourceDBInstanceIdentifier" : { "Ref" : "MasterDB" },
|
||||
"DBInstanceClass" : { "Ref" : "DBInstanceClass" },
|
||||
"Tags" : [{ "Key" : "Name", "Value" : "Read Replica Database" }]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"Outputs" : {
|
||||
"EC2Platform" : {
|
||||
"Description" : "Platform in which this stack is deployed",
|
||||
"Value" : { "Fn::If" : [ "Is-EC2-VPC", "EC2-VPC", "EC2-Classic" ]}
|
||||
},
|
||||
|
||||
"MasterJDBCConnectionString": {
|
||||
"Description" : "JDBC connection string for the master database",
|
||||
"Value" : { "Fn::Join": [ "", [ "jdbc:mysql://",
|
||||
{ "Fn::GetAtt": [ "MasterDB", "Endpoint.Address" ] },
|
||||
":",
|
||||
{ "Fn::GetAtt": [ "MasterDB", "Endpoint.Port" ] },
|
||||
"/",
|
||||
{ "Ref": "DBName" }]]}
|
||||
},
|
||||
"ReplicaJDBCConnectionString": {
|
||||
"Description" : "JDBC connection string for the replica database",
|
||||
"Value" : { "Fn::Join": [ "", [ "jdbc:mysql://",
|
||||
{ "Fn::GetAtt": [ "ReplicaDB", "Endpoint.Address" ] },
|
||||
":",
|
||||
{ "Fn::GetAtt": [ "ReplicaDB", "Endpoint.Port" ] },
|
||||
"/",
|
||||
{ "Ref": "DBName" }]]}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,187 +1,187 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
"Parameters" : {
|
||||
"DatabaseName" : {
|
||||
"Description" : "The name of the first database to be created when the cluster is created",
|
||||
"Type" : "String",
|
||||
"Default" : "dev",
|
||||
"AllowedPattern" : "([a-z]|[0-9])+"
|
||||
},
|
||||
"ClusterType" : {
|
||||
"Description" : "The type of cluster",
|
||||
"Type" : "String",
|
||||
"Default" : "single-node",
|
||||
"AllowedValues" : [ "single-node", "multi-node" ]
|
||||
},
|
||||
"NumberOfNodes" : {
|
||||
"Description" : "The number of compute nodes in the cluster. For multi-node clusters, the NumberOfNodes parameter must be greater than 1",
|
||||
"Type" : "Number",
|
||||
"Default" : "1"
|
||||
},
|
||||
"NodeType" : {
|
||||
"Description" : "The type of node to be provisioned",
|
||||
"Type" : "String",
|
||||
"Default" : "dw1.xlarge",
|
||||
"AllowedValues" : [ "dw1.xlarge", "dw1.8xlarge", "dw2.large", "dw2.8xlarge" ]
|
||||
},
|
||||
"MasterUsername" : {
|
||||
"Description" : "The user name that is associated with the master user account for the cluster that is being created",
|
||||
"Type" : "String",
|
||||
"Default" : "defaultuser",
|
||||
"AllowedPattern" : "([a-z])([a-z]|[0-9])*"
|
||||
},
|
||||
"MasterUserPassword" : {
|
||||
"Description" : "The password that is associated with the master user account for the cluster that is being created.",
|
||||
"Type" : "String",
|
||||
"NoEcho" : "true"
|
||||
},
|
||||
"InboundTraffic" : {
|
||||
"Description" : "Allow inbound traffic to the cluster from this CIDR range.",
|
||||
"Type" : "String",
|
||||
"MinLength": "9",
|
||||
"MaxLength": "18",
|
||||
"Default" : "0.0.0.0/0",
|
||||
"AllowedPattern" : "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
|
||||
"ConstraintDescription" : "must be a valid CIDR range of the form x.x.x.x/x."
|
||||
},
|
||||
"PortNumber" : {
|
||||
"Description" : "The port number on which the cluster accepts incoming connections.",
|
||||
"Type" : "Number",
|
||||
"Default" : "5439"
|
||||
}
|
||||
},
|
||||
"Conditions" : {
|
||||
"IsMultiNodeCluster" : {
|
||||
"Fn::Equals" : [{ "Ref" : "ClusterType" }, "multi-node" ]
|
||||
}
|
||||
},
|
||||
"Resources" : {
|
||||
"RedshiftCluster" : {
|
||||
"Type" : "AWS::Redshift::Cluster",
|
||||
"DependsOn" : "AttachGateway",
|
||||
"Properties" : {
|
||||
"ClusterType" : { "Ref" : "ClusterType" },
|
||||
"NumberOfNodes" : { "Fn::If" : [ "IsMultiNodeCluster", { "Ref" : "NumberOfNodes" }, { "Ref" : "AWS::NoValue" }]},
|
||||
"NodeType" : { "Ref" : "NodeType" },
|
||||
"DBName" : { "Ref" : "DatabaseName" },
|
||||
"MasterUsername" : { "Ref" : "MasterUsername" },
|
||||
"MasterUserPassword" : { "Ref" : "MasterUserPassword" },
|
||||
"ClusterParameterGroupName" : { "Ref" : "RedshiftClusterParameterGroup" },
|
||||
"VpcSecurityGroupIds" : [ { "Ref" : "SecurityGroup" } ],
|
||||
"ClusterSubnetGroupName" : { "Ref" : "RedshiftClusterSubnetGroup" },
|
||||
"PubliclyAccessible" : "true",
|
||||
"Port" : { "Ref" : "PortNumber" }
|
||||
}
|
||||
},
|
||||
"RedshiftClusterParameterGroup" : {
|
||||
"Type" : "AWS::Redshift::ClusterParameterGroup",
|
||||
"Properties" : {
|
||||
"Description" : "Cluster parameter group",
|
||||
"ParameterGroupFamily" : "redshift-1.0",
|
||||
"Parameters" : [{
|
||||
"ParameterName" : "enable_user_activity_logging",
|
||||
"ParameterValue" : "true"
|
||||
}]
|
||||
}
|
||||
},
|
||||
"RedshiftClusterSubnetGroup" : {
|
||||
"Type" : "AWS::Redshift::ClusterSubnetGroup",
|
||||
"Properties" : {
|
||||
"Description" : "Cluster subnet group",
|
||||
"SubnetIds" : [ { "Ref" : "PublicSubnet" } ]
|
||||
}
|
||||
},
|
||||
"VPC" : {
|
||||
"Type" : "AWS::EC2::VPC",
|
||||
"Properties" : {
|
||||
"CidrBlock" : "10.0.0.0/16"
|
||||
}
|
||||
},
|
||||
"PublicSubnet" : {
|
||||
"Type" : "AWS::EC2::Subnet",
|
||||
"Properties" : {
|
||||
"CidrBlock" : "10.0.0.0/24",
|
||||
"VpcId" : { "Ref" : "VPC" }
|
||||
}
|
||||
},
|
||||
"SecurityGroup" : {
|
||||
"Type" : "AWS::EC2::SecurityGroup",
|
||||
"Properties" : {
|
||||
"GroupDescription" : "Security group",
|
||||
"SecurityGroupIngress" : [ {
|
||||
"CidrIp" : { "Ref": "InboundTraffic" },
|
||||
"FromPort" : { "Ref" : "PortNumber" },
|
||||
"ToPort" : { "Ref" : "PortNumber" },
|
||||
"IpProtocol" : "tcp"
|
||||
} ],
|
||||
"VpcId" : { "Ref" : "VPC" }
|
||||
}
|
||||
},
|
||||
"myInternetGateway" : {
|
||||
"Type" : "AWS::EC2::InternetGateway"
|
||||
},
|
||||
"AttachGateway" : {
|
||||
"Type" : "AWS::EC2::VPCGatewayAttachment",
|
||||
"Properties" : {
|
||||
"VpcId" : { "Ref" : "VPC" },
|
||||
"InternetGatewayId" : { "Ref" : "myInternetGateway" }
|
||||
}
|
||||
},
|
||||
"PublicRouteTable" : {
|
||||
"Type" : "AWS::EC2::RouteTable",
|
||||
"Properties" : {
|
||||
"VpcId" : {
|
||||
"Ref" : "VPC"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PublicRoute" : {
|
||||
"Type" : "AWS::EC2::Route",
|
||||
"DependsOn" : "AttachGateway",
|
||||
"Properties" : {
|
||||
"RouteTableId" : {
|
||||
"Ref" : "PublicRouteTable"
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
"Parameters": {
|
||||
"DatabaseName": {
|
||||
"Description": "The name of the first database to be created when the cluster is created",
|
||||
"Type": "String",
|
||||
"Default": "dev",
|
||||
"AllowedPattern": "([a-z]|[0-9])+"
|
||||
},
|
||||
"DestinationCidrBlock" : "0.0.0.0/0",
|
||||
"GatewayId" : {
|
||||
"Ref" : "myInternetGateway"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PublicSubnetRouteTableAssociation" : {
|
||||
"Type" : "AWS::EC2::SubnetRouteTableAssociation",
|
||||
"Properties" : {
|
||||
"SubnetId" : {
|
||||
"Ref" : "PublicSubnet"
|
||||
"ClusterType": {
|
||||
"Description": "The type of cluster",
|
||||
"Type": "String",
|
||||
"Default": "single-node",
|
||||
"AllowedValues": ["single-node", "multi-node"]
|
||||
},
|
||||
"RouteTableId" : {
|
||||
"Ref" : "PublicRouteTable"
|
||||
"NumberOfNodes": {
|
||||
"Description": "The number of compute nodes in the cluster. For multi-node clusters, the NumberOfNodes parameter must be greater than 1",
|
||||
"Type": "Number",
|
||||
"Default": "1"
|
||||
},
|
||||
"NodeType": {
|
||||
"Description": "The type of node to be provisioned",
|
||||
"Type": "String",
|
||||
"Default": "dw1.xlarge",
|
||||
"AllowedValues": ["dw1.xlarge", "dw1.8xlarge", "dw2.large", "dw2.8xlarge"]
|
||||
},
|
||||
"MasterUsername": {
|
||||
"Description": "The user name that is associated with the master user account for the cluster that is being created",
|
||||
"Type": "String",
|
||||
"Default": "defaultuser",
|
||||
"AllowedPattern": "([a-z])([a-z]|[0-9])*"
|
||||
},
|
||||
"MasterUserPassword": {
|
||||
"Description": "The password that is associated with the master user account for the cluster that is being created.",
|
||||
"Type": "String",
|
||||
"NoEcho": "true"
|
||||
},
|
||||
"InboundTraffic": {
|
||||
"Description": "Allow inbound traffic to the cluster from this CIDR range.",
|
||||
"Type": "String",
|
||||
"MinLength": "9",
|
||||
"MaxLength": "18",
|
||||
"Default": "0.0.0.0/0",
|
||||
"AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
|
||||
"ConstraintDescription": "must be a valid CIDR range of the form x.x.x.x/x."
|
||||
},
|
||||
"PortNumber": {
|
||||
"Description": "The port number on which the cluster accepts incoming connections.",
|
||||
"Type": "Number",
|
||||
"Default": "5439"
|
||||
}
|
||||
},
|
||||
"Conditions": {
|
||||
"IsMultiNodeCluster": {
|
||||
"Fn::Equals": [{"Ref": "ClusterType"}, "multi-node"]
|
||||
}
|
||||
},
|
||||
"Resources": {
|
||||
"RedshiftCluster": {
|
||||
"Type": "AWS::Redshift::Cluster",
|
||||
"DependsOn": "AttachGateway",
|
||||
"Properties": {
|
||||
"ClusterType": {"Ref": "ClusterType"},
|
||||
"NumberOfNodes": {"Fn::If": ["IsMultiNodeCluster", {"Ref": "NumberOfNodes"}, {"Ref": "AWS::NoValue"}]},
|
||||
"NodeType": {"Ref": "NodeType"},
|
||||
"DBName": {"Ref": "DatabaseName"},
|
||||
"MasterUsername": {"Ref": "MasterUsername"},
|
||||
"MasterUserPassword": {"Ref": "MasterUserPassword"},
|
||||
"ClusterParameterGroupName": {"Ref": "RedshiftClusterParameterGroup"},
|
||||
"VpcSecurityGroupIds": [{"Ref": "SecurityGroup"}],
|
||||
"ClusterSubnetGroupName": {"Ref": "RedshiftClusterSubnetGroup"},
|
||||
"PubliclyAccessible": "true",
|
||||
"Port": {"Ref": "PortNumber"}
|
||||
}
|
||||
},
|
||||
"RedshiftClusterParameterGroup": {
|
||||
"Type": "AWS::Redshift::ClusterParameterGroup",
|
||||
"Properties": {
|
||||
"Description": "Cluster parameter group",
|
||||
"ParameterGroupFamily": "redshift-1.0",
|
||||
"Parameters": [{
|
||||
"ParameterName": "enable_user_activity_logging",
|
||||
"ParameterValue": "true"
|
||||
}]
|
||||
}
|
||||
},
|
||||
"RedshiftClusterSubnetGroup": {
|
||||
"Type": "AWS::Redshift::ClusterSubnetGroup",
|
||||
"Properties": {
|
||||
"Description": "Cluster subnet group",
|
||||
"SubnetIds": [{"Ref": "PublicSubnet"}]
|
||||
}
|
||||
},
|
||||
"VPC": {
|
||||
"Type": "AWS::EC2::VPC",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.0.0.0/16"
|
||||
}
|
||||
},
|
||||
"PublicSubnet": {
|
||||
"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {
|
||||
"CidrBlock": "10.0.0.0/24",
|
||||
"VpcId": {"Ref": "VPC"}
|
||||
}
|
||||
},
|
||||
"SecurityGroup": {
|
||||
"Type": "AWS::EC2::SecurityGroup",
|
||||
"Properties": {
|
||||
"GroupDescription": "Security group",
|
||||
"SecurityGroupIngress": [{
|
||||
"CidrIp": {"Ref": "InboundTraffic"},
|
||||
"FromPort": {"Ref": "PortNumber"},
|
||||
"ToPort": {"Ref": "PortNumber"},
|
||||
"IpProtocol": "tcp"
|
||||
}],
|
||||
"VpcId": {"Ref": "VPC"}
|
||||
}
|
||||
},
|
||||
"myInternetGateway": {
|
||||
"Type": "AWS::EC2::InternetGateway"
|
||||
},
|
||||
"AttachGateway": {
|
||||
"Type": "AWS::EC2::VPCGatewayAttachment",
|
||||
"Properties": {
|
||||
"VpcId": {"Ref": "VPC"},
|
||||
"InternetGatewayId": {"Ref": "myInternetGateway"}
|
||||
}
|
||||
},
|
||||
"PublicRouteTable": {
|
||||
"Type": "AWS::EC2::RouteTable",
|
||||
"Properties": {
|
||||
"VpcId": {
|
||||
"Ref": "VPC"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PublicRoute": {
|
||||
"Type": "AWS::EC2::Route",
|
||||
"DependsOn": "AttachGateway",
|
||||
"Properties": {
|
||||
"RouteTableId": {
|
||||
"Ref": "PublicRouteTable"
|
||||
},
|
||||
"DestinationCidrBlock": "0.0.0.0/0",
|
||||
"GatewayId": {
|
||||
"Ref": "myInternetGateway"
|
||||
}
|
||||
}
|
||||
},
|
||||
"PublicSubnetRouteTableAssociation": {
|
||||
"Type": "AWS::EC2::SubnetRouteTableAssociation",
|
||||
"Properties": {
|
||||
"SubnetId": {
|
||||
"Ref": "PublicSubnet"
|
||||
},
|
||||
"RouteTableId": {
|
||||
"Ref": "PublicRouteTable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"ClusterEndpoint": {
|
||||
"Description": "Cluster endpoint",
|
||||
"Value": {"Fn::Join": [":", [{"Fn::GetAtt": ["RedshiftCluster", "Endpoint.Address"]}, {"Fn::GetAtt": ["RedshiftCluster", "Endpoint.Port"]}]]}
|
||||
},
|
||||
"ClusterName": {
|
||||
"Description": "Name of cluster",
|
||||
"Value": {"Ref": "RedshiftCluster"}
|
||||
},
|
||||
"ParameterGroupName": {
|
||||
"Description": "Name of parameter group",
|
||||
"Value": {"Ref": "RedshiftClusterParameterGroup"}
|
||||
},
|
||||
"RedshiftClusterSubnetGroupName": {
|
||||
"Description": "Name of cluster subnet group",
|
||||
"Value": {"Ref": "RedshiftClusterSubnetGroup"}
|
||||
},
|
||||
"RedshiftClusterSecurityGroupName": {
|
||||
"Description": "Name of cluster security group",
|
||||
"Value": {"Ref": "SecurityGroup"}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs" : {
|
||||
"ClusterEndpoint" : {
|
||||
"Description" : "Cluster endpoint",
|
||||
"Value" : { "Fn::Join" : [ ":", [ { "Fn::GetAtt" : [ "RedshiftCluster", "Endpoint.Address" ] }, { "Fn::GetAtt" : [ "RedshiftCluster", "Endpoint.Port" ] } ] ] }
|
||||
},
|
||||
"ClusterName" : {
|
||||
"Description" : "Name of cluster",
|
||||
"Value" : { "Ref" : "RedshiftCluster" }
|
||||
},
|
||||
"ParameterGroupName" : {
|
||||
"Description" : "Name of parameter group",
|
||||
"Value" : { "Ref" : "RedshiftClusterParameterGroup" }
|
||||
},
|
||||
"RedshiftClusterSubnetGroupName" : {
|
||||
"Description" : "Name of cluster subnet group",
|
||||
"Value" : { "Ref" : "RedshiftClusterSubnetGroup" }
|
||||
},
|
||||
"RedshiftClusterSecurityGroupName" : {
|
||||
"Description" : "Name of cluster security group",
|
||||
"Value" : { "Ref" : "SecurityGroup" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,40 +1,40 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"Resources" : {
|
||||
"Ec2Instance" : {
|
||||
"Type" : "AWS::EC2::Instance",
|
||||
"Properties" : {
|
||||
"ImageId" : "ami-1234abcd",
|
||||
"Resources": {
|
||||
"Ec2Instance": {
|
||||
"Type": "AWS::EC2::Instance",
|
||||
"Properties": {
|
||||
"ImageId": "ami-1234abcd",
|
||||
"PrivateIpAddress": "10.0.0.25",
|
||||
}
|
||||
},
|
||||
|
||||
"HostedZone": {
|
||||
"Type" : "AWS::Route53::HostedZone",
|
||||
"Properties" : {
|
||||
"Name" : "my_zone"
|
||||
"Type": "AWS::Route53::HostedZone",
|
||||
"Properties": {
|
||||
"Name": "my_zone"
|
||||
}
|
||||
},
|
||||
|
||||
"myDNSRecord" : {
|
||||
"Type" : "AWS::Route53::RecordSet",
|
||||
"Properties" : {
|
||||
"HostedZoneName" : { "Ref" : "HostedZone" },
|
||||
"Comment" : "DNS name for my instance.",
|
||||
"Name" : {
|
||||
"Fn::Join" : [ "", [
|
||||
{"Ref" : "Ec2Instance"}, ".",
|
||||
{"Ref" : "AWS::Region"}, ".",
|
||||
{"Ref" : "HostedZone"} ,"."
|
||||
] ]
|
||||
},
|
||||
"Type" : "A",
|
||||
"TTL" : "900",
|
||||
"ResourceRecords" : [
|
||||
{ "Fn::GetAtt" : [ "Ec2Instance", "PrivateIp" ] }
|
||||
]
|
||||
}
|
||||
"myDNSRecord": {
|
||||
"Type": "AWS::Route53::RecordSet",
|
||||
"Properties": {
|
||||
"HostedZoneName": {"Ref": "HostedZone"},
|
||||
"Comment": "DNS name for my instance.",
|
||||
"Name": {
|
||||
"Fn::Join": ["", [
|
||||
{"Ref": "Ec2Instance"}, ".",
|
||||
{"Ref": "AWS::Region"}, ".",
|
||||
{"Ref": "HostedZone"}, "."
|
||||
]]
|
||||
},
|
||||
"Type": "A",
|
||||
"TTL": "900",
|
||||
"ResourceRecords": [
|
||||
{"Fn::GetAtt": ["Ec2Instance", "PrivateIp"]}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,39 +1,39 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"Resources" : {
|
||||
"Resources": {
|
||||
"HostedZone": {
|
||||
"Type" : "AWS::Route53::HostedZone",
|
||||
"Properties" : {
|
||||
"Name" : "my_zone"
|
||||
"Type": "AWS::Route53::HostedZone",
|
||||
"Properties": {
|
||||
"Name": "my_zone"
|
||||
}
|
||||
},
|
||||
|
||||
"my_health_check": {
|
||||
"Type": "AWS::Route53::HealthCheck",
|
||||
"Properties" : {
|
||||
"HealthCheckConfig" : {
|
||||
"FailureThreshold" : 3,
|
||||
"IPAddress" : "10.0.0.4",
|
||||
"Port" : 80,
|
||||
"RequestInterval" : 10,
|
||||
"ResourcePath" : "/",
|
||||
"Type" : "HTTP",
|
||||
"Properties": {
|
||||
"HealthCheckConfig": {
|
||||
"FailureThreshold": 3,
|
||||
"IPAddress": "10.0.0.4",
|
||||
"Port": 80,
|
||||
"RequestInterval": 10,
|
||||
"ResourcePath": "/",
|
||||
"Type": "HTTP",
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"myDNSRecord" : {
|
||||
"Type" : "AWS::Route53::RecordSet",
|
||||
"Properties" : {
|
||||
"HostedZoneName" : { "Ref" : "HostedZone" },
|
||||
"Comment" : "DNS name for my instance.",
|
||||
"Name" : "my_record_set",
|
||||
"Type" : "A",
|
||||
"TTL" : "900",
|
||||
"ResourceRecords" : ["my.example.com"],
|
||||
"HealthCheckId": {"Ref": "my_health_check"},
|
||||
}
|
||||
"myDNSRecord": {
|
||||
"Type": "AWS::Route53::RecordSet",
|
||||
"Properties": {
|
||||
"HostedZoneName": {"Ref": "HostedZone"},
|
||||
"Comment": "DNS name for my instance.",
|
||||
"Name": "my_record_set",
|
||||
"Type": "A",
|
||||
"TTL": "900",
|
||||
"ResourceRecords": ["my.example.com"],
|
||||
"HealthCheckId": {"Ref": "my_health_check"},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,47 +1,47 @@
|
|||
from __future__ import unicode_literals
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion" : "2010-09-09",
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
|
||||
"Description" : "AWS CloudFormation Sample Template Route53_RoundRobin: Sample template showing how to use weighted round robin (WRR) DNS entried via Amazon Route 53. This contrived sample uses weighted CNAME records to illustrate that the weighting influences the return records. It assumes that you already have a Hosted Zone registered with Amazon Route 53. **WARNING** This template creates one or more AWS resources. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
"Description": "AWS CloudFormation Sample Template Route53_RoundRobin: Sample template showing how to use weighted round robin (WRR) DNS entried via Amazon Route 53. This contrived sample uses weighted CNAME records to illustrate that the weighting influences the return records. It assumes that you already have a Hosted Zone registered with Amazon Route 53. **WARNING** This template creates one or more AWS resources. You will be billed for the AWS resources used if you create a stack from this template.",
|
||||
|
||||
"Resources" : {
|
||||
"Resources": {
|
||||
|
||||
"MyZone": {
|
||||
"Type" : "AWS::Route53::HostedZone",
|
||||
"Properties" : {
|
||||
"Name" : "my_zone"
|
||||
}
|
||||
"MyZone": {
|
||||
"Type": "AWS::Route53::HostedZone",
|
||||
"Properties": {
|
||||
"Name": "my_zone"
|
||||
}
|
||||
},
|
||||
|
||||
"MyDNSRecord": {
|
||||
"Type": "AWS::Route53::RecordSetGroup",
|
||||
"Properties": {
|
||||
"HostedZoneName": {"Ref": "MyZone"},
|
||||
"Comment": "Contrived example to redirect to aws.amazon.com 75% of the time and www.amazon.com 25% of the time.",
|
||||
"RecordSets": [{
|
||||
"SetIdentifier": {"Fn::Join": [" ", [{"Ref": "AWS::StackName"}, "AWS"]]},
|
||||
"Name": {"Fn::Join": ["", [{"Ref": "AWS::StackName"}, ".", {"Ref": "AWS::Region"}, ".", {"Ref": "MyZone"}, "."]]},
|
||||
"Type": "CNAME",
|
||||
"TTL": "900",
|
||||
"ResourceRecords": ["aws.amazon.com"],
|
||||
"Weight": "3"
|
||||
}, {
|
||||
"SetIdentifier": {"Fn::Join": [" ", [{"Ref": "AWS::StackName"}, "Amazon"]]},
|
||||
"Name": {"Fn::Join": ["", [{"Ref": "AWS::StackName"}, ".", {"Ref": "AWS::Region"}, ".", {"Ref": "MyZone"}, "."]]},
|
||||
"Type": "CNAME",
|
||||
"TTL": "900",
|
||||
"ResourceRecords": ["www.amazon.com"],
|
||||
"Weight": "1"
|
||||
}]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"MyDNSRecord" : {
|
||||
"Type" : "AWS::Route53::RecordSetGroup",
|
||||
"Properties" : {
|
||||
"HostedZoneName" : {"Ref": "MyZone"},
|
||||
"Comment" : "Contrived example to redirect to aws.amazon.com 75% of the time and www.amazon.com 25% of the time.",
|
||||
"RecordSets" : [{
|
||||
"SetIdentifier" : { "Fn::Join" : [ " ", [{"Ref" : "AWS::StackName"}, "AWS" ]]},
|
||||
"Name" : { "Fn::Join" : [ "", [{"Ref" : "AWS::StackName"}, ".", {"Ref" : "AWS::Region"}, ".", {"Ref" : "MyZone"}, "."]]},
|
||||
"Type" : "CNAME",
|
||||
"TTL" : "900",
|
||||
"ResourceRecords" : ["aws.amazon.com"],
|
||||
"Weight" : "3"
|
||||
},{
|
||||
"SetIdentifier" : { "Fn::Join" : [ " ", [{"Ref" : "AWS::StackName"}, "Amazon" ]]},
|
||||
"Name" : { "Fn::Join" : [ "", [{"Ref" : "AWS::StackName"}, ".", {"Ref" : "AWS::Region"}, ".", {"Ref" : "MyZone"}, "."]]},
|
||||
"Type" : "CNAME",
|
||||
"TTL" : "900",
|
||||
"ResourceRecords" : ["www.amazon.com"],
|
||||
"Weight" : "1"
|
||||
}]
|
||||
}
|
||||
"Outputs": {
|
||||
"DomainName": {
|
||||
"Description": "Fully qualified domain name",
|
||||
"Value": {"Ref": "MyDNSRecord"}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"Outputs" : {
|
||||
"DomainName" : {
|
||||
"Description" : "Fully qualified domain name",
|
||||
"Value" : { "Ref" : "MyDNSRecord" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,8 +35,8 @@ dummy_template3 = {
|
|||
"VPC": {
|
||||
"Properties": {
|
||||
"CidrBlock": "192.168.0.0/16",
|
||||
},
|
||||
"Type": "AWS::EC2::VPC"
|
||||
},
|
||||
"Type": "AWS::EC2::VPC"
|
||||
}
|
||||
},
|
||||
}
|
||||
|
|
@ -91,7 +91,8 @@ def test_create_stack_with_notification_arn():
|
|||
)
|
||||
|
||||
stack = conn.describe_stacks()[0]
|
||||
[n.value for n in stack.notification_arns].should.contain('arn:aws:sns:us-east-1:123456789012:fake-queue')
|
||||
[n.value for n in stack.notification_arns].should.contain(
|
||||
'arn:aws:sns:us-east-1:123456789012:fake-queue')
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated
|
||||
|
|
@ -111,16 +112,16 @@ def test_create_stack_from_s3_url():
|
|||
stack.stack_name.should.equal('new-stack')
|
||||
stack.get_template().should.equal(
|
||||
{
|
||||
'GetTemplateResponse': {
|
||||
'GetTemplateResult': {
|
||||
'TemplateBody': dummy_template_json,
|
||||
'ResponseMetadata': {
|
||||
'RequestId': '2d06e36c-ac1d-11e0-a958-f9382b6eb86bEXAMPLE'
|
||||
'GetTemplateResponse': {
|
||||
'GetTemplateResult': {
|
||||
'TemplateBody': dummy_template_json,
|
||||
'ResponseMetadata': {
|
||||
'RequestId': '2d06e36c-ac1d-11e0-a958-f9382b6eb86bEXAMPLE'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated
|
||||
|
|
@ -271,7 +272,8 @@ def test_cloudformation_params():
|
|||
}
|
||||
dummy_template_json = json.dumps(dummy_template)
|
||||
cfn = boto.connect_cloudformation()
|
||||
cfn.create_stack('test_stack1', template_body=dummy_template_json, parameters=[('APPNAME', 'testing123')])
|
||||
cfn.create_stack('test_stack1', template_body=dummy_template_json, parameters=[
|
||||
('APPNAME', 'testing123')])
|
||||
stack = cfn.describe_stacks('test_stack1')[0]
|
||||
stack.parameters.should.have.length_of(1)
|
||||
param = stack.parameters[0]
|
||||
|
|
@ -342,23 +344,28 @@ def test_update_stack():
|
|||
@mock_cloudformation_deprecated
|
||||
def test_update_stack_when_rolled_back():
|
||||
conn = boto.connect_cloudformation()
|
||||
stack_id = conn.create_stack("test_stack", template_body=dummy_template_json)
|
||||
stack_id = conn.create_stack(
|
||||
"test_stack", template_body=dummy_template_json)
|
||||
|
||||
cloudformation_backends[conn.region.name].stacks[stack_id].status = 'ROLLBACK_COMPLETE'
|
||||
cloudformation_backends[conn.region.name].stacks[
|
||||
stack_id].status = 'ROLLBACK_COMPLETE'
|
||||
|
||||
with assert_raises(BotoServerError) as err:
|
||||
conn.update_stack("test_stack", dummy_template_json)
|
||||
|
||||
ex = err.exception
|
||||
ex.body.should.match(r'is in ROLLBACK_COMPLETE state and can not be updated')
|
||||
ex.body.should.match(
|
||||
r'is in ROLLBACK_COMPLETE state and can not be updated')
|
||||
ex.error_code.should.equal('ValidationError')
|
||||
ex.reason.should.equal('Bad Request')
|
||||
ex.status.should.equal(400)
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated
|
||||
def test_describe_stack_events_shows_create_update_and_delete():
|
||||
conn = boto.connect_cloudformation()
|
||||
stack_id = conn.create_stack("test_stack", template_body=dummy_template_json)
|
||||
stack_id = conn.create_stack(
|
||||
"test_stack", template_body=dummy_template_json)
|
||||
conn.update_stack(stack_id, template_body=dummy_template_json2)
|
||||
conn.delete_stack(stack_id)
|
||||
|
||||
|
|
@ -367,7 +374,8 @@ def test_describe_stack_events_shows_create_update_and_delete():
|
|||
events[0].resource_type.should.equal("AWS::CloudFormation::Stack")
|
||||
events[-1].resource_type.should.equal("AWS::CloudFormation::Stack")
|
||||
|
||||
# testing ordering of stack events without assuming resource events will not exist
|
||||
# testing ordering of stack events without assuming resource events will
|
||||
# not exist
|
||||
stack_events_to_look_for = iter([
|
||||
("CREATE_IN_PROGRESS", "User Initiated"), ("CREATE_COMPLETE", None),
|
||||
("UPDATE_IN_PROGRESS", "User Initiated"), ("UPDATE_COMPLETE", None),
|
||||
|
|
@ -381,12 +389,13 @@ def test_describe_stack_events_shows_create_update_and_delete():
|
|||
event.logical_resource_id.should.equal("test_stack")
|
||||
event.physical_resource_id.should.equal(stack_id)
|
||||
|
||||
status_to_look_for, reason_to_look_for = next(stack_events_to_look_for)
|
||||
status_to_look_for, reason_to_look_for = next(
|
||||
stack_events_to_look_for)
|
||||
event.resource_status.should.equal(status_to_look_for)
|
||||
if reason_to_look_for is not None:
|
||||
event.resource_status_reason.should.equal(reason_to_look_for)
|
||||
event.resource_status_reason.should.equal(
|
||||
reason_to_look_for)
|
||||
except StopIteration:
|
||||
assert False, "Too many stack events"
|
||||
|
||||
list(stack_events_to_look_for).should.be.empty
|
||||
|
||||
|
|
|
|||
|
|
@ -124,7 +124,8 @@ def test_create_stack_from_s3_url():
|
|||
s3_conn = boto3.resource('s3')
|
||||
bucket = s3_conn.create_bucket(Bucket="foobar")
|
||||
|
||||
key = s3_conn.Object('foobar', 'template-key').put(Body=dummy_template_json)
|
||||
key = s3_conn.Object(
|
||||
'foobar', 'template-key').put(Body=dummy_template_json)
|
||||
key_url = s3.generate_presigned_url(
|
||||
ClientMethod='get_object',
|
||||
Params={
|
||||
|
|
@ -160,6 +161,7 @@ def test_describe_stack_resources():
|
|||
resource['ResourceType'].should.equal('AWS::EC2::Instance')
|
||||
resource['StackId'].should.equal(stack['StackId'])
|
||||
|
||||
|
||||
@mock_cloudformation
|
||||
def test_describe_stack_by_name():
|
||||
cf_conn = boto3.client('cloudformation', region_name='us-east-1')
|
||||
|
|
@ -249,6 +251,7 @@ def test_describe_deleted_stack():
|
|||
stack_by_id['StackName'].should.equal("test_stack")
|
||||
stack_by_id['StackStatus'].should.equal("DELETE_COMPLETE")
|
||||
|
||||
|
||||
@mock_cloudformation
|
||||
def test_describe_updated_stack():
|
||||
cf_conn = boto3.client('cloudformation', region_name='us-east-1')
|
||||
|
|
@ -299,9 +302,9 @@ def test_cloudformation_params():
|
|||
StackName='test_stack',
|
||||
TemplateBody=dummy_template_with_params_json,
|
||||
Parameters=[{
|
||||
"ParameterKey": "APPNAME",
|
||||
"ParameterValue": "testing123",
|
||||
}],
|
||||
"ParameterKey": "APPNAME",
|
||||
"ParameterValue": "testing123",
|
||||
}],
|
||||
)
|
||||
|
||||
stack.parameters.should.have.length_of(1)
|
||||
|
|
@ -334,6 +337,7 @@ def test_stack_tags():
|
|||
item for items in [tag.items() for tag in tags] for item in items)
|
||||
observed_tag_items.should.equal(expected_tag_items)
|
||||
|
||||
|
||||
@mock_cloudformation
|
||||
def test_stack_events():
|
||||
cf = boto3.resource('cloudformation', region_name='us-east-1')
|
||||
|
|
@ -350,7 +354,8 @@ def test_stack_events():
|
|||
events[0].resource_type.should.equal("AWS::CloudFormation::Stack")
|
||||
events[-1].resource_type.should.equal("AWS::CloudFormation::Stack")
|
||||
|
||||
# testing ordering of stack events without assuming resource events will not exist
|
||||
# testing ordering of stack events without assuming resource events will
|
||||
# not exist
|
||||
stack_events_to_look_for = iter([
|
||||
("CREATE_IN_PROGRESS", "User Initiated"), ("CREATE_COMPLETE", None),
|
||||
("UPDATE_IN_PROGRESS", "User Initiated"), ("UPDATE_COMPLETE", None),
|
||||
|
|
@ -364,10 +369,12 @@ def test_stack_events():
|
|||
event.logical_resource_id.should.equal("test_stack")
|
||||
event.physical_resource_id.should.equal(stack.stack_id)
|
||||
|
||||
status_to_look_for, reason_to_look_for = next(stack_events_to_look_for)
|
||||
status_to_look_for, reason_to_look_for = next(
|
||||
stack_events_to_look_for)
|
||||
event.resource_status.should.equal(status_to_look_for)
|
||||
if reason_to_look_for is not None:
|
||||
event.resource_status_reason.should.equal(reason_to_look_for)
|
||||
event.resource_status_reason.should.equal(
|
||||
reason_to_look_for)
|
||||
except StopIteration:
|
||||
assert False, "Too many stack events"
|
||||
|
||||
|
|
|
|||
|
|
@ -143,15 +143,18 @@ def test_update_stack():
|
|||
sqs_conn = boto.sqs.connect_to_region("us-west-1")
|
||||
queues = sqs_conn.get_all_queues()
|
||||
queues.should.have.length_of(1)
|
||||
queues[0].get_attributes('VisibilityTimeout')['VisibilityTimeout'].should.equal('60')
|
||||
queues[0].get_attributes('VisibilityTimeout')[
|
||||
'VisibilityTimeout'].should.equal('60')
|
||||
|
||||
sqs_template['Resources']['QueueGroup']['Properties']['VisibilityTimeout'] = 100
|
||||
sqs_template['Resources']['QueueGroup'][
|
||||
'Properties']['VisibilityTimeout'] = 100
|
||||
sqs_template_json = json.dumps(sqs_template)
|
||||
conn.update_stack("test_stack", sqs_template_json)
|
||||
|
||||
queues = sqs_conn.get_all_queues()
|
||||
queues.should.have.length_of(1)
|
||||
queues[0].get_attributes('VisibilityTimeout')['VisibilityTimeout'].should.equal('100')
|
||||
queues[0].get_attributes('VisibilityTimeout')[
|
||||
'VisibilityTimeout'].should.equal('100')
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated()
|
||||
|
|
@ -395,7 +398,8 @@ def test_stack_elb_integration_with_update():
|
|||
load_balancer = elb_conn.get_all_load_balancers()[0]
|
||||
load_balancer.availability_zones[0].should.equal('us-west-1a')
|
||||
|
||||
elb_template['Resources']['MyELB']['Properties']['AvailabilityZones'] = ['us-west-1b']
|
||||
elb_template['Resources']['MyELB']['Properties'][
|
||||
'AvailabilityZones'] = ['us-west-1b']
|
||||
elb_template_json = json.dumps(elb_template)
|
||||
conn.update_stack(
|
||||
"elb_stack",
|
||||
|
|
@ -431,7 +435,8 @@ def test_redshift_stack():
|
|||
redshift_conn = boto.redshift.connect_to_region("us-west-2")
|
||||
|
||||
cluster_res = redshift_conn.describe_clusters()
|
||||
clusters = cluster_res['DescribeClustersResponse']['DescribeClustersResult']['Clusters']
|
||||
clusters = cluster_res['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters']
|
||||
clusters.should.have.length_of(1)
|
||||
cluster = clusters[0]
|
||||
cluster['DBName'].should.equal("mydb")
|
||||
|
|
@ -499,12 +504,14 @@ def test_stack_security_groups():
|
|||
conn.create_stack(
|
||||
"security_group_stack",
|
||||
template_body=security_group_template_json,
|
||||
tags={"foo":"bar"}
|
||||
tags={"foo": "bar"}
|
||||
)
|
||||
|
||||
ec2_conn = boto.ec2.connect_to_region("us-west-1")
|
||||
instance_group = ec2_conn.get_all_security_groups(filters={'description': ['My security group']})[0]
|
||||
other_group = ec2_conn.get_all_security_groups(filters={'description': ['My other group']})[0]
|
||||
instance_group = ec2_conn.get_all_security_groups(
|
||||
filters={'description': ['My security group']})[0]
|
||||
other_group = ec2_conn.get_all_security_groups(
|
||||
filters={'description': ['My other group']})[0]
|
||||
|
||||
reservation = ec2_conn.get_all_instances()[0]
|
||||
ec2_instance = reservation.instances[0]
|
||||
|
|
@ -597,13 +604,17 @@ def test_autoscaling_group_with_elb():
|
|||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
as_group_resource = [resource for resource in resources if resource.resource_type == 'AWS::AutoScaling::AutoScalingGroup'][0]
|
||||
as_group_resource = [resource for resource in resources if resource.resource_type ==
|
||||
'AWS::AutoScaling::AutoScalingGroup'][0]
|
||||
as_group_resource.physical_resource_id.should.contain("my-as-group")
|
||||
|
||||
launch_config_resource = [resource for resource in resources if resource.resource_type == 'AWS::AutoScaling::LaunchConfiguration'][0]
|
||||
launch_config_resource.physical_resource_id.should.contain("my-launch-config")
|
||||
launch_config_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::AutoScaling::LaunchConfiguration'][0]
|
||||
launch_config_resource.physical_resource_id.should.contain(
|
||||
"my-launch-config")
|
||||
|
||||
elb_resource = [resource for resource in resources if resource.resource_type == 'AWS::ElasticLoadBalancing::LoadBalancer'][0]
|
||||
elb_resource = [resource for resource in resources if resource.resource_type ==
|
||||
'AWS::ElasticLoadBalancing::LoadBalancer'][0]
|
||||
elb_resource.physical_resource_id.should.contain("my-elb")
|
||||
|
||||
|
||||
|
|
@ -687,26 +698,32 @@ def test_vpc_single_instance_in_subnet():
|
|||
eip.domain.should.equal('vpc')
|
||||
eip.instance_id.should.equal(instance.id)
|
||||
|
||||
security_group = ec2_conn.get_all_security_groups(filters={'vpc_id': [vpc.id]})[0]
|
||||
security_group = ec2_conn.get_all_security_groups(
|
||||
filters={'vpc_id': [vpc.id]})[0]
|
||||
security_group.vpc_id.should.equal(vpc.id)
|
||||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
vpc_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::VPC'][0]
|
||||
vpc_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::VPC'][0]
|
||||
vpc_resource.physical_resource_id.should.equal(vpc.id)
|
||||
|
||||
subnet_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::Subnet'][0]
|
||||
subnet_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::Subnet'][0]
|
||||
subnet_resource.physical_resource_id.should.equal(subnet.id)
|
||||
|
||||
eip_resource = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
eip_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
eip_resource.physical_resource_id.should.equal(eip.allocation_id)
|
||||
|
||||
|
||||
@mock_cloudformation()
|
||||
@mock_ec2()
|
||||
@mock_rds2()
|
||||
def test_rds_db_parameter_groups():
|
||||
ec2_conn = boto3.client("ec2", region_name="us-west-1")
|
||||
ec2_conn.create_security_group(GroupName='application', Description='Our Application Group')
|
||||
ec2_conn.create_security_group(
|
||||
GroupName='application', Description='Our Application Group')
|
||||
|
||||
template_json = json.dumps(rds_mysql_with_db_parameter_group.template)
|
||||
cf_conn = boto3.client('cloudformation', 'us-west-1')
|
||||
|
|
@ -714,16 +731,16 @@ def test_rds_db_parameter_groups():
|
|||
StackName="test_stack",
|
||||
TemplateBody=template_json,
|
||||
Parameters=[{'ParameterKey': key, 'ParameterValue': value} for
|
||||
key, value in [
|
||||
("DBInstanceIdentifier", "master_db"),
|
||||
("DBName", "my_db"),
|
||||
("DBUser", "my_user"),
|
||||
("DBPassword", "my_password"),
|
||||
("DBAllocatedStorage", "20"),
|
||||
("DBInstanceClass", "db.m1.medium"),
|
||||
("EC2SecurityGroup", "application"),
|
||||
("MultiAZ", "true"),
|
||||
]
|
||||
key, value in [
|
||||
("DBInstanceIdentifier", "master_db"),
|
||||
("DBName", "my_db"),
|
||||
("DBUser", "my_user"),
|
||||
("DBPassword", "my_password"),
|
||||
("DBAllocatedStorage", "20"),
|
||||
("DBInstanceClass", "db.m1.medium"),
|
||||
("EC2SecurityGroup", "application"),
|
||||
("MultiAZ", "true"),
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
|
|
@ -731,7 +748,8 @@ def test_rds_db_parameter_groups():
|
|||
|
||||
db_parameter_groups = rds_conn.describe_db_parameter_groups()
|
||||
len(db_parameter_groups['DBParameterGroups']).should.equal(1)
|
||||
db_parameter_group_name = db_parameter_groups['DBParameterGroups'][0]['DBParameterGroupName']
|
||||
db_parameter_group_name = db_parameter_groups[
|
||||
'DBParameterGroups'][0]['DBParameterGroupName']
|
||||
|
||||
found_cloudformation_set_parameter = False
|
||||
for db_parameter in rds_conn.describe_db_parameters(DBParameterGroupName=db_parameter_group_name)['Parameters']:
|
||||
|
|
@ -741,7 +759,6 @@ def test_rds_db_parameter_groups():
|
|||
found_cloudformation_set_parameter.should.equal(True)
|
||||
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated()
|
||||
@mock_ec2_deprecated()
|
||||
@mock_rds_deprecated()
|
||||
|
|
@ -906,15 +923,20 @@ def test_iam_roles():
|
|||
|
||||
iam_conn = boto.iam.connect_to_region("us-west-1")
|
||||
|
||||
role_result = iam_conn.list_roles()['list_roles_response']['list_roles_result']['roles'][0]
|
||||
role_result = iam_conn.list_roles()['list_roles_response'][
|
||||
'list_roles_result']['roles'][0]
|
||||
role = iam_conn.get_role(role_result.role_name)
|
||||
role.role_name.should.contain("my-role")
|
||||
role.path.should.equal("my-path")
|
||||
|
||||
instance_profile_response = iam_conn.list_instance_profiles()['list_instance_profiles_response']
|
||||
cfn_instance_profile = instance_profile_response['list_instance_profiles_result']['instance_profiles'][0]
|
||||
instance_profile = iam_conn.get_instance_profile(cfn_instance_profile.instance_profile_name)
|
||||
instance_profile.instance_profile_name.should.contain("my-instance-profile")
|
||||
instance_profile_response = iam_conn.list_instance_profiles()[
|
||||
'list_instance_profiles_response']
|
||||
cfn_instance_profile = instance_profile_response[
|
||||
'list_instance_profiles_result']['instance_profiles'][0]
|
||||
instance_profile = iam_conn.get_instance_profile(
|
||||
cfn_instance_profile.instance_profile_name)
|
||||
instance_profile.instance_profile_name.should.contain(
|
||||
"my-instance-profile")
|
||||
instance_profile.path.should.equal("my-path")
|
||||
instance_profile.role_id.should.equal(role.role_id)
|
||||
|
||||
|
|
@ -924,10 +946,13 @@ def test_iam_roles():
|
|||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
instance_profile_resource = [resource for resource in resources if resource.resource_type == 'AWS::IAM::InstanceProfile'][0]
|
||||
instance_profile_resource.physical_resource_id.should.equal(instance_profile.instance_profile_name)
|
||||
instance_profile_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::IAM::InstanceProfile'][0]
|
||||
instance_profile_resource.physical_resource_id.should.equal(
|
||||
instance_profile.instance_profile_name)
|
||||
|
||||
role_resource = [resource for resource in resources if resource.resource_type == 'AWS::IAM::Role'][0]
|
||||
role_resource = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::IAM::Role'][0]
|
||||
role_resource.physical_resource_id.should.equal(role.role_id)
|
||||
|
||||
|
||||
|
|
@ -949,13 +974,15 @@ def test_single_instance_with_ebs_volume():
|
|||
|
||||
volumes = ec2_conn.get_all_volumes()
|
||||
# Grab the mounted drive
|
||||
volume = [volume for volume in volumes if volume.attach_data.device == '/dev/sdh'][0]
|
||||
volume = [
|
||||
volume for volume in volumes if volume.attach_data.device == '/dev/sdh'][0]
|
||||
volume.volume_state().should.equal('in-use')
|
||||
volume.attach_data.instance_id.should.equal(ec2_instance.id)
|
||||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
ebs_volumes = [resource for resource in resources if resource.resource_type == 'AWS::EC2::Volume']
|
||||
ebs_volumes = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::Volume']
|
||||
ebs_volumes[0].physical_resource_id.should.equal(volume.id)
|
||||
|
||||
|
||||
|
|
@ -981,7 +1008,8 @@ def test_classic_eip():
|
|||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
cfn_eip = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
cfn_eip = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
cfn_eip.physical_resource_id.should.equal(eip.public_ip)
|
||||
|
||||
|
||||
|
|
@ -997,7 +1025,8 @@ def test_vpc_eip():
|
|||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
cfn_eip = [resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
cfn_eip = [
|
||||
resource for resource in resources if resource.resource_type == 'AWS::EC2::EIP'][0]
|
||||
cfn_eip.physical_resource_id.should.equal(eip.allocation_id)
|
||||
|
||||
|
||||
|
|
@ -1111,7 +1140,8 @@ def test_conditional_if_handling():
|
|||
ec2_instance.terminate()
|
||||
|
||||
conn = boto.cloudformation.connect_to_region("us-west-2")
|
||||
conn.create_stack('test_stack1', template_body=dummy_template_json, parameters=[("ENV", "prd")])
|
||||
conn.create_stack(
|
||||
'test_stack1', template_body=dummy_template_json, parameters=[("ENV", "prd")])
|
||||
ec2_conn = boto.ec2.connect_to_region("us-west-2")
|
||||
reservation = ec2_conn.get_all_instances()[0]
|
||||
ec2_instance = reservation.instances[0]
|
||||
|
|
@ -1175,7 +1205,8 @@ def test_route53_roundrobin():
|
|||
template_body=template_json,
|
||||
)
|
||||
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse'][
|
||||
'HostedZones']
|
||||
list(zones).should.have.length_of(1)
|
||||
zone_id = zones[0]['Id']
|
||||
zone_id = zone_id.split('/')
|
||||
|
|
@ -1203,7 +1234,8 @@ def test_route53_roundrobin():
|
|||
stack = conn.describe_stacks()[0]
|
||||
output = stack.outputs[0]
|
||||
output.key.should.equal('DomainName')
|
||||
output.value.should.equal('arn:aws:route53:::hostedzone/{0}'.format(zone_id))
|
||||
output.value.should.equal(
|
||||
'arn:aws:route53:::hostedzone/{0}'.format(zone_id))
|
||||
|
||||
|
||||
@mock_cloudformation_deprecated()
|
||||
|
|
@ -1222,13 +1254,13 @@ def test_route53_ec2_instance_with_public_ip():
|
|||
|
||||
instance_id = ec2_conn.get_all_reservations()[0].instances[0].id
|
||||
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse'][
|
||||
'HostedZones']
|
||||
list(zones).should.have.length_of(1)
|
||||
zone_id = zones[0]['Id']
|
||||
zone_id = zone_id.split('/')
|
||||
zone_id = zone_id[2]
|
||||
|
||||
|
||||
rrsets = route53_conn.get_all_rrsets(zone_id)
|
||||
rrsets.should.have.length_of(1)
|
||||
|
||||
|
|
@ -1253,7 +1285,8 @@ def test_route53_associate_health_check():
|
|||
template_body=template_json,
|
||||
)
|
||||
|
||||
checks = route53_conn.get_list_health_checks()['ListHealthChecksResponse']['HealthChecks']
|
||||
checks = route53_conn.get_list_health_checks()['ListHealthChecksResponse'][
|
||||
'HealthChecks']
|
||||
list(checks).should.have.length_of(1)
|
||||
check = checks[0]
|
||||
health_check_id = check['Id']
|
||||
|
|
@ -1265,7 +1298,8 @@ def test_route53_associate_health_check():
|
|||
config["ResourcePath"].should.equal("/")
|
||||
config["Type"].should.equal("HTTP")
|
||||
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse'][
|
||||
'HostedZones']
|
||||
list(zones).should.have.length_of(1)
|
||||
zone_id = zones[0]['Id']
|
||||
zone_id = zone_id.split('/')
|
||||
|
|
@ -1290,7 +1324,8 @@ def test_route53_with_update():
|
|||
template_body=template_json,
|
||||
)
|
||||
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse'][
|
||||
'HostedZones']
|
||||
list(zones).should.have.length_of(1)
|
||||
zone_id = zones[0]['Id']
|
||||
zone_id = zone_id.split('/')
|
||||
|
|
@ -1302,14 +1337,16 @@ def test_route53_with_update():
|
|||
record_set = rrsets[0]
|
||||
record_set.resource_records.should.equal(["my.example.com"])
|
||||
|
||||
route53_health_check.template['Resources']['myDNSRecord']['Properties']['ResourceRecords'] = ["my_other.example.com"]
|
||||
route53_health_check.template['Resources']['myDNSRecord'][
|
||||
'Properties']['ResourceRecords'] = ["my_other.example.com"]
|
||||
template_json = json.dumps(route53_health_check.template)
|
||||
cf_conn.update_stack(
|
||||
"test_stack",
|
||||
template_body=template_json,
|
||||
)
|
||||
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse']['HostedZones']
|
||||
zones = route53_conn.get_all_hosted_zones()['ListHostedZonesResponse'][
|
||||
'HostedZones']
|
||||
list(zones).should.have.length_of(1)
|
||||
zone_id = zones[0]['Id']
|
||||
zone_id = zone_id.split('/')
|
||||
|
|
@ -1355,12 +1392,14 @@ def test_sns_topic():
|
|||
)
|
||||
|
||||
sns_conn = boto.sns.connect_to_region("us-west-1")
|
||||
topics = sns_conn.get_all_topics()["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
|
||||
topics = sns_conn.get_all_topics()["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"]
|
||||
topics.should.have.length_of(1)
|
||||
topic_arn = topics[0]['TopicArn']
|
||||
topic_arn.should.contain("my_topics")
|
||||
|
||||
subscriptions = sns_conn.get_all_subscriptions()["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions = sns_conn.get_all_subscriptions()["ListSubscriptionsResponse"][
|
||||
"ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions.should.have.length_of(1)
|
||||
subscription = subscriptions[0]
|
||||
subscription["TopicArn"].should.equal(topic_arn)
|
||||
|
|
@ -1504,12 +1543,15 @@ def test_multiple_security_group_ingress_separate_from_security_group_by_id():
|
|||
)
|
||||
ec2_conn = boto.ec2.connect_to_region("us-west-1")
|
||||
|
||||
security_group1 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg1"})[0]
|
||||
security_group2 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]
|
||||
security_group1 = ec2_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg1"})[0]
|
||||
security_group2 = ec2_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg2"})[0]
|
||||
|
||||
security_group1.rules.should.have.length_of(1)
|
||||
security_group1.rules[0].grants.should.have.length_of(1)
|
||||
security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].grants[
|
||||
0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].ip_protocol.should.equal('tcp')
|
||||
security_group1.rules[0].from_port.should.equal('80')
|
||||
security_group1.rules[0].to_port.should.equal('8080')
|
||||
|
|
@ -1519,7 +1561,8 @@ def test_multiple_security_group_ingress_separate_from_security_group_by_id():
|
|||
@mock_ec2_deprecated
|
||||
def test_security_group_ingress_separate_from_security_group_by_id():
|
||||
ec2_conn = boto.ec2.connect_to_region("us-west-1")
|
||||
ec2_conn.create_security_group("test-security-group1", "test security group")
|
||||
ec2_conn.create_security_group(
|
||||
"test-security-group1", "test security group")
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
|
|
@ -1555,12 +1598,15 @@ def test_security_group_ingress_separate_from_security_group_by_id():
|
|||
"test_stack",
|
||||
template_body=template_json,
|
||||
)
|
||||
security_group1 = ec2_conn.get_all_security_groups(groupnames=["test-security-group1"])[0]
|
||||
security_group2 = ec2_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]
|
||||
security_group1 = ec2_conn.get_all_security_groups(
|
||||
groupnames=["test-security-group1"])[0]
|
||||
security_group2 = ec2_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg2"})[0]
|
||||
|
||||
security_group1.rules.should.have.length_of(1)
|
||||
security_group1.rules[0].grants.should.have.length_of(1)
|
||||
security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].grants[
|
||||
0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].ip_protocol.should.equal('tcp')
|
||||
security_group1.rules[0].from_port.should.equal('80')
|
||||
security_group1.rules[0].to_port.should.equal('8080')
|
||||
|
|
@ -1621,12 +1667,15 @@ def test_security_group_ingress_separate_from_security_group_by_id_using_vpc():
|
|||
"test_stack",
|
||||
template_body=template_json,
|
||||
)
|
||||
security_group1 = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg1"})[0]
|
||||
security_group2 = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg2"})[0]
|
||||
security_group1 = vpc_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg1"})[0]
|
||||
security_group2 = vpc_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg2"})[0]
|
||||
|
||||
security_group1.rules.should.have.length_of(1)
|
||||
security_group1.rules[0].grants.should.have.length_of(1)
|
||||
security_group1.rules[0].grants[0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].grants[
|
||||
0].group_id.should.equal(security_group2.id)
|
||||
security_group1.rules[0].ip_protocol.should.equal('tcp')
|
||||
security_group1.rules[0].from_port.should.equal('80')
|
||||
security_group1.rules[0].to_port.should.equal('8080')
|
||||
|
|
@ -1663,17 +1712,20 @@ def test_security_group_with_update():
|
|||
"test_stack",
|
||||
template_body=template_json,
|
||||
)
|
||||
security_group = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg"})[0]
|
||||
security_group = vpc_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg"})[0]
|
||||
security_group.vpc_id.should.equal(vpc1.id)
|
||||
|
||||
vpc2 = vpc_conn.create_vpc("10.1.0.0/16")
|
||||
template['Resources']['test-security-group']['Properties']['VpcId'] = vpc2.id
|
||||
template['Resources'][
|
||||
'test-security-group']['Properties']['VpcId'] = vpc2.id
|
||||
template_json = json.dumps(template)
|
||||
cf_conn.update_stack(
|
||||
"test_stack",
|
||||
template_body=template_json,
|
||||
)
|
||||
security_group = vpc_conn.get_all_security_groups(filters={"tag:sg-name": "sg"})[0]
|
||||
security_group = vpc_conn.get_all_security_groups(
|
||||
filters={"tag:sg-name": "sg"})[0]
|
||||
security_group.vpc_id.should.equal(vpc2.id)
|
||||
|
||||
|
||||
|
|
@ -1779,11 +1831,14 @@ def test_datapipeline():
|
|||
data_pipelines = dp_conn.list_pipelines()
|
||||
|
||||
data_pipelines['pipelineIdList'].should.have.length_of(1)
|
||||
data_pipelines['pipelineIdList'][0]['name'].should.equal('testDataPipeline')
|
||||
data_pipelines['pipelineIdList'][0][
|
||||
'name'].should.equal('testDataPipeline')
|
||||
|
||||
stack_resources = cf_conn.list_stack_resources(stack_id)
|
||||
stack_resources.should.have.length_of(1)
|
||||
stack_resources[0].physical_resource_id.should.equal(data_pipelines['pipelineIdList'][0]['id'])
|
||||
stack_resources[0].physical_resource_id.should.equal(
|
||||
data_pipelines['pipelineIdList'][0]['id'])
|
||||
|
||||
|
||||
def _process_lamda(pfunc):
|
||||
import io
|
||||
|
|
@ -1849,33 +1904,35 @@ def test_lambda_function():
|
|||
def test_nat_gateway():
|
||||
ec2_conn = boto3.client('ec2', 'us-east-1')
|
||||
vpc_id = ec2_conn.create_vpc(CidrBlock="10.0.0.0/16")['Vpc']['VpcId']
|
||||
subnet_id = ec2_conn.create_subnet(CidrBlock='10.0.1.0/24', VpcId=vpc_id)['Subnet']['SubnetId']
|
||||
route_table_id = ec2_conn.create_route_table(VpcId=vpc_id)['RouteTable']['RouteTableId']
|
||||
subnet_id = ec2_conn.create_subnet(
|
||||
CidrBlock='10.0.1.0/24', VpcId=vpc_id)['Subnet']['SubnetId']
|
||||
route_table_id = ec2_conn.create_route_table(
|
||||
VpcId=vpc_id)['RouteTable']['RouteTableId']
|
||||
|
||||
template = {
|
||||
"AWSTemplateFormatVersion": "2010-09-09",
|
||||
"Resources": {
|
||||
"NAT" : {
|
||||
"DependsOn" : "vpcgatewayattachment",
|
||||
"Type" : "AWS::EC2::NatGateway",
|
||||
"Properties" : {
|
||||
"AllocationId" : { "Fn::GetAtt" : ["EIP", "AllocationId"]},
|
||||
"SubnetId" : subnet_id
|
||||
}
|
||||
},
|
||||
"EIP" : {
|
||||
"Type" : "AWS::EC2::EIP",
|
||||
"Properties" : {
|
||||
"Domain" : "vpc"
|
||||
"NAT": {
|
||||
"DependsOn": "vpcgatewayattachment",
|
||||
"Type": "AWS::EC2::NatGateway",
|
||||
"Properties": {
|
||||
"AllocationId": {"Fn::GetAtt": ["EIP", "AllocationId"]},
|
||||
"SubnetId": subnet_id
|
||||
}
|
||||
},
|
||||
"Route" : {
|
||||
"Type" : "AWS::EC2::Route",
|
||||
"Properties" : {
|
||||
"RouteTableId" : route_table_id,
|
||||
"DestinationCidrBlock" : "0.0.0.0/0",
|
||||
"NatGatewayId" : { "Ref" : "NAT" }
|
||||
}
|
||||
"EIP": {
|
||||
"Type": "AWS::EC2::EIP",
|
||||
"Properties": {
|
||||
"Domain": "vpc"
|
||||
}
|
||||
},
|
||||
"Route": {
|
||||
"Type": "AWS::EC2::Route",
|
||||
"Properties": {
|
||||
"RouteTableId": route_table_id,
|
||||
"DestinationCidrBlock": "0.0.0.0/0",
|
||||
"NatGatewayId": {"Ref": "NAT"}
|
||||
}
|
||||
},
|
||||
"internetgateway": {
|
||||
"Type": "AWS::EC2::InternetGateway"
|
||||
|
|
@ -1905,6 +1962,7 @@ def test_nat_gateway():
|
|||
result['NatGateways'][0]['SubnetId'].should.equal(subnet_id)
|
||||
result['NatGateways'][0]['State'].should.equal('available')
|
||||
|
||||
|
||||
@mock_cloudformation()
|
||||
@mock_kms()
|
||||
def test_stack_kms():
|
||||
|
|
@ -1944,42 +2002,43 @@ def test_stack_spot_fleet():
|
|||
conn = boto3.client('ec2', 'us-east-1')
|
||||
|
||||
vpc = conn.create_vpc(CidrBlock="10.0.0.0/8")['Vpc']
|
||||
subnet = conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet = conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet_id = subnet['SubnetId']
|
||||
|
||||
spot_fleet_template = {
|
||||
'Resources': {
|
||||
"SpotFleet": {
|
||||
"Type": "AWS::EC2::SpotFleet",
|
||||
"Properties": {
|
||||
"SpotFleetRequestConfigData": {
|
||||
"IamFleetRole": "arn:aws:iam::123456789012:role/fleet",
|
||||
"SpotPrice": "0.12",
|
||||
"TargetCapacity": 6,
|
||||
"AllocationStrategy": "diversified",
|
||||
"LaunchSpecifications": [
|
||||
{
|
||||
"EbsOptimized": "false",
|
||||
"InstanceType": 't2.small',
|
||||
"ImageId": "ami-1234",
|
||||
"SubnetId": subnet_id,
|
||||
"WeightedCapacity": "2",
|
||||
"SpotPrice": "0.13",
|
||||
},
|
||||
{
|
||||
"EbsOptimized": "true",
|
||||
"InstanceType": 't2.large',
|
||||
"ImageId": "ami-1234",
|
||||
"Monitoring": { "Enabled": "true" },
|
||||
"SecurityGroups": [{"GroupId": "sg-123"}],
|
||||
"SubnetId": subnet_id,
|
||||
"IamInstanceProfile": {"Arn": "arn:aws:iam::123456789012:role/fleet"},
|
||||
"WeightedCapacity": "4",
|
||||
"SpotPrice": "10.00",
|
||||
}
|
||||
]
|
||||
"Type": "AWS::EC2::SpotFleet",
|
||||
"Properties": {
|
||||
"SpotFleetRequestConfigData": {
|
||||
"IamFleetRole": "arn:aws:iam::123456789012:role/fleet",
|
||||
"SpotPrice": "0.12",
|
||||
"TargetCapacity": 6,
|
||||
"AllocationStrategy": "diversified",
|
||||
"LaunchSpecifications": [
|
||||
{
|
||||
"EbsOptimized": "false",
|
||||
"InstanceType": 't2.small',
|
||||
"ImageId": "ami-1234",
|
||||
"SubnetId": subnet_id,
|
||||
"WeightedCapacity": "2",
|
||||
"SpotPrice": "0.13",
|
||||
},
|
||||
{
|
||||
"EbsOptimized": "true",
|
||||
"InstanceType": 't2.large',
|
||||
"ImageId": "ami-1234",
|
||||
"Monitoring": {"Enabled": "true"},
|
||||
"SecurityGroups": [{"GroupId": "sg-123"}],
|
||||
"SubnetId": subnet_id,
|
||||
"IamInstanceProfile": {"Arn": "arn:aws:iam::123456789012:role/fleet"},
|
||||
"WeightedCapacity": "4",
|
||||
"SpotPrice": "10.00",
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1993,9 +2052,11 @@ def test_stack_spot_fleet():
|
|||
|
||||
stack_resources = cf_conn.list_stack_resources(StackName=stack_id)
|
||||
stack_resources['StackResourceSummaries'].should.have.length_of(1)
|
||||
spot_fleet_id = stack_resources['StackResourceSummaries'][0]['PhysicalResourceId']
|
||||
spot_fleet_id = stack_resources[
|
||||
'StackResourceSummaries'][0]['PhysicalResourceId']
|
||||
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(
|
||||
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
len(spot_fleet_requests).should.equal(1)
|
||||
spot_fleet_request = spot_fleet_requests[0]
|
||||
spot_fleet_request['SpotFleetRequestState'].should.equal("active")
|
||||
|
|
@ -2003,7 +2064,8 @@ def test_stack_spot_fleet():
|
|||
|
||||
spot_fleet_config['SpotPrice'].should.equal('0.12')
|
||||
spot_fleet_config['TargetCapacity'].should.equal(6)
|
||||
spot_fleet_config['IamFleetRole'].should.equal('arn:aws:iam::123456789012:role/fleet')
|
||||
spot_fleet_config['IamFleetRole'].should.equal(
|
||||
'arn:aws:iam::123456789012:role/fleet')
|
||||
spot_fleet_config['AllocationStrategy'].should.equal('diversified')
|
||||
spot_fleet_config['FulfilledCapacity'].should.equal(6.0)
|
||||
|
||||
|
|
|
|||
|
|
@ -20,11 +20,14 @@ def test_cloudformation_server_get():
|
|||
"Resources": {},
|
||||
}
|
||||
create_stack_resp = test_client.action_data("CreateStack", StackName=stack_name,
|
||||
TemplateBody=json.dumps(template_body))
|
||||
create_stack_resp.should.match(r"<CreateStackResponse>.*<CreateStackResult>.*<StackId>.*</StackId>.*</CreateStackResult>.*</CreateStackResponse>", re.DOTALL)
|
||||
stack_id_from_create_response = re.search("<StackId>(.*)</StackId>", create_stack_resp).groups()[0]
|
||||
TemplateBody=json.dumps(template_body))
|
||||
create_stack_resp.should.match(
|
||||
r"<CreateStackResponse>.*<CreateStackResult>.*<StackId>.*</StackId>.*</CreateStackResult>.*</CreateStackResponse>", re.DOTALL)
|
||||
stack_id_from_create_response = re.search(
|
||||
"<StackId>(.*)</StackId>", create_stack_resp).groups()[0]
|
||||
|
||||
list_stacks_resp = test_client.action_data("ListStacks")
|
||||
stack_id_from_list_response = re.search("<StackId>(.*)</StackId>", list_stacks_resp).groups()[0]
|
||||
stack_id_from_list_response = re.search(
|
||||
"<StackId>(.*)</StackId>", list_stacks_resp).groups()[0]
|
||||
|
||||
stack_id_from_create_response.should.equal(stack_id_from_list_response)
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ dummy_template = {
|
|||
}
|
||||
},
|
||||
"S3Bucket": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"DeletionPolicy": "Retain"
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"DeletionPolicy": "Retain"
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -71,15 +71,19 @@ get_attribute_output = {
|
|||
}
|
||||
}
|
||||
|
||||
outputs_template = dict(list(dummy_template.items()) + list(output_dict.items()))
|
||||
bad_outputs_template = dict(list(dummy_template.items()) + list(bad_output.items()))
|
||||
get_attribute_outputs_template = dict(list(dummy_template.items()) + list(get_attribute_output.items()))
|
||||
outputs_template = dict(list(dummy_template.items()) +
|
||||
list(output_dict.items()))
|
||||
bad_outputs_template = dict(
|
||||
list(dummy_template.items()) + list(bad_output.items()))
|
||||
get_attribute_outputs_template = dict(
|
||||
list(dummy_template.items()) + list(get_attribute_output.items()))
|
||||
|
||||
dummy_template_json = json.dumps(dummy_template)
|
||||
name_type_template_json = json.dumps(name_type_template)
|
||||
output_type_template_json = json.dumps(outputs_template)
|
||||
bad_output_template_json = json.dumps(bad_outputs_template)
|
||||
get_attribute_outputs_template_json = json.dumps(get_attribute_outputs_template)
|
||||
get_attribute_outputs_template_json = json.dumps(
|
||||
get_attribute_outputs_template)
|
||||
|
||||
|
||||
def test_parse_stack_resources():
|
||||
|
|
@ -104,7 +108,8 @@ def test_parse_stack_resources():
|
|||
@patch("moto.cloudformation.parsing.logger")
|
||||
def test_missing_resource_logs(logger):
|
||||
resource_class_from_type("foobar")
|
||||
logger.warning.assert_called_with('No Moto CloudFormation support for %s', 'foobar')
|
||||
logger.warning.assert_called_with(
|
||||
'No Moto CloudFormation support for %s', 'foobar')
|
||||
|
||||
|
||||
def test_parse_stack_with_name_type_resource():
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import sure # noqa
|
|||
|
||||
from moto import mock_cloudwatch_deprecated
|
||||
|
||||
|
||||
def alarm_fixture(name="tester", action=None):
|
||||
action = action or ['arn:alarm']
|
||||
return MetricAlarm(
|
||||
|
|
@ -23,6 +24,7 @@ def alarm_fixture(name="tester", action=None):
|
|||
unit='Seconds',
|
||||
)
|
||||
|
||||
|
||||
@mock_cloudwatch_deprecated
|
||||
def test_create_alarm():
|
||||
conn = boto.connect_cloudwatch()
|
||||
|
|
@ -42,7 +44,8 @@ def test_create_alarm():
|
|||
alarm.evaluation_periods.should.equal(5)
|
||||
alarm.statistic.should.equal('Average')
|
||||
alarm.description.should.equal('A test')
|
||||
dict(alarm.dimensions).should.equal({'InstanceId': ['i-0123456,i-0123457']})
|
||||
dict(alarm.dimensions).should.equal(
|
||||
{'InstanceId': ['i-0123456,i-0123457']})
|
||||
list(alarm.alarm_actions).should.equal(['arn:alarm'])
|
||||
list(alarm.ok_actions).should.equal(['arn:ok'])
|
||||
list(alarm.insufficient_data_actions).should.equal(['arn:insufficient'])
|
||||
|
|
@ -84,7 +87,8 @@ def test_put_metric_data():
|
|||
metric = metrics[0]
|
||||
metric.namespace.should.equal('tester')
|
||||
metric.name.should.equal('metric')
|
||||
dict(metric.dimensions).should.equal({'InstanceId': ['i-0123456,i-0123457']})
|
||||
dict(metric.dimensions).should.equal(
|
||||
{'InstanceId': ['i-0123456,i-0123457']})
|
||||
|
||||
|
||||
@mock_cloudwatch_deprecated
|
||||
|
|
@ -103,7 +107,8 @@ def test_describe_alarms():
|
|||
alarms.should.have.length_of(4)
|
||||
alarms = conn.describe_alarms(alarm_name_prefix="nfoo")
|
||||
alarms.should.have.length_of(2)
|
||||
alarms = conn.describe_alarms(alarm_names=["nfoobar", "nbarfoo", "nbazfoo"])
|
||||
alarms = conn.describe_alarms(
|
||||
alarm_names=["nfoobar", "nbarfoo", "nbazfoo"])
|
||||
alarms.should.have.length_of(3)
|
||||
alarms = conn.describe_alarms(action_prefix="afoo")
|
||||
alarms.should.have.length_of(2)
|
||||
|
|
@ -114,10 +119,11 @@ def test_describe_alarms():
|
|||
alarms = conn.describe_alarms()
|
||||
alarms.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_cloudwatch_deprecated
|
||||
def test_describe_state_value_unimplemented():
|
||||
conn = boto.connect_cloudwatch()
|
||||
|
||||
conn.describe_alarms()
|
||||
conn.describe_alarms.when.called_with(state_value="foo").should.throw(NotImplementedError)
|
||||
|
||||
conn.describe_alarms.when.called_with(
|
||||
state_value="foo").should.throw(NotImplementedError)
|
||||
|
|
|
|||
|
|
@ -59,11 +59,13 @@ def test_decorater_wrapped_gets_set():
|
|||
"""
|
||||
Moto decorator's __wrapped__ should get set to the tests function
|
||||
"""
|
||||
test_decorater_wrapped_gets_set.__wrapped__.__name__.should.equal('test_decorater_wrapped_gets_set')
|
||||
test_decorater_wrapped_gets_set.__wrapped__.__name__.should.equal(
|
||||
'test_decorater_wrapped_gets_set')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
class Tester(object):
|
||||
|
||||
def test_the_class(self):
|
||||
conn = boto.connect_ec2()
|
||||
list(conn.get_all_instances()).should.have.length_of(0)
|
||||
|
|
@ -75,6 +77,7 @@ class Tester(object):
|
|||
|
||||
@mock_s3_deprecated
|
||||
class TesterWithSetup(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.conn = boto.connect_s3()
|
||||
self.conn.create_bucket('mybucket')
|
||||
|
|
|
|||
|
|
@ -30,13 +30,15 @@ def test_meta_data_iam():
|
|||
|
||||
@mock_ec2
|
||||
def test_meta_data_security_credentials():
|
||||
res = requests.get("{0}/latest/meta-data/iam/security-credentials/".format(BASE_URL))
|
||||
res = requests.get(
|
||||
"{0}/latest/meta-data/iam/security-credentials/".format(BASE_URL))
|
||||
res.content.should.equal(b"default-role")
|
||||
|
||||
|
||||
@mock_ec2
|
||||
def test_meta_data_default_role():
|
||||
res = requests.get("{0}/latest/meta-data/iam/security-credentials/default-role".format(BASE_URL))
|
||||
res = requests.get(
|
||||
"{0}/latest/meta-data/iam/security-credentials/default-role".format(BASE_URL))
|
||||
json_response = res.json()
|
||||
json_response.should.contain('AccessKeyId')
|
||||
json_response.should.contain('SecretAccessKey')
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@ from moto.core.responses import flatten_json_request_body
|
|||
|
||||
|
||||
def test_flatten_json_request_body():
|
||||
spec = AWSServiceSpec('data/emr/2009-03-31/service-2.json').input_spec('RunJobFlow')
|
||||
spec = AWSServiceSpec(
|
||||
'data/emr/2009-03-31/service-2.json').input_spec('RunJobFlow')
|
||||
|
||||
body = {
|
||||
'Name': 'cluster',
|
||||
|
|
@ -42,25 +43,32 @@ def test_flatten_json_request_body():
|
|||
flat['Name'].should.equal(body['Name'])
|
||||
flat['Instances.Ec2KeyName'].should.equal(body['Instances']['Ec2KeyName'])
|
||||
for idx in range(2):
|
||||
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceRole'].should.equal(body['Instances']['InstanceGroups'][idx]['InstanceRole'])
|
||||
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceType'].should.equal(body['Instances']['InstanceGroups'][idx]['InstanceType'])
|
||||
flat['Instances.Placement.AvailabilityZone'].should.equal(body['Instances']['Placement']['AvailabilityZone'])
|
||||
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceRole'].should.equal(
|
||||
body['Instances']['InstanceGroups'][idx]['InstanceRole'])
|
||||
flat['Instances.InstanceGroups.member.' + str(idx + 1) + '.InstanceType'].should.equal(
|
||||
body['Instances']['InstanceGroups'][idx]['InstanceType'])
|
||||
flat['Instances.Placement.AvailabilityZone'].should.equal(
|
||||
body['Instances']['Placement']['AvailabilityZone'])
|
||||
|
||||
for idx in range(1):
|
||||
prefix = 'Steps.member.' + str(idx + 1) + '.HadoopJarStep'
|
||||
step = body['Steps'][idx]['HadoopJarStep']
|
||||
i = 0
|
||||
while prefix + '.Properties.member.' + str(i + 1) + '.Key' in flat:
|
||||
flat[prefix + '.Properties.member.' + str(i + 1) + '.Key'].should.equal(step['Properties'][i]['Key'])
|
||||
flat[prefix + '.Properties.member.' + str(i + 1) + '.Value'].should.equal(step['Properties'][i]['Value'])
|
||||
flat[prefix + '.Properties.member.' +
|
||||
str(i + 1) + '.Key'].should.equal(step['Properties'][i]['Key'])
|
||||
flat[prefix + '.Properties.member.' +
|
||||
str(i + 1) + '.Value'].should.equal(step['Properties'][i]['Value'])
|
||||
i += 1
|
||||
i = 0
|
||||
while prefix + '.Args.member.' + str(i + 1) in flat:
|
||||
flat[prefix + '.Args.member.' + str(i + 1)].should.equal(step['Args'][i])
|
||||
flat[prefix + '.Args.member.' +
|
||||
str(i + 1)].should.equal(step['Args'][i])
|
||||
i += 1
|
||||
|
||||
for idx in range(2):
|
||||
flat['Configurations.member.' + str(idx + 1) + '.Classification'].should.equal(body['Configurations'][idx]['Classification'])
|
||||
flat['Configurations.member.' + str(idx + 1) + '.Classification'].should.equal(
|
||||
body['Configurations'][idx]['Classification'])
|
||||
|
||||
props = {}
|
||||
i = 1
|
||||
|
|
|
|||
|
|
@ -32,19 +32,22 @@ def test_port_argument(run_simple):
|
|||
|
||||
def test_domain_dispatched():
|
||||
dispatcher = DomainDispatcherApplication(create_backend_app)
|
||||
backend_app = dispatcher.get_application({"HTTP_HOST": "email.us-east1.amazonaws.com"})
|
||||
backend_app = dispatcher.get_application(
|
||||
{"HTTP_HOST": "email.us-east1.amazonaws.com"})
|
||||
keys = list(backend_app.view_functions.keys())
|
||||
keys[0].should.equal('EmailResponse.dispatch')
|
||||
|
||||
|
||||
def test_domain_without_matches():
|
||||
dispatcher = DomainDispatcherApplication(create_backend_app)
|
||||
dispatcher.get_application.when.called_with({"HTTP_HOST": "not-matching-anything.com"}).should.throw(RuntimeError)
|
||||
dispatcher.get_application.when.called_with(
|
||||
{"HTTP_HOST": "not-matching-anything.com"}).should.throw(RuntimeError)
|
||||
|
||||
|
||||
def test_domain_dispatched_with_service():
|
||||
# If we pass a particular service, always return that.
|
||||
dispatcher = DomainDispatcherApplication(create_backend_app, service="s3")
|
||||
backend_app = dispatcher.get_application({"HTTP_HOST": "s3.us-east1.amazonaws.com"})
|
||||
backend_app = dispatcher.get_application(
|
||||
{"HTTP_HOST": "s3.us-east1.amazonaws.com"})
|
||||
keys = set(backend_app.view_functions.keys())
|
||||
keys.should.contain('ResponseObject.key_response')
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ def test_flask_path_converting_simple():
|
|||
|
||||
|
||||
def test_flask_path_converting_regex():
|
||||
convert_regex_to_flask_path("/(?P<key_name>[a-zA-Z0-9\-_]+)").should.equal('/<regex("[a-zA-Z0-9\-_]+"):key_name>')
|
||||
convert_regex_to_flask_path(
|
||||
"/(?P<key_name>[a-zA-Z0-9\-_]+)").should.equal('/<regex("[a-zA-Z0-9\-_]+"):key_name>')
|
||||
|
||||
convert_regex_to_flask_path("(?P<account_id>\d+)/(?P<queue_name>.*)$").should.equal(
|
||||
'<regex("\d+"):account_id>/<regex(".*"):queue_name>'
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ def test_create_pipeline():
|
|||
res = conn.create_pipeline("mypipeline", "some-unique-id")
|
||||
|
||||
pipeline_id = res["pipelineId"]
|
||||
pipeline_descriptions = conn.describe_pipelines([pipeline_id])["pipelineDescriptionList"]
|
||||
pipeline_descriptions = conn.describe_pipelines(
|
||||
[pipeline_id])["pipelineDescriptionList"]
|
||||
pipeline_descriptions.should.have.length_of(1)
|
||||
|
||||
pipeline_description = pipeline_descriptions[0]
|
||||
|
|
@ -105,7 +106,8 @@ def test_describing_pipeline_objects():
|
|||
|
||||
conn.put_pipeline_definition(PIPELINE_OBJECTS, pipeline_id)
|
||||
|
||||
objects = conn.describe_objects(["Schedule", "Default"], pipeline_id)['pipelineObjects']
|
||||
objects = conn.describe_objects(["Schedule", "Default"], pipeline_id)[
|
||||
'pipelineObjects']
|
||||
|
||||
objects.should.have.length_of(2)
|
||||
default_object = [x for x in objects if x['id'] == 'Default'][0]
|
||||
|
|
@ -125,7 +127,8 @@ def test_activate_pipeline():
|
|||
pipeline_id = res["pipelineId"]
|
||||
conn.activate_pipeline(pipeline_id)
|
||||
|
||||
pipeline_descriptions = conn.describe_pipelines([pipeline_id])["pipelineDescriptionList"]
|
||||
pipeline_descriptions = conn.describe_pipelines(
|
||||
[pipeline_id])["pipelineDescriptionList"]
|
||||
pipeline_descriptions.should.have.length_of(1)
|
||||
pipeline_description = pipeline_descriptions[0]
|
||||
fields = pipeline_description['fields']
|
||||
|
|
|
|||
|
|
@ -17,9 +17,10 @@ def test_list_streams():
|
|||
test_client = backend.test_client()
|
||||
|
||||
res = test_client.post('/',
|
||||
data={"pipelineIds": ["ASdf"]},
|
||||
headers={"X-Amz-Target": "DataPipeline.DescribePipelines"},
|
||||
)
|
||||
data={"pipelineIds": ["ASdf"]},
|
||||
headers={
|
||||
"X-Amz-Target": "DataPipeline.DescribePipelines"},
|
||||
)
|
||||
|
||||
json_data = json.loads(res.data.decode("utf-8"))
|
||||
json_data.should.equal({
|
||||
|
|
|
|||
|
|
@ -16,15 +16,18 @@ from boto.exception import DynamoDBResponseError
|
|||
@mock_dynamodb_deprecated
|
||||
def test_list_tables():
|
||||
name = 'TestTable'
|
||||
dynamodb_backend.create_table(name, hash_key_attr="name", hash_key_type="S")
|
||||
dynamodb_backend.create_table(
|
||||
name, hash_key_attr="name", hash_key_type="S")
|
||||
conn = boto.connect_dynamodb('the_key', 'the_secret')
|
||||
assert conn.list_tables() == ['TestTable']
|
||||
|
||||
|
||||
@mock_dynamodb_deprecated
|
||||
def test_list_tables_layer_1():
|
||||
dynamodb_backend.create_table("test_1", hash_key_attr="name", hash_key_type="S")
|
||||
dynamodb_backend.create_table("test_2", hash_key_attr="name", hash_key_type="S")
|
||||
dynamodb_backend.create_table(
|
||||
"test_1", hash_key_attr="name", hash_key_type="S")
|
||||
dynamodb_backend.create_table(
|
||||
"test_2", hash_key_attr="name", hash_key_type="S")
|
||||
conn = boto.connect_dynamodb('the_key', 'the_secret')
|
||||
res = conn.layer1.list_tables(limit=1)
|
||||
expected = {"TableNames": ["test_1"], "LastEvaluatedTableName": "test_1"}
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@ def test_delete_table():
|
|||
conn.layer1.delete_table('messages')
|
||||
conn.list_tables().should.have.length_of(0)
|
||||
|
||||
conn.layer1.delete_table.when.called_with('messages').should.throw(DynamoDBResponseError)
|
||||
conn.layer1.delete_table.when.called_with(
|
||||
'messages').should.throw(DynamoDBResponseError)
|
||||
|
||||
|
||||
@mock_dynamodb_deprecated
|
||||
|
|
@ -192,7 +193,8 @@ def test_get_item_without_range_key():
|
|||
new_item = table.new_item(hash_key=hash_key, range_key=range_key)
|
||||
new_item.put()
|
||||
|
||||
table.get_item.when.called_with(hash_key=hash_key).should.throw(DynamoDBValidationError)
|
||||
table.get_item.when.called_with(
|
||||
hash_key=hash_key).should.throw(DynamoDBValidationError)
|
||||
|
||||
|
||||
@mock_dynamodb_deprecated
|
||||
|
|
@ -304,22 +306,28 @@ def test_query():
|
|||
)
|
||||
item.put()
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.GT('1'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.GT('1'))
|
||||
results.response['Items'].should.have.length_of(3)
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.GT('234'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.GT('234'))
|
||||
results.response['Items'].should.have.length_of(2)
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.GT('9999'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.GT('9999'))
|
||||
results.response['Items'].should.have.length_of(0)
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.CONTAINS('12'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.CONTAINS('12'))
|
||||
results.response['Items'].should.have.length_of(1)
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.BEGINS_WITH('7'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.BEGINS_WITH('7'))
|
||||
results.response['Items'].should.have.length_of(1)
|
||||
|
||||
results = table.query(hash_key='the-key', range_key_condition=condition.BETWEEN('567', '890'))
|
||||
results = table.query(hash_key='the-key',
|
||||
range_key_condition=condition.BETWEEN('567', '890'))
|
||||
results.response['Items'].should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -63,7 +63,8 @@ def test_delete_table():
|
|||
conn.layer1.delete_table('messages')
|
||||
conn.list_tables().should.have.length_of(0)
|
||||
|
||||
conn.layer1.delete_table.when.called_with('messages').should.throw(DynamoDBResponseError)
|
||||
conn.layer1.delete_table.when.called_with(
|
||||
'messages').should.throw(DynamoDBResponseError)
|
||||
|
||||
|
||||
@mock_dynamodb_deprecated
|
||||
|
|
|
|||
|
|
@ -15,17 +15,18 @@ try:
|
|||
except ImportError:
|
||||
print("This boto version is not supported")
|
||||
|
||||
|
||||
@requires_boto_gte("2.9")
|
||||
@mock_dynamodb2_deprecated
|
||||
def test_list_tables():
|
||||
name = 'TestTable'
|
||||
#{'schema': }
|
||||
dynamodb_backend2.create_table(name,schema=[
|
||||
dynamodb_backend2.create_table(name, schema=[
|
||||
{u'KeyType': u'HASH', u'AttributeName': u'forum_name'},
|
||||
{u'KeyType': u'RANGE', u'AttributeName': u'subject'}
|
||||
])
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
'us-west-2',
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
'us-west-2',
|
||||
aws_access_key_id="ak",
|
||||
aws_secret_access_key="sk")
|
||||
assert conn.list_tables()["TableNames"] == [name]
|
||||
|
|
@ -34,13 +35,13 @@ def test_list_tables():
|
|||
@requires_boto_gte("2.9")
|
||||
@mock_dynamodb2_deprecated
|
||||
def test_list_tables_layer_1():
|
||||
dynamodb_backend2.create_table("test_1",schema=[
|
||||
dynamodb_backend2.create_table("test_1", schema=[
|
||||
{u'KeyType': u'HASH', u'AttributeName': u'name'}
|
||||
])
|
||||
dynamodb_backend2.create_table("test_2",schema=[
|
||||
dynamodb_backend2.create_table("test_2", schema=[
|
||||
{u'KeyType': u'HASH', u'AttributeName': u'name'}
|
||||
])
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
'us-west-2',
|
||||
aws_access_key_id="ak",
|
||||
aws_secret_access_key="sk")
|
||||
|
|
@ -57,7 +58,7 @@ def test_list_tables_layer_1():
|
|||
@requires_boto_gte("2.9")
|
||||
@mock_dynamodb2_deprecated
|
||||
def test_describe_missing_table():
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
conn = boto.dynamodb2.connect_to_region(
|
||||
'us-west-2',
|
||||
aws_access_key_id="ak",
|
||||
aws_secret_access_key="sk")
|
||||
|
|
|
|||
|
|
@ -140,7 +140,8 @@ def test_delete_table():
|
|||
|
||||
table.delete()
|
||||
conn.list_tables()["TableNames"].should.have.length_of(0)
|
||||
conn.delete_table.when.called_with('messages').should.throw(JSONResponseError)
|
||||
conn.delete_table.when.called_with(
|
||||
'messages').should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@requires_boto_gte("2.9")
|
||||
|
|
@ -181,7 +182,8 @@ def test_item_add_and_describe_and_update():
|
|||
})
|
||||
ok.should.equal(True)
|
||||
|
||||
table.get_item(forum_name="LOLCat Forum", subject='Check this out!').should_not.be.none
|
||||
table.get_item(forum_name="LOLCat Forum",
|
||||
subject='Check this out!').should_not.be.none
|
||||
|
||||
returned_item = table.get_item(
|
||||
forum_name='LOLCat Forum',
|
||||
|
|
@ -224,7 +226,8 @@ def test_item_partial_save():
|
|||
}
|
||||
|
||||
table.put_item(data=data)
|
||||
returned_item = table.get_item(forum_name="LOLCat Forum", subject='The LOLz')
|
||||
returned_item = table.get_item(
|
||||
forum_name="LOLCat Forum", subject='The LOLz')
|
||||
|
||||
returned_item['SentBy'] = 'User B'
|
||||
returned_item.partial_save()
|
||||
|
|
@ -270,7 +273,8 @@ def test_get_missing_item():
|
|||
@mock_dynamodb2_deprecated
|
||||
def test_get_item_with_undeclared_table():
|
||||
table = Table('undeclared-table')
|
||||
table.get_item.when.called_with(test_hash=3241526475).should.throw(JSONResponseError)
|
||||
table.get_item.when.called_with(
|
||||
test_hash=3241526475).should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@requires_boto_gte("2.9")
|
||||
|
|
@ -287,7 +291,8 @@ def test_get_item_without_range_key():
|
|||
hash_key = 3241526475
|
||||
range_key = 1234567890987
|
||||
table.put_item(data={'test_hash': hash_key, 'test_range': range_key})
|
||||
table.get_item.when.called_with(test_hash=hash_key).should.throw(ValidationException)
|
||||
table.get_item.when.called_with(
|
||||
test_hash=hash_key).should.throw(ValidationException)
|
||||
|
||||
|
||||
@requires_boto_gte("2.30.0")
|
||||
|
|
@ -355,19 +360,23 @@ def test_query():
|
|||
|
||||
table.count().should.equal(4)
|
||||
|
||||
results = table.query_2(forum_name__eq='the-key', subject__gt='1', consistent=True)
|
||||
results = table.query_2(forum_name__eq='the-key',
|
||||
subject__gt='1', consistent=True)
|
||||
expected = ["123", "456", "789"]
|
||||
for index, item in enumerate(results):
|
||||
item["subject"].should.equal(expected[index])
|
||||
|
||||
results = table.query_2(forum_name__eq="the-key", subject__gt='1', reverse=True)
|
||||
results = table.query_2(forum_name__eq="the-key",
|
||||
subject__gt='1', reverse=True)
|
||||
for index, item in enumerate(results):
|
||||
item["subject"].should.equal(expected[len(expected) - 1 - index])
|
||||
|
||||
results = table.query_2(forum_name__eq='the-key', subject__gt='1', consistent=True)
|
||||
results = table.query_2(forum_name__eq='the-key',
|
||||
subject__gt='1', consistent=True)
|
||||
sum(1 for _ in results).should.equal(3)
|
||||
|
||||
results = table.query_2(forum_name__eq='the-key', subject__gt='234', consistent=True)
|
||||
results = table.query_2(forum_name__eq='the-key',
|
||||
subject__gt='234', consistent=True)
|
||||
sum(1 for _ in results).should.equal(2)
|
||||
|
||||
results = table.query_2(forum_name__eq='the-key', subject__gt='9999')
|
||||
|
|
@ -379,7 +388,8 @@ def test_query():
|
|||
results = table.query_2(forum_name__eq='the-key', subject__beginswith='7')
|
||||
sum(1 for _ in results).should.equal(1)
|
||||
|
||||
results = table.query_2(forum_name__eq='the-key', subject__between=['567', '890'])
|
||||
results = table.query_2(forum_name__eq='the-key',
|
||||
subject__between=['567', '890'])
|
||||
sum(1 for _ in results).should.equal(1)
|
||||
|
||||
|
||||
|
|
@ -558,15 +568,15 @@ def test_create_with_global_indexes():
|
|||
RangeKey('version'),
|
||||
], global_indexes=[
|
||||
GlobalAllIndex('topic-created_at-index',
|
||||
parts=[
|
||||
HashKey('topic'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 6,
|
||||
'write': 1
|
||||
}
|
||||
),
|
||||
parts=[
|
||||
HashKey('topic'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 6,
|
||||
'write': 1
|
||||
}
|
||||
),
|
||||
])
|
||||
|
||||
table_description = conn.describe_table("messages")
|
||||
|
|
@ -601,25 +611,25 @@ def test_query_with_global_indexes():
|
|||
RangeKey('version'),
|
||||
], global_indexes=[
|
||||
GlobalAllIndex('topic-created_at-index',
|
||||
parts=[
|
||||
HashKey('topic'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 6,
|
||||
'write': 1
|
||||
}
|
||||
),
|
||||
parts=[
|
||||
HashKey('topic'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 6,
|
||||
'write': 1
|
||||
}
|
||||
),
|
||||
GlobalAllIndex('status-created_at-index',
|
||||
parts=[
|
||||
HashKey('status'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 2,
|
||||
'write': 1
|
||||
}
|
||||
)
|
||||
parts=[
|
||||
HashKey('status'),
|
||||
RangeKey('created_at', data_type='N')
|
||||
],
|
||||
throughput={
|
||||
'read': 2,
|
||||
'write': 1
|
||||
}
|
||||
)
|
||||
])
|
||||
|
||||
item_data = {
|
||||
|
|
@ -653,7 +663,8 @@ def test_query_with_local_indexes():
|
|||
|
||||
item['version'] = '2'
|
||||
item.save(overwrite=True)
|
||||
results = table.query(forum_name__eq='Cool Forum', index='threads_index', threads__eq=1)
|
||||
results = table.query(forum_name__eq='Cool Forum',
|
||||
index='threads_index', threads__eq=1)
|
||||
list(results).should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
@ -888,7 +899,8 @@ def test_failed_overwrite():
|
|||
table.put_item(data=data2, overwrite=True)
|
||||
|
||||
data3 = {'id': '123', 'range': 'abc', 'data': '812'}
|
||||
table.put_item.when.called_with(data=data3).should.throw(ConditionalCheckFailedException)
|
||||
table.put_item.when.called_with(data=data3).should.throw(
|
||||
ConditionalCheckFailedException)
|
||||
|
||||
returned_item = table.lookup('123', 'abc')
|
||||
dict(returned_item).should.equal(data2)
|
||||
|
|
@ -972,7 +984,8 @@ def test_boto3_conditions():
|
|||
|
||||
# Test a query returning all items
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").gt('1'),
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").gt('1'),
|
||||
ScanIndexForward=True,
|
||||
)
|
||||
expected = ["123", "456", "789"]
|
||||
|
|
@ -981,7 +994,8 @@ def test_boto3_conditions():
|
|||
|
||||
# Return all items again, but in reverse
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").gt('1'),
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").gt('1'),
|
||||
ScanIndexForward=False,
|
||||
)
|
||||
for index, item in enumerate(reversed(results['Items'])):
|
||||
|
|
@ -989,29 +1003,34 @@ def test_boto3_conditions():
|
|||
|
||||
# Filter the subjects to only return some of the results
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").gt('234'),
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").gt('234'),
|
||||
ConsistentRead=True,
|
||||
)
|
||||
results['Count'].should.equal(2)
|
||||
|
||||
# Filter to return no results
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").gt('9999')
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").gt('9999')
|
||||
)
|
||||
results['Count'].should.equal(0)
|
||||
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").begins_with('12')
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").begins_with('12')
|
||||
)
|
||||
results['Count'].should.equal(1)
|
||||
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key("subject").begins_with('7') & Key('forum_name').eq('the-key')
|
||||
KeyConditionExpression=Key("subject").begins_with(
|
||||
'7') & Key('forum_name').eq('the-key')
|
||||
)
|
||||
results['Count'].should.equal(1)
|
||||
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('forum_name').eq('the-key') & Key("subject").between('567', '890')
|
||||
KeyConditionExpression=Key('forum_name').eq(
|
||||
'the-key') & Key("subject").between('567', '890')
|
||||
)
|
||||
results['Count'].should.equal(1)
|
||||
|
||||
|
|
@ -1337,7 +1356,8 @@ def test_boto3_query_gsi_range_comparison():
|
|||
|
||||
# Test a query returning all johndoe items
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('username').eq('johndoe') & Key("created").gt(0),
|
||||
KeyConditionExpression=Key('username').eq(
|
||||
'johndoe') & Key("created").gt(0),
|
||||
ScanIndexForward=True,
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
|
|
@ -1347,7 +1367,8 @@ def test_boto3_query_gsi_range_comparison():
|
|||
|
||||
# Return all johndoe items again, but in reverse
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('username').eq('johndoe') & Key("created").gt(0),
|
||||
KeyConditionExpression=Key('username').eq(
|
||||
'johndoe') & Key("created").gt(0),
|
||||
ScanIndexForward=False,
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
|
|
@ -1357,7 +1378,8 @@ def test_boto3_query_gsi_range_comparison():
|
|||
# Filter the creation to only return some of the results
|
||||
# And reverse order of hash + range key
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key("created").gt(1) & Key('username').eq('johndoe'),
|
||||
KeyConditionExpression=Key("created").gt(
|
||||
1) & Key('username').eq('johndoe'),
|
||||
ConsistentRead=True,
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
|
|
@ -1365,20 +1387,23 @@ def test_boto3_query_gsi_range_comparison():
|
|||
|
||||
# Filter to return no results
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('username').eq('janedoe') & Key("created").gt(9),
|
||||
KeyConditionExpression=Key('username').eq(
|
||||
'janedoe') & Key("created").gt(9),
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
results['Count'].should.equal(0)
|
||||
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('username').eq('janedoe') & Key("created").eq(5),
|
||||
KeyConditionExpression=Key('username').eq(
|
||||
'janedoe') & Key("created").eq(5),
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
results['Count'].should.equal(1)
|
||||
|
||||
# Test range key sorting
|
||||
results = table.query(
|
||||
KeyConditionExpression=Key('username').eq('johndoe') & Key("created").gt(0),
|
||||
KeyConditionExpression=Key('username').eq(
|
||||
'johndoe') & Key("created").gt(0),
|
||||
IndexName='TestGSI',
|
||||
)
|
||||
expected = [Decimal('1'), Decimal('2'), Decimal('3')]
|
||||
|
|
@ -1516,7 +1541,6 @@ def test_boto3_update_table_gsi_throughput():
|
|||
gsi_throughput['WriteCapacityUnits'].should.equal(11)
|
||||
|
||||
|
||||
|
||||
@mock_dynamodb2
|
||||
def test_update_table_gsi_create():
|
||||
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
|
||||
|
|
|
|||
|
|
@ -71,7 +71,8 @@ def test_delete_table():
|
|||
conn.delete_table('messages')
|
||||
conn.list_tables()["TableNames"].should.have.length_of(0)
|
||||
|
||||
conn.delete_table.when.called_with('messages').should.throw(JSONResponseError)
|
||||
conn.delete_table.when.called_with(
|
||||
'messages').should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@requires_boto_gte("2.9")
|
||||
|
|
@ -239,7 +240,8 @@ def test_query_with_undeclared_table():
|
|||
|
||||
conn.query.when.called_with(
|
||||
table_name='undeclared-table',
|
||||
key_conditions={"forum_name": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "the-key"}]}}
|
||||
key_conditions={"forum_name": {
|
||||
"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "the-key"}]}}
|
||||
).should.throw(JSONResponseError)
|
||||
|
||||
|
||||
|
|
@ -396,7 +398,8 @@ def test_get_key_fields():
|
|||
@mock_dynamodb2_deprecated
|
||||
def test_get_missing_item():
|
||||
table = create_table()
|
||||
table.get_item.when.called_with(forum_name='missing').should.throw(ItemNotFound)
|
||||
table.get_item.when.called_with(
|
||||
forum_name='missing').should.throw(ItemNotFound)
|
||||
|
||||
|
||||
@requires_boto_gte("2.9")
|
||||
|
|
@ -436,7 +439,8 @@ def test_update_item_remove():
|
|||
}
|
||||
|
||||
# Then remove the SentBy field
|
||||
conn.update_item("messages", key_map, update_expression="REMOVE SentBy, SentTo")
|
||||
conn.update_item("messages", key_map,
|
||||
update_expression="REMOVE SentBy, SentTo")
|
||||
|
||||
returned_item = table.get_item(username="steve")
|
||||
dict(returned_item).should.equal({
|
||||
|
|
@ -460,7 +464,8 @@ def test_update_item_set():
|
|||
'username': {"S": "steve"}
|
||||
}
|
||||
|
||||
conn.update_item("messages", key_map, update_expression="SET foo=bar, blah=baz REMOVE SentBy")
|
||||
conn.update_item("messages", key_map,
|
||||
update_expression="SET foo=bar, blah=baz REMOVE SentBy")
|
||||
|
||||
returned_item = table.get_item(username="steve")
|
||||
dict(returned_item).should.equal({
|
||||
|
|
@ -470,7 +475,6 @@ def test_update_item_set():
|
|||
})
|
||||
|
||||
|
||||
|
||||
@mock_dynamodb2_deprecated
|
||||
def test_failed_overwrite():
|
||||
table = Table.create('messages', schema=[
|
||||
|
|
@ -487,7 +491,8 @@ def test_failed_overwrite():
|
|||
table.put_item(data=data2, overwrite=True)
|
||||
|
||||
data3 = {'id': '123', 'data': '812'}
|
||||
table.put_item.when.called_with(data=data3).should.throw(ConditionalCheckFailedException)
|
||||
table.put_item.when.called_with(data=data3).should.throw(
|
||||
ConditionalCheckFailedException)
|
||||
|
||||
returned_item = table.lookup('123')
|
||||
dict(returned_item).should.equal(data2)
|
||||
|
|
@ -521,6 +526,7 @@ def test_conflicting_writes():
|
|||
boto3
|
||||
"""
|
||||
|
||||
|
||||
@mock_dynamodb2
|
||||
def test_boto3_create_table():
|
||||
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
|
||||
|
|
@ -617,7 +623,6 @@ def test_boto3_put_item_conditions_pass():
|
|||
assert dict(returned_item)['Item']['foo'].should.equal("baz")
|
||||
|
||||
|
||||
|
||||
@mock_dynamodb2
|
||||
def test_scan_pagination():
|
||||
table = _create_user_table()
|
||||
|
|
|
|||
|
|
@ -20,10 +20,12 @@ def test_ami_create_and_delete():
|
|||
instance = reservation.instances[0]
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami", dry_run=True)
|
||||
image_id = conn.create_image(
|
||||
instance.id, "test-ami", "this is a test ami", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
|
||||
|
||||
|
|
@ -47,8 +49,10 @@ def test_ami_create_and_delete():
|
|||
snapshots.should.have.length_of(1)
|
||||
snapshot = snapshots[0]
|
||||
|
||||
image.block_device_mapping.current_value.snapshot_id.should.equal(snapshot.id)
|
||||
snapshot.description.should.equal("Auto-created snapshot for AMI {0}".format(image.id))
|
||||
image.block_device_mapping.current_value.snapshot_id.should.equal(
|
||||
snapshot.id)
|
||||
snapshot.description.should.equal(
|
||||
"Auto-created snapshot for AMI {0}".format(image.id))
|
||||
snapshot.volume_id.should.equal(volume.id)
|
||||
|
||||
# Deregister
|
||||
|
|
@ -56,7 +60,8 @@ def test_ami_create_and_delete():
|
|||
success = conn.deregister_image(image_id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeregisterImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeregisterImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
success = conn.deregister_image(image_id)
|
||||
success.should.be.true
|
||||
|
|
@ -75,23 +80,29 @@ def test_ami_copy():
|
|||
reservation = conn.run_instances('ami-1234abcd')
|
||||
instance = reservation.instances[0]
|
||||
|
||||
source_image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
|
||||
source_image_id = conn.create_image(
|
||||
instance.id, "test-ami", "this is a test ami")
|
||||
instance.terminate()
|
||||
source_image = conn.get_all_images(image_ids=[source_image_id])[0]
|
||||
|
||||
# Boto returns a 'CopyImage' object with an image_id attribute here. Use the image_id to fetch the full info.
|
||||
# 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:
|
||||
copy_image_ref = conn.copy_image(source_image.region.name, source_image.id, "test-copy-ami", "this is a test copy ami", dry_run=True)
|
||||
copy_image_ref = conn.copy_image(
|
||||
source_image.region.name, source_image.id, "test-copy-ami", "this is a test copy ami", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CopyImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CopyImage operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
copy_image_ref = conn.copy_image(source_image.region.name, source_image.id, "test-copy-ami", "this is a test copy ami")
|
||||
copy_image_ref = conn.copy_image(
|
||||
source_image.region.name, source_image.id, "test-copy-ami", "this is a test copy ami")
|
||||
copy_image_id = copy_image_ref.image_id
|
||||
copy_image = conn.get_all_images(image_ids=[copy_image_id])[0]
|
||||
|
||||
copy_image.id.should.equal(copy_image_id)
|
||||
copy_image.virtualization_type.should.equal(source_image.virtualization_type)
|
||||
copy_image.virtualization_type.should.equal(
|
||||
source_image.virtualization_type)
|
||||
copy_image.architecture.should.equal(source_image.architecture)
|
||||
copy_image.kernel_id.should.equal(source_image.kernel_id)
|
||||
copy_image.platform.should.equal(source_image.platform)
|
||||
|
|
@ -105,15 +116,18 @@ def test_ami_copy():
|
|||
|
||||
# Copy from non-existent source ID.
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.copy_image(source_image.region.name, 'ami-abcd1234', "test-copy-ami", "this is a test copy ami")
|
||||
conn.copy_image(source_image.region.name, 'ami-abcd1234',
|
||||
"test-copy-ami", "this is a test copy ami")
|
||||
cm.exception.code.should.equal('InvalidAMIID.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
# Copy from non-existent source region.
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
invalid_region = 'us-east-1' if (source_image.region.name != 'us-east-1') else 'us-west-1'
|
||||
conn.copy_image(invalid_region, source_image.id, "test-copy-ami", "this is a test copy ami")
|
||||
invalid_region = 'us-east-1' if (source_image.region.name !=
|
||||
'us-east-1') else 'us-west-1'
|
||||
conn.copy_image(invalid_region, source_image.id,
|
||||
"test-copy-ami", "this is a test copy ami")
|
||||
cm.exception.code.should.equal('InvalidAMIID.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
|
@ -131,7 +145,8 @@ def test_ami_tagging():
|
|||
image.add_tag("a key", "some value", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
image.add_tag("a key", "some value")
|
||||
|
||||
|
|
@ -179,7 +194,8 @@ def test_ami_filters():
|
|||
instanceA.modify_attribute("kernel", "k-1234abcd")
|
||||
instanceA.modify_attribute("platform", "windows")
|
||||
instanceA.modify_attribute("virtualization_type", "hvm")
|
||||
imageA_id = conn.create_image(instanceA.id, "test-ami-A", "this is a test ami")
|
||||
imageA_id = conn.create_image(
|
||||
instanceA.id, "test-ami-A", "this is a test ami")
|
||||
imageA = conn.get_image(imageA_id)
|
||||
|
||||
reservationB = conn.run_instances('ami-abcd1234')
|
||||
|
|
@ -188,18 +204,22 @@ def test_ami_filters():
|
|||
instanceB.modify_attribute("kernel", "k-abcd1234")
|
||||
instanceB.modify_attribute("platform", "linux")
|
||||
instanceB.modify_attribute("virtualization_type", "paravirtual")
|
||||
imageB_id = conn.create_image(instanceB.id, "test-ami-B", "this is a test ami")
|
||||
imageB_id = conn.create_image(
|
||||
instanceB.id, "test-ami-B", "this is a test ami")
|
||||
imageB = conn.get_image(imageB_id)
|
||||
imageB.set_launch_permissions(group_names=("all"))
|
||||
|
||||
amis_by_architecture = conn.get_all_images(filters={'architecture': 'x86_64'})
|
||||
amis_by_architecture = conn.get_all_images(
|
||||
filters={'architecture': 'x86_64'})
|
||||
set([ami.id for ami in amis_by_architecture]).should.equal(set([imageB.id]))
|
||||
|
||||
amis_by_kernel = conn.get_all_images(filters={'kernel-id': 'k-abcd1234'})
|
||||
set([ami.id for ami in amis_by_kernel]).should.equal(set([imageB.id]))
|
||||
|
||||
amis_by_virtualization = conn.get_all_images(filters={'virtualization-type': 'paravirtual'})
|
||||
set([ami.id for ami in amis_by_virtualization]).should.equal(set([imageB.id]))
|
||||
amis_by_virtualization = conn.get_all_images(
|
||||
filters={'virtualization-type': 'paravirtual'})
|
||||
set([ami.id for ami in amis_by_virtualization]
|
||||
).should.equal(set([imageB.id]))
|
||||
|
||||
amis_by_platform = conn.get_all_images(filters={'platform': 'windows'})
|
||||
set([ami.id for ami in amis_by_platform]).should.equal(set([imageA.id]))
|
||||
|
|
@ -208,7 +228,8 @@ def test_ami_filters():
|
|||
set([ami.id for ami in amis_by_id]).should.equal(set([imageA.id]))
|
||||
|
||||
amis_by_state = conn.get_all_images(filters={'state': 'available'})
|
||||
set([ami.id for ami in amis_by_state]).should.equal(set([imageA.id, imageB.id]))
|
||||
set([ami.id for ami in amis_by_state]).should.equal(
|
||||
set([imageA.id, imageB.id]))
|
||||
|
||||
amis_by_name = conn.get_all_images(filters={'name': imageA.name})
|
||||
set([ami.id for ami in amis_by_name]).should.equal(set([imageA.id]))
|
||||
|
|
@ -226,20 +247,23 @@ def test_ami_filtering_via_tag():
|
|||
|
||||
reservationA = conn.run_instances('ami-1234abcd')
|
||||
instanceA = reservationA.instances[0]
|
||||
imageA_id = conn.create_image(instanceA.id, "test-ami-A", "this is a test ami")
|
||||
imageA_id = conn.create_image(
|
||||
instanceA.id, "test-ami-A", "this is a test ami")
|
||||
imageA = conn.get_image(imageA_id)
|
||||
imageA.add_tag("a key", "some value")
|
||||
|
||||
reservationB = conn.run_instances('ami-abcd1234')
|
||||
instanceB = reservationB.instances[0]
|
||||
imageB_id = conn.create_image(instanceB.id, "test-ami-B", "this is a test ami")
|
||||
imageB_id = conn.create_image(
|
||||
instanceB.id, "test-ami-B", "this is a test ami")
|
||||
imageB = conn.get_image(imageB_id)
|
||||
imageB.add_tag("another key", "some other value")
|
||||
|
||||
amis_by_tagA = conn.get_all_images(filters={'tag:a key': 'some value'})
|
||||
set([ami.id for ami in amis_by_tagA]).should.equal(set([imageA.id]))
|
||||
|
||||
amis_by_tagB = conn.get_all_images(filters={'tag:another key': 'some other value'})
|
||||
amis_by_tagB = conn.get_all_images(
|
||||
filters={'tag:another key': 'some other value'})
|
||||
set([ami.id for ami in amis_by_tagB]).should.equal(set([imageB.id]))
|
||||
|
||||
|
||||
|
|
@ -274,7 +298,8 @@ def test_ami_attribute_group_permissions():
|
|||
image = conn.get_image(image_id)
|
||||
|
||||
# Baseline
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.name.should.equal('launch_permission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
|
|
@ -290,32 +315,38 @@ def test_ami_attribute_group_permissions():
|
|||
|
||||
# Add 'all' group and confirm
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.modify_image_attribute(**dict(ADD_GROUP_ARGS, **{'dry_run': True}))
|
||||
conn.modify_image_attribute(
|
||||
**dict(ADD_GROUP_ARGS, **{'dry_run': True}))
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyImageAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyImageAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.modify_image_attribute(**ADD_GROUP_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs['groups'].should.have.length_of(1)
|
||||
attributes.attrs['groups'].should.equal(['all'])
|
||||
image = conn.get_image(image_id)
|
||||
image.is_public.should.equal(True)
|
||||
|
||||
# Add is idempotent
|
||||
conn.modify_image_attribute.when.called_with(**ADD_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_image_attribute.when.called_with(
|
||||
**ADD_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
# Remove 'all' group and confirm
|
||||
conn.modify_image_attribute(**REMOVE_GROUP_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
image = conn.get_image(image_id)
|
||||
image.is_public.should.equal(False)
|
||||
|
||||
# Remove is idempotent
|
||||
conn.modify_image_attribute.when.called_with(**REMOVE_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_image_attribute.when.called_with(
|
||||
**REMOVE_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
|
||||
@mock_emr_deprecated
|
||||
|
|
@ -327,7 +358,8 @@ def test_ami_attribute_user_permissions():
|
|||
image = conn.get_image(image_id)
|
||||
|
||||
# Baseline
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.name.should.equal('launch_permission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
|
|
@ -353,19 +385,23 @@ def test_ami_attribute_user_permissions():
|
|||
# Add multiple users and confirm
|
||||
conn.modify_image_attribute(**ADD_USERS_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs['user_ids'].should.have.length_of(2)
|
||||
set(attributes.attrs['user_ids']).should.equal(set([str(USER1), str(USER2)]))
|
||||
set(attributes.attrs['user_ids']).should.equal(
|
||||
set([str(USER1), str(USER2)]))
|
||||
image = conn.get_image(image_id)
|
||||
image.is_public.should.equal(False)
|
||||
|
||||
# Add is idempotent
|
||||
conn.modify_image_attribute.when.called_with(**ADD_USERS_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_image_attribute.when.called_with(
|
||||
**ADD_USERS_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
# Remove single user and confirm
|
||||
conn.modify_image_attribute(**REMOVE_SINGLE_USER_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs['user_ids'].should.have.length_of(1)
|
||||
set(attributes.attrs['user_ids']).should.equal(set([str(USER2)]))
|
||||
image = conn.get_image(image_id)
|
||||
|
|
@ -374,13 +410,15 @@ def test_ami_attribute_user_permissions():
|
|||
# Remove multiple users and confirm
|
||||
conn.modify_image_attribute(**REMOVE_USERS_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
image = conn.get_image(image_id)
|
||||
image.is_public.should.equal(False)
|
||||
|
||||
# Remove is idempotent
|
||||
conn.modify_image_attribute.when.called_with(**REMOVE_USERS_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_image_attribute.when.called_with(
|
||||
**REMOVE_USERS_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
|
||||
@mock_emr_deprecated
|
||||
|
|
@ -397,7 +435,8 @@ def test_ami_attribute_user_and_group_permissions():
|
|||
image = conn.get_image(image_id)
|
||||
|
||||
# Baseline
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.name.should.equal('launch_permission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
|
|
@ -419,7 +458,8 @@ def test_ami_attribute_user_and_group_permissions():
|
|||
# Add and confirm
|
||||
conn.modify_image_attribute(**ADD_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs['user_ids'].should.have.length_of(2)
|
||||
set(attributes.attrs['user_ids']).should.equal(set([USER1, USER2]))
|
||||
set(attributes.attrs['groups']).should.equal(set(['all']))
|
||||
|
|
@ -429,7 +469,8 @@ def test_ami_attribute_user_and_group_permissions():
|
|||
# Remove and confirm
|
||||
conn.modify_image_attribute(**REMOVE_ARGS)
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
image = conn.get_image(image_id)
|
||||
image.is_public.should.equal(False)
|
||||
|
|
@ -483,7 +524,8 @@ def test_ami_attribute_error_cases():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
# Error: Add with one invalid user ID among other valid IDs, ensure no partial changes.
|
||||
# Error: Add with one invalid user ID among other valid IDs, ensure no
|
||||
# partial changes.
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.modify_image_attribute(image.id,
|
||||
attribute='launchPermission',
|
||||
|
|
@ -493,7 +535,8 @@ def test_ami_attribute_error_cases():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
attributes = conn.get_image_attribute(image.id, attribute='launchPermission')
|
||||
attributes = conn.get_image_attribute(
|
||||
image.id, attribute='launchPermission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
# Error: Add with invalid image ID
|
||||
|
|
|
|||
|
|
@ -12,26 +12,31 @@ from moto import mock_ec2_deprecated
|
|||
def test_create_customer_gateways():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
||||
customer_gateway = conn.create_customer_gateway('ipsec.1', '205.251.242.54', 65534)
|
||||
customer_gateway = conn.create_customer_gateway(
|
||||
'ipsec.1', '205.251.242.54', 65534)
|
||||
customer_gateway.should_not.be.none
|
||||
customer_gateway.id.should.match(r'cgw-\w+')
|
||||
customer_gateway.type.should.equal('ipsec.1')
|
||||
customer_gateway.bgp_asn.should.equal(65534)
|
||||
customer_gateway.ip_address.should.equal('205.251.242.54')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_describe_customer_gateways():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
customer_gateway = conn.create_customer_gateway('ipsec.1', '205.251.242.54', 65534)
|
||||
customer_gateway = conn.create_customer_gateway(
|
||||
'ipsec.1', '205.251.242.54', 65534)
|
||||
cgws = conn.get_all_customer_gateways()
|
||||
cgws.should.have.length_of(1)
|
||||
cgws[0].id.should.match(customer_gateway.id)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_delete_customer_gateways():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
||||
customer_gateway = conn.create_customer_gateway('ipsec.1', '205.251.242.54', 65534)
|
||||
customer_gateway = conn.create_customer_gateway(
|
||||
'ipsec.1', '205.251.242.54', 65534)
|
||||
customer_gateway.should_not.be.none
|
||||
cgws = conn.get_all_customer_gateways()
|
||||
cgws[0].id.should.match(customer_gateway.id)
|
||||
|
|
@ -39,6 +44,7 @@ def test_delete_customer_gateways():
|
|||
cgws = conn.get_all_customer_gateways()
|
||||
cgws.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_delete_customer_gateways_bad_id():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ SAMPLE_NAME_SERVERS = [u'10.0.0.6', u'10.0.0.7']
|
|||
def test_dhcp_options_associate():
|
||||
""" associate dhcp option """
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
|
||||
rval = conn.associate_dhcp_options(dhcp_options.id, vpc.id)
|
||||
|
|
@ -43,7 +44,8 @@ def test_dhcp_options_associate_invalid_dhcp_id():
|
|||
def test_dhcp_options_associate_invalid_vpc_id():
|
||||
""" associate dhcp option invalid vpc id """
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.associate_dhcp_options(dhcp_options.id, "foo")
|
||||
|
|
@ -56,7 +58,8 @@ def test_dhcp_options_associate_invalid_vpc_id():
|
|||
def test_dhcp_options_delete_with_vpc():
|
||||
"""Test deletion of dhcp options with vpc"""
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options_id = dhcp_options.id
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
|
||||
|
|
@ -83,10 +86,13 @@ def test_create_dhcp_options():
|
|||
"""Create most basic dhcp option"""
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
||||
dhcp_option = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_option = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_option.options[u'domain-name'][0].should.be.equal(SAMPLE_DOMAIN_NAME)
|
||||
dhcp_option.options[u'domain-name-servers'][0].should.be.equal(SAMPLE_NAME_SERVERS[0])
|
||||
dhcp_option.options[u'domain-name-servers'][1].should.be.equal(SAMPLE_NAME_SERVERS[1])
|
||||
dhcp_option.options[
|
||||
u'domain-name-servers'][0].should.be.equal(SAMPLE_NAME_SERVERS[0])
|
||||
dhcp_option.options[
|
||||
u'domain-name-servers'][1].should.be.equal(SAMPLE_NAME_SERVERS[1])
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -210,8 +216,10 @@ def test_dhcp_options_get_by_tag():
|
|||
dhcp_options_sets = conn.get_all_dhcp_options(filters=filters)
|
||||
|
||||
dhcp_options_sets.should.have.length_of(1)
|
||||
dhcp_options_sets[0].options['domain-name'][0].should.be.equal('example.com')
|
||||
dhcp_options_sets[0].options['domain-name-servers'][0].should.be.equal('10.0.10.2')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name'][0].should.be.equal('example.com')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name-servers'][0].should.be.equal('10.0.10.2')
|
||||
dhcp_options_sets[0].tags['Name'].should.equal('TestDhcpOptions1')
|
||||
dhcp_options_sets[0].tags['test-tag'].should.equal('test-value')
|
||||
|
||||
|
|
@ -219,8 +227,10 @@ def test_dhcp_options_get_by_tag():
|
|||
dhcp_options_sets = conn.get_all_dhcp_options(filters=filters)
|
||||
|
||||
dhcp_options_sets.should.have.length_of(1)
|
||||
dhcp_options_sets[0].options['domain-name'][0].should.be.equal('example.com')
|
||||
dhcp_options_sets[0].options['domain-name-servers'][0].should.be.equal('10.0.20.2')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name'][0].should.be.equal('example.com')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name-servers'][0].should.be.equal('10.0.20.2')
|
||||
dhcp_options_sets[0].tags['Name'].should.equal('TestDhcpOptions2')
|
||||
dhcp_options_sets[0].tags['test-tag'].should.equal('test-value')
|
||||
|
||||
|
|
@ -247,17 +257,21 @@ def test_dhcp_options_get_by_id():
|
|||
dhcp_options_sets = conn.get_all_dhcp_options()
|
||||
dhcp_options_sets.should.have.length_of(2)
|
||||
|
||||
dhcp_options_sets = conn.get_all_dhcp_options(filters={'dhcp-options-id': dhcp1_id})
|
||||
dhcp_options_sets = conn.get_all_dhcp_options(
|
||||
filters={'dhcp-options-id': dhcp1_id})
|
||||
|
||||
dhcp_options_sets.should.have.length_of(1)
|
||||
dhcp_options_sets[0].options['domain-name'][0].should.be.equal('test1.com')
|
||||
dhcp_options_sets[0].options['domain-name-servers'][0].should.be.equal('10.0.10.2')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name-servers'][0].should.be.equal('10.0.10.2')
|
||||
|
||||
dhcp_options_sets = conn.get_all_dhcp_options(filters={'dhcp-options-id': dhcp2_id})
|
||||
dhcp_options_sets = conn.get_all_dhcp_options(
|
||||
filters={'dhcp-options-id': dhcp2_id})
|
||||
|
||||
dhcp_options_sets.should.have.length_of(1)
|
||||
dhcp_options_sets[0].options['domain-name'][0].should.be.equal('test2.com')
|
||||
dhcp_options_sets[0].options['domain-name-servers'][0].should.be.equal('10.0.20.2')
|
||||
dhcp_options_sets[0].options[
|
||||
'domain-name-servers'][0].should.be.equal('10.0.20.2')
|
||||
|
||||
|
||||
@mock_ec2
|
||||
|
|
@ -315,4 +329,5 @@ def test_dhcp_options_get_by_invalid_filter():
|
|||
conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
filters = {'invalid-filter': 'invalid-value'}
|
||||
|
||||
conn.get_all_dhcp_options.when.called_with(filters=filters).should.throw(NotImplementedError)
|
||||
conn.get_all_dhcp_options.when.called_with(
|
||||
filters=filters).should.throw(NotImplementedError)
|
||||
|
|
|
|||
|
|
@ -28,7 +28,8 @@ def test_create_and_delete_volume():
|
|||
volume.delete(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
volume.delete()
|
||||
|
||||
|
|
@ -42,7 +43,6 @@ def test_create_and_delete_volume():
|
|||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_create_encrypted_volume_dryrun():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
|
@ -50,7 +50,8 @@ def test_create_encrypted_volume_dryrun():
|
|||
conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -62,7 +63,8 @@ def test_create_encrypted_volume():
|
|||
conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
all_volumes = conn.get_all_volumes()
|
||||
all_volumes[0].encrypted.should.be(True)
|
||||
|
|
@ -108,29 +110,42 @@ def test_volume_filters():
|
|||
|
||||
block_mapping = instance.block_device_mapping['/dev/sda1']
|
||||
|
||||
volumes_by_attach_time = conn.get_all_volumes(filters={'attachment.attach-time': block_mapping.attach_time})
|
||||
set([vol.id for vol in volumes_by_attach_time]).should.equal(set([block_mapping.volume_id]))
|
||||
volumes_by_attach_time = conn.get_all_volumes(
|
||||
filters={'attachment.attach-time': block_mapping.attach_time})
|
||||
set([vol.id for vol in volumes_by_attach_time]
|
||||
).should.equal(set([block_mapping.volume_id]))
|
||||
|
||||
volumes_by_attach_device = conn.get_all_volumes(filters={'attachment.device': '/dev/sda1'})
|
||||
set([vol.id for vol in volumes_by_attach_device]).should.equal(set([block_mapping.volume_id]))
|
||||
volumes_by_attach_device = conn.get_all_volumes(
|
||||
filters={'attachment.device': '/dev/sda1'})
|
||||
set([vol.id for vol in volumes_by_attach_device]
|
||||
).should.equal(set([block_mapping.volume_id]))
|
||||
|
||||
volumes_by_attach_instance_id = conn.get_all_volumes(filters={'attachment.instance-id': instance.id})
|
||||
set([vol.id for vol in volumes_by_attach_instance_id]).should.equal(set([block_mapping.volume_id]))
|
||||
volumes_by_attach_instance_id = conn.get_all_volumes(
|
||||
filters={'attachment.instance-id': instance.id})
|
||||
set([vol.id for vol in volumes_by_attach_instance_id]
|
||||
).should.equal(set([block_mapping.volume_id]))
|
||||
|
||||
volumes_by_attach_status = conn.get_all_volumes(filters={'attachment.status': 'attached'})
|
||||
set([vol.id for vol in volumes_by_attach_status]).should.equal(set([block_mapping.volume_id]))
|
||||
volumes_by_attach_status = conn.get_all_volumes(
|
||||
filters={'attachment.status': 'attached'})
|
||||
set([vol.id for vol in volumes_by_attach_status]
|
||||
).should.equal(set([block_mapping.volume_id]))
|
||||
|
||||
volumes_by_create_time = conn.get_all_volumes(filters={'create-time': volume4.create_time})
|
||||
set([vol.create_time for vol in volumes_by_create_time]).should.equal(set([volume4.create_time]))
|
||||
volumes_by_create_time = conn.get_all_volumes(
|
||||
filters={'create-time': volume4.create_time})
|
||||
set([vol.create_time for vol in volumes_by_create_time]
|
||||
).should.equal(set([volume4.create_time]))
|
||||
|
||||
volumes_by_size = conn.get_all_volumes(filters={'size': volume2.size})
|
||||
set([vol.id for vol in volumes_by_size]).should.equal(set([volume2.id]))
|
||||
|
||||
volumes_by_snapshot_id = conn.get_all_volumes(filters={'snapshot-id': snapshot.id})
|
||||
set([vol.id for vol in volumes_by_snapshot_id]).should.equal(set([volume4.id]))
|
||||
volumes_by_snapshot_id = conn.get_all_volumes(
|
||||
filters={'snapshot-id': snapshot.id})
|
||||
set([vol.id for vol in volumes_by_snapshot_id]
|
||||
).should.equal(set([volume4.id]))
|
||||
|
||||
volumes_by_status = conn.get_all_volumes(filters={'status': 'in-use'})
|
||||
set([vol.id for vol in volumes_by_status]).should.equal(set([block_mapping.volume_id]))
|
||||
set([vol.id for vol in volumes_by_status]).should.equal(
|
||||
set([block_mapping.volume_id]))
|
||||
|
||||
volumes_by_id = conn.get_all_volumes(filters={'volume-id': volume1.id})
|
||||
set([vol.id for vol in volumes_by_id]).should.equal(set([volume1.id]))
|
||||
|
|
@ -138,13 +153,17 @@ def test_volume_filters():
|
|||
volumes_by_tag_key = conn.get_all_volumes(filters={'tag-key': 'testkey1'})
|
||||
set([vol.id for vol in volumes_by_tag_key]).should.equal(set([volume1.id]))
|
||||
|
||||
volumes_by_tag_value = conn.get_all_volumes(filters={'tag-value': 'testvalue1'})
|
||||
set([vol.id for vol in volumes_by_tag_value]).should.equal(set([volume1.id]))
|
||||
volumes_by_tag_value = conn.get_all_volumes(
|
||||
filters={'tag-value': 'testvalue1'})
|
||||
set([vol.id for vol in volumes_by_tag_value]
|
||||
).should.equal(set([volume1.id]))
|
||||
|
||||
volumes_by_tag = conn.get_all_volumes(filters={'tag:testkey1': 'testvalue1'})
|
||||
volumes_by_tag = conn.get_all_volumes(
|
||||
filters={'tag:testkey1': 'testvalue1'})
|
||||
set([vol.id for vol in volumes_by_tag]).should.equal(set([volume1.id]))
|
||||
|
||||
volumes_by_unencrypted = conn.get_all_volumes(filters={'encrypted': 'false'})
|
||||
volumes_by_unencrypted = conn.get_all_volumes(
|
||||
filters={'encrypted': 'false'})
|
||||
set([vol.id for vol in volumes_by_unencrypted]).should.equal(
|
||||
set([block_mapping.volume_id, volume2.id])
|
||||
)
|
||||
|
|
@ -169,7 +188,8 @@ def test_volume_attach_and_detach():
|
|||
volume.attach(instance.id, "/dev/sdh", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AttachVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AttachVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
volume.attach(instance.id, "/dev/sdh")
|
||||
|
||||
|
|
@ -183,7 +203,8 @@ def test_volume_attach_and_detach():
|
|||
volume.detach(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DetachVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DetachVolume operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
volume.detach()
|
||||
|
||||
|
|
@ -218,7 +239,8 @@ def test_create_snapshot():
|
|||
snapshot = volume.create_snapshot('a dryrun snapshot', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
snapshot = volume.create_snapshot('a test snapshot')
|
||||
snapshot.update()
|
||||
|
|
@ -294,32 +316,50 @@ def test_snapshot_filters():
|
|||
conn.create_tags([snapshot1.id], {'testkey1': 'testvalue1'})
|
||||
conn.create_tags([snapshot2.id], {'testkey2': 'testvalue2'})
|
||||
|
||||
snapshots_by_description = conn.get_all_snapshots(filters={'description': 'testsnapshot1'})
|
||||
set([snap.id for snap in snapshots_by_description]).should.equal(set([snapshot1.id]))
|
||||
snapshots_by_description = conn.get_all_snapshots(
|
||||
filters={'description': 'testsnapshot1'})
|
||||
set([snap.id for snap in snapshots_by_description]
|
||||
).should.equal(set([snapshot1.id]))
|
||||
|
||||
snapshots_by_id = conn.get_all_snapshots(filters={'snapshot-id': snapshot1.id})
|
||||
set([snap.id for snap in snapshots_by_id]).should.equal(set([snapshot1.id]))
|
||||
snapshots_by_id = conn.get_all_snapshots(
|
||||
filters={'snapshot-id': snapshot1.id})
|
||||
set([snap.id for snap in snapshots_by_id]
|
||||
).should.equal(set([snapshot1.id]))
|
||||
|
||||
snapshots_by_start_time = conn.get_all_snapshots(filters={'start-time': snapshot1.start_time})
|
||||
set([snap.start_time for snap in snapshots_by_start_time]).should.equal(set([snapshot1.start_time]))
|
||||
snapshots_by_start_time = conn.get_all_snapshots(
|
||||
filters={'start-time': snapshot1.start_time})
|
||||
set([snap.start_time for snap in snapshots_by_start_time]
|
||||
).should.equal(set([snapshot1.start_time]))
|
||||
|
||||
snapshots_by_volume_id = conn.get_all_snapshots(filters={'volume-id': volume1.id})
|
||||
set([snap.id for snap in snapshots_by_volume_id]).should.equal(set([snapshot1.id, snapshot2.id]))
|
||||
snapshots_by_volume_id = conn.get_all_snapshots(
|
||||
filters={'volume-id': volume1.id})
|
||||
set([snap.id for snap in snapshots_by_volume_id]
|
||||
).should.equal(set([snapshot1.id, snapshot2.id]))
|
||||
|
||||
snapshots_by_volume_size = conn.get_all_snapshots(filters={'volume-size': volume1.size})
|
||||
set([snap.id for snap in snapshots_by_volume_size]).should.equal(set([snapshot1.id, snapshot2.id]))
|
||||
snapshots_by_volume_size = conn.get_all_snapshots(
|
||||
filters={'volume-size': volume1.size})
|
||||
set([snap.id for snap in snapshots_by_volume_size]
|
||||
).should.equal(set([snapshot1.id, snapshot2.id]))
|
||||
|
||||
snapshots_by_tag_key = conn.get_all_snapshots(filters={'tag-key': 'testkey1'})
|
||||
set([snap.id for snap in snapshots_by_tag_key]).should.equal(set([snapshot1.id]))
|
||||
snapshots_by_tag_key = conn.get_all_snapshots(
|
||||
filters={'tag-key': 'testkey1'})
|
||||
set([snap.id for snap in snapshots_by_tag_key]
|
||||
).should.equal(set([snapshot1.id]))
|
||||
|
||||
snapshots_by_tag_value = conn.get_all_snapshots(filters={'tag-value': 'testvalue1'})
|
||||
set([snap.id for snap in snapshots_by_tag_value]).should.equal(set([snapshot1.id]))
|
||||
snapshots_by_tag_value = conn.get_all_snapshots(
|
||||
filters={'tag-value': 'testvalue1'})
|
||||
set([snap.id for snap in snapshots_by_tag_value]
|
||||
).should.equal(set([snapshot1.id]))
|
||||
|
||||
snapshots_by_tag = conn.get_all_snapshots(filters={'tag:testkey1': 'testvalue1'})
|
||||
set([snap.id for snap in snapshots_by_tag]).should.equal(set([snapshot1.id]))
|
||||
snapshots_by_tag = conn.get_all_snapshots(
|
||||
filters={'tag:testkey1': 'testvalue1'})
|
||||
set([snap.id for snap in snapshots_by_tag]
|
||||
).should.equal(set([snapshot1.id]))
|
||||
|
||||
snapshots_by_encrypted = conn.get_all_snapshots(filters={'encrypted': 'true'})
|
||||
set([snap.id for snap in snapshots_by_encrypted]).should.equal(set([snapshot3.id]))
|
||||
snapshots_by_encrypted = conn.get_all_snapshots(
|
||||
filters={'encrypted': 'true'})
|
||||
set([snap.id for snap in snapshots_by_encrypted]
|
||||
).should.equal(set([snapshot3.id]))
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -331,7 +371,8 @@ def test_snapshot_attribute():
|
|||
snapshot = volume.create_snapshot()
|
||||
|
||||
# Baseline
|
||||
attributes = conn.get_snapshot_attribute(snapshot.id, attribute='createVolumePermission')
|
||||
attributes = conn.get_snapshot_attribute(
|
||||
snapshot.id, attribute='createVolumePermission')
|
||||
attributes.name.should.equal('create_volume_permission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
|
|
@ -348,34 +389,42 @@ def test_snapshot_attribute():
|
|||
# Add 'all' group and confirm
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.modify_snapshot_attribute(**dict(ADD_GROUP_ARGS, **{'dry_run': True}))
|
||||
conn.modify_snapshot_attribute(
|
||||
**dict(ADD_GROUP_ARGS, **{'dry_run': True}))
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.modify_snapshot_attribute(**ADD_GROUP_ARGS)
|
||||
|
||||
attributes = conn.get_snapshot_attribute(snapshot.id, attribute='createVolumePermission')
|
||||
attributes = conn.get_snapshot_attribute(
|
||||
snapshot.id, attribute='createVolumePermission')
|
||||
attributes.attrs['groups'].should.have.length_of(1)
|
||||
attributes.attrs['groups'].should.equal(['all'])
|
||||
|
||||
# Add is idempotent
|
||||
conn.modify_snapshot_attribute.when.called_with(**ADD_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_snapshot_attribute.when.called_with(
|
||||
**ADD_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
# Remove 'all' group and confirm
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.modify_snapshot_attribute(**dict(REMOVE_GROUP_ARGS, **{'dry_run': True}))
|
||||
conn.modify_snapshot_attribute(
|
||||
**dict(REMOVE_GROUP_ARGS, **{'dry_run': True}))
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifySnapshotAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.modify_snapshot_attribute(**REMOVE_GROUP_ARGS)
|
||||
|
||||
attributes = conn.get_snapshot_attribute(snapshot.id, attribute='createVolumePermission')
|
||||
attributes = conn.get_snapshot_attribute(
|
||||
snapshot.id, attribute='createVolumePermission')
|
||||
attributes.attrs.should.have.length_of(0)
|
||||
|
||||
# Remove is idempotent
|
||||
conn.modify_snapshot_attribute.when.called_with(**REMOVE_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
conn.modify_snapshot_attribute.when.called_with(
|
||||
**REMOVE_GROUP_ARGS).should_not.throw(EC2ResponseError)
|
||||
|
||||
# Error: Add with group != 'all'
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
|
|
@ -428,7 +477,8 @@ def test_create_volume_from_snapshot():
|
|||
snapshot = volume.create_snapshot('a test snapshot', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateSnapshot operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
snapshot = volume.create_snapshot('a test snapshot')
|
||||
snapshot.update()
|
||||
|
|
@ -469,16 +519,19 @@ def test_modify_attribute_blockDeviceMapping():
|
|||
instance = reservation.instances[0]
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
instance.modify_attribute('blockDeviceMapping', {'/dev/sda1': True}, dry_run=True)
|
||||
instance.modify_attribute('blockDeviceMapping', {
|
||||
'/dev/sda1': True}, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyInstanceAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyInstanceAttribute operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.modify_attribute('blockDeviceMapping', {'/dev/sda1': True})
|
||||
|
||||
instance = ec2_backends[conn.region.name].get_instance(instance.id)
|
||||
instance.block_device_mapping.should.have.key('/dev/sda1')
|
||||
instance.block_device_mapping['/dev/sda1'].delete_on_termination.should.be(True)
|
||||
instance.block_device_mapping[
|
||||
'/dev/sda1'].delete_on_termination.should.be(True)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -491,8 +544,10 @@ def test_volume_tag_escaping():
|
|||
snapshot.add_tags({'key': '</closed>'}, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
dict(conn.get_all_snapshots()[0].tags).should_not.be.equal({'key': '</closed>'})
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
dict(conn.get_all_snapshots()[0].tags).should_not.be.equal(
|
||||
{'key': '</closed>'})
|
||||
|
||||
snapshot.add_tags({'key': '</closed>'})
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@ def test_eip_allocate_classic():
|
|||
standard = conn.allocate_address(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
standard = conn.allocate_address()
|
||||
standard.should.be.a(boto.ec2.address.Address)
|
||||
|
|
@ -36,7 +37,8 @@ def test_eip_allocate_classic():
|
|||
standard.release(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
standard.release()
|
||||
standard.should_not.be.within(conn.get_all_addresses())
|
||||
|
|
@ -51,7 +53,8 @@ def test_eip_allocate_vpc():
|
|||
vpc = conn.allocate_address(domain="vpc", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
vpc = conn.allocate_address(domain="vpc")
|
||||
vpc.should.be.a(boto.ec2.address.Address)
|
||||
|
|
@ -90,23 +93,28 @@ def test_eip_associate_classic():
|
|||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.associate_address(instance_id=instance.id, public_ip=eip.public_ip, dry_run=True)
|
||||
conn.associate_address(instance_id=instance.id,
|
||||
public_ip=eip.public_ip, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AssociateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AssociateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.associate_address(instance_id=instance.id, public_ip=eip.public_ip)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.instance_id.should.be.equal(instance.id)
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.disassociate_address(public_ip=eip.public_ip, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DisAssociateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DisAssociateAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.disassociate_address(public_ip=eip.public_ip)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.instance_id.should.be.equal(u'')
|
||||
eip.release()
|
||||
eip.should_not.be.within(conn.get_all_addresses())
|
||||
|
|
@ -114,6 +122,7 @@ def test_eip_associate_classic():
|
|||
|
||||
instance.terminate()
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_eip_associate_vpc():
|
||||
"""Associate/Disassociate EIP to VPC instance"""
|
||||
|
|
@ -131,11 +140,14 @@ def test_eip_associate_vpc():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
conn.associate_address(instance_id=instance.id, allocation_id=eip.allocation_id)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
conn.associate_address(instance_id=instance.id,
|
||||
allocation_id=eip.allocation_id)
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.instance_id.should.be.equal(instance.id)
|
||||
conn.disassociate_address(association_id=eip.association_id)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.instance_id.should.be.equal(u'')
|
||||
eip.association_id.should.be.none
|
||||
|
||||
|
|
@ -143,13 +155,15 @@ def test_eip_associate_vpc():
|
|||
eip.release(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ReleaseAddress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
eip.release()
|
||||
eip = None
|
||||
|
||||
instance.terminate()
|
||||
|
||||
|
||||
@mock_ec2
|
||||
def test_eip_boto3_vpc_association():
|
||||
"""Associate EIP to VPC instance in a new subnet with boto3"""
|
||||
|
|
@ -157,7 +171,7 @@ def test_eip_boto3_vpc_association():
|
|||
client = boto3.client('ec2', region_name='us-west-1')
|
||||
vpc_res = client.create_vpc(CidrBlock='10.0.0.0/24')
|
||||
subnet_res = client.create_subnet(
|
||||
VpcId=vpc_res['Vpc']['VpcId'], CidrBlock='10.0.0.0/24')
|
||||
VpcId=vpc_res['Vpc']['VpcId'], CidrBlock='10.0.0.0/24')
|
||||
instance = service.create_instances(**{
|
||||
'InstanceType': 't2.micro',
|
||||
'ImageId': 'ami-test',
|
||||
|
|
@ -192,17 +206,21 @@ def test_eip_associate_network_interface():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
conn.associate_address(network_interface_id=eni.id, allocation_id=eip.allocation_id)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
conn.associate_address(network_interface_id=eni.id,
|
||||
allocation_id=eip.allocation_id)
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.network_interface_id.should.be.equal(eni.id)
|
||||
|
||||
conn.disassociate_address(association_id=eip.association_id)
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0] # no .update() on address ):
|
||||
# no .update() on address ):
|
||||
eip = conn.get_all_addresses(addresses=[eip.public_ip])[0]
|
||||
eip.network_interface_id.should.be.equal(u'')
|
||||
eip.association_id.should.be.none
|
||||
eip.release()
|
||||
eip = None
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_eip_reassociate():
|
||||
"""reassociate EIP"""
|
||||
|
|
@ -219,12 +237,14 @@ def test_eip_reassociate():
|
|||
|
||||
# Different ID detects resource association
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.associate_address(instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=False)
|
||||
conn.associate_address(
|
||||
instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=False)
|
||||
cm.exception.code.should.equal('Resource.AlreadyAssociated')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
conn.associate_address.when.called_with(instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=True).should_not.throw(EC2ResponseError)
|
||||
conn.associate_address.when.called_with(
|
||||
instance_id=instance2.id, public_ip=eip.public_ip, allow_reassociation=True).should_not.throw(EC2ResponseError)
|
||||
|
||||
eip.release()
|
||||
eip = None
|
||||
|
|
@ -232,6 +252,7 @@ def test_eip_reassociate():
|
|||
instance1.terminate()
|
||||
instance2.terminate()
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_eip_reassociate_nic():
|
||||
"""reassociate EIP"""
|
||||
|
|
@ -243,23 +264,28 @@ def test_eip_reassociate_nic():
|
|||
eni2 = conn.create_network_interface(subnet.id)
|
||||
|
||||
eip = conn.allocate_address()
|
||||
conn.associate_address(network_interface_id=eni1.id, public_ip=eip.public_ip)
|
||||
conn.associate_address(network_interface_id=eni1.id,
|
||||
public_ip=eip.public_ip)
|
||||
|
||||
# Same ID is idempotent
|
||||
conn.associate_address(network_interface_id=eni1.id, public_ip=eip.public_ip)
|
||||
conn.associate_address(network_interface_id=eni1.id,
|
||||
public_ip=eip.public_ip)
|
||||
|
||||
# Different ID detects resource association
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.associate_address(network_interface_id=eni2.id, public_ip=eip.public_ip)
|
||||
conn.associate_address(
|
||||
network_interface_id=eni2.id, public_ip=eip.public_ip)
|
||||
cm.exception.code.should.equal('Resource.AlreadyAssociated')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
conn.associate_address.when.called_with(network_interface_id=eni2.id, public_ip=eip.public_ip, allow_reassociation=True).should_not.throw(EC2ResponseError)
|
||||
conn.associate_address.when.called_with(
|
||||
network_interface_id=eni2.id, public_ip=eip.public_ip, allow_reassociation=True).should_not.throw(EC2ResponseError)
|
||||
|
||||
eip.release()
|
||||
eip = None
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_eip_associate_invalid_args():
|
||||
"""Associate EIP, invalid args """
|
||||
|
|
@ -290,6 +316,7 @@ def test_eip_disassociate_bogus_association():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_eip_release_bogus_eip():
|
||||
"""Release bogus EIP"""
|
||||
|
|
@ -334,7 +361,7 @@ def test_eip_describe():
|
|||
number_of_classic_ips = 2
|
||||
number_of_vpc_ips = 2
|
||||
|
||||
#allocate some IPs
|
||||
# allocate some IPs
|
||||
for _ in range(number_of_classic_ips):
|
||||
eips.append(conn.allocate_address())
|
||||
for _ in range(number_of_vpc_ips):
|
||||
|
|
@ -344,19 +371,22 @@ def test_eip_describe():
|
|||
# Can we find each one individually?
|
||||
for eip in eips:
|
||||
if eip.allocation_id:
|
||||
lookup_addresses = conn.get_all_addresses(allocation_ids=[eip.allocation_id])
|
||||
lookup_addresses = conn.get_all_addresses(
|
||||
allocation_ids=[eip.allocation_id])
|
||||
else:
|
||||
lookup_addresses = conn.get_all_addresses(addresses=[eip.public_ip])
|
||||
lookup_addresses = conn.get_all_addresses(
|
||||
addresses=[eip.public_ip])
|
||||
len(lookup_addresses).should.be.equal(1)
|
||||
lookup_addresses[0].public_ip.should.be.equal(eip.public_ip)
|
||||
|
||||
# Can we find first two when we search for them?
|
||||
lookup_addresses = conn.get_all_addresses(addresses=[eips[0].public_ip, eips[1].public_ip])
|
||||
lookup_addresses = conn.get_all_addresses(
|
||||
addresses=[eips[0].public_ip, eips[1].public_ip])
|
||||
len(lookup_addresses).should.be.equal(2)
|
||||
lookup_addresses[0].public_ip.should.be.equal(eips[0].public_ip)
|
||||
lookup_addresses[1].public_ip.should.be.equal(eips[1].public_ip)
|
||||
|
||||
#Release all IPs
|
||||
# Release all IPs
|
||||
for eip in eips:
|
||||
eip.release()
|
||||
len(conn.get_all_addresses()).should.be.equal(0)
|
||||
|
|
@ -372,4 +402,3 @@ def test_eip_describe_none():
|
|||
cm.exception.code.should.equal('InvalidAddress.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ def test_elastic_network_interfaces():
|
|||
eni = conn.create_network_interface(subnet.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
eni = conn.create_network_interface(subnet.id)
|
||||
|
||||
|
|
@ -41,7 +42,8 @@ def test_elastic_network_interfaces():
|
|||
conn.delete_network_interface(eni.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.delete_network_interface(eni.id)
|
||||
|
||||
|
|
@ -89,16 +91,20 @@ def test_elastic_network_interfaces_with_groups():
|
|||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
conn.create_network_interface(subnet.id, groups=[security_group1.id, security_group2.id])
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
conn.create_network_interface(
|
||||
subnet.id, groups=[security_group1.id, security_group2.id])
|
||||
|
||||
all_enis = conn.get_all_network_interfaces()
|
||||
all_enis.should.have.length_of(1)
|
||||
|
||||
eni = all_enis[0]
|
||||
eni.groups.should.have.length_of(2)
|
||||
set([group.id for group in eni.groups]).should.equal(set([security_group1.id, security_group2.id]))
|
||||
set([group.id for group in eni.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
|
||||
|
||||
@requires_boto_gte("2.12.0")
|
||||
|
|
@ -107,8 +113,10 @@ def test_elastic_network_interfaces_modify_attribute():
|
|||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
conn.create_network_interface(subnet.id, groups=[security_group1.id])
|
||||
|
||||
all_enis = conn.get_all_network_interfaces()
|
||||
|
|
@ -119,12 +127,15 @@ def test_elastic_network_interfaces_modify_attribute():
|
|||
eni.groups[0].id.should.equal(security_group1.id)
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.modify_network_interface_attribute(eni.id, 'groupset', [security_group2.id], dry_run=True)
|
||||
conn.modify_network_interface_attribute(
|
||||
eni.id, 'groupset', [security_group2.id], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.modify_network_interface_attribute(eni.id, 'groupset', [security_group2.id])
|
||||
conn.modify_network_interface_attribute(
|
||||
eni.id, 'groupset', [security_group2.id])
|
||||
|
||||
all_enis = conn.get_all_network_interfaces()
|
||||
all_enis.should.have.length_of(1)
|
||||
|
|
@ -140,11 +151,15 @@ def test_elastic_network_interfaces_filtering():
|
|||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
|
||||
eni1 = conn.create_network_interface(subnet.id, groups=[security_group1.id, security_group2.id])
|
||||
eni2 = conn.create_network_interface(subnet.id, groups=[security_group1.id])
|
||||
eni1 = conn.create_network_interface(
|
||||
subnet.id, groups=[security_group1.id, security_group2.id])
|
||||
eni2 = conn.create_network_interface(
|
||||
subnet.id, groups=[security_group1.id])
|
||||
eni3 = conn.create_network_interface(subnet.id)
|
||||
|
||||
all_enis = conn.get_all_network_interfaces()
|
||||
|
|
@ -156,22 +171,26 @@ def test_elastic_network_interfaces_filtering():
|
|||
set([eni.id for eni in enis_by_id]).should.equal(set([eni1.id]))
|
||||
|
||||
# Filter by ENI ID
|
||||
enis_by_id = conn.get_all_network_interfaces(filters={'network-interface-id': eni1.id})
|
||||
enis_by_id = conn.get_all_network_interfaces(
|
||||
filters={'network-interface-id': eni1.id})
|
||||
enis_by_id.should.have.length_of(1)
|
||||
set([eni.id for eni in enis_by_id]).should.equal(set([eni1.id]))
|
||||
|
||||
# Filter by Security Group
|
||||
enis_by_group = conn.get_all_network_interfaces(filters={'group-id': security_group1.id})
|
||||
enis_by_group = conn.get_all_network_interfaces(
|
||||
filters={'group-id': security_group1.id})
|
||||
enis_by_group.should.have.length_of(2)
|
||||
set([eni.id for eni in enis_by_group]).should.equal(set([eni1.id, eni2.id]))
|
||||
|
||||
# Filter by ENI ID and Security Group
|
||||
enis_by_group = conn.get_all_network_interfaces(filters={'network-interface-id': eni1.id, 'group-id': security_group1.id})
|
||||
enis_by_group = conn.get_all_network_interfaces(
|
||||
filters={'network-interface-id': eni1.id, 'group-id': security_group1.id})
|
||||
enis_by_group.should.have.length_of(1)
|
||||
set([eni.id for eni in enis_by_group]).should.equal(set([eni1.id]))
|
||||
|
||||
# Unsupported filter
|
||||
conn.get_all_network_interfaces.when.called_with(filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
conn.get_all_network_interfaces.when.called_with(
|
||||
filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
|
||||
|
||||
@mock_ec2
|
||||
|
|
@ -180,15 +199,19 @@ def test_elastic_network_interfaces_get_by_tag_name():
|
|||
ec2_client = boto3.client('ec2', region_name='us-west-2')
|
||||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
|
||||
eni1 = ec2.create_network_interface(SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
eni1 = ec2.create_network_interface(
|
||||
SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
|
||||
with assert_raises(ClientError) as ex:
|
||||
eni1.create_tags(Tags=[{'Key': 'Name', 'Value': 'eni1'}], DryRun=True)
|
||||
ex.exception.response['Error']['Code'].should.equal('DryRunOperation')
|
||||
ex.exception.response['ResponseMetadata']['HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.response['ResponseMetadata'][
|
||||
'HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
eni1.create_tags(Tags=[{'Key': 'Name', 'Value': 'eni1'}])
|
||||
|
||||
|
|
@ -211,9 +234,11 @@ def test_elastic_network_interfaces_get_by_private_ip():
|
|||
ec2_client = boto3.client('ec2', region_name='us-west-2')
|
||||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
|
||||
eni1 = ec2.create_network_interface(SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
eni1 = ec2.create_network_interface(
|
||||
SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
|
||||
# The status of the new interface should be 'available'
|
||||
waiter = ec2_client.get_waiter('network_interface_available')
|
||||
|
|
@ -242,9 +267,11 @@ def test_elastic_network_interfaces_get_by_vpc_id():
|
|||
ec2_client = boto3.client('ec2', region_name='us-west-2')
|
||||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
|
||||
eni1 = ec2.create_network_interface(SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
eni1 = ec2.create_network_interface(
|
||||
SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
|
||||
# The status of the new interface should be 'available'
|
||||
waiter = ec2_client.get_waiter('network_interface_available')
|
||||
|
|
@ -265,9 +292,11 @@ def test_elastic_network_interfaces_get_by_subnet_id():
|
|||
ec2_client = boto3.client('ec2', region_name='us-west-2')
|
||||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
|
||||
|
||||
eni1 = ec2.create_network_interface(SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
eni1 = ec2.create_network_interface(
|
||||
SubnetId=subnet.id, PrivateIpAddress='10.0.10.5')
|
||||
|
||||
# The status of the new interface should be 'available'
|
||||
waiter = ec2_client.get_waiter('network_interface_available')
|
||||
|
|
@ -297,5 +326,6 @@ def test_elastic_network_interfaces_cloudformation():
|
|||
|
||||
stack = conn.describe_stacks()[0]
|
||||
resources = stack.describe_resources()
|
||||
cfn_eni = [resource for resource in resources if resource.resource_type == 'AWS::EC2::NetworkInterface'][0]
|
||||
cfn_eni = [resource for resource in resources if resource.resource_type ==
|
||||
'AWS::EC2::NetworkInterface'][0]
|
||||
cfn_eni.physical_resource_id.should.equal(eni.id)
|
||||
|
|
|
|||
|
|
@ -45,7 +45,8 @@ def test_instance_launch_and_terminate():
|
|||
reservation = conn.run_instances('ami-1234abcd', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the RunInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the RunInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
reservation = conn.run_instances('ami-1234abcd')
|
||||
reservation.should.be.a(Reservation)
|
||||
|
|
@ -66,7 +67,8 @@ def test_instance_launch_and_terminate():
|
|||
instance.placement.should.equal('us-east-1a')
|
||||
|
||||
root_device_name = instance.root_device_name
|
||||
instance.block_device_mapping[root_device_name].status.should.equal('in-use')
|
||||
instance.block_device_mapping[
|
||||
root_device_name].status.should.equal('in-use')
|
||||
volume_id = instance.block_device_mapping[root_device_name].volume_id
|
||||
volume_id.should.match(r'vol-\w+')
|
||||
|
||||
|
|
@ -78,7 +80,8 @@ def test_instance_launch_and_terminate():
|
|||
conn.terminate_instances([instance.id], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the TerminateInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the TerminateInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.terminate_instances([instance.id])
|
||||
|
||||
|
|
@ -90,7 +93,8 @@ def test_instance_launch_and_terminate():
|
|||
@mock_ec2_deprecated
|
||||
def test_terminate_empty_instances():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
conn.terminate_instances.when.called_with([]).should.throw(EC2ResponseError)
|
||||
conn.terminate_instances.when.called_with(
|
||||
[]).should.throw(EC2ResponseError)
|
||||
|
||||
|
||||
@freeze_time("2014-01-01 05:00:00")
|
||||
|
|
@ -117,8 +121,10 @@ def test_instance_attach_volume():
|
|||
|
||||
for v in conn.get_all_volumes(volume_ids=[instance.block_device_mapping['/dev/sdc1'].volume_id]):
|
||||
v.attach_data.instance_id.should.equal(instance.id)
|
||||
v.attach_data.attach_time.should.equal(instance.launch_time) # can do due to freeze_time decorator.
|
||||
v.create_time.should.equal(instance.launch_time) # can do due to freeze_time decorator.
|
||||
# can do due to freeze_time decorator.
|
||||
v.attach_data.attach_time.should.equal(instance.launch_time)
|
||||
# can do due to freeze_time decorator.
|
||||
v.create_time.should.equal(instance.launch_time)
|
||||
v.region.name.should.equal(instance.region.name)
|
||||
v.status.should.equal('in-use')
|
||||
|
||||
|
|
@ -135,7 +141,8 @@ def test_get_instances_by_id():
|
|||
reservation.instances.should.have.length_of(1)
|
||||
reservation.instances[0].id.should.equal(instance1.id)
|
||||
|
||||
reservations = conn.get_all_instances(instance_ids=[instance1.id, instance2.id])
|
||||
reservations = conn.get_all_instances(
|
||||
instance_ids=[instance1.id, instance2.id])
|
||||
reservations.should.have.length_of(1)
|
||||
reservation = reservations[0]
|
||||
reservation.instances.should.have.length_of(2)
|
||||
|
|
@ -158,25 +165,31 @@ def test_get_instances_filtering_by_state():
|
|||
|
||||
conn.terminate_instances([instance1.id])
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-state-name': 'running'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-state-name': 'running'})
|
||||
reservations.should.have.length_of(1)
|
||||
# Since we terminated instance1, only instance2 and instance3 should be returned
|
||||
# Since we terminated instance1, only instance2 and instance3 should be
|
||||
# returned
|
||||
instance_ids = [instance.id for instance in reservations[0].instances]
|
||||
set(instance_ids).should.equal(set([instance2.id, instance3.id]))
|
||||
|
||||
reservations = conn.get_all_instances([instance2.id], filters={'instance-state-name': 'running'})
|
||||
reservations = conn.get_all_instances(
|
||||
[instance2.id], filters={'instance-state-name': 'running'})
|
||||
reservations.should.have.length_of(1)
|
||||
instance_ids = [instance.id for instance in reservations[0].instances]
|
||||
instance_ids.should.equal([instance2.id])
|
||||
|
||||
reservations = conn.get_all_instances([instance2.id], filters={'instance-state-name': 'terminated'})
|
||||
reservations = conn.get_all_instances(
|
||||
[instance2.id], filters={'instance-state-name': 'terminated'})
|
||||
list(reservations).should.equal([])
|
||||
|
||||
# get_all_instances should still return all 3
|
||||
reservations = conn.get_all_instances()
|
||||
reservations[0].instances.should.have.length_of(3)
|
||||
|
||||
conn.get_all_instances.when.called_with(filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
conn.get_all_instances.when.called_with(
|
||||
filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_instances_filtering_by_instance_id():
|
||||
|
|
@ -184,16 +197,19 @@ def test_get_instances_filtering_by_instance_id():
|
|||
reservation = conn.run_instances('ami-1234abcd', min_count=3)
|
||||
instance1, instance2, instance3 = reservation.instances
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-id': instance1.id})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-id': instance1.id})
|
||||
# get_all_instances should return just instance1
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-id': [instance1.id, instance2.id]})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-id': [instance1.id, instance2.id]})
|
||||
# get_all_instances should return two
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-id': 'non-existing-id'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-id': 'non-existing-id'})
|
||||
reservations.should.have.length_of(0)
|
||||
|
||||
|
||||
|
|
@ -207,22 +223,25 @@ def test_get_instances_filtering_by_instance_type():
|
|||
reservation3 = conn.run_instances('ami-1234abcd', instance_type='t1.micro')
|
||||
instance3 = reservation3.instances[0]
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-type': 'm1.small'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-type': 'm1.small'})
|
||||
# get_all_instances should return instance1,2
|
||||
reservations.should.have.length_of(2)
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[1].instances.should.have.length_of(1)
|
||||
instance_ids = [ reservations[0].instances[0].id,
|
||||
reservations[1].instances[0].id ]
|
||||
instance_ids = [reservations[0].instances[0].id,
|
||||
reservations[1].instances[0].id]
|
||||
set(instance_ids).should.equal(set([instance1.id, instance2.id]))
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-type': 't1.micro'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-type': 't1.micro'})
|
||||
# get_all_instances should return one
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[0].instances[0].id.should.equal(instance3.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-type': ['t1.micro', 'm1.small']})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'instance-type': ['t1.micro', 'm1.small']})
|
||||
reservations.should.have.length_of(3)
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[1].instances.should.have.length_of(1)
|
||||
|
|
@ -231,13 +250,15 @@ def test_get_instances_filtering_by_instance_type():
|
|||
reservations[0].instances[0].id,
|
||||
reservations[1].instances[0].id,
|
||||
reservations[2].instances[0].id,
|
||||
]
|
||||
set(instance_ids).should.equal(set([instance1.id, instance2.id, instance3.id]))
|
||||
]
|
||||
set(instance_ids).should.equal(
|
||||
set([instance1.id, instance2.id, instance3.id]))
|
||||
|
||||
reservations = conn.get_all_instances(filters={'instance-type': 'bogus'})
|
||||
#bogus instance-type should return none
|
||||
# bogus instance-type should return none
|
||||
reservations.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_instances_filtering_by_reason_code():
|
||||
conn = boto.connect_ec2()
|
||||
|
|
@ -246,10 +267,12 @@ def test_get_instances_filtering_by_reason_code():
|
|||
instance1.stop()
|
||||
instance2.terminate()
|
||||
|
||||
reservations = conn.get_all_instances(filters={'state-reason-code': 'Client.UserInitiatedShutdown'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'state-reason-code': 'Client.UserInitiatedShutdown'})
|
||||
# get_all_instances should return instance1 and instance2
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
set([instance1.id, instance2.id]).should.equal(set([i.id for i in reservations[0].instances]))
|
||||
set([instance1.id, instance2.id]).should.equal(
|
||||
set([i.id for i in reservations[0].instances]))
|
||||
|
||||
reservations = conn.get_all_instances(filters={'state-reason-code': ''})
|
||||
# get_all_instances should return instance 3
|
||||
|
|
@ -262,10 +285,13 @@ def test_get_instances_filtering_by_source_dest_check():
|
|||
conn = boto.connect_ec2()
|
||||
reservation = conn.run_instances('ami-1234abcd', min_count=2)
|
||||
instance1, instance2 = reservation.instances
|
||||
conn.modify_instance_attribute(instance1.id, attribute='sourceDestCheck', value=False)
|
||||
conn.modify_instance_attribute(
|
||||
instance1.id, attribute='sourceDestCheck', value=False)
|
||||
|
||||
source_dest_check_false = conn.get_all_instances(filters={'source-dest-check': 'false'})
|
||||
source_dest_check_true = conn.get_all_instances(filters={'source-dest-check': 'true'})
|
||||
source_dest_check_false = conn.get_all_instances(
|
||||
filters={'source-dest-check': 'false'})
|
||||
source_dest_check_true = conn.get_all_instances(
|
||||
filters={'source-dest-check': 'true'})
|
||||
|
||||
source_dest_check_false[0].instances.should.have.length_of(1)
|
||||
source_dest_check_false[0].instances[0].id.should.equal(instance1.id)
|
||||
|
|
@ -279,12 +305,14 @@ def test_get_instances_filtering_by_vpc_id():
|
|||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc1 = conn.create_vpc("10.0.0.0/16")
|
||||
subnet1 = conn.create_subnet(vpc1.id, "10.0.0.0/27")
|
||||
reservation1 = conn.run_instances('ami-1234abcd', min_count=1, subnet_id=subnet1.id)
|
||||
reservation1 = conn.run_instances(
|
||||
'ami-1234abcd', min_count=1, subnet_id=subnet1.id)
|
||||
instance1 = reservation1.instances[0]
|
||||
|
||||
vpc2 = conn.create_vpc("10.1.0.0/16")
|
||||
subnet2 = conn.create_subnet(vpc2.id, "10.1.0.0/27")
|
||||
reservation2 = conn.run_instances('ami-1234abcd', min_count=1, subnet_id=subnet2.id)
|
||||
reservation2 = conn.run_instances(
|
||||
'ami-1234abcd', min_count=1, subnet_id=subnet2.id)
|
||||
instance2 = reservation2.instances[0]
|
||||
|
||||
reservations1 = conn.get_all_instances(filters={'vpc-id': vpc1.id})
|
||||
|
|
@ -320,31 +348,35 @@ def test_get_instances_filtering_by_tag():
|
|||
instance2.add_tag('tag2', 'wrong value')
|
||||
instance3.add_tag('tag2', 'value2')
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag:tag0' : 'value0'})
|
||||
reservations = conn.get_all_instances(filters={'tag:tag0': 'value0'})
|
||||
# get_all_instances should return no instances
|
||||
reservations.should.have.length_of(0)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag:tag1' : 'value1'})
|
||||
reservations = conn.get_all_instances(filters={'tag:tag1': 'value1'})
|
||||
# get_all_instances should return both instances with this tag value
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance2.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag:tag1' : 'value1', 'tag:tag2' : 'value2'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag:tag1': 'value1', 'tag:tag2': 'value2'})
|
||||
# get_all_instances should return the instance with both tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag:tag1' : 'value1', 'tag:tag2' : 'value2'})
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag:tag1': 'value1', 'tag:tag2': 'value2'})
|
||||
# get_all_instances should return the instance with both tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(1)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag:tag2' : ['value2', 'bogus']})
|
||||
# get_all_instances should return both instances with one of the acceptable tag values
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag:tag2': ['value2', 'bogus']})
|
||||
# get_all_instances should return both instances with one of the
|
||||
# acceptable tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
|
|
@ -362,32 +394,37 @@ def test_get_instances_filtering_by_tag_value():
|
|||
instance2.add_tag('tag2', 'wrong value')
|
||||
instance3.add_tag('tag2', 'value2')
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-value' : 'value0'})
|
||||
reservations = conn.get_all_instances(filters={'tag-value': 'value0'})
|
||||
# get_all_instances should return no instances
|
||||
reservations.should.have.length_of(0)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-value' : 'value1'})
|
||||
reservations = conn.get_all_instances(filters={'tag-value': 'value1'})
|
||||
# get_all_instances should return both instances with this tag value
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance2.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-value' : ['value2', 'value1']})
|
||||
# get_all_instances should return both instances with one of the acceptable tag values
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag-value': ['value2', 'value1']})
|
||||
# get_all_instances should return both instances with one of the
|
||||
# acceptable tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(3)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance2.id)
|
||||
reservations[0].instances[2].id.should.equal(instance3.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-value' : ['value2', 'bogus']})
|
||||
# get_all_instances should return both instances with one of the acceptable tag values
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag-value': ['value2', 'bogus']})
|
||||
# get_all_instances should return both instances with one of the
|
||||
# acceptable tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance3.id)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_instances_filtering_by_tag_name():
|
||||
conn = boto.connect_ec2()
|
||||
|
|
@ -399,25 +436,28 @@ def test_get_instances_filtering_by_tag_name():
|
|||
instance2.add_tag('tag2X')
|
||||
instance3.add_tag('tag3')
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-key' : 'tagX'})
|
||||
reservations = conn.get_all_instances(filters={'tag-key': 'tagX'})
|
||||
# get_all_instances should return no instances
|
||||
reservations.should.have.length_of(0)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-key' : 'tag1'})
|
||||
reservations = conn.get_all_instances(filters={'tag-key': 'tag1'})
|
||||
# get_all_instances should return both instances with this tag value
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(2)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance2.id)
|
||||
|
||||
reservations = conn.get_all_instances(filters={'tag-key' : ['tag1', 'tag3']})
|
||||
# get_all_instances should return both instances with one of the acceptable tag values
|
||||
reservations = conn.get_all_instances(
|
||||
filters={'tag-key': ['tag1', 'tag3']})
|
||||
# get_all_instances should return both instances with one of the
|
||||
# acceptable tag values
|
||||
reservations.should.have.length_of(1)
|
||||
reservations[0].instances.should.have.length_of(3)
|
||||
reservations[0].instances[0].id.should.equal(instance1.id)
|
||||
reservations[0].instances[1].id.should.equal(instance2.id)
|
||||
reservations[0].instances[2].id.should.equal(instance3.id)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_instance_start_and_stop():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
|
@ -431,7 +471,8 @@ def test_instance_start_and_stop():
|
|||
stopped_instances = conn.stop_instances(instance_ids, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the StopInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the StopInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
stopped_instances = conn.stop_instances(instance_ids)
|
||||
|
||||
|
|
@ -439,10 +480,12 @@ def test_instance_start_and_stop():
|
|||
instance.state.should.equal('stopping')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
started_instances = conn.start_instances([instances[0].id], dry_run=True)
|
||||
started_instances = conn.start_instances(
|
||||
[instances[0].id], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the StartInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the StartInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
started_instances = conn.start_instances([instances[0].id])
|
||||
started_instances[0].state.should.equal('pending')
|
||||
|
|
@ -458,7 +501,8 @@ def test_instance_reboot():
|
|||
instance.reboot(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the RebootInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the RebootInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.reboot()
|
||||
instance.state.should.equal('pending')
|
||||
|
|
@ -474,7 +518,8 @@ def test_instance_attribute_instance_type():
|
|||
instance.modify_attribute("instanceType", "m1.small", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyInstanceType operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyInstanceType operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.modify_attribute("instanceType", "m1.small")
|
||||
|
||||
|
|
@ -482,6 +527,7 @@ def test_instance_attribute_instance_type():
|
|||
instance_attribute.should.be.a(InstanceAttribute)
|
||||
instance_attribute.get('instanceType').should.equal("m1.small")
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_modify_instance_attribute_security_groups():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
|
@ -495,7 +541,8 @@ def test_modify_instance_attribute_security_groups():
|
|||
instance.modify_attribute("groupSet", [sg_id, sg_id2], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.modify_attribute("groupSet", [sg_id, sg_id2])
|
||||
|
||||
|
|
@ -513,10 +560,12 @@ def test_instance_attribute_user_data():
|
|||
instance = reservation.instances[0]
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
instance.modify_attribute("userData", "this is my user data", dry_run=True)
|
||||
instance.modify_attribute(
|
||||
"userData", "this is my user data", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyUserData operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyUserData operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.modify_attribute("userData", "this is my user data")
|
||||
|
||||
|
|
@ -544,7 +593,8 @@ def test_instance_attribute_source_dest_check():
|
|||
instance.modify_attribute("sourceDestCheck", False, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifySourceDestCheck operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifySourceDestCheck operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.modify_attribute("sourceDestCheck", False)
|
||||
|
||||
|
|
@ -585,10 +635,12 @@ def test_run_instance_with_security_group_name():
|
|||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
group = conn.create_security_group('group1', "some description", dry_run=True)
|
||||
group = conn.create_security_group(
|
||||
'group1', "some description", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
group = conn.create_security_group('group1', "some description")
|
||||
|
||||
|
|
@ -658,14 +710,16 @@ def test_run_instance_with_nic_autocreated():
|
|||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
private_ip = "54.0.0.1"
|
||||
|
||||
reservation = conn.run_instances('ami-1234abcd', subnet_id=subnet.id,
|
||||
security_groups=[security_group1.name],
|
||||
security_group_ids=[security_group2.id],
|
||||
private_ip_address=private_ip)
|
||||
security_groups=[security_group1.name],
|
||||
security_group_ids=[security_group2.id],
|
||||
private_ip_address=private_ip)
|
||||
instance = reservation.instances[0]
|
||||
|
||||
all_enis = conn.get_all_network_interfaces()
|
||||
|
|
@ -677,11 +731,13 @@ def test_run_instance_with_nic_autocreated():
|
|||
|
||||
instance.subnet_id.should.equal(subnet.id)
|
||||
instance.groups.should.have.length_of(2)
|
||||
set([group.id for group in instance.groups]).should.equal(set([security_group1.id,security_group2.id]))
|
||||
set([group.id for group in instance.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
|
||||
eni.subnet_id.should.equal(subnet.id)
|
||||
eni.groups.should.have.length_of(2)
|
||||
set([group.id for group in eni.groups]).should.equal(set([security_group1.id,security_group2.id]))
|
||||
set([group.id for group in eni.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
eni.private_ip_addresses.should.have.length_of(1)
|
||||
eni.private_ip_addresses[0].private_ip_address.should.equal(private_ip)
|
||||
|
||||
|
|
@ -691,20 +747,24 @@ def test_run_instance_with_nic_preexisting():
|
|||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
private_ip = "54.0.0.1"
|
||||
eni = conn.create_network_interface(subnet.id, private_ip, groups=[security_group1.id])
|
||||
eni = conn.create_network_interface(
|
||||
subnet.id, private_ip, groups=[security_group1.id])
|
||||
|
||||
# Boto requires NetworkInterfaceCollection of NetworkInterfaceSpecifications...
|
||||
# annoying, but generates the desired querystring.
|
||||
from boto.ec2.networkinterface import NetworkInterfaceSpecification, NetworkInterfaceCollection
|
||||
interface = NetworkInterfaceSpecification(network_interface_id=eni.id, device_index=0)
|
||||
interface = NetworkInterfaceSpecification(
|
||||
network_interface_id=eni.id, device_index=0)
|
||||
interfaces = NetworkInterfaceCollection(interface)
|
||||
# end Boto objects
|
||||
|
||||
reservation = conn.run_instances('ami-1234abcd', network_interfaces=interfaces,
|
||||
security_group_ids=[security_group2.id])
|
||||
security_group_ids=[security_group2.id])
|
||||
instance = reservation.instances[0]
|
||||
|
||||
instance.subnet_id.should.equal(subnet.id)
|
||||
|
|
@ -718,9 +778,11 @@ def test_run_instance_with_nic_preexisting():
|
|||
|
||||
instance_eni.subnet_id.should.equal(subnet.id)
|
||||
instance_eni.groups.should.have.length_of(2)
|
||||
set([group.id for group in instance_eni.groups]).should.equal(set([security_group1.id,security_group2.id]))
|
||||
set([group.id for group in instance_eni.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
instance_eni.private_ip_addresses.should.have.length_of(1)
|
||||
instance_eni.private_ip_addresses[0].private_ip_address.should.equal(private_ip)
|
||||
instance_eni.private_ip_addresses[
|
||||
0].private_ip_address.should.equal(private_ip)
|
||||
|
||||
|
||||
@requires_boto_gte("2.32.0")
|
||||
|
|
@ -730,10 +792,13 @@ def test_instance_with_nic_attach_detach():
|
|||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")
|
||||
|
||||
security_group1 = conn.create_security_group('test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group('test security group #2', 'this is a test security group')
|
||||
security_group1 = conn.create_security_group(
|
||||
'test security group #1', 'this is a test security group')
|
||||
security_group2 = conn.create_security_group(
|
||||
'test security group #2', 'this is a test security group')
|
||||
|
||||
reservation = conn.run_instances('ami-1234abcd', security_group_ids=[security_group1.id])
|
||||
reservation = conn.run_instances(
|
||||
'ami-1234abcd', security_group_ids=[security_group1.id])
|
||||
instance = reservation.instances[0]
|
||||
|
||||
eni = conn.create_network_interface(subnet.id, groups=[security_group2.id])
|
||||
|
|
@ -742,14 +807,17 @@ def test_instance_with_nic_attach_detach():
|
|||
instance.interfaces.should.have.length_of(1)
|
||||
|
||||
eni.groups.should.have.length_of(1)
|
||||
set([group.id for group in eni.groups]).should.equal(set([security_group2.id]))
|
||||
set([group.id for group in eni.groups]).should.equal(
|
||||
set([security_group2.id]))
|
||||
|
||||
# Attach
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.attach_network_interface(eni.id, instance.id, device_index=1, dry_run=True)
|
||||
conn.attach_network_interface(
|
||||
eni.id, instance.id, device_index=1, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AttachNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AttachNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.attach_network_interface(eni.id, instance.id, device_index=1)
|
||||
|
||||
|
|
@ -759,18 +827,22 @@ def test_instance_with_nic_attach_detach():
|
|||
instance_eni = instance.interfaces[1]
|
||||
instance_eni.id.should.equal(eni.id)
|
||||
instance_eni.groups.should.have.length_of(2)
|
||||
set([group.id for group in instance_eni.groups]).should.equal(set([security_group1.id,security_group2.id]))
|
||||
set([group.id for group in instance_eni.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
|
||||
eni = conn.get_all_network_interfaces(filters={'network-interface-id': eni.id})[0]
|
||||
eni = conn.get_all_network_interfaces(
|
||||
filters={'network-interface-id': eni.id})[0]
|
||||
eni.groups.should.have.length_of(2)
|
||||
set([group.id for group in eni.groups]).should.equal(set([security_group1.id,security_group2.id]))
|
||||
set([group.id for group in eni.groups]).should.equal(
|
||||
set([security_group1.id, security_group2.id]))
|
||||
|
||||
# Detach
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.detach_network_interface(instance_eni.attachment.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DetachNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DetachNetworkInterface operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.detach_network_interface(instance_eni.attachment.id)
|
||||
|
||||
|
|
@ -778,9 +850,11 @@ def test_instance_with_nic_attach_detach():
|
|||
instance.update()
|
||||
instance.interfaces.should.have.length_of(1)
|
||||
|
||||
eni = conn.get_all_network_interfaces(filters={'network-interface-id': eni.id})[0]
|
||||
eni = conn.get_all_network_interfaces(
|
||||
filters={'network-interface-id': eni.id})[0]
|
||||
eni.groups.should.have.length_of(1)
|
||||
set([group.id for group in eni.groups]).should.equal(set([security_group2.id]))
|
||||
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:
|
||||
|
|
@ -851,6 +925,7 @@ def test_describe_instance_status_with_instance_filter():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@requires_boto_gte("2.32.0")
|
||||
@mock_ec2_deprecated
|
||||
def test_describe_instance_status_with_non_running_instances():
|
||||
|
|
@ -877,6 +952,7 @@ def test_describe_instance_status_with_non_running_instances():
|
|||
status3 = next((s for s in all_status if s.id == instance3.id), None)
|
||||
status3.state_name.should.equal('running')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_instance_by_security_group():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
|
@ -887,12 +963,15 @@ def test_get_instance_by_security_group():
|
|||
security_group = conn.create_security_group('test', 'test')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.modify_instance_attribute(instance.id, "groupSet", [security_group.id], dry_run=True)
|
||||
conn.modify_instance_attribute(instance.id, "groupSet", [
|
||||
security_group.id], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ModifyInstanceSecurityGroups operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.modify_instance_attribute(instance.id, "groupSet", [security_group.id])
|
||||
conn.modify_instance_attribute(
|
||||
instance.id, "groupSet", [security_group.id])
|
||||
|
||||
security_group_instances = security_group.instances()
|
||||
|
||||
|
|
|
|||
|
|
@ -13,9 +13,10 @@ import sure # noqa
|
|||
from moto import mock_ec2_deprecated
|
||||
|
||||
|
||||
VPC_CIDR="10.0.0.0/16"
|
||||
BAD_VPC="vpc-deadbeef"
|
||||
BAD_IGW="igw-deadbeef"
|
||||
VPC_CIDR = "10.0.0.0/16"
|
||||
BAD_VPC = "vpc-deadbeef"
|
||||
BAD_IGW = "igw-deadbeef"
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_create():
|
||||
|
|
@ -28,7 +29,8 @@ def test_igw_create():
|
|||
igw = conn.create_internet_gateway(dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
igw = conn.create_internet_gateway()
|
||||
conn.get_all_internet_gateways().should.have.length_of(1)
|
||||
|
|
@ -37,6 +39,7 @@ def test_igw_create():
|
|||
igw = conn.get_all_internet_gateways()[0]
|
||||
igw.attachments.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_attach():
|
||||
""" internet gateway attach """
|
||||
|
|
@ -48,13 +51,15 @@ def test_igw_attach():
|
|||
conn.attach_internet_gateway(igw.id, vpc.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the AttachInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the AttachInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.attach_internet_gateway(igw.id, vpc.id)
|
||||
|
||||
igw = conn.get_all_internet_gateways()[0]
|
||||
igw.attachments[0].vpc_id.should.be.equal(vpc.id)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_attach_bad_vpc():
|
||||
""" internet gateway fail to attach w/ bad vpc """
|
||||
|
|
@ -67,6 +72,7 @@ def test_igw_attach_bad_vpc():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_attach_twice():
|
||||
""" internet gateway fail to attach twice """
|
||||
|
|
@ -82,6 +88,7 @@ def test_igw_attach_twice():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_detach():
|
||||
""" internet gateway detach"""
|
||||
|
|
@ -94,12 +101,14 @@ def test_igw_detach():
|
|||
conn.detach_internet_gateway(igw.id, vpc.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DetachInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DetachInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.detach_internet_gateway(igw.id, vpc.id)
|
||||
igw = conn.get_all_internet_gateways()[0]
|
||||
igw.attachments.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_detach_wrong_vpc():
|
||||
""" internet gateway fail to detach w/ wrong vpc """
|
||||
|
|
@ -115,6 +124,7 @@ def test_igw_detach_wrong_vpc():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_detach_invalid_vpc():
|
||||
""" internet gateway fail to detach w/ invalid vpc """
|
||||
|
|
@ -129,6 +139,7 @@ def test_igw_detach_invalid_vpc():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_detach_unattached():
|
||||
""" internet gateway fail to detach unattached """
|
||||
|
|
@ -142,6 +153,7 @@ def test_igw_detach_unattached():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_delete():
|
||||
""" internet gateway delete"""
|
||||
|
|
@ -155,11 +167,13 @@ def test_igw_delete():
|
|||
conn.delete_internet_gateway(igw.id, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteInternetGateway operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.delete_internet_gateway(igw.id)
|
||||
conn.get_all_internet_gateways().should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_delete_attached():
|
||||
""" internet gateway fail to delete attached """
|
||||
|
|
@ -174,6 +188,7 @@ def test_igw_delete_attached():
|
|||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_desribe():
|
||||
""" internet gateway fetch by id """
|
||||
|
|
@ -182,6 +197,7 @@ def test_igw_desribe():
|
|||
igw_by_search = conn.get_all_internet_gateways([igw.id])[0]
|
||||
igw.id.should.equal(igw_by_search.id)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_igw_desribe_bad_id():
|
||||
""" internet gateway fail to fetch by bad id """
|
||||
|
|
@ -203,7 +219,8 @@ def test_igw_filter_by_vpc_id():
|
|||
vpc = conn.create_vpc(VPC_CIDR)
|
||||
conn.attach_internet_gateway(igw1.id, vpc.id)
|
||||
|
||||
result = conn.get_all_internet_gateways(filters={"attachment.vpc-id": vpc.id})
|
||||
result = conn.get_all_internet_gateways(
|
||||
filters={"attachment.vpc-id": vpc.id})
|
||||
result.should.have.length_of(1)
|
||||
result[0].id.should.equal(igw1.id)
|
||||
|
||||
|
|
@ -230,7 +247,8 @@ def test_igw_filter_by_internet_gateway_id():
|
|||
igw1 = conn.create_internet_gateway()
|
||||
igw2 = conn.create_internet_gateway()
|
||||
|
||||
result = conn.get_all_internet_gateways(filters={"internet-gateway-id": igw1.id})
|
||||
result = conn.get_all_internet_gateways(
|
||||
filters={"internet-gateway-id": igw1.id})
|
||||
result.should.have.length_of(1)
|
||||
result[0].id.should.equal(igw1.id)
|
||||
|
||||
|
|
@ -245,6 +263,7 @@ def test_igw_filter_by_attachment_state():
|
|||
vpc = conn.create_vpc(VPC_CIDR)
|
||||
conn.attach_internet_gateway(igw1.id, vpc.id)
|
||||
|
||||
result = conn.get_all_internet_gateways(filters={"attachment.state": "available"})
|
||||
result = conn.get_all_internet_gateways(
|
||||
filters={"attachment.state": "available"})
|
||||
result.should.have.length_of(1)
|
||||
result[0].id.should.equal(igw1.id)
|
||||
|
|
|
|||
|
|
@ -36,7 +36,8 @@ def test_key_pairs_create():
|
|||
kp = conn.create_key_pair('foo', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
kp = conn.create_key_pair('foo')
|
||||
assert kp.material.startswith('---- BEGIN RSA PRIVATE KEY ----')
|
||||
|
|
@ -91,7 +92,8 @@ def test_key_pairs_delete_exist():
|
|||
r = conn.delete_key_pair('foo', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
r = conn.delete_key_pair('foo')
|
||||
r.should.be.ok
|
||||
|
|
@ -106,7 +108,8 @@ def test_key_pairs_import():
|
|||
kp = conn.import_key_pair('foo', b'content', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the ImportKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the ImportKeyPair operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
kp = conn.import_key_pair('foo', b'content')
|
||||
assert kp.name == 'foo'
|
||||
|
|
|
|||
|
|
@ -56,7 +56,8 @@ def test_delete_nat_gateway():
|
|||
nat_gateway_id = nat_gateway['NatGateway']['NatGatewayId']
|
||||
response = conn.delete_nat_gateway(NatGatewayId=nat_gateway_id)
|
||||
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None) # this is hard to match against, so remove it
|
||||
# this is hard to match against, so remove it
|
||||
response['ResponseMetadata'].pop('HTTPHeaders', None)
|
||||
response['ResponseMetadata'].pop('RetryAttempts', None)
|
||||
response.should.equal({
|
||||
'NatGatewayId': nat_gateway_id,
|
||||
|
|
@ -89,14 +90,20 @@ def test_create_and_describe_nat_gateway():
|
|||
|
||||
enis = conn.describe_network_interfaces()['NetworkInterfaces']
|
||||
eni_id = enis[0]['NetworkInterfaceId']
|
||||
public_ip = conn.describe_addresses(AllocationIds=[allocation_id])['Addresses'][0]['PublicIp']
|
||||
public_ip = conn.describe_addresses(AllocationIds=[allocation_id])[
|
||||
'Addresses'][0]['PublicIp']
|
||||
|
||||
describe_response['NatGateways'].should.have.length_of(1)
|
||||
describe_response['NatGateways'][0]['NatGatewayId'].should.equal(nat_gateway_id)
|
||||
describe_response['NatGateways'][0][
|
||||
'NatGatewayId'].should.equal(nat_gateway_id)
|
||||
describe_response['NatGateways'][0]['State'].should.equal('available')
|
||||
describe_response['NatGateways'][0]['SubnetId'].should.equal(subnet_id)
|
||||
describe_response['NatGateways'][0]['VpcId'].should.equal(vpc_id)
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][0]['AllocationId'].should.equal(allocation_id)
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][0]['NetworkInterfaceId'].should.equal(eni_id)
|
||||
assert describe_response['NatGateways'][0]['NatGatewayAddresses'][0]['PrivateIp'].startswith('10.')
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][0]['PublicIp'].should.equal(public_ip)
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][
|
||||
0]['AllocationId'].should.equal(allocation_id)
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][
|
||||
0]['NetworkInterfaceId'].should.equal(eni_id)
|
||||
assert describe_response['NatGateways'][0][
|
||||
'NatGatewayAddresses'][0]['PrivateIp'].startswith('10.')
|
||||
describe_response['NatGateways'][0]['NatGatewayAddresses'][
|
||||
0]['PublicIp'].should.equal(public_ip)
|
||||
|
|
|
|||
|
|
@ -50,9 +50,11 @@ def test_add_servers_to_multiple_regions():
|
|||
@mock_elb_deprecated
|
||||
def test_create_autoscaling_group():
|
||||
elb_conn = boto.ec2.elb.connect_to_region('us-east-1')
|
||||
elb_conn.create_load_balancer('us_test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
elb_conn.create_load_balancer(
|
||||
'us_test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
elb_conn = boto.ec2.elb.connect_to_region('ap-northeast-1')
|
||||
elb_conn.create_load_balancer('ap_test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
elb_conn.create_load_balancer(
|
||||
'ap_test_lb', zones=[], listeners=[(80, 8080, 'http')])
|
||||
|
||||
us_conn = boto.ec2.autoscale.connect_to_region('us-east-1')
|
||||
config = boto.ec2.autoscale.LaunchConfiguration(
|
||||
|
|
@ -79,7 +81,6 @@ def test_create_autoscaling_group():
|
|||
)
|
||||
us_conn.create_auto_scaling_group(group)
|
||||
|
||||
|
||||
ap_conn = boto.ec2.autoscale.connect_to_region('ap-northeast-1')
|
||||
config = boto.ec2.autoscale.LaunchConfiguration(
|
||||
name='ap_tester',
|
||||
|
|
@ -105,7 +106,6 @@ def test_create_autoscaling_group():
|
|||
)
|
||||
ap_conn.create_auto_scaling_group(group)
|
||||
|
||||
|
||||
len(us_conn.get_all_groups()).should.equal(1)
|
||||
len(ap_conn.get_all_groups()).should.equal(1)
|
||||
|
||||
|
|
@ -122,7 +122,8 @@ def test_create_autoscaling_group():
|
|||
us_group.health_check_type.should.equal("EC2")
|
||||
list(us_group.load_balancers).should.equal(["us_test_lb"])
|
||||
us_group.placement_group.should.equal("us_test_placement")
|
||||
list(us_group.termination_policies).should.equal(["OldestInstance", "NewestInstance"])
|
||||
list(us_group.termination_policies).should.equal(
|
||||
["OldestInstance", "NewestInstance"])
|
||||
|
||||
ap_group = ap_conn.get_all_groups()[0]
|
||||
ap_group.name.should.equal('ap_tester_group')
|
||||
|
|
@ -137,4 +138,5 @@ def test_create_autoscaling_group():
|
|||
ap_group.health_check_type.should.equal("EC2")
|
||||
list(ap_group.load_balancers).should.equal(["ap_test_lb"])
|
||||
ap_group.placement_group.should.equal("ap_test_placement")
|
||||
list(ap_group.termination_policies).should.equal(["OldestInstance", "NewestInstance"])
|
||||
list(ap_group.termination_policies).should.equal(
|
||||
["OldestInstance", "NewestInstance"])
|
||||
|
|
|
|||
|
|
@ -91,28 +91,34 @@ def test_route_tables_filters_standard():
|
|||
all_route_tables.should.have.length_of(5)
|
||||
|
||||
# Filter by main route table
|
||||
main_route_tables = conn.get_all_route_tables(filters={'association.main':'true'})
|
||||
main_route_tables = conn.get_all_route_tables(
|
||||
filters={'association.main': 'true'})
|
||||
main_route_tables.should.have.length_of(3)
|
||||
main_route_table_ids = [route_table.id for route_table in main_route_tables]
|
||||
main_route_table_ids = [
|
||||
route_table.id for route_table in main_route_tables]
|
||||
main_route_table_ids.should_not.contain(route_table1.id)
|
||||
main_route_table_ids.should_not.contain(route_table2.id)
|
||||
|
||||
# Filter by VPC
|
||||
vpc1_route_tables = conn.get_all_route_tables(filters={'vpc-id':vpc1.id})
|
||||
vpc1_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc1.id})
|
||||
vpc1_route_tables.should.have.length_of(2)
|
||||
vpc1_route_table_ids = [route_table.id for route_table in vpc1_route_tables]
|
||||
vpc1_route_table_ids = [
|
||||
route_table.id for route_table in vpc1_route_tables]
|
||||
vpc1_route_table_ids.should.contain(route_table1.id)
|
||||
vpc1_route_table_ids.should_not.contain(route_table2.id)
|
||||
|
||||
# Filter by VPC and main route table
|
||||
vpc2_main_route_tables = conn.get_all_route_tables(filters={'association.main':'true', 'vpc-id':vpc2.id})
|
||||
vpc2_main_route_tables = conn.get_all_route_tables(
|
||||
filters={'association.main': 'true', 'vpc-id': vpc2.id})
|
||||
vpc2_main_route_tables.should.have.length_of(1)
|
||||
vpc2_main_route_table_ids = [route_table.id for route_table in vpc2_main_route_tables]
|
||||
vpc2_main_route_table_ids = [
|
||||
route_table.id for route_table in vpc2_main_route_tables]
|
||||
vpc2_main_route_table_ids.should_not.contain(route_table1.id)
|
||||
vpc2_main_route_table_ids.should_not.contain(route_table2.id)
|
||||
|
||||
# Unsupported filter
|
||||
conn.get_all_route_tables.when.called_with(filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
conn.get_all_route_tables.when.called_with(
|
||||
filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -134,19 +140,22 @@ def test_route_tables_filters_associations():
|
|||
all_route_tables.should.have.length_of(4)
|
||||
|
||||
# Filter by association ID
|
||||
association1_route_tables = conn.get_all_route_tables(filters={'association.route-table-association-id':association_id1})
|
||||
association1_route_tables = conn.get_all_route_tables(
|
||||
filters={'association.route-table-association-id': association_id1})
|
||||
association1_route_tables.should.have.length_of(1)
|
||||
association1_route_tables[0].id.should.equal(route_table1.id)
|
||||
association1_route_tables[0].associations.should.have.length_of(2)
|
||||
|
||||
# Filter by route table ID
|
||||
route_table2_route_tables = conn.get_all_route_tables(filters={'association.route-table-id':route_table2.id})
|
||||
route_table2_route_tables = conn.get_all_route_tables(
|
||||
filters={'association.route-table-id': route_table2.id})
|
||||
route_table2_route_tables.should.have.length_of(1)
|
||||
route_table2_route_tables[0].id.should.equal(route_table2.id)
|
||||
route_table2_route_tables[0].associations.should.have.length_of(1)
|
||||
|
||||
# Filter by subnet ID
|
||||
subnet_route_tables = conn.get_all_route_tables(filters={'association.subnet-id':subnet1.id})
|
||||
subnet_route_tables = conn.get_all_route_tables(
|
||||
filters={'association.subnet-id': subnet1.id})
|
||||
subnet_route_tables.should.have.length_of(1)
|
||||
subnet_route_tables[0].id.should.equal(route_table1.id)
|
||||
association1_route_tables[0].associations.should.have.length_of(2)
|
||||
|
|
@ -179,7 +188,8 @@ def test_route_table_associations():
|
|||
route_table.associations[0].subnet_id.should.equal(subnet.id)
|
||||
|
||||
# Associate is idempotent
|
||||
association_id_idempotent = conn.associate_route_table(route_table.id, subnet.id)
|
||||
association_id_idempotent = conn.associate_route_table(
|
||||
route_table.id, subnet.id)
|
||||
association_id_idempotent.should.equal(association_id)
|
||||
|
||||
# Error: Attempt delete associated route table.
|
||||
|
|
@ -255,7 +265,8 @@ def test_route_table_replace_route_table_association():
|
|||
route_table1.associations[0].subnet_id.should.equal(subnet.id)
|
||||
|
||||
# Replace Association
|
||||
association_id2 = conn.replace_route_table_association_with_assoc(association_id1, route_table2.id)
|
||||
association_id2 = conn.replace_route_table_association_with_assoc(
|
||||
association_id1, route_table2.id)
|
||||
|
||||
# Refresh
|
||||
route_table1 = conn.get_all_route_tables(route_table1.id)[0]
|
||||
|
|
@ -271,19 +282,22 @@ def test_route_table_replace_route_table_association():
|
|||
route_table2.associations[0].subnet_id.should.equal(subnet.id)
|
||||
|
||||
# Replace Association is idempotent
|
||||
association_id_idempotent = conn.replace_route_table_association_with_assoc(association_id2, route_table2.id)
|
||||
association_id_idempotent = conn.replace_route_table_association_with_assoc(
|
||||
association_id2, route_table2.id)
|
||||
association_id_idempotent.should.equal(association_id2)
|
||||
|
||||
# Error: Replace association with invalid association ID
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.replace_route_table_association_with_assoc("rtbassoc-1234abcd", route_table1.id)
|
||||
conn.replace_route_table_association_with_assoc(
|
||||
"rtbassoc-1234abcd", route_table1.id)
|
||||
cm.exception.code.should.equal('InvalidAssociationID.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
# Error: Replace association with invalid route table ID
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.replace_route_table_association_with_assoc(association_id2, "rtb-1234abcd")
|
||||
conn.replace_route_table_association_with_assoc(
|
||||
association_id2, "rtb-1234abcd")
|
||||
cm.exception.code.should.equal('InvalidRouteTableID.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
|
@ -298,7 +312,8 @@ def test_route_table_get_by_tag():
|
|||
route_table = conn.create_route_table(vpc.id)
|
||||
route_table.add_tag('Name', 'TestRouteTable')
|
||||
|
||||
route_tables = conn.get_all_route_tables(filters={'tag:Name': 'TestRouteTable'})
|
||||
route_tables = conn.get_all_route_tables(
|
||||
filters={'tag:Name': 'TestRouteTable'})
|
||||
|
||||
route_tables.should.have.length_of(1)
|
||||
route_tables[0].vpc_id.should.equal(vpc.id)
|
||||
|
|
@ -323,7 +338,8 @@ def test_route_table_get_by_tag_boto3():
|
|||
route_tables[0].vpc_id.should.equal(vpc.id)
|
||||
route_tables[0].id.should.equal(route_table.id)
|
||||
route_tables[0].tags.should.have.length_of(1)
|
||||
route_tables[0].tags[0].should.equal({'Key': 'Name', 'Value': 'TestRouteTable'})
|
||||
route_tables[0].tags[0].should.equal(
|
||||
{'Key': 'Name', 'Value': 'TestRouteTable'})
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -337,10 +353,12 @@ def test_routes_additional():
|
|||
|
||||
conn.create_route(main_route_table.id, ROUTE_CIDR, gateway_id=igw.id)
|
||||
|
||||
main_route_table = conn.get_all_route_tables(filters={'vpc-id': vpc.id})[0] # Refresh route table
|
||||
main_route_table = conn.get_all_route_tables(
|
||||
filters={'vpc-id': vpc.id})[0] # Refresh route table
|
||||
|
||||
main_route_table.routes.should.have.length_of(2)
|
||||
new_routes = [route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes = [
|
||||
route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes.should.have.length_of(1)
|
||||
|
||||
new_route = new_routes[0]
|
||||
|
|
@ -351,10 +369,12 @@ def test_routes_additional():
|
|||
|
||||
conn.delete_route(main_route_table.id, ROUTE_CIDR)
|
||||
|
||||
main_route_table = conn.get_all_route_tables(filters={'vpc-id': vpc.id})[0] # Refresh route table
|
||||
main_route_table = conn.get_all_route_tables(
|
||||
filters={'vpc-id': vpc.id})[0] # Refresh route table
|
||||
|
||||
main_route_table.routes.should.have.length_of(1)
|
||||
new_routes = [route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes = [
|
||||
route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes.should.have.length_of(0)
|
||||
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
|
|
@ -368,7 +388,8 @@ def test_routes_additional():
|
|||
def test_routes_replace():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
main_route_table = conn.get_all_route_tables(filters={'association.main':'true','vpc-id':vpc.id})[0]
|
||||
main_route_table = conn.get_all_route_tables(
|
||||
filters={'association.main': 'true', 'vpc-id': vpc.id})[0]
|
||||
local_route = main_route_table.routes[0]
|
||||
ROUTE_CIDR = "10.0.0.4/24"
|
||||
|
||||
|
|
@ -384,11 +405,13 @@ def test_routes_replace():
|
|||
# Replace...
|
||||
def get_target_route():
|
||||
route_table = conn.get_all_route_tables(main_route_table.id)[0]
|
||||
routes = [route for route in route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
routes = [
|
||||
route for route in route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
routes.should.have.length_of(1)
|
||||
return routes[0]
|
||||
|
||||
conn.replace_route(main_route_table.id, ROUTE_CIDR, instance_id=instance.id)
|
||||
conn.replace_route(main_route_table.id, ROUTE_CIDR,
|
||||
instance_id=instance.id)
|
||||
|
||||
target_route = get_target_route()
|
||||
target_route.gateway_id.should.be.none
|
||||
|
|
@ -422,12 +445,14 @@ def test_routes_not_supported():
|
|||
ROUTE_CIDR = "10.0.0.4/24"
|
||||
|
||||
# Create
|
||||
conn.create_route.when.called_with(main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError)
|
||||
conn.create_route.when.called_with(
|
||||
main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError)
|
||||
|
||||
# Replace
|
||||
igw = conn.create_internet_gateway()
|
||||
conn.create_route(main_route_table.id, ROUTE_CIDR, gateway_id=igw.id)
|
||||
conn.replace_route.when.called_with(main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError)
|
||||
conn.replace_route.when.called_with(
|
||||
main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError)
|
||||
|
||||
|
||||
@requires_boto_gte("2.34.0")
|
||||
|
|
@ -435,18 +460,21 @@ def test_routes_not_supported():
|
|||
def test_routes_vpc_peering_connection():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
main_route_table = conn.get_all_route_tables(filters={'association.main':'true','vpc-id':vpc.id})[0]
|
||||
main_route_table = conn.get_all_route_tables(
|
||||
filters={'association.main': 'true', 'vpc-id': vpc.id})[0]
|
||||
local_route = main_route_table.routes[0]
|
||||
ROUTE_CIDR = "10.0.0.4/24"
|
||||
|
||||
peer_vpc = conn.create_vpc("11.0.0.0/16")
|
||||
vpc_pcx = conn.create_vpc_peering_connection(vpc.id, peer_vpc.id)
|
||||
|
||||
conn.create_route(main_route_table.id, ROUTE_CIDR, vpc_peering_connection_id=vpc_pcx.id)
|
||||
conn.create_route(main_route_table.id, ROUTE_CIDR,
|
||||
vpc_peering_connection_id=vpc_pcx.id)
|
||||
|
||||
# Refresh route table
|
||||
main_route_table = conn.get_all_route_tables(main_route_table.id)[0]
|
||||
new_routes = [route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes = [
|
||||
route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes.should.have.length_of(1)
|
||||
|
||||
new_route = new_routes[0]
|
||||
|
|
@ -463,7 +491,8 @@ def test_routes_vpn_gateway():
|
|||
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
main_route_table = conn.get_all_route_tables(filters={'association.main':'true','vpc-id':vpc.id})[0]
|
||||
main_route_table = conn.get_all_route_tables(
|
||||
filters={'association.main': 'true', 'vpc-id': vpc.id})[0]
|
||||
ROUTE_CIDR = "10.0.0.4/24"
|
||||
|
||||
vpn_gw = conn.create_vpn_gateway(type="ipsec.1")
|
||||
|
|
@ -471,7 +500,8 @@ def test_routes_vpn_gateway():
|
|||
conn.create_route(main_route_table.id, ROUTE_CIDR, gateway_id=vpn_gw.id)
|
||||
|
||||
main_route_table = conn.get_all_route_tables(main_route_table.id)[0]
|
||||
new_routes = [route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes = [
|
||||
route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block]
|
||||
new_routes.should.have.length_of(1)
|
||||
|
||||
new_route = new_routes[0]
|
||||
|
|
|
|||
|
|
@ -20,25 +20,30 @@ def test_create_and_describe_security_group():
|
|||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
security_group = conn.create_security_group('test security group', 'this is a test security group', dry_run=True)
|
||||
security_group = conn.create_security_group(
|
||||
'test security group', 'this is a test security group', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
security_group = conn.create_security_group('test security group', 'this is a test security group')
|
||||
security_group = conn.create_security_group(
|
||||
'test security group', 'this is a test security group')
|
||||
|
||||
security_group.name.should.equal('test 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:
|
||||
conn.create_security_group('test security group', 'this is a test security group')
|
||||
conn.create_security_group(
|
||||
'test security group', 'this is a test security group')
|
||||
cm.exception.code.should.equal('InvalidGroup.Duplicate')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
all_groups = conn.get_all_security_groups()
|
||||
all_groups.should.have.length_of(3) # The default group gets created automatically
|
||||
# The default group gets created automatically
|
||||
all_groups.should.have.length_of(3)
|
||||
group_names = [group.name for group in all_groups]
|
||||
set(group_names).should.equal(set(["default", "test security group"]))
|
||||
|
||||
|
|
@ -66,16 +71,19 @@ def test_default_security_group():
|
|||
def test_create_and_describe_vpc_security_group():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
vpc_id = 'vpc-5300000c'
|
||||
security_group = conn.create_security_group('test security group', 'this is a test security group', vpc_id=vpc_id)
|
||||
security_group = conn.create_security_group(
|
||||
'test security group', 'this is a test security group', vpc_id=vpc_id)
|
||||
|
||||
security_group.vpc_id.should.equal(vpc_id)
|
||||
|
||||
security_group.name.should.equal('test security group')
|
||||
security_group.description.should.equal('this is a test security group')
|
||||
|
||||
# Trying to create another group with the same name in the same VPC should throw an error
|
||||
# Trying to create another group with the same name in the same VPC should
|
||||
# throw an error
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.create_security_group('test security group', 'this is a test security group', vpc_id)
|
||||
conn.create_security_group(
|
||||
'test security group', 'this is a test security group', vpc_id)
|
||||
cm.exception.code.should.equal('InvalidGroup.Duplicate')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
|
@ -94,8 +102,10 @@ def test_create_two_security_groups_with_same_name_in_different_vpc():
|
|||
vpc_id = 'vpc-5300000c'
|
||||
vpc_id2 = 'vpc-5300000d'
|
||||
|
||||
conn.create_security_group('test security group', 'this is a test security group', vpc_id)
|
||||
conn.create_security_group('test security group', 'this is a test security group', vpc_id2)
|
||||
conn.create_security_group(
|
||||
'test security group', 'this is a test security group', vpc_id)
|
||||
conn.create_security_group(
|
||||
'test security group', 'this is a test security group', vpc_id2)
|
||||
|
||||
all_groups = conn.get_all_security_groups()
|
||||
|
||||
|
|
@ -125,7 +135,8 @@ def test_deleting_security_groups():
|
|||
conn.delete_security_group('test2', dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteSecurityGroup operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.delete_security_group('test2')
|
||||
conn.get_all_security_groups().should.have.length_of(3)
|
||||
|
|
@ -151,65 +162,83 @@ def test_authorize_ip_range_and_revoke():
|
|||
security_group = conn.create_security_group('test', 'test')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
success = security_group.authorize(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
success = security_group.authorize(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the GrantSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the GrantSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
success = security_group.authorize(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
success = security_group.authorize(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
assert success.should.be.true
|
||||
|
||||
security_group = conn.get_all_security_groups(groupnames=['test'])[0]
|
||||
int(security_group.rules[0].to_port).should.equal(2222)
|
||||
security_group.rules[0].grants[0].cidr_ip.should.equal("123.123.123.123/32")
|
||||
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:
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.122/32")
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22",
|
||||
to_port="2222", cidr_ip="123.123.123.122/32")
|
||||
cm.exception.code.should.equal('InvalidPermission.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
# Actually revoke
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22",
|
||||
to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the RevokeSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the RevokeSecurityGroupIngress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22",
|
||||
to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
|
||||
security_group = conn.get_all_security_groups()[0]
|
||||
security_group.rules.should.have.length_of(0)
|
||||
|
||||
# Test for egress as well
|
||||
egress_security_group = conn.create_security_group('testegress', 'testegress', vpc_id='vpc-3432589')
|
||||
egress_security_group = conn.create_security_group(
|
||||
'testegress', 'testegress', vpc_id='vpc-3432589')
|
||||
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
success = conn.authorize_security_group_egress(egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
success = conn.authorize_security_group_egress(
|
||||
egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the GrantSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the GrantSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
success = conn.authorize_security_group_egress(egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
success = conn.authorize_security_group_egress(
|
||||
egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
assert success.should.be.true
|
||||
egress_security_group = conn.get_all_security_groups(groupnames='testegress')[0]
|
||||
egress_security_group = conn.get_all_security_groups(
|
||||
groupnames='testegress')[0]
|
||||
# There are two egress rules associated with the security group:
|
||||
# the default outbound rule and the new one
|
||||
int(egress_security_group.rules_egress[1].to_port).should.equal(2222)
|
||||
egress_security_group.rules_egress[1].grants[0].cidr_ip.should.equal("123.123.123.123/32")
|
||||
egress_security_group.rules_egress[1].grants[
|
||||
0].cidr_ip.should.equal("123.123.123.123/32")
|
||||
|
||||
# Wrong Cidr should throw error
|
||||
egress_security_group.revoke.when.called_with(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.122/32").should.throw(EC2ResponseError)
|
||||
egress_security_group.revoke.when.called_with(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.122/32").should.throw(EC2ResponseError)
|
||||
|
||||
# Actually revoke
|
||||
with assert_raises(EC2ResponseError) as ex:
|
||||
conn.revoke_security_group_egress(egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
conn.revoke_security_group_egress(
|
||||
egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the RevokeSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the RevokeSecurityGroupEgress operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.revoke_security_group_egress(egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
conn.revoke_security_group_egress(
|
||||
egress_security_group.id, "tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123/32")
|
||||
|
||||
egress_security_group = conn.get_all_security_groups()[0]
|
||||
# There is still the default outbound rule
|
||||
|
|
@ -223,24 +252,30 @@ def test_authorize_other_group_and_revoke():
|
|||
other_security_group = conn.create_security_group('other', 'other')
|
||||
wrong_group = conn.create_security_group('wrong', 'wrong')
|
||||
|
||||
success = security_group.authorize(ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
success = security_group.authorize(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
assert success.should.be.true
|
||||
|
||||
security_group = [group for group in conn.get_all_security_groups() if group.name == 'test'][0]
|
||||
security_group = [
|
||||
group for group in conn.get_all_security_groups() if group.name == 'test'][0]
|
||||
int(security_group.rules[0].to_port).should.equal(2222)
|
||||
security_group.rules[0].grants[0].group_id.should.equal(other_security_group.id)
|
||||
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:
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", src_group=wrong_group)
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22",
|
||||
to_port="2222", src_group=wrong_group)
|
||||
cm.exception.code.should.equal('InvalidPermission.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
# Actually revoke
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
security_group.revoke(ip_protocol="tcp", from_port="22",
|
||||
to_port="2222", src_group=other_security_group)
|
||||
|
||||
security_group = [group for group in conn.get_all_security_groups() if group.name == 'test'][0]
|
||||
security_group = [
|
||||
group for group in conn.get_all_security_groups() if group.name == 'test'][0]
|
||||
security_group.rules.should.have.length_of(0)
|
||||
|
||||
|
||||
|
|
@ -250,8 +285,10 @@ def test_authorize_other_group_egress_and_revoke():
|
|||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
|
||||
sg01 = ec2.create_security_group(GroupName='sg01', Description='Test security group sg01', VpcId=vpc.id)
|
||||
sg02 = ec2.create_security_group(GroupName='sg02', Description='Test security group sg02', VpcId=vpc.id)
|
||||
sg01 = ec2.create_security_group(
|
||||
GroupName='sg01', Description='Test security group sg01', VpcId=vpc.id)
|
||||
sg02 = ec2.create_security_group(
|
||||
GroupName='sg02', Description='Test security group sg02', VpcId=vpc.id)
|
||||
|
||||
ip_permission = {
|
||||
'IpProtocol': 'tcp',
|
||||
|
|
@ -278,27 +315,33 @@ def test_authorize_group_in_vpc():
|
|||
security_group = conn.create_security_group('test1', 'test1', vpc_id)
|
||||
other_security_group = conn.create_security_group('test2', 'test2', vpc_id)
|
||||
|
||||
success = security_group.authorize(ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
success = security_group.authorize(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
success.should.be.true
|
||||
|
||||
# Check that the rule is accurate
|
||||
security_group = [group for group in conn.get_all_security_groups() if group.name == 'test1'][0]
|
||||
security_group = [
|
||||
group for group in conn.get_all_security_groups() if group.name == 'test1'][0]
|
||||
int(security_group.rules[0].to_port).should.equal(2222)
|
||||
security_group.rules[0].grants[0].group_id.should.equal(other_security_group.id)
|
||||
security_group.rules[0].grants[
|
||||
0].group_id.should.equal(other_security_group.id)
|
||||
|
||||
# Now remove the rule
|
||||
success = security_group.revoke(ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
success = security_group.revoke(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", src_group=other_security_group)
|
||||
success.should.be.true
|
||||
|
||||
# And check that it gets revoked
|
||||
security_group = [group for group in conn.get_all_security_groups() if group.name == 'test1'][0]
|
||||
security_group = [
|
||||
group for group in conn.get_all_security_groups() if group.name == 'test1'][0]
|
||||
security_group.rules.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_all_security_groups():
|
||||
conn = boto.connect_ec2()
|
||||
sg1 = conn.create_security_group(name='test1', description='test1', vpc_id='vpc-mjm05d27')
|
||||
sg1 = conn.create_security_group(
|
||||
name='test1', description='test1', vpc_id='vpc-mjm05d27')
|
||||
conn.create_security_group(name='test2', description='test2')
|
||||
|
||||
resp = conn.get_all_security_groups(groupnames=['test1'])
|
||||
|
|
@ -326,7 +369,8 @@ 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:
|
||||
security_group.authorize(ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123")
|
||||
security_group.authorize(
|
||||
ip_protocol="tcp", from_port="22", to_port="2222", cidr_ip="123.123.123.123")
|
||||
cm.exception.code.should.equal('InvalidParameterValue')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
|
@ -343,7 +387,8 @@ def test_security_group_tagging():
|
|||
sg.add_tag("Test", "Tag", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
sg.add_tag("Test", "Tag")
|
||||
|
||||
|
|
@ -362,7 +407,8 @@ def test_security_group_tag_filtering():
|
|||
sg = conn.create_security_group("test-sg", "Test SG")
|
||||
sg.add_tag("test-tag", "test-value")
|
||||
|
||||
groups = conn.get_all_security_groups(filters={"tag:test-tag": "test-value"})
|
||||
groups = conn.get_all_security_groups(
|
||||
filters={"tag:test-tag": "test-value"})
|
||||
groups.should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
@ -507,18 +553,18 @@ def test_sec_group_rule_limit_vpc():
|
|||
cm.exception.error_code.should.equal('RulesPerSecurityGroupLimitExceeded')
|
||||
|
||||
|
||||
|
||||
|
||||
'''
|
||||
Boto3
|
||||
'''
|
||||
|
||||
|
||||
@mock_ec2
|
||||
def test_add_same_rule_twice_throws_error():
|
||||
ec2 = boto3.resource('ec2', region_name='us-west-1')
|
||||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
sg = ec2.create_security_group(GroupName='sg1', Description='Test security group sg1', VpcId=vpc.id)
|
||||
sg = ec2.create_security_group(
|
||||
GroupName='sg1', Description='Test security group sg1', VpcId=vpc.id)
|
||||
|
||||
ip_permissions = [
|
||||
{
|
||||
|
|
@ -541,13 +587,18 @@ def test_security_group_tagging_boto3():
|
|||
sg = conn.create_security_group(GroupName="test-sg", Description="Test SG")
|
||||
|
||||
with assert_raises(ClientError) as ex:
|
||||
conn.create_tags(Resources=[sg['GroupId']], Tags=[{'Key': 'Test', 'Value': 'Tag'}], DryRun=True)
|
||||
conn.create_tags(Resources=[sg['GroupId']], Tags=[
|
||||
{'Key': 'Test', 'Value': 'Tag'}], DryRun=True)
|
||||
ex.exception.response['Error']['Code'].should.equal('DryRunOperation')
|
||||
ex.exception.response['ResponseMetadata']['HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.response['ResponseMetadata'][
|
||||
'HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.create_tags(Resources=[sg['GroupId']], Tags=[{'Key': 'Test', 'Value': 'Tag'}])
|
||||
describe = conn.describe_security_groups(Filters=[{'Name': 'tag-value', 'Values': ['Tag']}])
|
||||
conn.create_tags(Resources=[sg['GroupId']], Tags=[
|
||||
{'Key': 'Test', 'Value': 'Tag'}])
|
||||
describe = conn.describe_security_groups(
|
||||
Filters=[{'Name': 'tag-value', 'Values': ['Tag']}])
|
||||
tag = describe["SecurityGroups"][0]['Tags'][0]
|
||||
tag['Value'].should.equal("Tag")
|
||||
tag['Key'].should.equal("Test")
|
||||
|
|
@ -559,9 +610,12 @@ def test_authorize_and_revoke_in_bulk():
|
|||
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
|
||||
sg01 = ec2.create_security_group(GroupName='sg01', Description='Test security group sg01', VpcId=vpc.id)
|
||||
sg02 = ec2.create_security_group(GroupName='sg02', Description='Test security group sg02', VpcId=vpc.id)
|
||||
sg03 = ec2.create_security_group(GroupName='sg03', Description='Test security group sg03')
|
||||
sg01 = ec2.create_security_group(
|
||||
GroupName='sg01', Description='Test security group sg01', VpcId=vpc.id)
|
||||
sg02 = ec2.create_security_group(
|
||||
GroupName='sg02', Description='Test security group sg02', VpcId=vpc.id)
|
||||
sg03 = ec2.create_security_group(
|
||||
GroupName='sg03', Description='Test security group sg03')
|
||||
|
||||
ip_permissions = [
|
||||
{
|
||||
|
|
@ -611,15 +665,19 @@ def test_authorize_and_revoke_in_bulk():
|
|||
for ip_permission in expected_ip_permissions:
|
||||
sg01.ip_permissions_egress.shouldnt.contain(ip_permission)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_get_all_security_groups_filter_with_same_vpc_id():
|
||||
conn = boto.connect_ec2('the_key', 'the_secret')
|
||||
vpc_id = 'vpc-5300000c'
|
||||
security_group = conn.create_security_group('test1', 'test1', vpc_id=vpc_id)
|
||||
security_group2 = conn.create_security_group('test2', 'test2', vpc_id=vpc_id)
|
||||
security_group = conn.create_security_group(
|
||||
'test1', 'test1', vpc_id=vpc_id)
|
||||
security_group2 = conn.create_security_group(
|
||||
'test2', 'test2', vpc_id=vpc_id)
|
||||
|
||||
security_group.vpc_id.should.equal(vpc_id)
|
||||
security_group2.vpc_id.should.equal(vpc_id)
|
||||
|
||||
security_groups = conn.get_all_security_groups(group_ids=[security_group.id], filters={'vpc-id': [vpc_id]})
|
||||
security_groups = conn.get_all_security_groups(
|
||||
group_ids=[security_group.id], filters={'vpc-id': [vpc_id]})
|
||||
security_groups.should.have.length_of(1)
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ def test_ec2_server_get():
|
|||
headers={"Host": "ec2.us-east-1.amazonaws.com"}
|
||||
)
|
||||
|
||||
groups = re.search("<instanceId>(.*)</instanceId>", res.data.decode('utf-8'))
|
||||
groups = re.search("<instanceId>(.*)</instanceId>",
|
||||
res.data.decode('utf-8'))
|
||||
instance_id = groups.groups()[0]
|
||||
|
||||
res = test_client.get('/?Action=DescribeInstances')
|
||||
|
|
|
|||
|
|
@ -5,9 +5,11 @@ import sure # noqa
|
|||
|
||||
from moto import mock_ec2
|
||||
|
||||
|
||||
def get_subnet_id(conn):
|
||||
vpc = conn.create_vpc(CidrBlock="10.0.0.0/8")['Vpc']
|
||||
subnet = conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet = conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet_id = subnet['SubnetId']
|
||||
return subnet_id
|
||||
|
||||
|
|
@ -19,60 +21,60 @@ def spot_config(subnet_id, allocation_strategy="lowestPrice"):
|
|||
'TargetCapacity': 6,
|
||||
'IamFleetRole': 'arn:aws:iam::123456789012:role/fleet',
|
||||
'LaunchSpecifications': [{
|
||||
'ImageId': 'ami-123',
|
||||
'KeyName': 'my-key',
|
||||
'SecurityGroups': [
|
||||
{
|
||||
'ImageId': 'ami-123',
|
||||
'KeyName': 'my-key',
|
||||
'SecurityGroups': [
|
||||
{
|
||||
'GroupId': 'sg-123'
|
||||
},
|
||||
],
|
||||
'UserData': 'some user data',
|
||||
'InstanceType': 't2.small',
|
||||
'BlockDeviceMappings': [
|
||||
{
|
||||
},
|
||||
],
|
||||
'UserData': 'some user data',
|
||||
'InstanceType': 't2.small',
|
||||
'BlockDeviceMappings': [
|
||||
{
|
||||
'VirtualName': 'string',
|
||||
'DeviceName': 'string',
|
||||
'Ebs': {
|
||||
'SnapshotId': 'string',
|
||||
'VolumeSize': 123,
|
||||
'DeleteOnTermination': True|False,
|
||||
'DeleteOnTermination': True | False,
|
||||
'VolumeType': 'standard',
|
||||
'Iops': 123,
|
||||
'Encrypted': True|False
|
||||
'Encrypted': True | False
|
||||
},
|
||||
'NoDevice': 'string'
|
||||
},
|
||||
],
|
||||
'Monitoring': {
|
||||
'Enabled': True
|
||||
'NoDevice': 'string'
|
||||
},
|
||||
'SubnetId': subnet_id,
|
||||
'IamInstanceProfile': {
|
||||
'Arn': 'arn:aws:iam::123456789012:role/fleet'
|
||||
},
|
||||
'EbsOptimized': False,
|
||||
'WeightedCapacity': 2.0,
|
||||
'SpotPrice': '0.13'
|
||||
],
|
||||
'Monitoring': {
|
||||
'Enabled': True
|
||||
},
|
||||
'SubnetId': subnet_id,
|
||||
'IamInstanceProfile': {
|
||||
'Arn': 'arn:aws:iam::123456789012:role/fleet'
|
||||
},
|
||||
'EbsOptimized': False,
|
||||
'WeightedCapacity': 2.0,
|
||||
'SpotPrice': '0.13'
|
||||
}, {
|
||||
'ImageId': 'ami-123',
|
||||
'KeyName': 'my-key',
|
||||
'SecurityGroups': [
|
||||
{
|
||||
'GroupId': 'sg-123'
|
||||
},
|
||||
],
|
||||
'UserData': 'some user data',
|
||||
'InstanceType': 't2.large',
|
||||
'Monitoring': {
|
||||
'Enabled': True
|
||||
'ImageId': 'ami-123',
|
||||
'KeyName': 'my-key',
|
||||
'SecurityGroups': [
|
||||
{
|
||||
'GroupId': 'sg-123'
|
||||
},
|
||||
'SubnetId': subnet_id,
|
||||
'IamInstanceProfile': {
|
||||
'Arn': 'arn:aws:iam::123456789012:role/fleet'
|
||||
},
|
||||
'EbsOptimized': False,
|
||||
'WeightedCapacity': 4.0,
|
||||
'SpotPrice': '10.00',
|
||||
],
|
||||
'UserData': 'some user data',
|
||||
'InstanceType': 't2.large',
|
||||
'Monitoring': {
|
||||
'Enabled': True
|
||||
},
|
||||
'SubnetId': subnet_id,
|
||||
'IamInstanceProfile': {
|
||||
'Arn': 'arn:aws:iam::123456789012:role/fleet'
|
||||
},
|
||||
'EbsOptimized': False,
|
||||
'WeightedCapacity': 4.0,
|
||||
'SpotPrice': '10.00',
|
||||
}],
|
||||
'AllocationStrategy': allocation_strategy,
|
||||
'FulfilledCapacity': 6,
|
||||
|
|
@ -89,7 +91,8 @@ def test_create_spot_fleet_with_lowest_price():
|
|||
)
|
||||
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
|
||||
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(
|
||||
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
len(spot_fleet_requests).should.equal(1)
|
||||
spot_fleet_request = spot_fleet_requests[0]
|
||||
spot_fleet_request['SpotFleetRequestState'].should.equal("active")
|
||||
|
|
@ -97,7 +100,8 @@ def test_create_spot_fleet_with_lowest_price():
|
|||
|
||||
spot_fleet_config['SpotPrice'].should.equal('0.12')
|
||||
spot_fleet_config['TargetCapacity'].should.equal(6)
|
||||
spot_fleet_config['IamFleetRole'].should.equal('arn:aws:iam::123456789012:role/fleet')
|
||||
spot_fleet_config['IamFleetRole'].should.equal(
|
||||
'arn:aws:iam::123456789012:role/fleet')
|
||||
spot_fleet_config['AllocationStrategy'].should.equal('lowestPrice')
|
||||
spot_fleet_config['FulfilledCapacity'].should.equal(6.0)
|
||||
|
||||
|
|
@ -106,7 +110,8 @@ def test_create_spot_fleet_with_lowest_price():
|
|||
|
||||
launch_spec['EbsOptimized'].should.equal(False)
|
||||
launch_spec['SecurityGroups'].should.equal([{"GroupId": "sg-123"}])
|
||||
launch_spec['IamInstanceProfile'].should.equal({"Arn": "arn:aws:iam::123456789012:role/fleet"})
|
||||
launch_spec['IamInstanceProfile'].should.equal(
|
||||
{"Arn": "arn:aws:iam::123456789012:role/fleet"})
|
||||
launch_spec['ImageId'].should.equal("ami-123")
|
||||
launch_spec['InstanceType'].should.equal("t2.small")
|
||||
launch_spec['KeyName'].should.equal("my-key")
|
||||
|
|
@ -116,7 +121,8 @@ def test_create_spot_fleet_with_lowest_price():
|
|||
launch_spec['UserData'].should.equal("some user data")
|
||||
launch_spec['WeightedCapacity'].should.equal(2.0)
|
||||
|
||||
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
|
||||
instance_res = conn.describe_spot_fleet_instances(
|
||||
SpotFleetRequestId=spot_fleet_id)
|
||||
instances = instance_res['ActiveInstances']
|
||||
len(instances).should.equal(3)
|
||||
|
||||
|
|
@ -125,14 +131,16 @@ def test_create_spot_fleet_with_lowest_price():
|
|||
def test_create_diversified_spot_fleet():
|
||||
conn = boto3.client("ec2", region_name='us-west-2')
|
||||
subnet_id = get_subnet_id(conn)
|
||||
diversified_config = spot_config(subnet_id, allocation_strategy='diversified')
|
||||
diversified_config = spot_config(
|
||||
subnet_id, allocation_strategy='diversified')
|
||||
|
||||
spot_fleet_res = conn.request_spot_fleet(
|
||||
SpotFleetRequestConfig=diversified_config
|
||||
)
|
||||
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
|
||||
|
||||
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
|
||||
instance_res = conn.describe_spot_fleet_instances(
|
||||
SpotFleetRequestId=spot_fleet_id)
|
||||
instances = instance_res['ActiveInstances']
|
||||
len(instances).should.equal(2)
|
||||
instance_types = set([instance['InstanceType'] for instance in instances])
|
||||
|
|
@ -150,7 +158,9 @@ def test_cancel_spot_fleet_request():
|
|||
)
|
||||
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
|
||||
|
||||
conn.cancel_spot_fleet_requests(SpotFleetRequestIds=[spot_fleet_id], TerminateInstances=True)
|
||||
conn.cancel_spot_fleet_requests(
|
||||
SpotFleetRequestIds=[spot_fleet_id], TerminateInstances=True)
|
||||
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
spot_fleet_requests = conn.describe_spot_fleet_requests(
|
||||
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
|
||||
len(spot_fleet_requests).should.equal(0)
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ from moto.core.utils import iso_8601_datetime_with_milliseconds
|
|||
def test_request_spot_instances():
|
||||
conn = boto3.client('ec2', 'us-east-1')
|
||||
vpc = conn.create_vpc(CidrBlock="10.0.0.0/8")['Vpc']
|
||||
subnet = conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet = conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
|
||||
subnet_id = subnet['SubnetId']
|
||||
|
||||
conn.create_security_group(GroupName='group1', Description='description')
|
||||
|
|
@ -53,29 +54,31 @@ def test_request_spot_instances():
|
|||
DryRun=True,
|
||||
)
|
||||
ex.exception.response['Error']['Code'].should.equal('DryRunOperation')
|
||||
ex.exception.response['ResponseMetadata']['HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal('An error occurred (DryRunOperation) when calling the RequestSpotInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.response['ResponseMetadata'][
|
||||
'HTTPStatusCode'].should.equal(400)
|
||||
ex.exception.response['Error']['Message'].should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the RequestSpotInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
request = conn.request_spot_instances(
|
||||
SpotPrice="0.5", InstanceCount=1, Type='one-time',
|
||||
ValidFrom=start, ValidUntil=end, LaunchGroup="the-group",
|
||||
AvailabilityZoneGroup='my-group',
|
||||
LaunchSpecification={
|
||||
"ImageId": 'ami-abcd1234',
|
||||
"KeyName": "test",
|
||||
"SecurityGroups": ['group1', 'group2'],
|
||||
"UserData": b"some test data",
|
||||
"InstanceType": 'm1.small',
|
||||
"Placement": {
|
||||
"AvailabilityZone": 'us-east-1c',
|
||||
},
|
||||
"KernelId": "test-kernel",
|
||||
"RamdiskId": "test-ramdisk",
|
||||
"Monitoring": {
|
||||
"Enabled": True,
|
||||
},
|
||||
"SubnetId": subnet_id,
|
||||
SpotPrice="0.5", InstanceCount=1, Type='one-time',
|
||||
ValidFrom=start, ValidUntil=end, LaunchGroup="the-group",
|
||||
AvailabilityZoneGroup='my-group',
|
||||
LaunchSpecification={
|
||||
"ImageId": 'ami-abcd1234',
|
||||
"KeyName": "test",
|
||||
"SecurityGroups": ['group1', 'group2'],
|
||||
"UserData": b"some test data",
|
||||
"InstanceType": 'm1.small',
|
||||
"Placement": {
|
||||
"AvailabilityZone": 'us-east-1c',
|
||||
},
|
||||
"KernelId": "test-kernel",
|
||||
"RamdiskId": "test-ramdisk",
|
||||
"Monitoring": {
|
||||
"Enabled": True,
|
||||
},
|
||||
"SubnetId": subnet_id,
|
||||
},
|
||||
)
|
||||
|
||||
requests = conn.describe_spot_instance_requests()['SpotInstanceRequests']
|
||||
|
|
@ -91,7 +94,8 @@ def test_request_spot_instances():
|
|||
request['AvailabilityZoneGroup'].should.equal('my-group')
|
||||
|
||||
launch_spec = request['LaunchSpecification']
|
||||
security_group_names = [group['GroupName'] for group in launch_spec['SecurityGroups']]
|
||||
security_group_names = [group['GroupName']
|
||||
for group in launch_spec['SecurityGroups']]
|
||||
set(security_group_names).should.equal(set(['group1', 'group2']))
|
||||
|
||||
launch_spec['ImageId'].should.equal('ami-abcd1234')
|
||||
|
|
@ -112,7 +116,7 @@ def test_request_spot_instances_default_arguments():
|
|||
request = conn.request_spot_instances(
|
||||
SpotPrice="0.5",
|
||||
LaunchSpecification={
|
||||
"ImageId": 'ami-abcd1234',
|
||||
"ImageId": 'ami-abcd1234',
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -130,7 +134,8 @@ def test_request_spot_instances_default_arguments():
|
|||
|
||||
launch_spec = request['LaunchSpecification']
|
||||
|
||||
security_group_names = [group['GroupName'] for group in launch_spec['SecurityGroups']]
|
||||
security_group_names = [group['GroupName']
|
||||
for group in launch_spec['SecurityGroups']]
|
||||
security_group_names.should.equal(["default"])
|
||||
|
||||
launch_spec['ImageId'].should.equal('ami-abcd1234')
|
||||
|
|
@ -152,12 +157,12 @@ 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:
|
||||
conn.cancel_spot_instance_requests([requests[0].id], dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CancelSpotInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CancelSpotInstance operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.cancel_spot_instance_requests([requests[0].id])
|
||||
|
||||
|
|
@ -239,10 +244,12 @@ def test_get_all_spot_instance_requests_filtering():
|
|||
requests = conn.get_all_spot_instance_requests(filters={'state': 'open'})
|
||||
requests.should.have.length_of(3)
|
||||
|
||||
requests = conn.get_all_spot_instance_requests(filters={'tag:tag1': 'value1'})
|
||||
requests = conn.get_all_spot_instance_requests(
|
||||
filters={'tag:tag1': 'value1'})
|
||||
requests.should.have.length_of(2)
|
||||
|
||||
requests = conn.get_all_spot_instance_requests(filters={'tag:tag1': 'value1', 'tag:tag2': 'value2'})
|
||||
requests = conn.get_all_spot_instance_requests(
|
||||
filters={'tag:tag1': 'value1', 'tag:tag2': 'value2'})
|
||||
requests.should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
@ -259,4 +266,3 @@ def test_request_spot_instances_setting_instance_id():
|
|||
request = conn.get_all_spot_instance_requests()[0]
|
||||
assert request.state == 'active'
|
||||
assert request.instance_id == 'i-12345678'
|
||||
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@ def test_subnet_tagging():
|
|||
def test_subnet_should_have_proper_availability_zone_set():
|
||||
conn = boto.vpc.connect_to_region('us-west-1')
|
||||
vpcA = conn.create_vpc("10.0.0.0/16")
|
||||
subnetA = conn.create_subnet(vpcA.id, "10.0.0.0/24", availability_zone='us-west-1b')
|
||||
subnetA = conn.create_subnet(
|
||||
vpcA.id, "10.0.0.0/24", availability_zone='us-west-1b')
|
||||
subnetA.availability_zone.should.equal('us-west-1b')
|
||||
|
||||
|
||||
|
|
@ -82,7 +83,8 @@ def test_default_subnet():
|
|||
default_vpc.reload()
|
||||
default_vpc.is_default.should.be.ok
|
||||
|
||||
subnet = ec2.create_subnet(VpcId=default_vpc.id, CidrBlock='172.31.0.0/20', AvailabilityZone='us-west-1a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=default_vpc.id, CidrBlock='172.31.0.0/20', AvailabilityZone='us-west-1a')
|
||||
subnet.reload()
|
||||
subnet.map_public_ip_on_launch.shouldnt.be.ok
|
||||
|
||||
|
|
@ -109,7 +111,8 @@ def test_boto3_non_default_subnet():
|
|||
vpc.reload()
|
||||
vpc.is_default.shouldnt.be.ok
|
||||
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
subnet.reload()
|
||||
subnet.map_public_ip_on_launch.shouldnt.be.ok
|
||||
|
||||
|
|
@ -122,7 +125,8 @@ def test_modify_subnet_attribute():
|
|||
# Get the default VPC
|
||||
vpc = list(ec2.vpcs.all())[0]
|
||||
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
|
||||
# 'map_public_ip_on_launch' is set when calling 'DescribeSubnets' action
|
||||
subnet.reload()
|
||||
|
|
@ -130,11 +134,13 @@ def test_modify_subnet_attribute():
|
|||
# For non default subnet, attribute value should be 'False'
|
||||
subnet.map_public_ip_on_launch.shouldnt.be.ok
|
||||
|
||||
client.modify_subnet_attribute(SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': False})
|
||||
client.modify_subnet_attribute(
|
||||
SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': False})
|
||||
subnet.reload()
|
||||
subnet.map_public_ip_on_launch.shouldnt.be.ok
|
||||
|
||||
client.modify_subnet_attribute(SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': True})
|
||||
client.modify_subnet_attribute(
|
||||
SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': True})
|
||||
subnet.reload()
|
||||
subnet.map_public_ip_on_launch.should.be.ok
|
||||
|
||||
|
|
@ -144,10 +150,12 @@ def test_modify_subnet_attribute_validation():
|
|||
ec2 = boto3.resource('ec2', region_name='us-west-1')
|
||||
client = boto3.client('ec2', region_name='us-west-1')
|
||||
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
|
||||
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
subnet = ec2.create_subnet(
|
||||
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
|
||||
|
||||
with assert_raises(ParamValidationError):
|
||||
client.modify_subnet_attribute(SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': 'invalid'})
|
||||
client.modify_subnet_attribute(
|
||||
SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': 'invalid'})
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -155,10 +163,13 @@ def test_get_subnets_filtering():
|
|||
ec2 = boto.ec2.connect_to_region('us-west-1')
|
||||
conn = boto.vpc.connect_to_region('us-west-1')
|
||||
vpcA = conn.create_vpc("10.0.0.0/16")
|
||||
subnetA = conn.create_subnet(vpcA.id, "10.0.0.0/24", availability_zone='us-west-1a')
|
||||
subnetA = conn.create_subnet(
|
||||
vpcA.id, "10.0.0.0/24", availability_zone='us-west-1a')
|
||||
vpcB = conn.create_vpc("10.0.0.0/16")
|
||||
subnetB1 = conn.create_subnet(vpcB.id, "10.0.0.0/24", availability_zone='us-west-1a')
|
||||
subnetB2 = conn.create_subnet(vpcB.id, "10.0.1.0/24", availability_zone='us-west-1b')
|
||||
subnetB1 = conn.create_subnet(
|
||||
vpcB.id, "10.0.0.0/24", availability_zone='us-west-1a')
|
||||
subnetB2 = conn.create_subnet(
|
||||
vpcB.id, "10.0.1.0/24", availability_zone='us-west-1b')
|
||||
|
||||
all_subnets = conn.get_all_subnets()
|
||||
all_subnets.should.have.length_of(3 + len(ec2.get_all_zones()))
|
||||
|
|
@ -166,25 +177,33 @@ def test_get_subnets_filtering():
|
|||
# Filter by VPC ID
|
||||
subnets_by_vpc = conn.get_all_subnets(filters={'vpc-id': vpcB.id})
|
||||
subnets_by_vpc.should.have.length_of(2)
|
||||
set([subnet.id for subnet in subnets_by_vpc]).should.equal(set([subnetB1.id, subnetB2.id]))
|
||||
set([subnet.id for subnet in subnets_by_vpc]).should.equal(
|
||||
set([subnetB1.id, subnetB2.id]))
|
||||
|
||||
# Filter by CIDR variations
|
||||
subnets_by_cidr1 = conn.get_all_subnets(filters={'cidr': "10.0.0.0/24"})
|
||||
subnets_by_cidr1.should.have.length_of(2)
|
||||
set([subnet.id for subnet in subnets_by_cidr1]).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
set([subnet.id for subnet in subnets_by_cidr1]
|
||||
).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
|
||||
subnets_by_cidr2 = conn.get_all_subnets(filters={'cidr-block': "10.0.0.0/24"})
|
||||
subnets_by_cidr2 = conn.get_all_subnets(
|
||||
filters={'cidr-block': "10.0.0.0/24"})
|
||||
subnets_by_cidr2.should.have.length_of(2)
|
||||
set([subnet.id for subnet in subnets_by_cidr2]).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
set([subnet.id for subnet in subnets_by_cidr2]
|
||||
).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
|
||||
subnets_by_cidr3 = conn.get_all_subnets(filters={'cidrBlock': "10.0.0.0/24"})
|
||||
subnets_by_cidr3 = conn.get_all_subnets(
|
||||
filters={'cidrBlock': "10.0.0.0/24"})
|
||||
subnets_by_cidr3.should.have.length_of(2)
|
||||
set([subnet.id for subnet in subnets_by_cidr3]).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
set([subnet.id for subnet in subnets_by_cidr3]
|
||||
).should.equal(set([subnetA.id, subnetB1.id]))
|
||||
|
||||
# Filter by VPC ID and CIDR
|
||||
subnets_by_vpc_and_cidr = conn.get_all_subnets(filters={'vpc-id': vpcB.id, 'cidr': "10.0.0.0/24"})
|
||||
subnets_by_vpc_and_cidr = conn.get_all_subnets(
|
||||
filters={'vpc-id': vpcB.id, 'cidr': "10.0.0.0/24"})
|
||||
subnets_by_vpc_and_cidr.should.have.length_of(1)
|
||||
set([subnet.id for subnet in subnets_by_vpc_and_cidr]).should.equal(set([subnetB1.id]))
|
||||
set([subnet.id for subnet in subnets_by_vpc_and_cidr]
|
||||
).should.equal(set([subnetB1.id]))
|
||||
|
||||
# Filter by subnet ID
|
||||
subnets_by_id = conn.get_all_subnets(filters={'subnet-id': subnetA.id})
|
||||
|
|
@ -192,9 +211,11 @@ def test_get_subnets_filtering():
|
|||
set([subnet.id for subnet in subnets_by_id]).should.equal(set([subnetA.id]))
|
||||
|
||||
# Filter by availabilityZone
|
||||
subnets_by_az = conn.get_all_subnets(filters={'availabilityZone': 'us-west-1a', 'vpc-id': vpcB.id})
|
||||
subnets_by_az = conn.get_all_subnets(
|
||||
filters={'availabilityZone': 'us-west-1a', 'vpc-id': vpcB.id})
|
||||
subnets_by_az.should.have.length_of(1)
|
||||
set([subnet.id for subnet in subnets_by_az]).should.equal(set([subnetB1.id]))
|
||||
set([subnet.id for subnet in subnets_by_az]
|
||||
).should.equal(set([subnetB1.id]))
|
||||
|
||||
# Filter by defaultForAz
|
||||
|
||||
|
|
@ -202,7 +223,8 @@ def test_get_subnets_filtering():
|
|||
subnets_by_az.should.have.length_of(len(conn.get_all_zones()))
|
||||
|
||||
# Unsupported filter
|
||||
conn.get_all_subnets.when.called_with(filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
conn.get_all_subnets.when.called_with(
|
||||
filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
|
|||
|
|
@ -22,11 +22,13 @@ def test_add_tag():
|
|||
instance.add_tag("a key", "some value", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.add_tag("a key", "some value")
|
||||
chain = itertools.chain.from_iterable
|
||||
existing_instances = list(chain([res.instances for res in conn.get_all_instances()]))
|
||||
existing_instances = list(
|
||||
chain([res.instances for res in conn.get_all_instances()]))
|
||||
existing_instances.should.have.length_of(1)
|
||||
existing_instance = existing_instances[0]
|
||||
existing_instance.tags["a key"].should.equal("some value")
|
||||
|
|
@ -49,7 +51,8 @@ def test_remove_tag():
|
|||
instance.remove_tag("a key", dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the DeleteTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the DeleteTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
instance.remove_tag("a key")
|
||||
conn.get_all_tags().should.have.length_of(0)
|
||||
|
|
@ -100,12 +103,15 @@ def test_create_tags():
|
|||
conn.create_tags(instance.id, tag_dict, dry_run=True)
|
||||
ex.exception.error_code.should.equal('DryRunOperation')
|
||||
ex.exception.status.should.equal(400)
|
||||
ex.exception.message.should.equal('An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
ex.exception.message.should.equal(
|
||||
'An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set')
|
||||
|
||||
conn.create_tags(instance.id, tag_dict)
|
||||
tags = conn.get_all_tags()
|
||||
set([key for key in tag_dict]).should.equal(set([tag.name for tag in tags]))
|
||||
set([tag_dict[key] for key in tag_dict]).should.equal(set([tag.value for tag in tags]))
|
||||
set([key for key in tag_dict]).should.equal(
|
||||
set([tag.name for tag in tags]))
|
||||
set([tag_dict[key] for key in tag_dict]).should.equal(
|
||||
set([tag.value for tag in tags]))
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -115,7 +121,7 @@ def test_tag_limit_exceeded():
|
|||
instance = reservation.instances[0]
|
||||
tag_dict = {}
|
||||
for i in range(51):
|
||||
tag_dict['{0:02d}'.format(i+1)] = ''
|
||||
tag_dict['{0:02d}'.format(i + 1)] = ''
|
||||
|
||||
with assert_raises(EC2ResponseError) as cm:
|
||||
conn.create_tags(instance.id, tag_dict)
|
||||
|
|
@ -342,7 +348,8 @@ def test_retrieved_snapshots_must_contain_their_tags():
|
|||
tag_key = 'Tag name'
|
||||
tag_value = 'Tag value'
|
||||
tags_to_be_set = {tag_key: tag_value}
|
||||
conn = boto.connect_ec2(aws_access_key_id='the_key', aws_secret_access_key='the_secret')
|
||||
conn = boto.connect_ec2(aws_access_key_id='the_key',
|
||||
aws_secret_access_key='the_secret')
|
||||
volume = conn.create_volume(80, "eu-west-1a")
|
||||
snapshot = conn.create_snapshot(volume.id)
|
||||
conn.create_tags([snapshot.id], tags_to_be_set)
|
||||
|
|
@ -361,7 +368,8 @@ def test_retrieved_snapshots_must_contain_their_tags():
|
|||
|
||||
@mock_ec2_deprecated
|
||||
def test_filter_instances_by_wildcard_tags():
|
||||
conn = boto.connect_ec2(aws_access_key_id='the_key', aws_secret_access_key='the_secret')
|
||||
conn = boto.connect_ec2(aws_access_key_id='the_key',
|
||||
aws_secret_access_key='the_secret')
|
||||
reservation = conn.run_instances('ami-1234abcd')
|
||||
instance_a = reservation.instances[0]
|
||||
instance_a.add_tag("Key1", "Value1")
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ def test_virtual_private_gateways():
|
|||
vpn_gateway.state.should.equal('available')
|
||||
vpn_gateway.availability_zone.should.equal('us-east-1a')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_describe_vpn_gateway():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
|
|
|||
|
|
@ -93,4 +93,3 @@ def test_vpc_peering_connections_delete():
|
|||
cm.exception.code.should.equal('InvalidVpcPeeringConnectionId.NotFound')
|
||||
cm.exception.status.should.equal(400)
|
||||
cm.exception.request_id.should_not.be.none
|
||||
|
||||
|
|
|
|||
|
|
@ -42,13 +42,16 @@ def test_vpc_defaults():
|
|||
|
||||
conn.get_all_vpcs().should.have.length_of(2)
|
||||
conn.get_all_route_tables().should.have.length_of(2)
|
||||
conn.get_all_security_groups(filters={'vpc-id': [vpc.id]}).should.have.length_of(1)
|
||||
conn.get_all_security_groups(
|
||||
filters={'vpc-id': [vpc.id]}).should.have.length_of(1)
|
||||
|
||||
vpc.delete()
|
||||
|
||||
conn.get_all_vpcs().should.have.length_of(1)
|
||||
conn.get_all_route_tables().should.have.length_of(1)
|
||||
conn.get_all_security_groups(filters={'vpc-id': [vpc.id]}).should.have.length_of(0)
|
||||
conn.get_all_security_groups(
|
||||
filters={'vpc-id': [vpc.id]}).should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_vpc_isdefault_filter():
|
||||
|
|
@ -80,6 +83,7 @@ def test_vpc_state_available_filter():
|
|||
vpc.delete()
|
||||
conn.get_all_vpcs(filters={'state': 'available'}).should.have.length_of(2)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_vpc_tagging():
|
||||
conn = boto.connect_vpc()
|
||||
|
|
@ -127,7 +131,8 @@ def test_vpc_get_by_cidr_block():
|
|||
@mock_ec2_deprecated
|
||||
def test_vpc_get_by_dhcp_options_id():
|
||||
conn = boto.connect_vpc()
|
||||
dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
vpc1 = conn.create_vpc("10.0.0.0/16")
|
||||
vpc2 = conn.create_vpc("10.0.0.0/16")
|
||||
conn.create_vpc("10.0.0.0/24")
|
||||
|
|
@ -284,6 +289,7 @@ def test_non_default_vpc():
|
|||
attr = response.get('EnableDnsHostnames')
|
||||
attr.get('Value').shouldnt.be.ok
|
||||
|
||||
|
||||
@mock_ec2
|
||||
def test_vpc_dedicated_tenancy():
|
||||
ec2 = boto3.resource('ec2', region_name='us-west-1')
|
||||
|
|
@ -298,6 +304,7 @@ def test_vpc_dedicated_tenancy():
|
|||
|
||||
vpc.instance_tenancy.should.equal('dedicated')
|
||||
|
||||
|
||||
@mock_ec2
|
||||
def test_vpc_modify_enable_dns_support():
|
||||
ec2 = boto3.resource('ec2', region_name='us-west-1')
|
||||
|
|
@ -339,10 +346,12 @@ def test_vpc_modify_enable_dns_hostnames():
|
|||
attr = response.get('EnableDnsHostnames')
|
||||
attr.get('Value').should.be.ok
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_vpc_associate_dhcp_options():
|
||||
conn = boto.connect_vpc()
|
||||
dhcp_options = conn.create_dhcp_options(SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
dhcp_options = conn.create_dhcp_options(
|
||||
SAMPLE_DOMAIN_NAME, SAMPLE_NAME_SERVERS)
|
||||
vpc = conn.create_vpc("10.0.0.0/16")
|
||||
|
||||
conn.associate_dhcp_options(dhcp_options.id, vpc.id)
|
||||
|
|
|
|||
|
|
@ -10,27 +10,32 @@ from moto import mock_ec2_deprecated
|
|||
@mock_ec2_deprecated
|
||||
def test_create_vpn_connections():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpn_connection = conn.create_vpn_connection('ipsec.1', 'vgw-0123abcd', 'cgw-0123abcd')
|
||||
vpn_connection = conn.create_vpn_connection(
|
||||
'ipsec.1', 'vgw-0123abcd', 'cgw-0123abcd')
|
||||
vpn_connection.should_not.be.none
|
||||
vpn_connection.id.should.match(r'vpn-\w+')
|
||||
vpn_connection.type.should.equal('ipsec.1')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_delete_vpn_connections():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
vpn_connection = conn.create_vpn_connection('ipsec.1', 'vgw-0123abcd', 'cgw-0123abcd')
|
||||
vpn_connection = conn.create_vpn_connection(
|
||||
'ipsec.1', 'vgw-0123abcd', 'cgw-0123abcd')
|
||||
list_of_vpn_connections = conn.get_all_vpn_connections()
|
||||
list_of_vpn_connections.should.have.length_of(1)
|
||||
conn.delete_vpn_connection(vpn_connection.id)
|
||||
list_of_vpn_connections = conn.get_all_vpn_connections()
|
||||
list_of_vpn_connections.should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_delete_vpn_connections_bad_id():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
with assert_raises(EC2ResponseError):
|
||||
conn.delete_vpn_connection('vpn-0123abcd')
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
def test_describe_vpn_connections():
|
||||
conn = boto.connect_vpc('the_key', 'the_secret')
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ def test_create_cluster():
|
|||
clusterName='test_ecs_cluster'
|
||||
)
|
||||
response['cluster']['clusterName'].should.equal('test_ecs_cluster')
|
||||
response['cluster']['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['cluster']['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['cluster']['status'].should.equal('ACTIVE')
|
||||
response['cluster']['registeredContainerInstancesCount'].should.equal(0)
|
||||
response['cluster']['runningTasksCount'].should.equal(0)
|
||||
|
|
@ -38,8 +39,10 @@ def test_list_clusters():
|
|||
clusterName='test_cluster1'
|
||||
)
|
||||
response = client.list_clusters()
|
||||
response['clusterArns'].should.contain('arn:aws:ecs:us-east-1:012345678910:cluster/test_cluster0')
|
||||
response['clusterArns'].should.contain('arn:aws:ecs:us-east-1:012345678910:cluster/test_cluster1')
|
||||
response['clusterArns'].should.contain(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_cluster0')
|
||||
response['clusterArns'].should.contain(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_cluster1')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -50,7 +53,8 @@ def test_delete_cluster():
|
|||
)
|
||||
response = client.delete_cluster(cluster='test_ecs_cluster')
|
||||
response['cluster']['clusterName'].should.equal('test_ecs_cluster')
|
||||
response['cluster']['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['cluster']['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['cluster']['status'].should.equal('ACTIVE')
|
||||
response['cluster']['registeredContainerInstancesCount'].should.equal(0)
|
||||
response['cluster']['runningTasksCount'].should.equal(0)
|
||||
|
|
@ -82,15 +86,24 @@ def test_register_task_definition():
|
|||
]
|
||||
)
|
||||
type(response['taskDefinition']).should.be(dict)
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinition']['containerDefinitions'][0]['name'].should.equal('hello_world')
|
||||
response['taskDefinition']['containerDefinitions'][0]['image'].should.equal('docker/hello-world:latest')
|
||||
response['taskDefinition']['containerDefinitions'][0]['cpu'].should.equal(1024)
|
||||
response['taskDefinition']['containerDefinitions'][0]['memory'].should.equal(400)
|
||||
response['taskDefinition']['containerDefinitions'][0]['essential'].should.equal(True)
|
||||
response['taskDefinition']['containerDefinitions'][0]['environment'][0]['name'].should.equal('AWS_ACCESS_KEY_ID')
|
||||
response['taskDefinition']['containerDefinitions'][0]['environment'][0]['value'].should.equal('SOME_ACCESS_KEY')
|
||||
response['taskDefinition']['containerDefinitions'][0]['logConfiguration']['logDriver'].should.equal('json-file')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['name'].should.equal('hello_world')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'image'].should.equal('docker/hello-world:latest')
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['cpu'].should.equal(1024)
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['memory'].should.equal(400)
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['essential'].should.equal(True)
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'environment'][0]['name'].should.equal('AWS_ACCESS_KEY_ID')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'environment'][0]['value'].should.equal('SOME_ACCESS_KEY')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'logConfiguration']['logDriver'].should.equal('json-file')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -132,8 +145,10 @@ def test_list_task_definitions():
|
|||
)
|
||||
response = client.list_task_definitions()
|
||||
len(response['taskDefinitionArns']).should.equal(2)
|
||||
response['taskDefinitionArns'][0].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinitionArns'][1].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:2')
|
||||
response['taskDefinitionArns'][0].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinitionArns'][1].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:2')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -191,10 +206,13 @@ def test_describe_task_definition():
|
|||
]
|
||||
)
|
||||
response = client.describe_task_definition(taskDefinition='test_ecs_task')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:3')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:3')
|
||||
|
||||
response = client.describe_task_definition(taskDefinition='test_ecs_task:2')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:2')
|
||||
response = client.describe_task_definition(
|
||||
taskDefinition='test_ecs_task:2')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:2')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -221,15 +239,24 @@ def test_deregister_task_definition():
|
|||
taskDefinition='test_ecs_task:1'
|
||||
)
|
||||
type(response['taskDefinition']).should.be(dict)
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinition']['containerDefinitions'][0]['name'].should.equal('hello_world')
|
||||
response['taskDefinition']['containerDefinitions'][0]['image'].should.equal('docker/hello-world:latest')
|
||||
response['taskDefinition']['containerDefinitions'][0]['cpu'].should.equal(1024)
|
||||
response['taskDefinition']['containerDefinitions'][0]['memory'].should.equal(400)
|
||||
response['taskDefinition']['containerDefinitions'][0]['essential'].should.equal(True)
|
||||
response['taskDefinition']['containerDefinitions'][0]['environment'][0]['name'].should.equal('AWS_ACCESS_KEY_ID')
|
||||
response['taskDefinition']['containerDefinitions'][0]['environment'][0]['value'].should.equal('SOME_ACCESS_KEY')
|
||||
response['taskDefinition']['containerDefinitions'][0]['logConfiguration']['logDriver'].should.equal('json-file')
|
||||
response['taskDefinition']['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['name'].should.equal('hello_world')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'image'].should.equal('docker/hello-world:latest')
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['cpu'].should.equal(1024)
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['memory'].should.equal(400)
|
||||
response['taskDefinition']['containerDefinitions'][
|
||||
0]['essential'].should.equal(True)
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'environment'][0]['name'].should.equal('AWS_ACCESS_KEY_ID')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'environment'][0]['value'].should.equal('SOME_ACCESS_KEY')
|
||||
response['taskDefinition']['containerDefinitions'][0][
|
||||
'logConfiguration']['logDriver'].should.equal('json-file')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -261,16 +288,19 @@ def test_create_service():
|
|||
taskDefinition='test_ecs_task',
|
||||
desiredCount=2
|
||||
)
|
||||
response['service']['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['service']['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['service']['desiredCount'].should.equal(2)
|
||||
len(response['service']['events']).should.equal(0)
|
||||
len(response['service']['loadBalancers']).should.equal(0)
|
||||
response['service']['pendingCount'].should.equal(0)
|
||||
response['service']['runningCount'].should.equal(0)
|
||||
response['service']['serviceArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service')
|
||||
response['service']['serviceArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service')
|
||||
response['service']['serviceName'].should.equal('test_ecs_service')
|
||||
response['service']['status'].should.equal('ACTIVE')
|
||||
response['service']['taskDefinition'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['service']['taskDefinition'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -312,8 +342,10 @@ def test_list_services():
|
|||
cluster='test_ecs_cluster'
|
||||
)
|
||||
len(response['serviceArns']).should.equal(2)
|
||||
response['serviceArns'][0].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service1')
|
||||
response['serviceArns'][1].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2')
|
||||
response['serviceArns'][0].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service1')
|
||||
response['serviceArns'][1].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2')
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -359,12 +391,15 @@ def test_describe_services():
|
|||
)
|
||||
response = client.describe_services(
|
||||
cluster='test_ecs_cluster',
|
||||
services=['test_ecs_service1', 'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2']
|
||||
services=['test_ecs_service1',
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2']
|
||||
)
|
||||
len(response['services']).should.equal(2)
|
||||
response['services'][0]['serviceArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service1')
|
||||
response['services'][0]['serviceArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service1')
|
||||
response['services'][0]['serviceName'].should.equal('test_ecs_service1')
|
||||
response['services'][1]['serviceArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2')
|
||||
response['services'][1]['serviceArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service2')
|
||||
response['services'][1]['serviceName'].should.equal('test_ecs_service2')
|
||||
|
||||
|
||||
|
|
@ -446,16 +481,20 @@ def test_delete_service():
|
|||
cluster='test_ecs_cluster',
|
||||
service='test_ecs_service'
|
||||
)
|
||||
response['service']['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['service']['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['service']['desiredCount'].should.equal(0)
|
||||
len(response['service']['events']).should.equal(0)
|
||||
len(response['service']['loadBalancers']).should.equal(0)
|
||||
response['service']['pendingCount'].should.equal(0)
|
||||
response['service']['runningCount'].should.equal(0)
|
||||
response['service']['serviceArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service')
|
||||
response['service']['serviceArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:service/test_ecs_service')
|
||||
response['service']['serviceName'].should.equal('test_ecs_service')
|
||||
response['service']['status'].should.equal('ACTIVE')
|
||||
response['service']['taskDefinition'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['service']['taskDefinition'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
|
||||
|
||||
@mock_ec2
|
||||
@mock_ecs
|
||||
|
|
@ -484,18 +523,23 @@ def test_register_container_instance():
|
|||
instanceIdentityDocument=instance_id_document
|
||||
)
|
||||
|
||||
response['containerInstance']['ec2InstanceId'].should.equal(test_instance.id)
|
||||
response['containerInstance'][
|
||||
'ec2InstanceId'].should.equal(test_instance.id)
|
||||
full_arn = response['containerInstance']['containerInstanceArn']
|
||||
arn_part = full_arn.split('/')
|
||||
arn_part[0].should.equal('arn:aws:ecs:us-east-1:012345678910:container-instance')
|
||||
arn_part[0].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:container-instance')
|
||||
arn_part[1].should.equal(str(UUID(arn_part[1])))
|
||||
response['containerInstance']['status'].should.equal('ACTIVE')
|
||||
len(response['containerInstance']['registeredResources']).should.equal(0)
|
||||
len(response['containerInstance']['remainingResources']).should.equal(0)
|
||||
response['containerInstance']['agentConnected'].should.equal(True)
|
||||
response['containerInstance']['versionInfo']['agentVersion'].should.equal('1.0.0')
|
||||
response['containerInstance']['versionInfo']['agentHash'].should.equal('4023248')
|
||||
response['containerInstance']['versionInfo']['dockerVersion'].should.equal('DockerVersion: 1.5.0')
|
||||
response['containerInstance']['versionInfo'][
|
||||
'agentVersion'].should.equal('1.0.0')
|
||||
response['containerInstance']['versionInfo'][
|
||||
'agentHash'].should.equal('4023248')
|
||||
response['containerInstance']['versionInfo'][
|
||||
'dockerVersion'].should.equal('DockerVersion: 1.5.0')
|
||||
|
||||
|
||||
@mock_ec2
|
||||
|
|
@ -526,7 +570,8 @@ def test_list_container_instances():
|
|||
cluster=test_cluster_name,
|
||||
instanceIdentityDocument=instance_id_document)
|
||||
|
||||
test_instance_arns.append(response['containerInstance']['containerInstanceArn'])
|
||||
test_instance_arns.append(response['containerInstance'][
|
||||
'containerInstanceArn'])
|
||||
|
||||
response = ecs_client.list_container_instances(cluster=test_cluster_name)
|
||||
|
||||
|
|
@ -563,13 +608,17 @@ def test_describe_container_instances():
|
|||
cluster=test_cluster_name,
|
||||
instanceIdentityDocument=instance_id_document)
|
||||
|
||||
test_instance_arns.append(response['containerInstance']['containerInstanceArn'])
|
||||
test_instance_arns.append(response['containerInstance'][
|
||||
'containerInstanceArn'])
|
||||
|
||||
test_instance_ids = list(map((lambda x: x.split('/')[1]), test_instance_arns))
|
||||
response = ecs_client.describe_container_instances(cluster=test_cluster_name, containerInstances=test_instance_ids)
|
||||
test_instance_ids = list(
|
||||
map((lambda x: x.split('/')[1]), test_instance_arns))
|
||||
response = ecs_client.describe_container_instances(
|
||||
cluster=test_cluster_name, containerInstances=test_instance_ids)
|
||||
len(response['failures']).should.equal(0)
|
||||
len(response['containerInstances']).should.equal(instance_to_create)
|
||||
response_arns = [ci['containerInstanceArn'] for ci in response['containerInstances']]
|
||||
response_arns = [ci['containerInstanceArn']
|
||||
for ci in response['containerInstances']]
|
||||
for arn in test_instance_arns:
|
||||
response_arns.should.contain(arn)
|
||||
|
||||
|
|
@ -626,10 +675,14 @@ def test_run_task():
|
|||
startedBy='moto'
|
||||
)
|
||||
len(response['tasks']).should.equal(2)
|
||||
response['tasks'][0]['taskArn'].should.contain('arn:aws:ecs:us-east-1:012345678910:task/')
|
||||
response['tasks'][0]['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['tasks'][0]['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['tasks'][0]['containerInstanceArn'].should.contain('arn:aws:ecs:us-east-1:012345678910:container-instance/')
|
||||
response['tasks'][0]['taskArn'].should.contain(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task/')
|
||||
response['tasks'][0]['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['tasks'][0]['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['tasks'][0]['containerInstanceArn'].should.contain(
|
||||
'arn:aws:ecs:us-east-1:012345678910:container-instance/')
|
||||
response['tasks'][0]['overrides'].should.equal({})
|
||||
response['tasks'][0]['lastStatus'].should.equal("RUNNING")
|
||||
response['tasks'][0]['desiredStatus'].should.equal("RUNNING")
|
||||
|
|
@ -664,8 +717,10 @@ def test_start_task():
|
|||
instanceIdentityDocument=instance_id_document
|
||||
)
|
||||
|
||||
container_instances = client.list_container_instances(cluster=test_cluster_name)
|
||||
container_instance_id = container_instances['containerInstanceArns'][0].split('/')[-1]
|
||||
container_instances = client.list_container_instances(
|
||||
cluster=test_cluster_name)
|
||||
container_instance_id = container_instances[
|
||||
'containerInstanceArns'][0].split('/')[-1]
|
||||
|
||||
_ = client.register_task_definition(
|
||||
family='test_ecs_task',
|
||||
|
|
@ -694,10 +749,14 @@ def test_start_task():
|
|||
)
|
||||
|
||||
len(response['tasks']).should.equal(1)
|
||||
response['tasks'][0]['taskArn'].should.contain('arn:aws:ecs:us-east-1:012345678910:task/')
|
||||
response['tasks'][0]['clusterArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['tasks'][0]['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['tasks'][0]['containerInstanceArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:container-instance/{0}'.format(container_instance_id))
|
||||
response['tasks'][0]['taskArn'].should.contain(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task/')
|
||||
response['tasks'][0]['clusterArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:cluster/test_ecs_cluster')
|
||||
response['tasks'][0]['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task:1')
|
||||
response['tasks'][0]['containerInstanceArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:container-instance/{0}'.format(container_instance_id))
|
||||
response['tasks'][0]['overrides'].should.equal({})
|
||||
response['tasks'][0]['lastStatus'].should.equal("RUNNING")
|
||||
response['tasks'][0]['desiredStatus'].should.equal("RUNNING")
|
||||
|
|
@ -732,8 +791,10 @@ def test_list_tasks():
|
|||
instanceIdentityDocument=instance_id_document
|
||||
)
|
||||
|
||||
container_instances = client.list_container_instances(cluster=test_cluster_name)
|
||||
container_instance_id = container_instances['containerInstanceArns'][0].split('/')[-1]
|
||||
container_instances = client.list_container_instances(
|
||||
cluster=test_cluster_name)
|
||||
container_instance_id = container_instances[
|
||||
'containerInstanceArns'][0].split('/')[-1]
|
||||
|
||||
_ = client.register_task_definition(
|
||||
family='test_ecs_task',
|
||||
|
|
@ -770,7 +831,8 @@ def test_list_tasks():
|
|||
)
|
||||
|
||||
assert len(client.list_tasks()['taskArns']).should.equal(2)
|
||||
assert len(client.list_tasks(cluster='test_ecs_cluster')['taskArns']).should.equal(2)
|
||||
assert len(client.list_tasks(cluster='test_ecs_cluster')
|
||||
['taskArns']).should.equal(2)
|
||||
assert len(client.list_tasks(startedBy='foo')['taskArns']).should.equal(1)
|
||||
|
||||
|
||||
|
|
@ -819,7 +881,7 @@ def test_describe_tasks():
|
|||
]
|
||||
)
|
||||
tasks_arns = [
|
||||
task['taskArn'] for task in client.run_task(
|
||||
task['taskArn'] for task in client.run_task(
|
||||
cluster='test_ecs_cluster',
|
||||
overrides={},
|
||||
taskDefinition='test_ecs_task',
|
||||
|
|
@ -833,7 +895,8 @@ def test_describe_tasks():
|
|||
)
|
||||
|
||||
len(response['tasks']).should.equal(2)
|
||||
set([response['tasks'][0]['taskArn'], response['tasks'][1]['taskArn']]).should.equal(set(tasks_arns))
|
||||
set([response['tasks'][0]['taskArn'], response['tasks']
|
||||
[1]['taskArn']]).should.equal(set(tasks_arns))
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -858,9 +921,11 @@ def describe_task_definition():
|
|||
family = task_definition['family']
|
||||
task = client.describe_task_definition(taskDefinition=family)
|
||||
task['containerDefinitions'][0].should.equal(container_definition)
|
||||
task['taskDefinitionArn'].should.equal('arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task2:1')
|
||||
task['taskDefinitionArn'].should.equal(
|
||||
'arn:aws:ecs:us-east-1:012345678910:task-definition/test_ecs_task2:1')
|
||||
task['volumes'].should.equal([])
|
||||
|
||||
|
||||
@mock_ec2
|
||||
@mock_ecs
|
||||
def test_stop_task():
|
||||
|
|
@ -918,7 +983,8 @@ def test_stop_task():
|
|||
reason='moto testing'
|
||||
)
|
||||
|
||||
stop_response['task']['taskArn'].should.equal(run_response['tasks'][0].get('taskArn'))
|
||||
stop_response['task']['taskArn'].should.equal(
|
||||
run_response['tasks'][0].get('taskArn'))
|
||||
stop_response['task']['lastStatus'].should.equal('STOPPED')
|
||||
stop_response['task']['desiredStatus'].should.equal('STOPPED')
|
||||
stop_response['task']['stoppedReason'].should.equal('moto testing')
|
||||
|
|
@ -967,7 +1033,8 @@ def test_update_cluster_name_through_cloudformation_should_trigger_a_replacement
|
|||
}
|
||||
}
|
||||
template2 = deepcopy(template1)
|
||||
template2['Resources']['testCluster']['Properties']['ClusterName'] = 'testcluster2'
|
||||
template2['Resources']['testCluster'][
|
||||
'Properties']['ClusterName'] = 'testcluster2'
|
||||
template1_json = json.dumps(template1)
|
||||
cfn_conn = boto3.client('cloudformation', region_name='us-west-1')
|
||||
stack_resp = cfn_conn.create_stack(
|
||||
|
|
@ -994,18 +1061,18 @@ def test_create_task_definition_through_cloudformation():
|
|||
"Description": "ECS Cluster Test CloudFormation",
|
||||
"Resources": {
|
||||
"testTaskDefinition": {
|
||||
"Type" : "AWS::ECS::TaskDefinition",
|
||||
"Properties" : {
|
||||
"ContainerDefinitions" : [
|
||||
"Type": "AWS::ECS::TaskDefinition",
|
||||
"Properties": {
|
||||
"ContainerDefinitions": [
|
||||
{
|
||||
"Name": "ecs-sample",
|
||||
"Image":"amazon/amazon-ecs-sample",
|
||||
"Image": "amazon/amazon-ecs-sample",
|
||||
"Cpu": "200",
|
||||
"Memory": "500",
|
||||
"Essential": "true"
|
||||
}
|
||||
],
|
||||
"Volumes" : [],
|
||||
"Volumes": [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1030,19 +1097,19 @@ def test_update_task_definition_family_through_cloudformation_should_trigger_a_r
|
|||
"Description": "ECS Cluster Test CloudFormation",
|
||||
"Resources": {
|
||||
"testTaskDefinition": {
|
||||
"Type" : "AWS::ECS::TaskDefinition",
|
||||
"Properties" : {
|
||||
"Type": "AWS::ECS::TaskDefinition",
|
||||
"Properties": {
|
||||
"Family": "testTaskDefinition1",
|
||||
"ContainerDefinitions" : [
|
||||
"ContainerDefinitions": [
|
||||
{
|
||||
"Name": "ecs-sample",
|
||||
"Image":"amazon/amazon-ecs-sample",
|
||||
"Image": "amazon/amazon-ecs-sample",
|
||||
"Cpu": "200",
|
||||
"Memory": "500",
|
||||
"Essential": "true"
|
||||
}
|
||||
],
|
||||
"Volumes" : [],
|
||||
"Volumes": [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1055,7 +1122,8 @@ def test_update_task_definition_family_through_cloudformation_should_trigger_a_r
|
|||
)
|
||||
|
||||
template2 = deepcopy(template1)
|
||||
template2['Resources']['testTaskDefinition']['Properties']['Family'] = 'testTaskDefinition2'
|
||||
template2['Resources']['testTaskDefinition'][
|
||||
'Properties']['Family'] = 'testTaskDefinition2'
|
||||
template2_json = json.dumps(template2)
|
||||
cfn_conn.update_stack(
|
||||
StackName="test_stack",
|
||||
|
|
@ -1065,7 +1133,8 @@ def test_update_task_definition_family_through_cloudformation_should_trigger_a_r
|
|||
ecs_conn = boto3.client('ecs', region_name='us-west-1')
|
||||
resp = ecs_conn.list_task_definitions(familyPrefix='testTaskDefinition')
|
||||
len(resp['taskDefinitionArns']).should.equal(1)
|
||||
resp['taskDefinitionArns'][0].endswith('testTaskDefinition2:1').should.be.true
|
||||
resp['taskDefinitionArns'][0].endswith(
|
||||
'testTaskDefinition2:1').should.be.true
|
||||
|
||||
|
||||
@mock_ecs
|
||||
|
|
@ -1082,18 +1151,18 @@ def test_create_service_through_cloudformation():
|
|||
}
|
||||
},
|
||||
"testTaskDefinition": {
|
||||
"Type" : "AWS::ECS::TaskDefinition",
|
||||
"Properties" : {
|
||||
"ContainerDefinitions" : [
|
||||
"Type": "AWS::ECS::TaskDefinition",
|
||||
"Properties": {
|
||||
"ContainerDefinitions": [
|
||||
{
|
||||
"Name": "ecs-sample",
|
||||
"Image":"amazon/amazon-ecs-sample",
|
||||
"Image": "amazon/amazon-ecs-sample",
|
||||
"Cpu": "200",
|
||||
"Memory": "500",
|
||||
"Essential": "true"
|
||||
}
|
||||
],
|
||||
"Volumes" : [],
|
||||
"Volumes": [],
|
||||
}
|
||||
},
|
||||
"testService": {
|
||||
|
|
@ -1132,18 +1201,18 @@ def test_update_service_through_cloudformation_should_trigger_replacement():
|
|||
}
|
||||
},
|
||||
"testTaskDefinition": {
|
||||
"Type" : "AWS::ECS::TaskDefinition",
|
||||
"Properties" : {
|
||||
"ContainerDefinitions" : [
|
||||
"Type": "AWS::ECS::TaskDefinition",
|
||||
"Properties": {
|
||||
"ContainerDefinitions": [
|
||||
{
|
||||
"Name": "ecs-sample",
|
||||
"Image":"amazon/amazon-ecs-sample",
|
||||
"Image": "amazon/amazon-ecs-sample",
|
||||
"Cpu": "200",
|
||||
"Memory": "500",
|
||||
"Essential": "true"
|
||||
}
|
||||
],
|
||||
"Volumes" : [],
|
||||
"Volumes": [],
|
||||
}
|
||||
},
|
||||
"testService": {
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import sure # noqa
|
|||
|
||||
from moto import mock_elb, mock_ec2, mock_elb_deprecated, mock_ec2_deprecated
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_load_balancer():
|
||||
conn = boto.connect_elb()
|
||||
|
|
@ -32,7 +33,8 @@ def test_create_load_balancer():
|
|||
balancer = balancers[0]
|
||||
balancer.name.should.equal("my-lb")
|
||||
balancer.scheme.should.equal("internal")
|
||||
set(balancer.availability_zones).should.equal(set(['us-east-1a', 'us-east-1b']))
|
||||
set(balancer.availability_zones).should.equal(
|
||||
set(['us-east-1a', 'us-east-1b']))
|
||||
listener1 = balancer.listeners[0]
|
||||
listener1.load_balancer_port.should.equal(80)
|
||||
listener1.instance_port.should.equal(8080)
|
||||
|
|
@ -46,7 +48,8 @@ def test_create_load_balancer():
|
|||
@mock_elb_deprecated
|
||||
def test_getting_missing_elb():
|
||||
conn = boto.connect_elb()
|
||||
conn.get_all_load_balancers.when.called_with(load_balancer_names='aaa').should.throw(BotoServerError)
|
||||
conn.get_all_load_balancers.when.called_with(
|
||||
load_balancer_names='aaa').should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
|
|
@ -63,12 +66,14 @@ def test_create_elb_in_multiple_region():
|
|||
list(west1_conn.get_all_load_balancers()).should.have.length_of(1)
|
||||
list(west2_conn.get_all_load_balancers()).should.have.length_of(1)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_load_balancer_with_certificate():
|
||||
conn = boto.connect_elb()
|
||||
|
||||
zones = ['us-east-1a']
|
||||
ports = [(443, 8443, 'https', 'arn:aws:iam:123456789012:server-certificate/test-cert')]
|
||||
ports = [
|
||||
(443, 8443, 'https', 'arn:aws:iam:123456789012:server-certificate/test-cert')]
|
||||
conn.create_load_balancer('my-lb', zones, ports)
|
||||
|
||||
balancers = conn.get_all_load_balancers()
|
||||
|
|
@ -80,7 +85,8 @@ def test_create_load_balancer_with_certificate():
|
|||
listener.load_balancer_port.should.equal(443)
|
||||
listener.instance_port.should.equal(8443)
|
||||
listener.protocol.should.equal("HTTPS")
|
||||
listener.ssl_certificate_id.should.equal('arn:aws:iam:123456789012:server-certificate/test-cert')
|
||||
listener.ssl_certificate_id.should.equal(
|
||||
'arn:aws:iam:123456789012:server-certificate/test-cert')
|
||||
|
||||
|
||||
@mock_elb
|
||||
|
|
@ -89,15 +95,19 @@ def test_create_and_delete_boto3_support():
|
|||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
list(client.describe_load_balancers()['LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
list(client.describe_load_balancers()[
|
||||
'LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
|
||||
client.delete_load_balancer(
|
||||
LoadBalancerName='my-lb'
|
||||
)
|
||||
list(client.describe_load_balancers()['LoadBalancerDescriptions']).should.have.length_of(0)
|
||||
list(client.describe_load_balancers()[
|
||||
'LoadBalancerDescriptions']).should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_add_listener():
|
||||
|
|
@ -142,23 +152,32 @@ def test_create_and_delete_listener_boto3_support():
|
|||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'http', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[{'Protocol': 'http',
|
||||
'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
list(client.describe_load_balancers()['LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
list(client.describe_load_balancers()[
|
||||
'LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
|
||||
client.create_load_balancer_listeners(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':443, 'InstancePort':8443}]
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 443, 'InstancePort': 8443}]
|
||||
)
|
||||
balancer = client.describe_load_balancers()['LoadBalancerDescriptions'][0]
|
||||
list(balancer['ListenerDescriptions']).should.have.length_of(2)
|
||||
balancer['ListenerDescriptions'][0]['Listener']['Protocol'].should.equal('HTTP')
|
||||
balancer['ListenerDescriptions'][0]['Listener']['LoadBalancerPort'].should.equal(80)
|
||||
balancer['ListenerDescriptions'][0]['Listener']['InstancePort'].should.equal(8080)
|
||||
balancer['ListenerDescriptions'][1]['Listener']['Protocol'].should.equal('TCP')
|
||||
balancer['ListenerDescriptions'][1]['Listener']['LoadBalancerPort'].should.equal(443)
|
||||
balancer['ListenerDescriptions'][1]['Listener']['InstancePort'].should.equal(8443)
|
||||
balancer['ListenerDescriptions'][0][
|
||||
'Listener']['Protocol'].should.equal('HTTP')
|
||||
balancer['ListenerDescriptions'][0]['Listener'][
|
||||
'LoadBalancerPort'].should.equal(80)
|
||||
balancer['ListenerDescriptions'][0]['Listener'][
|
||||
'InstancePort'].should.equal(8080)
|
||||
balancer['ListenerDescriptions'][1][
|
||||
'Listener']['Protocol'].should.equal('TCP')
|
||||
balancer['ListenerDescriptions'][1]['Listener'][
|
||||
'LoadBalancerPort'].should.equal(443)
|
||||
balancer['ListenerDescriptions'][1]['Listener'][
|
||||
'InstancePort'].should.equal(8443)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
|
|
@ -189,8 +208,10 @@ def test_get_load_balancers_by_name():
|
|||
conn.create_load_balancer('my-lb3', zones, ports)
|
||||
|
||||
conn.get_all_load_balancers().should.have.length_of(3)
|
||||
conn.get_all_load_balancers(load_balancer_names=['my-lb1']).should.have.length_of(1)
|
||||
conn.get_all_load_balancers(load_balancer_names=['my-lb1', 'my-lb2']).should.have.length_of(2)
|
||||
conn.get_all_load_balancers(
|
||||
load_balancer_names=['my-lb1']).should.have.length_of(1)
|
||||
conn.get_all_load_balancers(
|
||||
load_balancer_names=['my-lb1', 'my-lb2']).should.have.length_of(2)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
|
|
@ -240,7 +261,8 @@ def test_create_health_check_boto3():
|
|||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'http', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[{'Protocol': 'http',
|
||||
'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
client.configure_health_check(
|
||||
|
|
@ -285,14 +307,16 @@ def test_register_instances():
|
|||
@mock_elb
|
||||
def test_register_instances_boto3():
|
||||
ec2 = boto3.resource('ec2', region_name='us-east-1')
|
||||
response = ec2.create_instances(ImageId='ami-1234abcd', MinCount=2, MaxCount=2)
|
||||
response = ec2.create_instances(
|
||||
ImageId='ami-1234abcd', MinCount=2, MaxCount=2)
|
||||
instance_id1 = response[0].id
|
||||
instance_id2 = response[1].id
|
||||
|
||||
client = boto3.client('elb', region_name='us-east-1')
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'http', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[{'Protocol': 'http',
|
||||
'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
client.register_instances_with_load_balancer(
|
||||
|
|
@ -303,7 +327,8 @@ def test_register_instances_boto3():
|
|||
]
|
||||
)
|
||||
balancer = client.describe_load_balancers()['LoadBalancerDescriptions'][0]
|
||||
instance_ids = [instance['InstanceId'] for instance in balancer['Instances']]
|
||||
instance_ids = [instance['InstanceId']
|
||||
for instance in balancer['Instances']]
|
||||
set(instance_ids).should.equal(set([instance_id1, instance_id2]))
|
||||
|
||||
|
||||
|
|
@ -328,18 +353,21 @@ def test_deregister_instances():
|
|||
balancer.instances.should.have.length_of(1)
|
||||
balancer.instances[0].id.should.equal(instance_id2)
|
||||
|
||||
|
||||
@mock_ec2
|
||||
@mock_elb
|
||||
def test_deregister_instances_boto3():
|
||||
ec2 = boto3.resource('ec2', region_name='us-east-1')
|
||||
response = ec2.create_instances(ImageId='ami-1234abcd', MinCount=2, MaxCount=2)
|
||||
response = ec2.create_instances(
|
||||
ImageId='ami-1234abcd', MinCount=2, MaxCount=2)
|
||||
instance_id1 = response[0].id
|
||||
instance_id2 = response[1].id
|
||||
|
||||
client = boto3.client('elb', region_name='us-east-1')
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'http', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[{'Protocol': 'http',
|
||||
'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
client.register_instances_with_load_balancer(
|
||||
|
|
@ -403,18 +431,21 @@ def test_connection_draining_attribute():
|
|||
connection_draining.enabled = True
|
||||
connection_draining.timeout = 60
|
||||
|
||||
conn.modify_lb_attribute("my-lb", "ConnectionDraining", connection_draining)
|
||||
conn.modify_lb_attribute(
|
||||
"my-lb", "ConnectionDraining", connection_draining)
|
||||
attributes = lb.get_attributes(force=True)
|
||||
attributes.connection_draining.enabled.should.be.true
|
||||
attributes.connection_draining.timeout.should.equal(60)
|
||||
|
||||
connection_draining.timeout = 30
|
||||
conn.modify_lb_attribute("my-lb", "ConnectionDraining", connection_draining)
|
||||
conn.modify_lb_attribute(
|
||||
"my-lb", "ConnectionDraining", connection_draining)
|
||||
attributes = lb.get_attributes(force=True)
|
||||
attributes.connection_draining.timeout.should.equal(30)
|
||||
|
||||
connection_draining.enabled = False
|
||||
conn.modify_lb_attribute("my-lb", "ConnectionDraining", connection_draining)
|
||||
conn.modify_lb_attribute(
|
||||
"my-lb", "ConnectionDraining", connection_draining)
|
||||
attributes = lb.get_attributes(force=True)
|
||||
attributes.connection_draining.enabled.should.be.false
|
||||
|
||||
|
|
@ -453,15 +484,18 @@ def test_connection_settings_attribute():
|
|||
connection_settings = ConnectionSettingAttribute(conn)
|
||||
connection_settings.idle_timeout = 120
|
||||
|
||||
conn.modify_lb_attribute("my-lb", "ConnectingSettings", connection_settings)
|
||||
conn.modify_lb_attribute(
|
||||
"my-lb", "ConnectingSettings", connection_settings)
|
||||
attributes = lb.get_attributes(force=True)
|
||||
attributes.connecting_settings.idle_timeout.should.equal(120)
|
||||
|
||||
connection_settings.idle_timeout = 60
|
||||
conn.modify_lb_attribute("my-lb", "ConnectingSettings", connection_settings)
|
||||
conn.modify_lb_attribute(
|
||||
"my-lb", "ConnectingSettings", connection_settings)
|
||||
attributes = lb.get_attributes(force=True)
|
||||
attributes.connecting_settings.idle_timeout.should.equal(60)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_lb_cookie_stickiness_policy():
|
||||
conn = boto.connect_elb()
|
||||
|
|
@ -478,9 +512,13 @@ def test_create_lb_cookie_stickiness_policy():
|
|||
# documentation to be a long numeric.
|
||||
#
|
||||
# To work around that, this value is converted to an int and checked.
|
||||
cookie_expiration_period_response_str = lb.policies.lb_cookie_stickiness_policies[0].cookie_expiration_period
|
||||
int(cookie_expiration_period_response_str).should.equal(cookie_expiration_period)
|
||||
lb.policies.lb_cookie_stickiness_policies[0].policy_name.should.equal(policy_name)
|
||||
cookie_expiration_period_response_str = lb.policies.lb_cookie_stickiness_policies[
|
||||
0].cookie_expiration_period
|
||||
int(cookie_expiration_period_response_str).should.equal(
|
||||
cookie_expiration_period)
|
||||
lb.policies.lb_cookie_stickiness_policies[
|
||||
0].policy_name.should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_lb_cookie_stickiness_policy_no_expiry():
|
||||
|
|
@ -492,8 +530,11 @@ def test_create_lb_cookie_stickiness_policy_no_expiry():
|
|||
lb.create_cookie_stickiness_policy(None, policy_name)
|
||||
|
||||
lb = conn.get_all_load_balancers()[0]
|
||||
lb.policies.lb_cookie_stickiness_policies[0].cookie_expiration_period.should.be.none
|
||||
lb.policies.lb_cookie_stickiness_policies[0].policy_name.should.equal(policy_name)
|
||||
lb.policies.lb_cookie_stickiness_policies[
|
||||
0].cookie_expiration_period.should.be.none
|
||||
lb.policies.lb_cookie_stickiness_policies[
|
||||
0].policy_name.should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_app_cookie_stickiness_policy():
|
||||
|
|
@ -506,8 +547,11 @@ def test_create_app_cookie_stickiness_policy():
|
|||
lb.create_app_cookie_stickiness_policy(cookie_name, policy_name)
|
||||
|
||||
lb = conn.get_all_load_balancers()[0]
|
||||
lb.policies.app_cookie_stickiness_policies[0].cookie_name.should.equal(cookie_name)
|
||||
lb.policies.app_cookie_stickiness_policies[0].policy_name.should.equal(policy_name)
|
||||
lb.policies.app_cookie_stickiness_policies[
|
||||
0].cookie_name.should.equal(cookie_name)
|
||||
lb.policies.app_cookie_stickiness_policies[
|
||||
0].policy_name.should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_create_lb_policy():
|
||||
|
|
@ -516,11 +560,13 @@ def test_create_lb_policy():
|
|||
lb = conn.create_load_balancer('my-lb', [], ports)
|
||||
policy_name = "ProxyPolicy"
|
||||
|
||||
lb.create_lb_policy(policy_name, 'ProxyProtocolPolicyType', {'ProxyProtocol': True})
|
||||
lb.create_lb_policy(policy_name, 'ProxyProtocolPolicyType', {
|
||||
'ProxyProtocol': True})
|
||||
|
||||
lb = conn.get_all_load_balancers()[0]
|
||||
lb.policies.other_policies[0].policy_name.should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_set_policies_of_listener():
|
||||
conn = boto.connect_elb()
|
||||
|
|
@ -543,6 +589,7 @@ def test_set_policies_of_listener():
|
|||
# by contrast to a backend, a listener stores only policy name strings
|
||||
listener.policy_names[0].should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_elb_deprecated
|
||||
def test_set_policies_of_backend_server():
|
||||
conn = boto.connect_elb()
|
||||
|
|
@ -553,7 +600,8 @@ def test_set_policies_of_backend_server():
|
|||
|
||||
# in a real flow, it is necessary first to create a policy,
|
||||
# then to set that policy to the backend
|
||||
lb.create_lb_policy(policy_name, 'ProxyProtocolPolicyType', {'ProxyProtocol': True})
|
||||
lb.create_lb_policy(policy_name, 'ProxyProtocolPolicyType', {
|
||||
'ProxyProtocol': True})
|
||||
lb.set_policies_of_backend_server(instance_port, [policy_name])
|
||||
|
||||
lb = conn.get_all_load_balancers()[0]
|
||||
|
|
@ -562,6 +610,7 @@ def test_set_policies_of_backend_server():
|
|||
# by contrast to a listener, a backend stores OtherPolicy objects
|
||||
backend.policies[0].policy_name.should.equal(policy_name)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
@mock_elb_deprecated
|
||||
def test_describe_instance_health():
|
||||
|
|
@ -583,7 +632,8 @@ def test_describe_instance_health():
|
|||
instances_health = conn.describe_instance_health('my-lb')
|
||||
instances_health.should.have.length_of(2)
|
||||
for instance_health in instances_health:
|
||||
instance_health.instance_id.should.be.within([instance_id1, instance_id2])
|
||||
instance_health.instance_id.should.be.within(
|
||||
[instance_id1, instance_id2])
|
||||
instance_health.state.should.equal('InService')
|
||||
|
||||
instances_health = conn.describe_instance_health('my-lb', [instance_id1])
|
||||
|
|
@ -597,76 +647,78 @@ def test_add_remove_tags():
|
|||
client = boto3.client('elb', region_name='us-east-1')
|
||||
|
||||
client.add_tags.when.called_with(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
}]).should.throw(botocore.exceptions.ClientError)
|
||||
|
||||
Tags=[{
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
}]).should.throw(botocore.exceptions.ClientError)
|
||||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
|
||||
list(client.describe_load_balancers()['LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
list(client.describe_load_balancers()[
|
||||
'LoadBalancerDescriptions']).should.have.length_of(1)
|
||||
|
||||
client.add_tags(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
}])
|
||||
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(
|
||||
LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
tags.should.have.key('a').which.should.equal('b')
|
||||
|
||||
client.add_tags(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
'Key': 'a',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'b',
|
||||
'Value': 'b'
|
||||
'Key': 'b',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'c',
|
||||
'Value': 'b'
|
||||
'Key': 'c',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'd',
|
||||
'Value': 'b'
|
||||
'Key': 'd',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'e',
|
||||
'Value': 'b'
|
||||
'Key': 'e',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'f',
|
||||
'Value': 'b'
|
||||
'Key': 'f',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'g',
|
||||
'Value': 'b'
|
||||
'Key': 'g',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'h',
|
||||
'Value': 'b'
|
||||
'Key': 'h',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'i',
|
||||
'Value': 'b'
|
||||
'Key': 'i',
|
||||
'Value': 'b'
|
||||
}, {
|
||||
'Key': 'j',
|
||||
'Value': 'b'
|
||||
'Key': 'j',
|
||||
'Value': 'b'
|
||||
}])
|
||||
|
||||
client.add_tags.when.called_with(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'k',
|
||||
'Value': 'b'
|
||||
}]).should.throw(botocore.exceptions.ClientError)
|
||||
Tags=[{
|
||||
'Key': 'k',
|
||||
'Value': 'b'
|
||||
}]).should.throw(botocore.exceptions.ClientError)
|
||||
|
||||
client.add_tags(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'j',
|
||||
'Value': 'c'
|
||||
'Key': 'j',
|
||||
'Value': 'c'
|
||||
}])
|
||||
|
||||
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(
|
||||
LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
|
||||
tags.should.have.key('a').which.should.equal('b')
|
||||
tags.should.have.key('b').which.should.equal('b')
|
||||
|
|
@ -681,11 +733,12 @@ def test_add_remove_tags():
|
|||
tags.shouldnt.have.key('k')
|
||||
|
||||
client.remove_tags(LoadBalancerNames=['my-lb'],
|
||||
Tags=[{
|
||||
'Key': 'a'
|
||||
}])
|
||||
Tags=[{
|
||||
'Key': 'a'
|
||||
}])
|
||||
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(
|
||||
LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
|
||||
|
||||
tags.shouldnt.have.key('a')
|
||||
tags.should.have.key('b').which.should.equal('b')
|
||||
|
|
@ -698,17 +751,17 @@ def test_add_remove_tags():
|
|||
tags.should.have.key('i').which.should.equal('b')
|
||||
tags.should.have.key('j').which.should.equal('c')
|
||||
|
||||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='other-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':433, 'InstancePort':8433}],
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 433, 'InstancePort': 8433}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b']
|
||||
)
|
||||
|
||||
client.add_tags(LoadBalancerNames=['other-lb'],
|
||||
Tags=[{
|
||||
'Key': 'other',
|
||||
'Value': 'something'
|
||||
'Key': 'other',
|
||||
'Value': 'something'
|
||||
}])
|
||||
|
||||
lb_tags = dict([(l['LoadBalancerName'], dict([(d['Key'], d['Value']) for d in l['Tags']]))
|
||||
|
|
@ -718,7 +771,8 @@ def test_add_remove_tags():
|
|||
lb_tags.should.have.key('other-lb')
|
||||
|
||||
lb_tags['my-lb'].shouldnt.have.key('other')
|
||||
lb_tags['other-lb'].should.have.key('other').which.should.equal('something')
|
||||
lb_tags[
|
||||
'other-lb'].should.have.key('other').which.should.equal('something')
|
||||
|
||||
|
||||
@mock_elb
|
||||
|
|
@ -727,15 +781,17 @@ def test_create_with_tags():
|
|||
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
AvailabilityZones=['us-east-1a', 'us-east-1b'],
|
||||
Tags=[{
|
||||
'Key': 'k',
|
||||
'Value': 'v'
|
||||
'Key': 'k',
|
||||
'Value': 'v'
|
||||
}]
|
||||
)
|
||||
|
||||
tags = dict((d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags'])
|
||||
tags = dict((d['Key'], d['Value']) for d in client.describe_tags(
|
||||
LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags'])
|
||||
tags.should.have.key('k').which.should.equal('v')
|
||||
|
||||
|
||||
|
|
@ -754,7 +810,8 @@ def test_subnets():
|
|||
client = boto3.client('elb', region_name='us-east-1')
|
||||
client.create_load_balancer(
|
||||
LoadBalancerName='my-lb',
|
||||
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
|
||||
Listeners=[
|
||||
{'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstancePort': 8080}],
|
||||
Subnets=[subnet.id]
|
||||
)
|
||||
|
||||
|
|
@ -770,5 +827,5 @@ def test_create_load_balancer_duplicate():
|
|||
conn = boto.connect_elb()
|
||||
ports = [(80, 8080, 'http'), (443, 8443, 'tcp')]
|
||||
conn.create_load_balancer('my-lb', [], ports)
|
||||
conn.create_load_balancer.when.called_with('my-lb', [], ports).should.throw(BotoServerError)
|
||||
|
||||
conn.create_load_balancer.when.called_with(
|
||||
'my-lb', [], ports).should.throw(BotoServerError)
|
||||
|
|
|
|||
|
|
@ -100,7 +100,8 @@ def test_describe_cluster():
|
|||
# cluster.status.timeline.enddatetime.should.be.a(six.string_types)
|
||||
# cluster.status.timeline.readydatetime.should.be.a(six.string_types)
|
||||
|
||||
dict((item.key, item.value) for item in cluster.tags).should.equal(input_tags)
|
||||
dict((item.key, item.value)
|
||||
for item in cluster.tags).should.equal(input_tags)
|
||||
|
||||
cluster.terminationprotected.should.equal('false')
|
||||
cluster.visibletoallusers.should.equal('true')
|
||||
|
|
@ -285,7 +286,8 @@ def test_list_clusters():
|
|||
y = expected[x.id]
|
||||
x.id.should.equal(y['id'])
|
||||
x.name.should.equal(y['name'])
|
||||
x.normalizedinstancehours.should.equal(y['normalizedinstancehours'])
|
||||
x.normalizedinstancehours.should.equal(
|
||||
y['normalizedinstancehours'])
|
||||
x.status.state.should.equal(y['state'])
|
||||
x.status.timeline.creationdatetime.should.be.a(six.string_types)
|
||||
if y['state'] == 'TERMINATED':
|
||||
|
|
@ -371,11 +373,13 @@ def test_run_jobflow_with_instance_groups():
|
|||
job_id = conn.run_jobflow(instance_groups=input_instance_groups,
|
||||
**run_jobflow_args)
|
||||
job_flow = conn.describe_jobflow(job_id)
|
||||
int(job_flow.instancecount).should.equal(sum(g.num_instances for g in input_instance_groups))
|
||||
int(job_flow.instancecount).should.equal(
|
||||
sum(g.num_instances for g in input_instance_groups))
|
||||
for instance_group in job_flow.instancegroups:
|
||||
expected = input_groups[instance_group.name]
|
||||
instance_group.should.have.property('instancegroupid')
|
||||
int(instance_group.instancerunningcount).should.equal(expected.num_instances)
|
||||
int(instance_group.instancerunningcount).should.equal(
|
||||
expected.num_instances)
|
||||
instance_group.instancerole.should.equal(expected.role)
|
||||
instance_group.instancetype.should.equal(expected.type)
|
||||
instance_group.market.should.equal(expected.market)
|
||||
|
|
@ -483,7 +487,8 @@ def test_instance_groups():
|
|||
conn.add_instance_groups(job_id, input_instance_groups[2:])
|
||||
|
||||
jf = conn.describe_jobflow(job_id)
|
||||
int(jf.instancecount).should.equal(sum(g.num_instances for g in input_instance_groups))
|
||||
int(jf.instancecount).should.equal(
|
||||
sum(g.num_instances for g in input_instance_groups))
|
||||
for x in jf.instancegroups:
|
||||
y = input_groups[x.name]
|
||||
if hasattr(y, 'bidprice'):
|
||||
|
|
@ -572,7 +577,8 @@ def test_steps():
|
|||
list(arg.value for arg in step.args).should.have.length_of(8)
|
||||
step.creationdatetime.should.be.a(six.string_types)
|
||||
# step.enddatetime.should.be.a(six.string_types)
|
||||
step.jar.should.equal('/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
step.jar.should.equal(
|
||||
'/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
step.laststatechangereason.should.be.a(six.string_types)
|
||||
step.mainclass.should.equal('')
|
||||
step.name.should.be.a(six.string_types)
|
||||
|
|
@ -592,7 +598,8 @@ def test_steps():
|
|||
'-input', y.input,
|
||||
'-output', y.output,
|
||||
])
|
||||
x.config.jar.should.equal('/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
x.config.jar.should.equal(
|
||||
'/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
x.config.mainclass.should.equal('')
|
||||
# properties
|
||||
x.should.have.property('id').should.be.a(six.string_types)
|
||||
|
|
@ -610,7 +617,8 @@ def test_steps():
|
|||
'-input', y.input,
|
||||
'-output', y.output,
|
||||
])
|
||||
x.config.jar.should.equal('/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
x.config.jar.should.equal(
|
||||
'/home/hadoop/contrib/streaming/hadoop-streaming.jar')
|
||||
x.config.mainclass.should.equal('')
|
||||
# properties
|
||||
x.should.have.property('id').should.be.a(six.string_types)
|
||||
|
|
|
|||
|
|
@ -88,15 +88,20 @@ def test_describe_cluster():
|
|||
config['Properties'].should.equal(args['Configurations'][0]['Properties'])
|
||||
|
||||
attrs = cl['Ec2InstanceAttributes']
|
||||
attrs['AdditionalMasterSecurityGroups'].should.equal(args['Instances']['AdditionalMasterSecurityGroups'])
|
||||
attrs['AdditionalSlaveSecurityGroups'].should.equal(args['Instances']['AdditionalSlaveSecurityGroups'])
|
||||
attrs['AdditionalMasterSecurityGroups'].should.equal(
|
||||
args['Instances']['AdditionalMasterSecurityGroups'])
|
||||
attrs['AdditionalSlaveSecurityGroups'].should.equal(
|
||||
args['Instances']['AdditionalSlaveSecurityGroups'])
|
||||
attrs['Ec2AvailabilityZone'].should.equal('us-east-1a')
|
||||
attrs['Ec2KeyName'].should.equal(args['Instances']['Ec2KeyName'])
|
||||
attrs['Ec2SubnetId'].should.equal(args['Instances']['Ec2SubnetId'])
|
||||
attrs['EmrManagedMasterSecurityGroup'].should.equal(args['Instances']['EmrManagedMasterSecurityGroup'])
|
||||
attrs['EmrManagedSlaveSecurityGroup'].should.equal(args['Instances']['EmrManagedSlaveSecurityGroup'])
|
||||
attrs['EmrManagedMasterSecurityGroup'].should.equal(
|
||||
args['Instances']['EmrManagedMasterSecurityGroup'])
|
||||
attrs['EmrManagedSlaveSecurityGroup'].should.equal(
|
||||
args['Instances']['EmrManagedSlaveSecurityGroup'])
|
||||
attrs['IamInstanceProfile'].should.equal(args['JobFlowRole'])
|
||||
attrs['ServiceAccessSecurityGroup'].should.equal(args['Instances']['ServiceAccessSecurityGroup'])
|
||||
attrs['ServiceAccessSecurityGroup'].should.equal(
|
||||
args['Instances']['ServiceAccessSecurityGroup'])
|
||||
cl['Id'].should.equal(cluster_id)
|
||||
cl['LogUri'].should.equal(args['LogUri'])
|
||||
cl['MasterPublicDnsName'].should.be.a(six.string_types)
|
||||
|
|
@ -222,11 +227,14 @@ def test_describe_job_flow():
|
|||
ig['State'].should.equal('RUNNING')
|
||||
attrs['KeepJobFlowAliveWhenNoSteps'].should.equal(True)
|
||||
# attrs['MasterInstanceId'].should.be.a(six.string_types)
|
||||
attrs['MasterInstanceType'].should.equal(args['Instances']['MasterInstanceType'])
|
||||
attrs['MasterInstanceType'].should.equal(
|
||||
args['Instances']['MasterInstanceType'])
|
||||
attrs['MasterPublicDnsName'].should.be.a(six.string_types)
|
||||
attrs['NormalizedInstanceHours'].should.equal(0)
|
||||
attrs['Placement']['AvailabilityZone'].should.equal(args['Instances']['Placement']['AvailabilityZone'])
|
||||
attrs['SlaveInstanceType'].should.equal(args['Instances']['SlaveInstanceType'])
|
||||
attrs['Placement']['AvailabilityZone'].should.equal(
|
||||
args['Instances']['Placement']['AvailabilityZone'])
|
||||
attrs['SlaveInstanceType'].should.equal(
|
||||
args['Instances']['SlaveInstanceType'])
|
||||
attrs['TerminationProtected'].should.equal(False)
|
||||
jf['JobFlowId'].should.equal(cluster_id)
|
||||
jf['JobFlowRole'].should.equal(args['JobFlowRole'])
|
||||
|
|
@ -282,14 +290,18 @@ def test_list_clusters():
|
|||
y = expected[x['Id']]
|
||||
x['Id'].should.equal(y['Id'])
|
||||
x['Name'].should.equal(y['Name'])
|
||||
x['NormalizedInstanceHours'].should.equal(y['NormalizedInstanceHours'])
|
||||
x['NormalizedInstanceHours'].should.equal(
|
||||
y['NormalizedInstanceHours'])
|
||||
x['Status']['State'].should.equal(y['State'])
|
||||
x['Status']['Timeline']['CreationDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'CreationDateTime'].should.be.a('datetime.datetime')
|
||||
if y['State'] == 'TERMINATED':
|
||||
x['Status']['Timeline']['EndDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'EndDateTime'].should.be.a('datetime.datetime')
|
||||
else:
|
||||
x['Status']['Timeline'].shouldnt.have.key('EndDateTime')
|
||||
x['Status']['Timeline']['ReadyDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'ReadyDateTime'].should.be.a('datetime.datetime')
|
||||
marker = resp.get('Marker')
|
||||
if marker is None:
|
||||
break
|
||||
|
|
@ -316,8 +328,10 @@ def test_run_job_flow():
|
|||
resp['ExecutionStatusDetail']['State'].should.equal('WAITING')
|
||||
resp['JobFlowId'].should.equal(cluster_id)
|
||||
resp['Name'].should.equal(args['Name'])
|
||||
resp['Instances']['MasterInstanceType'].should.equal(args['Instances']['MasterInstanceType'])
|
||||
resp['Instances']['SlaveInstanceType'].should.equal(args['Instances']['SlaveInstanceType'])
|
||||
resp['Instances']['MasterInstanceType'].should.equal(
|
||||
args['Instances']['MasterInstanceType'])
|
||||
resp['Instances']['SlaveInstanceType'].should.equal(
|
||||
args['Instances']['SlaveInstanceType'])
|
||||
resp['LogUri'].should.equal(args['LogUri'])
|
||||
resp['VisibleToAllUsers'].should.equal(args['VisibleToAllUsers'])
|
||||
resp['Instances']['NormalizedInstanceHours'].should.equal(0)
|
||||
|
|
@ -333,7 +347,8 @@ def test_run_job_flow_with_invalid_params():
|
|||
args['AmiVersion'] = '2.4'
|
||||
args['ReleaseLabel'] = 'emr-5.0.0'
|
||||
client.run_job_flow(**args)
|
||||
ex.exception.response['Error']['Message'].should.contain('ValidationException')
|
||||
ex.exception.response['Error'][
|
||||
'Message'].should.contain('ValidationException')
|
||||
|
||||
|
||||
@mock_emr
|
||||
|
|
@ -378,7 +393,8 @@ def test_run_job_flow_with_instance_groups():
|
|||
args = deepcopy(run_job_flow_args)
|
||||
args['Instances'] = {'InstanceGroups': input_instance_groups}
|
||||
cluster_id = client.run_job_flow(**args)['JobFlowId']
|
||||
groups = client.list_instance_groups(ClusterId=cluster_id)['InstanceGroups']
|
||||
groups = client.list_instance_groups(ClusterId=cluster_id)[
|
||||
'InstanceGroups']
|
||||
for x in groups:
|
||||
y = input_groups[x['Name']]
|
||||
x.should.have.key('Id')
|
||||
|
|
@ -484,10 +500,12 @@ def test_instance_groups():
|
|||
jf = client.describe_job_flows(JobFlowIds=[cluster_id])['JobFlows'][0]
|
||||
base_instance_count = jf['Instances']['InstanceCount']
|
||||
|
||||
client.add_instance_groups(JobFlowId=cluster_id, InstanceGroups=input_instance_groups[2:])
|
||||
client.add_instance_groups(
|
||||
JobFlowId=cluster_id, InstanceGroups=input_instance_groups[2:])
|
||||
|
||||
jf = client.describe_job_flows(JobFlowIds=[cluster_id])['JobFlows'][0]
|
||||
jf['Instances']['InstanceCount'].should.equal(sum(g['InstanceCount'] for g in input_instance_groups))
|
||||
jf['Instances']['InstanceCount'].should.equal(
|
||||
sum(g['InstanceCount'] for g in input_instance_groups))
|
||||
for x in jf['Instances']['InstanceGroups']:
|
||||
y = input_groups[x['Name']]
|
||||
if hasattr(y, 'BidPrice'):
|
||||
|
|
@ -506,7 +524,8 @@ def test_instance_groups():
|
|||
x['StartDateTime'].should.be.a('datetime.datetime')
|
||||
x['State'].should.equal('RUNNING')
|
||||
|
||||
groups = client.list_instance_groups(ClusterId=cluster_id)['InstanceGroups']
|
||||
groups = client.list_instance_groups(ClusterId=cluster_id)[
|
||||
'InstanceGroups']
|
||||
for x in groups:
|
||||
y = input_groups[x['Name']]
|
||||
if hasattr(y, 'BidPrice'):
|
||||
|
|
@ -525,9 +544,11 @@ def test_instance_groups():
|
|||
x['Status']['State'].should.equal('RUNNING')
|
||||
x['Status']['StateChangeReason']['Code'].should.be.a(six.string_types)
|
||||
# x['Status']['StateChangeReason']['Message'].should.be.a(six.string_types)
|
||||
x['Status']['Timeline']['CreationDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'CreationDateTime'].should.be.a('datetime.datetime')
|
||||
# x['Status']['Timeline']['EndDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline']['ReadyDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'ReadyDateTime'].should.be.a('datetime.datetime')
|
||||
|
||||
igs = dict((g['Name'], g) for g in groups)
|
||||
client.modify_instance_groups(
|
||||
|
|
@ -592,14 +613,19 @@ def test_steps():
|
|||
# x['ExecutionStatusDetail'].should.have.key('EndDateTime')
|
||||
# x['ExecutionStatusDetail'].should.have.key('LastStateChangeReason')
|
||||
# x['ExecutionStatusDetail'].should.have.key('StartDateTime')
|
||||
x['ExecutionStatusDetail']['State'].should.equal('STARTING' if idx == 0 else 'PENDING')
|
||||
x['ExecutionStatusDetail']['State'].should.equal(
|
||||
'STARTING' if idx == 0 else 'PENDING')
|
||||
x['StepConfig']['ActionOnFailure'].should.equal('TERMINATE_CLUSTER')
|
||||
x['StepConfig']['HadoopJarStep']['Args'].should.equal(y['HadoopJarStep']['Args'])
|
||||
x['StepConfig']['HadoopJarStep']['Jar'].should.equal(y['HadoopJarStep']['Jar'])
|
||||
x['StepConfig']['HadoopJarStep'][
|
||||
'Args'].should.equal(y['HadoopJarStep']['Args'])
|
||||
x['StepConfig']['HadoopJarStep'][
|
||||
'Jar'].should.equal(y['HadoopJarStep']['Jar'])
|
||||
if 'MainClass' in y['HadoopJarStep']:
|
||||
x['StepConfig']['HadoopJarStep']['MainClass'].should.equal(y['HadoopJarStep']['MainClass'])
|
||||
x['StepConfig']['HadoopJarStep']['MainClass'].should.equal(
|
||||
y['HadoopJarStep']['MainClass'])
|
||||
if 'Properties' in y['HadoopJarStep']:
|
||||
x['StepConfig']['HadoopJarStep']['Properties'].should.equal(y['HadoopJarStep']['Properties'])
|
||||
x['StepConfig']['HadoopJarStep']['Properties'].should.equal(
|
||||
y['HadoopJarStep']['Properties'])
|
||||
x['StepConfig']['Name'].should.equal(y['Name'])
|
||||
|
||||
expected = dict((s['Name'], s) for s in input_steps)
|
||||
|
|
@ -617,7 +643,8 @@ def test_steps():
|
|||
x['Name'].should.equal(y['Name'])
|
||||
x['Status']['State'].should.be.within(['STARTING', 'PENDING'])
|
||||
# StateChangeReason
|
||||
x['Status']['Timeline']['CreationDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'CreationDateTime'].should.be.a('datetime.datetime')
|
||||
# x['Status']['Timeline']['EndDateTime'].should.be.a('datetime.datetime')
|
||||
# x['Status']['Timeline']['StartDateTime'].should.be.a('datetime.datetime')
|
||||
|
||||
|
|
@ -631,7 +658,8 @@ def test_steps():
|
|||
x['Name'].should.equal(y['Name'])
|
||||
x['Status']['State'].should.be.within(['STARTING', 'PENDING'])
|
||||
# StateChangeReason
|
||||
x['Status']['Timeline']['CreationDateTime'].should.be.a('datetime.datetime')
|
||||
x['Status']['Timeline'][
|
||||
'CreationDateTime'].should.be.a('datetime.datetime')
|
||||
# x['Status']['Timeline']['EndDateTime'].should.be.a('datetime.datetime')
|
||||
# x['Status']['Timeline']['StartDateTime'].should.be.a('datetime.datetime')
|
||||
|
||||
|
|
@ -640,7 +668,8 @@ def test_steps():
|
|||
steps.should.have.length_of(1)
|
||||
steps[0]['Id'].should.equal(step_id)
|
||||
|
||||
steps = client.list_steps(ClusterId=cluster_id, StepStates=['STARTING'])['Steps']
|
||||
steps = client.list_steps(ClusterId=cluster_id,
|
||||
StepStates=['STARTING'])['Steps']
|
||||
steps.should.have.length_of(1)
|
||||
steps[0]['Id'].should.equal(step_id)
|
||||
|
||||
|
|
@ -656,8 +685,10 @@ def test_tags():
|
|||
client.add_tags(ResourceId=cluster_id, Tags=input_tags)
|
||||
resp = client.describe_cluster(ClusterId=cluster_id)['Cluster']
|
||||
resp['Tags'].should.have.length_of(2)
|
||||
dict((t['Key'], t['Value']) for t in resp['Tags']).should.equal(dict((t['Key'], t['Value']) for t in input_tags))
|
||||
dict((t['Key'], t['Value']) for t in resp['Tags']).should.equal(
|
||||
dict((t['Key'], t['Value']) for t in input_tags))
|
||||
|
||||
client.remove_tags(ResourceId=cluster_id, TagKeys=[t['Key'] for t in input_tags])
|
||||
client.remove_tags(ResourceId=cluster_id, TagKeys=[
|
||||
t['Key'] for t in input_tags])
|
||||
resp = client.describe_cluster(ClusterId=cluster_id)['Cluster']
|
||||
resp['Tags'].should.equal([])
|
||||
|
|
|
|||
|
|
@ -13,14 +13,16 @@ def test_init_glacier_job():
|
|||
conn = Layer1(region_name="us-west-2")
|
||||
vault_name = "my_vault"
|
||||
conn.create_vault(vault_name)
|
||||
archive_id = conn.upload_archive(vault_name, "some stuff", "", "", "some description")
|
||||
archive_id = conn.upload_archive(
|
||||
vault_name, "some stuff", "", "", "some description")
|
||||
|
||||
job_response = conn.initiate_job(vault_name, {
|
||||
"ArchiveId": archive_id,
|
||||
"Type": "archive-retrieval",
|
||||
})
|
||||
job_id = job_response['JobId']
|
||||
job_response['Location'].should.equal("//vaults/my_vault/jobs/{0}".format(job_id))
|
||||
job_response['Location'].should.equal(
|
||||
"//vaults/my_vault/jobs/{0}".format(job_id))
|
||||
|
||||
|
||||
@mock_glacier_deprecated
|
||||
|
|
@ -28,7 +30,8 @@ def test_describe_job():
|
|||
conn = Layer1(region_name="us-west-2")
|
||||
vault_name = "my_vault"
|
||||
conn.create_vault(vault_name)
|
||||
archive_id = conn.upload_archive(vault_name, "some stuff", "", "", "some description")
|
||||
archive_id = conn.upload_archive(
|
||||
vault_name, "some stuff", "", "", "some description")
|
||||
job_response = conn.initiate_job(vault_name, {
|
||||
"ArchiveId": archive_id,
|
||||
"Type": "archive-retrieval",
|
||||
|
|
@ -61,8 +64,10 @@ def test_list_glacier_jobs():
|
|||
conn = Layer1(region_name="us-west-2")
|
||||
vault_name = "my_vault"
|
||||
conn.create_vault(vault_name)
|
||||
archive_id1 = conn.upload_archive(vault_name, "some stuff", "", "", "some description")['ArchiveId']
|
||||
archive_id2 = conn.upload_archive(vault_name, "some other stuff", "", "", "some description")['ArchiveId']
|
||||
archive_id1 = conn.upload_archive(
|
||||
vault_name, "some stuff", "", "", "some description")['ArchiveId']
|
||||
archive_id2 = conn.upload_archive(
|
||||
vault_name, "some other stuff", "", "", "some description")['ArchiveId']
|
||||
|
||||
conn.initiate_job(vault_name, {
|
||||
"ArchiveId": archive_id1,
|
||||
|
|
@ -82,7 +87,8 @@ def test_get_job_output():
|
|||
conn = Layer1(region_name="us-west-2")
|
||||
vault_name = "my_vault"
|
||||
conn.create_vault(vault_name)
|
||||
archive_response = conn.upload_archive(vault_name, "some stuff", "", "", "some description")
|
||||
archive_response = conn.upload_archive(
|
||||
vault_name, "some stuff", "", "", "some description")
|
||||
archive_id = archive_response['ArchiveId']
|
||||
job_response = conn.initiate_job(vault_name, {
|
||||
"ArchiveId": archive_id,
|
||||
|
|
|
|||
|
|
@ -18,4 +18,5 @@ def test_list_vaults():
|
|||
|
||||
res = test_client.get('/1234bcd/vaults')
|
||||
|
||||
json.loads(res.data.decode("utf-8")).should.equal({u'Marker': None, u'VaultList': []})
|
||||
json.loads(res.data.decode("utf-8")
|
||||
).should.equal({u'Marker': None, u'VaultList': []})
|
||||
|
|
|
|||
|
|
@ -19,11 +19,13 @@ def test_get_all_server_certs():
|
|||
conn = boto.connect_iam()
|
||||
|
||||
conn.upload_server_cert("certname", "certbody", "privatekey")
|
||||
certs = conn.get_all_server_certs()['list_server_certificates_response']['list_server_certificates_result']['server_certificate_metadata_list']
|
||||
certs = conn.get_all_server_certs()['list_server_certificates_response'][
|
||||
'list_server_certificates_result']['server_certificate_metadata_list']
|
||||
certs.should.have.length_of(1)
|
||||
cert1 = certs[0]
|
||||
cert1.server_certificate_name.should.equal("certname")
|
||||
cert1.arn.should.equal("arn:aws:iam::123456789012:server-certificate/certname")
|
||||
cert1.arn.should.equal(
|
||||
"arn:aws:iam::123456789012:server-certificate/certname")
|
||||
|
||||
|
||||
@mock_iam_deprecated()
|
||||
|
|
@ -41,7 +43,8 @@ def test_get_server_cert():
|
|||
conn.upload_server_cert("certname", "certbody", "privatekey")
|
||||
cert = conn.get_server_certificate("certname")
|
||||
cert.server_certificate_name.should.equal("certname")
|
||||
cert.arn.should.equal("arn:aws:iam::123456789012:server-certificate/certname")
|
||||
cert.arn.should.equal(
|
||||
"arn:aws:iam::123456789012:server-certificate/certname")
|
||||
|
||||
|
||||
@mock_iam_deprecated()
|
||||
|
|
@ -51,7 +54,8 @@ def test_upload_server_cert():
|
|||
conn.upload_server_cert("certname", "certbody", "privatekey")
|
||||
cert = conn.get_server_certificate("certname")
|
||||
cert.server_certificate_name.should.equal("certname")
|
||||
cert.arn.should.equal("arn:aws:iam::123456789012:server-certificate/certname")
|
||||
cert.arn.should.equal(
|
||||
"arn:aws:iam::123456789012:server-certificate/certname")
|
||||
|
||||
|
||||
@mock_iam_deprecated()
|
||||
|
|
@ -74,7 +78,8 @@ def test_get_instance_profile__should_throw__when_instance_profile_does_not_exis
|
|||
def test_create_role_and_instance_profile():
|
||||
conn = boto.connect_iam()
|
||||
conn.create_instance_profile("my-profile", path="my-path")
|
||||
conn.create_role("my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.create_role(
|
||||
"my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
|
||||
conn.add_role_to_instance_profile("my-profile", "my-role")
|
||||
|
||||
|
|
@ -95,7 +100,8 @@ def test_create_role_and_instance_profile():
|
|||
def test_remove_role_from_instance_profile():
|
||||
conn = boto.connect_iam()
|
||||
conn.create_instance_profile("my-profile", path="my-path")
|
||||
conn.create_role("my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.create_role(
|
||||
"my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.add_role_to_instance_profile("my-profile", "my-role")
|
||||
|
||||
profile = conn.get_instance_profile("my-profile")
|
||||
|
|
@ -127,29 +133,37 @@ def test_list_instance_profiles():
|
|||
def test_list_instance_profiles_for_role():
|
||||
conn = boto.connect_iam()
|
||||
|
||||
conn.create_role(role_name="my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.create_role(role_name="my-role2", assume_role_policy_document="some policy2", path="my-path2")
|
||||
conn.create_role(role_name="my-role",
|
||||
assume_role_policy_document="some policy", path="my-path")
|
||||
conn.create_role(role_name="my-role2",
|
||||
assume_role_policy_document="some policy2", path="my-path2")
|
||||
|
||||
profile_name_list = ['my-profile', 'my-profile2']
|
||||
profile_path_list = ['my-path', 'my-path2']
|
||||
for profile_count in range(0, 2):
|
||||
conn.create_instance_profile(profile_name_list[profile_count], path=profile_path_list[profile_count])
|
||||
conn.create_instance_profile(
|
||||
profile_name_list[profile_count], path=profile_path_list[profile_count])
|
||||
|
||||
for profile_count in range(0, 2):
|
||||
conn.add_role_to_instance_profile(profile_name_list[profile_count], "my-role")
|
||||
conn.add_role_to_instance_profile(
|
||||
profile_name_list[profile_count], "my-role")
|
||||
|
||||
profile_dump = conn.list_instance_profiles_for_role(role_name="my-role")
|
||||
profile_list = profile_dump['list_instance_profiles_for_role_response']['list_instance_profiles_for_role_result']['instance_profiles']
|
||||
profile_list = profile_dump['list_instance_profiles_for_role_response'][
|
||||
'list_instance_profiles_for_role_result']['instance_profiles']
|
||||
for profile_count in range(0, len(profile_list)):
|
||||
profile_name_list.remove(profile_list[profile_count]["instance_profile_name"])
|
||||
profile_name_list.remove(profile_list[profile_count][
|
||||
"instance_profile_name"])
|
||||
profile_path_list.remove(profile_list[profile_count]["path"])
|
||||
profile_list[profile_count]["roles"]["member"]["role_name"].should.equal("my-role")
|
||||
profile_list[profile_count]["roles"]["member"][
|
||||
"role_name"].should.equal("my-role")
|
||||
|
||||
len(profile_name_list).should.equal(0)
|
||||
len(profile_path_list).should.equal(0)
|
||||
|
||||
profile_dump2 = conn.list_instance_profiles_for_role(role_name="my-role2")
|
||||
profile_list = profile_dump2['list_instance_profiles_for_role_response']['list_instance_profiles_for_role_result']['instance_profiles']
|
||||
profile_list = profile_dump2['list_instance_profiles_for_role_response'][
|
||||
'list_instance_profiles_for_role_result']['instance_profiles']
|
||||
len(profile_list).should.equal(0)
|
||||
|
||||
|
||||
|
|
@ -165,9 +179,11 @@ def test_list_role_policies():
|
|||
@mock_iam_deprecated()
|
||||
def test_put_role_policy():
|
||||
conn = boto.connect_iam()
|
||||
conn.create_role("my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.create_role(
|
||||
"my-role", assume_role_policy_document="some policy", path="my-path")
|
||||
conn.put_role_policy("my-role", "test policy", "my policy")
|
||||
policy = conn.get_role_policy("my-role", "test policy")['get_role_policy_response']['get_role_policy_result']['policy_name']
|
||||
policy = conn.get_role_policy(
|
||||
"my-role", "test policy")['get_role_policy_response']['get_role_policy_result']['policy_name']
|
||||
policy.should.equal("test policy")
|
||||
|
||||
|
||||
|
|
@ -246,13 +262,15 @@ def test_get_all_access_keys():
|
|||
conn.create_user('my-user')
|
||||
response = conn.get_all_access_keys('my-user')
|
||||
assert_equals(
|
||||
response['list_access_keys_response']['list_access_keys_result']['access_key_metadata'],
|
||||
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_not_equals(
|
||||
response['list_access_keys_response']['list_access_keys_result']['access_key_metadata'],
|
||||
response['list_access_keys_response'][
|
||||
'list_access_keys_result']['access_key_metadata'],
|
||||
[]
|
||||
)
|
||||
|
||||
|
|
@ -261,7 +279,8 @@ def test_get_all_access_keys():
|
|||
def test_delete_access_key():
|
||||
conn = boto.connect_iam()
|
||||
conn.create_user('my-user')
|
||||
access_key_id = conn.create_access_key('my-user')['create_access_key_response']['create_access_key_result']['access_key']['access_key_id']
|
||||
access_key_id = conn.create_access_key('my-user')['create_access_key_response'][
|
||||
'create_access_key_result']['access_key']['access_key_id']
|
||||
conn.delete_access_key(access_key_id, 'my-user')
|
||||
|
||||
|
||||
|
|
@ -278,9 +297,11 @@ def test_delete_user():
|
|||
def test_generate_credential_report():
|
||||
conn = boto.connect_iam()
|
||||
result = conn.generate_credential_report()
|
||||
result['generate_credential_report_response']['generate_credential_report_result']['state'].should.equal('STARTED')
|
||||
result['generate_credential_report_response'][
|
||||
'generate_credential_report_result']['state'].should.equal('STARTED')
|
||||
result = conn.generate_credential_report()
|
||||
result['generate_credential_report_response']['generate_credential_report_result']['state'].should.equal('COMPLETE')
|
||||
result['generate_credential_report_response'][
|
||||
'generate_credential_report_result']['state'].should.equal('COMPLETE')
|
||||
|
||||
|
||||
@mock_iam_deprecated()
|
||||
|
|
@ -293,7 +314,8 @@ def test_get_credential_report():
|
|||
while result['generate_credential_report_response']['generate_credential_report_result']['state'] != 'COMPLETE':
|
||||
result = conn.generate_credential_report()
|
||||
result = conn.get_credential_report()
|
||||
report = base64.b64decode(result['get_credential_report_response']['get_credential_report_result']['content'].encode('ascii')).decode('ascii')
|
||||
report = base64.b64decode(result['get_credential_report_response'][
|
||||
'get_credential_report_result']['content'].encode('ascii')).decode('ascii')
|
||||
report.should.match(r'.*my-user.*')
|
||||
|
||||
|
||||
|
|
@ -307,23 +329,31 @@ def test_managed_policy():
|
|||
path='/mypolicy/',
|
||||
description='my user managed policy')
|
||||
|
||||
aws_policies = conn.list_policies(scope='AWS')['list_policies_response']['list_policies_result']['policies']
|
||||
set(p.name for p in aws_managed_policies).should.equal(set(p['policy_name'] for p in aws_policies))
|
||||
aws_policies = conn.list_policies(scope='AWS')['list_policies_response'][
|
||||
'list_policies_result']['policies']
|
||||
set(p.name for p in aws_managed_policies).should.equal(
|
||||
set(p['policy_name'] for p in aws_policies))
|
||||
|
||||
user_policies = conn.list_policies(scope='Local')['list_policies_response']['list_policies_result']['policies']
|
||||
set(['UserManagedPolicy']).should.equal(set(p['policy_name'] for p in user_policies))
|
||||
user_policies = conn.list_policies(scope='Local')['list_policies_response'][
|
||||
'list_policies_result']['policies']
|
||||
set(['UserManagedPolicy']).should.equal(
|
||||
set(p['policy_name'] for p in user_policies))
|
||||
|
||||
all_policies = conn.list_policies()['list_policies_response']['list_policies_result']['policies']
|
||||
set(p['policy_name'] for p in aws_policies + user_policies).should.equal(set(p['policy_name'] for p in all_policies))
|
||||
all_policies = conn.list_policies()['list_policies_response'][
|
||||
'list_policies_result']['policies']
|
||||
set(p['policy_name'] for p in aws_policies +
|
||||
user_policies).should.equal(set(p['policy_name'] for p in all_policies))
|
||||
|
||||
role_name = 'my-role'
|
||||
conn.create_role(role_name, assume_role_policy_document={'policy': 'test'}, path="my-path")
|
||||
conn.create_role(role_name, assume_role_policy_document={
|
||||
'policy': 'test'}, path="my-path")
|
||||
for policy_name in ['AmazonElasticMapReduceRole',
|
||||
'AmazonElasticMapReduceforEC2Role']:
|
||||
policy_arn = 'arn:aws:iam::aws:policy/service-role/' + policy_name
|
||||
conn.attach_role_policy(policy_arn, role_name)
|
||||
|
||||
rows = conn.list_policies(only_attached=True)['list_policies_response']['list_policies_result']['policies']
|
||||
rows = conn.list_policies(only_attached=True)['list_policies_response'][
|
||||
'list_policies_result']['policies']
|
||||
rows.should.have.length_of(2)
|
||||
for x in rows:
|
||||
int(x['attachment_count']).should.be.greater_than(0)
|
||||
|
|
@ -332,7 +362,8 @@ def test_managed_policy():
|
|||
resp = conn.get_response('ListAttachedRolePolicies',
|
||||
{'RoleName': role_name},
|
||||
list_marker='AttachedPolicies')
|
||||
resp['list_attached_role_policies_response']['list_attached_role_policies_result']['attached_policies'].should.have.length_of(2)
|
||||
resp['list_attached_role_policies_response']['list_attached_role_policies_result'][
|
||||
'attached_policies'].should.have.length_of(2)
|
||||
|
||||
|
||||
@mock_iam
|
||||
|
|
|
|||
|
|
@ -29,7 +29,8 @@ def test_get_all_groups():
|
|||
conn = boto.connect_iam()
|
||||
conn.create_group('my-group1')
|
||||
conn.create_group('my-group2')
|
||||
groups = conn.get_all_groups()['list_groups_response']['list_groups_result']['groups']
|
||||
groups = conn.get_all_groups()['list_groups_response'][
|
||||
'list_groups_result']['groups']
|
||||
groups.should.have.length_of(2)
|
||||
|
||||
|
||||
|
|
@ -68,5 +69,6 @@ def test_get_groups_for_user():
|
|||
conn.add_user_to_group('my-group1', 'my-user')
|
||||
conn.add_user_to_group('my-group2', 'my-user')
|
||||
|
||||
groups = conn.get_groups_for_user('my-user')['list_groups_for_user_response']['list_groups_for_user_result']['groups']
|
||||
groups = conn.get_groups_for_user(
|
||||
'my-user')['list_groups_for_user_response']['list_groups_for_user_result']['groups']
|
||||
groups.should.have.length_of(2)
|
||||
|
|
|
|||
|
|
@ -16,10 +16,11 @@ def test_iam_server_get():
|
|||
backend = server.create_backend_app("iam")
|
||||
test_client = backend.test_client()
|
||||
|
||||
group_data = test_client.action_data("CreateGroup", GroupName="test group", Path="/")
|
||||
group_data = test_client.action_data(
|
||||
"CreateGroup", GroupName="test group", Path="/")
|
||||
group_id = re.search("<GroupId>(.*)</GroupId>", group_data).groups()[0]
|
||||
|
||||
groups_data = test_client.action_data("ListGroups")
|
||||
groups_ids = re.findall("<GroupId>(.*)</GroupId>", groups_data)
|
||||
|
||||
assert group_id in groups_ids
|
||||
assert group_id in groups_ids
|
||||
|
|
|
|||
|
|
@ -132,11 +132,13 @@ def test_create_stream_without_redshift():
|
|||
"HasMoreDestinations": False,
|
||||
})
|
||||
|
||||
|
||||
@mock_kinesis
|
||||
def test_deescribe_non_existant_stream():
|
||||
client = boto3.client('firehose', region_name='us-east-1')
|
||||
|
||||
client.describe_delivery_stream.when.called_with(DeliveryStreamName='not-a-stream').should.throw(ClientError)
|
||||
client.describe_delivery_stream.when.called_with(
|
||||
DeliveryStreamName='not-a-stream').should.throw(ClientError)
|
||||
|
||||
|
||||
@mock_kinesis
|
||||
|
|
@ -146,11 +148,13 @@ def test_list_and_delete_stream():
|
|||
create_stream(client, 'stream1')
|
||||
create_stream(client, 'stream2')
|
||||
|
||||
set(client.list_delivery_streams()['DeliveryStreamNames']).should.equal(set(['stream1', 'stream2']))
|
||||
set(client.list_delivery_streams()['DeliveryStreamNames']).should.equal(
|
||||
set(['stream1', 'stream2']))
|
||||
|
||||
client.delete_delivery_stream(DeliveryStreamName='stream1')
|
||||
|
||||
set(client.list_delivery_streams()['DeliveryStreamNames']).should.equal(set(['stream2']))
|
||||
set(client.list_delivery_streams()[
|
||||
'DeliveryStreamNames']).should.equal(set(['stream2']))
|
||||
|
||||
|
||||
@mock_kinesis
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ def test_create_cluster():
|
|||
stream = stream_response["StreamDescription"]
|
||||
stream["StreamName"].should.equal("my_stream")
|
||||
stream["HasMoreShards"].should.equal(False)
|
||||
stream["StreamARN"].should.equal("arn:aws:kinesis:us-west-2:123456789012:my_stream")
|
||||
stream["StreamARN"].should.equal(
|
||||
"arn:aws:kinesis:us-west-2:123456789012:my_stream")
|
||||
stream["StreamStatus"].should.equal("ACTIVE")
|
||||
|
||||
shards = stream['Shards']
|
||||
|
|
@ -28,7 +29,8 @@ def test_create_cluster():
|
|||
@mock_kinesis_deprecated
|
||||
def test_describe_non_existant_stream():
|
||||
conn = boto.kinesis.connect_to_region("us-east-1")
|
||||
conn.describe_stream.when.called_with("not-a-stream").should.throw(ResourceNotFoundException)
|
||||
conn.describe_stream.when.called_with(
|
||||
"not-a-stream").should.throw(ResourceNotFoundException)
|
||||
|
||||
|
||||
@mock_kinesis_deprecated
|
||||
|
|
@ -45,7 +47,8 @@ def test_list_and_delete_stream():
|
|||
conn.list_streams()['StreamNames'].should.have.length_of(1)
|
||||
|
||||
# Delete invalid id
|
||||
conn.delete_stream.when.called_with("not-a-stream").should.throw(ResourceNotFoundException)
|
||||
conn.delete_stream.when.called_with(
|
||||
"not-a-stream").should.throw(ResourceNotFoundException)
|
||||
|
||||
|
||||
@mock_kinesis_deprecated
|
||||
|
|
@ -73,7 +76,8 @@ def test_get_invalid_shard_iterator():
|
|||
stream_name = "my_stream"
|
||||
conn.create_stream(stream_name, 1)
|
||||
|
||||
conn.get_shard_iterator.when.called_with(stream_name, "123", 'TRIM_HORIZON').should.throw(ResourceNotFoundException)
|
||||
conn.get_shard_iterator.when.called_with(
|
||||
stream_name, "123", 'TRIM_HORIZON').should.throw(ResourceNotFoundException)
|
||||
|
||||
|
||||
@mock_kinesis_deprecated
|
||||
|
|
@ -138,7 +142,8 @@ def test_get_records_limit():
|
|||
|
||||
@mock_kinesis_deprecated
|
||||
def test_get_records_at_sequence_number():
|
||||
# AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted by a specific sequence number.
|
||||
# AT_SEQUENCE_NUMBER - Start reading exactly from the position denoted by
|
||||
# a specific sequence number.
|
||||
conn = boto.kinesis.connect_to_region("us-west-2")
|
||||
stream_name = "my_stream"
|
||||
conn.create_stream(stream_name, 1)
|
||||
|
|
@ -158,7 +163,8 @@ def test_get_records_at_sequence_number():
|
|||
second_sequence_id = response['Records'][1]['SequenceNumber']
|
||||
|
||||
# Then get a new iterator starting at that id
|
||||
response = conn.get_shard_iterator(stream_name, shard_id, 'AT_SEQUENCE_NUMBER', second_sequence_id)
|
||||
response = conn.get_shard_iterator(
|
||||
stream_name, shard_id, 'AT_SEQUENCE_NUMBER', second_sequence_id)
|
||||
shard_iterator = response['ShardIterator']
|
||||
|
||||
response = conn.get_records(shard_iterator)
|
||||
|
|
@ -169,7 +175,8 @@ def test_get_records_at_sequence_number():
|
|||
|
||||
@mock_kinesis_deprecated
|
||||
def test_get_records_after_sequence_number():
|
||||
# AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted by a specific sequence number.
|
||||
# AFTER_SEQUENCE_NUMBER - Start reading right after the position denoted
|
||||
# by a specific sequence number.
|
||||
conn = boto.kinesis.connect_to_region("us-west-2")
|
||||
stream_name = "my_stream"
|
||||
conn.create_stream(stream_name, 1)
|
||||
|
|
@ -189,7 +196,8 @@ def test_get_records_after_sequence_number():
|
|||
second_sequence_id = response['Records'][1]['SequenceNumber']
|
||||
|
||||
# Then get a new iterator starting after that id
|
||||
response = conn.get_shard_iterator(stream_name, shard_id, 'AFTER_SEQUENCE_NUMBER', second_sequence_id)
|
||||
response = conn.get_shard_iterator(
|
||||
stream_name, shard_id, 'AFTER_SEQUENCE_NUMBER', second_sequence_id)
|
||||
shard_iterator = response['ShardIterator']
|
||||
|
||||
response = conn.get_records(shard_iterator)
|
||||
|
|
@ -199,7 +207,8 @@ def test_get_records_after_sequence_number():
|
|||
|
||||
@mock_kinesis_deprecated
|
||||
def test_get_records_latest():
|
||||
# LATEST - Start reading just after the most recent record in the shard, so that you always read the most recent data in the shard.
|
||||
# LATEST - Start reading just after the most recent record in the shard,
|
||||
# so that you always read the most recent data in the shard.
|
||||
conn = boto.kinesis.connect_to_region("us-west-2")
|
||||
stream_name = "my_stream"
|
||||
conn.create_stream(stream_name, 1)
|
||||
|
|
@ -219,7 +228,8 @@ def test_get_records_latest():
|
|||
second_sequence_id = response['Records'][1]['SequenceNumber']
|
||||
|
||||
# Then get a new iterator starting after that id
|
||||
response = conn.get_shard_iterator(stream_name, shard_id, 'LATEST', second_sequence_id)
|
||||
response = conn.get_shard_iterator(
|
||||
stream_name, shard_id, 'LATEST', second_sequence_id)
|
||||
shard_iterator = response['ShardIterator']
|
||||
|
||||
# Write some more data
|
||||
|
|
@ -251,10 +261,10 @@ def test_add_tags():
|
|||
conn.create_stream(stream_name, 1)
|
||||
|
||||
conn.describe_stream(stream_name)
|
||||
conn.add_tags_to_stream(stream_name, {'tag1':'val1'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag2':'val2'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag1':'val3'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag2':'val4'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag1': 'val1'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag2': 'val2'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag1': 'val3'})
|
||||
conn.add_tags_to_stream(stream_name, {'tag2': 'val4'})
|
||||
|
||||
|
||||
@mock_kinesis_deprecated
|
||||
|
|
@ -264,17 +274,21 @@ def test_list_tags():
|
|||
conn.create_stream(stream_name, 1)
|
||||
|
||||
conn.describe_stream(stream_name)
|
||||
conn.add_tags_to_stream(stream_name, {'tag1':'val1'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag1': 'val1'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag1').should.equal('val1')
|
||||
conn.add_tags_to_stream(stream_name, {'tag2':'val2'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag2': 'val2'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag2').should.equal('val2')
|
||||
conn.add_tags_to_stream(stream_name, {'tag1':'val3'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag1': 'val3'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag1').should.equal('val3')
|
||||
conn.add_tags_to_stream(stream_name, {'tag2':'val4'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag2': 'val4'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag2').should.equal('val4')
|
||||
|
||||
|
||||
|
|
@ -285,18 +299,22 @@ def test_remove_tags():
|
|||
conn.create_stream(stream_name, 1)
|
||||
|
||||
conn.describe_stream(stream_name)
|
||||
conn.add_tags_to_stream(stream_name, {'tag1':'val1'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag1': 'val1'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag1').should.equal('val1')
|
||||
conn.remove_tags_from_stream(stream_name, ['tag1'])
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag1').should.equal(None)
|
||||
|
||||
conn.add_tags_to_stream(stream_name, {'tag2':'val2'})
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
conn.add_tags_to_stream(stream_name, {'tag2': 'val2'})
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag2').should.equal('val2')
|
||||
conn.remove_tags_from_stream(stream_name, ['tag2'])
|
||||
tags = dict([(tag['Key'], tag['Value']) for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags = dict([(tag['Key'], tag['Value'])
|
||||
for tag in conn.list_tags_for_stream(stream_name)['Tags']])
|
||||
tags.get('tag2').should.equal(None)
|
||||
|
||||
|
||||
|
|
@ -316,10 +334,12 @@ def test_split_shard():
|
|||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(2)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
|
||||
shard_range = shards[0]['HashKeyRange']
|
||||
new_starting_hash = (int(shard_range['EndingHashKey'])+int(shard_range['StartingHashKey'])) // 2
|
||||
new_starting_hash = (
|
||||
int(shard_range['EndingHashKey']) + int(shard_range['StartingHashKey'])) // 2
|
||||
conn.split_shard("my_stream", shards[0]['ShardId'], str(new_starting_hash))
|
||||
|
||||
stream_response = conn.describe_stream(stream_name)
|
||||
|
|
@ -327,10 +347,12 @@ def test_split_shard():
|
|||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(3)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
|
||||
shard_range = shards[2]['HashKeyRange']
|
||||
new_starting_hash = (int(shard_range['EndingHashKey'])+int(shard_range['StartingHashKey'])) // 2
|
||||
new_starting_hash = (
|
||||
int(shard_range['EndingHashKey']) + int(shard_range['StartingHashKey'])) // 2
|
||||
conn.split_shard("my_stream", shards[2]['ShardId'], str(new_starting_hash))
|
||||
|
||||
stream_response = conn.describe_stream(stream_name)
|
||||
|
|
@ -338,7 +360,8 @@ def test_split_shard():
|
|||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(4)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
|
||||
|
||||
@mock_kinesis_deprecated
|
||||
|
|
@ -358,28 +381,34 @@ def test_merge_shards():
|
|||
shards = stream['Shards']
|
||||
shards.should.have.length_of(4)
|
||||
|
||||
conn.merge_shards.when.called_with(stream_name, 'shardId-000000000000', 'shardId-000000000002').should.throw(InvalidArgumentException)
|
||||
conn.merge_shards.when.called_with(
|
||||
stream_name, 'shardId-000000000000', 'shardId-000000000002').should.throw(InvalidArgumentException)
|
||||
|
||||
stream_response = conn.describe_stream(stream_name)
|
||||
|
||||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(4)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
|
||||
conn.merge_shards(stream_name, 'shardId-000000000000', 'shardId-000000000001')
|
||||
conn.merge_shards(stream_name, 'shardId-000000000000',
|
||||
'shardId-000000000001')
|
||||
|
||||
stream_response = conn.describe_stream(stream_name)
|
||||
|
||||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(3)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
conn.merge_shards(stream_name, 'shardId-000000000002', 'shardId-000000000000')
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
conn.merge_shards(stream_name, 'shardId-000000000002',
|
||||
'shardId-000000000000')
|
||||
|
||||
stream_response = conn.describe_stream(stream_name)
|
||||
|
||||
stream = stream_response["StreamDescription"]
|
||||
shards = stream['Shards']
|
||||
shards.should.have.length_of(2)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber'] for shard in shards]).should.equal(99)
|
||||
sum([shard['SequenceNumberRange']['EndingSequenceNumber']
|
||||
for shard in shards]).should.equal(99)
|
||||
|
|
|
|||
|
|
@ -8,11 +8,13 @@ import sure # noqa
|
|||
from moto import mock_kms_deprecated
|
||||
from nose.tools import assert_raises
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_create_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
|
||||
key['KeyMetadata']['Description'].should.equal("my key")
|
||||
key['KeyMetadata']['KeyUsage'].should.equal("ENCRYPT_DECRYPT")
|
||||
|
|
@ -22,7 +24,8 @@ def test_create_key():
|
|||
@mock_kms_deprecated
|
||||
def test_describe_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
key = conn.describe_key(key_id)
|
||||
|
|
@ -33,8 +36,10 @@ def test_describe_key():
|
|||
@mock_kms_deprecated
|
||||
def test_describe_key_via_alias():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias', target_key_id=key['KeyMetadata']['KeyId'])
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias',
|
||||
target_key_id=key['KeyMetadata']['KeyId'])
|
||||
|
||||
alias_key = conn.describe_key('alias/my-key-alias')
|
||||
alias_key['KeyMetadata']['Description'].should.equal("my key")
|
||||
|
|
@ -45,16 +50,20 @@ def test_describe_key_via_alias():
|
|||
@mock_kms_deprecated
|
||||
def test_describe_key_via_alias_not_found():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias', target_key_id=key['KeyMetadata']['KeyId'])
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias',
|
||||
target_key_id=key['KeyMetadata']['KeyId'])
|
||||
|
||||
conn.describe_key.when.called_with('alias/not-found-alias').should.throw(JSONResponseError)
|
||||
conn.describe_key.when.called_with(
|
||||
'alias/not-found-alias').should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_describe_key_via_arn():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
arn = key['KeyMetadata']['Arn']
|
||||
|
||||
the_key = conn.describe_key(arn)
|
||||
|
|
@ -66,15 +75,18 @@ def test_describe_key_via_arn():
|
|||
@mock_kms_deprecated
|
||||
def test_describe_missing_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
conn.describe_key.when.called_with("not-a-key").should.throw(JSONResponseError)
|
||||
conn.describe_key.when.called_with(
|
||||
"not-a-key").should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_list_keys():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
conn.create_key(policy="my policy", description="my key1", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_key(policy="my policy", description="my key2", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_key(policy="my policy", description="my key1",
|
||||
key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_key(policy="my policy", description="my key2",
|
||||
key_usage='ENCRYPT_DECRYPT')
|
||||
|
||||
keys = conn.list_keys()
|
||||
keys['Keys'].should.have.length_of(2)
|
||||
|
|
@ -84,56 +96,67 @@ def test_list_keys():
|
|||
def test_enable_key_rotation():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
conn.enable_key_rotation(key_id)
|
||||
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_enable_key_rotation_via_arn():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['Arn']
|
||||
|
||||
conn.enable_key_rotation(key_id)
|
||||
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_enable_key_rotation_with_missing_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
conn.enable_key_rotation.when.called_with("not-a-key").should.throw(JSONResponseError)
|
||||
conn.enable_key_rotation.when.called_with(
|
||||
"not-a-key").should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_enable_key_rotation_with_alias_name_should_fail():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias', target_key_id=key['KeyMetadata']['KeyId'])
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias',
|
||||
target_key_id=key['KeyMetadata']['KeyId'])
|
||||
|
||||
alias_key = conn.describe_key('alias/my-key-alias')
|
||||
alias_key['KeyMetadata']['Arn'].should.equal(key['KeyMetadata']['Arn'])
|
||||
|
||||
conn.enable_key_rotation.when.called_with('alias/my-alias').should.throw(JSONResponseError)
|
||||
conn.enable_key_rotation.when.called_with(
|
||||
'alias/my-alias').should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_disable_key_rotation():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
conn.enable_key_rotation(key_id)
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(True)
|
||||
|
||||
conn.disable_key_rotation(key_id)
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
|
|
@ -157,59 +180,70 @@ def test_decrypt():
|
|||
@mock_kms_deprecated
|
||||
def test_disable_key_rotation_with_missing_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
conn.disable_key_rotation.when.called_with("not-a-key").should.throw(JSONResponseError)
|
||||
conn.disable_key_rotation.when.called_with(
|
||||
"not-a-key").should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_get_key_rotation_status_with_missing_key():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
conn.get_key_rotation_status.when.called_with("not-a-key").should.throw(JSONResponseError)
|
||||
conn.get_key_rotation_status.when.called_with(
|
||||
"not-a-key").should.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_get_key_rotation_status():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_create_key_defaults_key_rotation():
|
||||
conn = boto.kms.connect_to_region("us-west-2")
|
||||
|
||||
key = conn.create_key(policy="my policy", description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy="my policy",
|
||||
description="my key", key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
conn.get_key_rotation_status(key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
conn.get_key_rotation_status(
|
||||
key_id)['KeyRotationEnabled'].should.equal(False)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_get_key_policy():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
policy = conn.get_key_policy(key_id, 'default')
|
||||
policy['Policy'].should.equal('my policy')
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_get_key_policy_via_arn():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
policy = conn.get_key_policy(key['KeyMetadata']['Arn'], 'default')
|
||||
|
||||
policy['Policy'].should.equal('my policy')
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test_put_key_policy():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
conn.put_key_policy(key_id, 'default', 'new policy')
|
||||
|
|
@ -221,7 +255,8 @@ def test_put_key_policy():
|
|||
def test_put_key_policy_via_arn():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['Arn']
|
||||
|
||||
conn.put_key_policy(key_id, 'default', 'new policy')
|
||||
|
|
@ -233,10 +268,13 @@ def test_put_key_policy_via_arn():
|
|||
def test_put_key_policy_via_alias_should_not_update():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias', target_key_id=key['KeyMetadata']['KeyId'])
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
conn.create_alias(alias_name='alias/my-key-alias',
|
||||
target_key_id=key['KeyMetadata']['KeyId'])
|
||||
|
||||
conn.put_key_policy.when.called_with('alias/my-key-alias', 'default', 'new policy').should.throw(JSONResponseError)
|
||||
conn.put_key_policy.when.called_with(
|
||||
'alias/my-key-alias', 'default', 'new policy').should.throw(JSONResponseError)
|
||||
|
||||
policy = conn.get_key_policy(key['KeyMetadata']['KeyId'], 'default')
|
||||
policy['Policy'].should.equal('my policy')
|
||||
|
|
@ -246,7 +284,8 @@ def test_put_key_policy_via_alias_should_not_update():
|
|||
def test_put_key_policy():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
conn.put_key_policy(key['KeyMetadata']['Arn'], 'default', 'new policy')
|
||||
|
||||
policy = conn.get_key_policy(key['KeyMetadata']['KeyId'], 'default')
|
||||
|
|
@ -257,7 +296,8 @@ def test_put_key_policy():
|
|||
def test_list_key_policies():
|
||||
conn = boto.kms.connect_to_region('us-west-2')
|
||||
|
||||
key = conn.create_key(policy='my policy', description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key = conn.create_key(policy='my policy',
|
||||
description='my key1', key_usage='ENCRYPT_DECRYPT')
|
||||
key_id = key['KeyMetadata']['KeyId']
|
||||
|
||||
policies = conn.list_key_policies(key_id)
|
||||
|
|
@ -323,7 +363,8 @@ def test__create_alias__raises_if_wrong_prefix():
|
|||
ex = err.exception
|
||||
ex.error_message.should.equal('Invalid identifier')
|
||||
ex.error_code.should.equal('ValidationException')
|
||||
ex.body.should.equal({'message': 'Invalid identifier', '__type': 'ValidationException'})
|
||||
ex.body.should.equal({'message': 'Invalid identifier',
|
||||
'__type': 'ValidationException'})
|
||||
ex.reason.should.equal('Bad Request')
|
||||
ex.status.should.equal(400)
|
||||
|
||||
|
|
@ -371,16 +412,19 @@ def test__create_alias__raises_if_alias_has_restricted_characters():
|
|||
kms.create_alias(alias_name, key_id)
|
||||
ex = err.exception
|
||||
ex.body['__type'].should.equal('ValidationException')
|
||||
ex.body['message'].should.equal("1 validation error detected: Value '{alias_name}' at 'aliasName' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9:/_-]+$".format(**locals()))
|
||||
ex.body['message'].should.equal(
|
||||
"1 validation error detected: Value '{alias_name}' at 'aliasName' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9:/_-]+$".format(**locals()))
|
||||
ex.error_code.should.equal('ValidationException')
|
||||
ex.message.should.equal("1 validation error detected: Value '{alias_name}' at 'aliasName' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9:/_-]+$".format(**locals()))
|
||||
ex.message.should.equal(
|
||||
"1 validation error detected: Value '{alias_name}' at 'aliasName' failed to satisfy constraint: Member must satisfy regular expression pattern: ^[a-zA-Z0-9:/_-]+$".format(**locals()))
|
||||
ex.reason.should.equal('Bad Request')
|
||||
ex.status.should.equal(400)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test__create_alias__raises_if_alias_has_colon_character():
|
||||
# For some reason, colons are not accepted for an alias, even though they are accepted by regex ^[a-zA-Z0-9:/_-]+$
|
||||
# For some reason, colons are not accepted for an alias, even though they
|
||||
# are accepted by regex ^[a-zA-Z0-9:/_-]+$
|
||||
kms = boto.connect_kms()
|
||||
create_resp = kms.create_key()
|
||||
key_id = create_resp['KeyMetadata']['KeyId']
|
||||
|
|
@ -394,9 +438,11 @@ def test__create_alias__raises_if_alias_has_colon_character():
|
|||
kms.create_alias(alias_name, key_id)
|
||||
ex = err.exception
|
||||
ex.body['__type'].should.equal('ValidationException')
|
||||
ex.body['message'].should.equal("{alias_name} contains invalid characters for an alias".format(**locals()))
|
||||
ex.body['message'].should.equal(
|
||||
"{alias_name} contains invalid characters for an alias".format(**locals()))
|
||||
ex.error_code.should.equal('ValidationException')
|
||||
ex.message.should.equal("{alias_name} contains invalid characters for an alias".format(**locals()))
|
||||
ex.message.should.equal(
|
||||
"{alias_name} contains invalid characters for an alias".format(**locals()))
|
||||
ex.reason.should.equal('Bad Request')
|
||||
ex.status.should.equal(400)
|
||||
|
||||
|
|
@ -481,10 +527,12 @@ def test__delete_alias__raises_if_alias_is_not_found():
|
|||
|
||||
ex = err.exception
|
||||
ex.body['__type'].should.equal('NotFoundException')
|
||||
ex.body['message'].should.match(r'Alias arn:aws:kms:{region}:\d{{12}}:{alias_name} is not found.'.format(**locals()))
|
||||
ex.body['message'].should.match(
|
||||
r'Alias arn:aws:kms:{region}:\d{{12}}:{alias_name} is not found.'.format(**locals()))
|
||||
ex.box_usage.should.be.none
|
||||
ex.error_code.should.be.none
|
||||
ex.message.should.match(r'Alias arn:aws:kms:{region}:\d{{12}}:{alias_name} is not found.'.format(**locals()))
|
||||
ex.message.should.match(
|
||||
r'Alias arn:aws:kms:{region}:\d{{12}}:{alias_name} is not found.'.format(**locals()))
|
||||
ex.reason.should.equal('Bad Request')
|
||||
ex.request_id.should.be.none
|
||||
ex.status.should.equal(400)
|
||||
|
|
@ -527,7 +575,8 @@ def test__list_aliases():
|
|||
len([alias for alias in aliases if
|
||||
has_correct_arn(alias) and 'alias/my-alias2' == alias['AliasName']]).should.equal(1)
|
||||
|
||||
len([alias for alias in aliases if 'TargetKeyId' in alias and key_id == alias['TargetKeyId']]).should.equal(3)
|
||||
len([alias for alias in aliases if 'TargetKeyId' in alias and key_id ==
|
||||
alias['TargetKeyId']]).should.equal(3)
|
||||
|
||||
len(aliases).should.equal(7)
|
||||
|
||||
|
|
@ -537,13 +586,17 @@ def test__assert_valid_key_id():
|
|||
from moto.kms.responses import _assert_valid_key_id
|
||||
import uuid
|
||||
|
||||
_assert_valid_key_id.when.called_with("not-a-key").should.throw(JSONResponseError)
|
||||
_assert_valid_key_id.when.called_with(str(uuid.uuid4())).should_not.throw(JSONResponseError)
|
||||
_assert_valid_key_id.when.called_with(
|
||||
"not-a-key").should.throw(JSONResponseError)
|
||||
_assert_valid_key_id.when.called_with(
|
||||
str(uuid.uuid4())).should_not.throw(JSONResponseError)
|
||||
|
||||
|
||||
@mock_kms_deprecated
|
||||
def test__assert_default_policy():
|
||||
from moto.kms.responses import _assert_default_policy
|
||||
|
||||
_assert_default_policy.when.called_with("not-default").should.throw(JSONResponseError)
|
||||
_assert_default_policy.when.called_with("default").should_not.throw(JSONResponseError)
|
||||
_assert_default_policy.when.called_with(
|
||||
"not-default").should.throw(JSONResponseError)
|
||||
_assert_default_policy.when.called_with(
|
||||
"default").should_not.throw(JSONResponseError)
|
||||
|
|
|
|||
|
|
@ -102,7 +102,8 @@ def test_describe_instances():
|
|||
S1L1_i1.should.be.within([i["InstanceId"] for i in response])
|
||||
S1L1_i2.should.be.within([i["InstanceId"] for i in response])
|
||||
|
||||
response2 = client.describe_instances(InstanceIds=[S1L1_i1, S1L1_i2])['Instances']
|
||||
response2 = client.describe_instances(
|
||||
InstanceIds=[S1L1_i1, S1L1_i2])['Instances']
|
||||
sorted(response2, key=lambda d: d['InstanceId']).should.equal(
|
||||
sorted(response, key=lambda d: d['InstanceId']))
|
||||
|
||||
|
|
@ -168,9 +169,8 @@ def test_ec2_integration():
|
|||
reservations = ec2.describe_instances()['Reservations']
|
||||
reservations[0]['Instances'].should.have.length_of(1)
|
||||
instance = reservations[0]['Instances'][0]
|
||||
opsworks_instance = opsworks.describe_instances(StackId=stack_id)['Instances'][0]
|
||||
opsworks_instance = opsworks.describe_instances(StackId=stack_id)[
|
||||
'Instances'][0]
|
||||
|
||||
instance['InstanceId'].should.equal(opsworks_instance['Ec2InstanceId'])
|
||||
instance['PrivateIpAddress'].should.equal(opsworks_instance['PrivateIp'])
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,8 @@ def test_create_layer_response():
|
|||
Name="_",
|
||||
Shortname="TestLayerShortName"
|
||||
).should.throw(
|
||||
Exception, re.compile(r'already a layer with shortname "TestLayerShortName"')
|
||||
Exception, re.compile(
|
||||
r'already a layer with shortname "TestLayerShortName"')
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -69,4 +70,3 @@ def test_describe_layers():
|
|||
rv1['Layers'].should.equal(rv2['Layers'])
|
||||
|
||||
rv1['Layers'][0]['Name'].should.equal("TestLayer")
|
||||
|
||||
|
|
|
|||
|
|
@ -44,5 +44,3 @@ def test_describe_stacks():
|
|||
client.describe_stacks.when.called_with(StackIds=["foo"]).should.throw(
|
||||
Exception, re.compile(r'foo')
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -15,14 +15,15 @@ def test_create_database():
|
|||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
|
||||
database = conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2',
|
||||
security_groups=["my_sg"])
|
||||
security_groups=["my_sg"])
|
||||
|
||||
database.status.should.equal('available')
|
||||
database.id.should.equal("db-master-1")
|
||||
database.allocated_storage.should.equal(10)
|
||||
database.instance_class.should.equal("db.m1.small")
|
||||
database.master_username.should.equal("root")
|
||||
database.endpoint.should.equal(('db-master-1.aaaaaaaaaa.us-west-2.rds.amazonaws.com', 3306))
|
||||
database.endpoint.should.equal(
|
||||
('db-master-1.aaaaaaaaaa.us-west-2.rds.amazonaws.com', 3306))
|
||||
database.security_groups[0].name.should.equal('my_sg')
|
||||
|
||||
|
||||
|
|
@ -47,7 +48,8 @@ def test_get_databases():
|
|||
@mock_rds_deprecated
|
||||
def test_describe_non_existant_database():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
conn.get_all_dbinstances.when.called_with("not-a-db").should.throw(BotoServerError)
|
||||
conn.get_all_dbinstances.when.called_with(
|
||||
"not-a-db").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -66,7 +68,8 @@ def test_delete_database():
|
|||
@mock_rds_deprecated
|
||||
def test_delete_non_existant_database():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
conn.delete_dbinstance.when.called_with("not-a-db").should.throw(BotoServerError)
|
||||
conn.delete_dbinstance.when.called_with(
|
||||
"not-a-db").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_rds_deprecated
|
||||
|
|
@ -99,7 +102,8 @@ def test_get_security_groups():
|
|||
@mock_rds_deprecated
|
||||
def test_get_non_existant_security_group():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
conn.get_all_dbsecurity_groups.when.called_with("not-a-sg").should.throw(BotoServerError)
|
||||
conn.get_all_dbsecurity_groups.when.called_with(
|
||||
"not-a-sg").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_rds_deprecated
|
||||
|
|
@ -116,7 +120,8 @@ def test_delete_database_security_group():
|
|||
@mock_rds_deprecated
|
||||
def test_delete_non_existant_security_group():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
conn.delete_dbsecurity_group.when.called_with("not-a-db").should.throw(BotoServerError)
|
||||
conn.delete_dbsecurity_group.when.called_with(
|
||||
"not-a-db").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -137,7 +142,8 @@ def test_security_group_authorize():
|
|||
def test_add_security_group_to_database():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
|
||||
database = conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
database = conn.create_dbinstance(
|
||||
"db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
security_group = conn.create_dbsecurity_group('db_sg', 'DB Security Group')
|
||||
database.modify(security_groups=[security_group])
|
||||
|
||||
|
|
@ -157,7 +163,8 @@ def test_add_database_subnet_group():
|
|||
|
||||
subnet_ids = [subnet1.id, subnet2.id]
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
subnet_group = conn.create_db_subnet_group("db_subnet", "my db subnet", subnet_ids)
|
||||
subnet_group = conn.create_db_subnet_group(
|
||||
"db_subnet", "my db subnet", subnet_ids)
|
||||
subnet_group.name.should.equal('db_subnet')
|
||||
subnet_group.description.should.equal("my db subnet")
|
||||
list(subnet_group.subnet_ids).should.equal(subnet_ids)
|
||||
|
|
@ -177,7 +184,8 @@ def test_describe_database_subnet_group():
|
|||
list(conn.get_all_db_subnet_groups()).should.have.length_of(2)
|
||||
list(conn.get_all_db_subnet_groups("db_subnet1")).should.have.length_of(1)
|
||||
|
||||
conn.get_all_db_subnet_groups.when.called_with("not-a-subnet").should.throw(BotoServerError)
|
||||
conn.get_all_db_subnet_groups.when.called_with(
|
||||
"not-a-subnet").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_ec2_deprecated
|
||||
|
|
@ -194,7 +202,8 @@ def test_delete_database_subnet_group():
|
|||
conn.delete_db_subnet_group("db_subnet1")
|
||||
list(conn.get_all_db_subnet_groups()).should.have.length_of(0)
|
||||
|
||||
conn.delete_db_subnet_group.when.called_with("db_subnet1").should.throw(BotoServerError)
|
||||
conn.delete_db_subnet_group.when.called_with(
|
||||
"db_subnet1").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -209,7 +218,7 @@ def test_create_database_in_subnet_group():
|
|||
conn.create_db_subnet_group("db_subnet1", "my db subnet", [subnet.id])
|
||||
|
||||
database = conn.create_dbinstance("db-master-1", 10, 'db.m1.small',
|
||||
'root', 'hunter2', db_subnet_group_name="db_subnet1")
|
||||
'root', 'hunter2', db_subnet_group_name="db_subnet1")
|
||||
|
||||
database = conn.get_all_dbinstances("db-master-1")[0]
|
||||
database.subnet_group.name.should.equal("db_subnet1")
|
||||
|
|
@ -220,9 +229,11 @@ def test_create_database_in_subnet_group():
|
|||
def test_create_database_replica():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
|
||||
primary = conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
primary = conn.create_dbinstance(
|
||||
"db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
|
||||
replica = conn.create_dbinstance_read_replica("replica", "db-master-1", "db.m1.small")
|
||||
replica = conn.create_dbinstance_read_replica(
|
||||
"replica", "db-master-1", "db.m1.small")
|
||||
replica.id.should.equal("replica")
|
||||
replica.instance_class.should.equal("db.m1.small")
|
||||
status_info = replica.status_infos[0]
|
||||
|
|
@ -238,13 +249,15 @@ def test_create_database_replica():
|
|||
primary = conn.get_all_dbinstances("db-master-1")[0]
|
||||
list(primary.read_replica_dbinstance_identifiers).should.have.length_of(0)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds_deprecated
|
||||
def test_create_cross_region_database_replica():
|
||||
west_1_conn = boto.rds.connect_to_region("us-west-1")
|
||||
west_2_conn = boto.rds.connect_to_region("us-west-2")
|
||||
|
||||
primary = west_1_conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
primary = west_1_conn.create_dbinstance(
|
||||
"db-master-1", 10, 'db.m1.small', 'root', 'hunter2')
|
||||
|
||||
primary_arn = "arn:aws:rds:us-west-1:1234567890:db:db-master-1"
|
||||
replica = west_2_conn.create_dbinstance_read_replica(
|
||||
|
|
@ -274,14 +287,15 @@ def test_connecting_to_us_east_1():
|
|||
conn = boto.rds.connect_to_region("us-east-1")
|
||||
|
||||
database = conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2',
|
||||
security_groups=["my_sg"])
|
||||
security_groups=["my_sg"])
|
||||
|
||||
database.status.should.equal('available')
|
||||
database.id.should.equal("db-master-1")
|
||||
database.allocated_storage.should.equal(10)
|
||||
database.instance_class.should.equal("db.m1.small")
|
||||
database.master_username.should.equal("root")
|
||||
database.endpoint.should.equal(('db-master-1.aaaaaaaaaa.us-east-1.rds.amazonaws.com', 3306))
|
||||
database.endpoint.should.equal(
|
||||
('db-master-1.aaaaaaaaaa.us-east-1.rds.amazonaws.com', 3306))
|
||||
database.security_groups[0].name.should.equal('my_sg')
|
||||
|
||||
|
||||
|
|
@ -290,7 +304,8 @@ def test_connecting_to_us_east_1():
|
|||
def test_create_database_with_iops():
|
||||
conn = boto.rds.connect_to_region("us-west-2")
|
||||
|
||||
database = conn.create_dbinstance("db-master-1", 10, 'db.m1.small', 'root', 'hunter2', iops=6000)
|
||||
database = conn.create_dbinstance(
|
||||
"db-master-1", 10, 'db.m1.small', 'root', 'hunter2', iops=6000)
|
||||
|
||||
database.status.should.equal('available')
|
||||
database.iops.should.equal(6000)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@ def test_create_database():
|
|||
database['DBInstance']['AllocatedStorage'].should.equal(10)
|
||||
database['DBInstance']['DBInstanceClass'].should.equal("db.m1.small")
|
||||
database['DBInstance']['MasterUsername'].should.equal("root")
|
||||
database['DBInstance']['DBSecurityGroups'][0]['DBSecurityGroupName'].should.equal('my_sg')
|
||||
database['DBInstance']['DBSecurityGroups'][0][
|
||||
'DBSecurityGroupName'].should.equal('my_sg')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -56,14 +57,16 @@ def test_get_databases():
|
|||
|
||||
instances = conn.describe_db_instances(DBInstanceIdentifier="db-master-1")
|
||||
list(instances['DBInstances']).should.have.length_of(1)
|
||||
instances['DBInstances'][0]['DBInstanceIdentifier'].should.equal("db-master-1")
|
||||
instances['DBInstances'][0][
|
||||
'DBInstanceIdentifier'].should.equal("db-master-1")
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_describe_non_existant_database():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.describe_db_instances.when.called_with(DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
conn.describe_db_instances.when.called_with(
|
||||
DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -95,6 +98,7 @@ def test_modify_non_existant_database():
|
|||
AllocatedStorage=20,
|
||||
ApplyImmediately=True).should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_reboot_db_instance():
|
||||
|
|
@ -115,7 +119,8 @@ def test_reboot_db_instance():
|
|||
@mock_rds2
|
||||
def test_reboot_non_existant_database():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.reboot_db_instance.when.called_with(DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
conn.reboot_db_instance.when.called_with(
|
||||
DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -144,7 +149,8 @@ def test_delete_database():
|
|||
@mock_rds2
|
||||
def test_delete_non_existant_database():
|
||||
conn = boto3.client('rds2', region_name="us-west-2")
|
||||
conn.delete_db_instance.when.called_with(DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
conn.delete_db_instance.when.called_with(
|
||||
DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -157,7 +163,8 @@ def test_create_option_group():
|
|||
OptionGroupDescription='test option group')
|
||||
option_group['OptionGroup']['OptionGroupName'].should.equal('test')
|
||||
option_group['OptionGroup']['EngineName'].should.equal('mysql')
|
||||
option_group['OptionGroup']['OptionGroupDescription'].should.equal('test option group')
|
||||
option_group['OptionGroup'][
|
||||
'OptionGroupDescription'].should.equal('test option group')
|
||||
option_group['OptionGroup']['MajorEngineVersion'].should.equal('5.6')
|
||||
|
||||
|
||||
|
|
@ -214,14 +221,16 @@ def test_describe_option_group():
|
|||
MajorEngineVersion='5.6',
|
||||
OptionGroupDescription='test option group')
|
||||
option_groups = conn.describe_option_groups(OptionGroupName='test')
|
||||
option_groups['OptionGroupsList'][0]['OptionGroupName'].should.equal('test')
|
||||
option_groups['OptionGroupsList'][0][
|
||||
'OptionGroupName'].should.equal('test')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_describe_non_existant_option_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.describe_option_groups.when.called_with(OptionGroupName="not-a-option-group").should.throw(ClientError)
|
||||
conn.describe_option_groups.when.called_with(
|
||||
OptionGroupName="not-a-option-group").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -233,41 +242,51 @@ def test_delete_option_group():
|
|||
MajorEngineVersion='5.6',
|
||||
OptionGroupDescription='test option group')
|
||||
option_groups = conn.describe_option_groups(OptionGroupName='test')
|
||||
option_groups['OptionGroupsList'][0]['OptionGroupName'].should.equal('test')
|
||||
option_groups['OptionGroupsList'][0][
|
||||
'OptionGroupName'].should.equal('test')
|
||||
conn.delete_option_group(OptionGroupName='test')
|
||||
conn.describe_option_groups.when.called_with(OptionGroupName='test').should.throw(ClientError)
|
||||
conn.describe_option_groups.when.called_with(
|
||||
OptionGroupName='test').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_delete_non_existant_option_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.delete_option_group.when.called_with(OptionGroupName='non-existant').should.throw(ClientError)
|
||||
conn.delete_option_group.when.called_with(
|
||||
OptionGroupName='non-existant').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_describe_option_group_options():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
option_group_options = conn.describe_option_group_options(EngineName='sqlserver-ee')
|
||||
option_group_options = conn.describe_option_group_options(
|
||||
EngineName='sqlserver-ee')
|
||||
len(option_group_options['OptionGroupOptions']).should.equal(4)
|
||||
option_group_options = conn.describe_option_group_options(EngineName='sqlserver-ee', MajorEngineVersion='11.00')
|
||||
option_group_options = conn.describe_option_group_options(
|
||||
EngineName='sqlserver-ee', MajorEngineVersion='11.00')
|
||||
len(option_group_options['OptionGroupOptions']).should.equal(2)
|
||||
option_group_options = conn.describe_option_group_options(EngineName='mysql', MajorEngineVersion='5.6')
|
||||
option_group_options = conn.describe_option_group_options(
|
||||
EngineName='mysql', MajorEngineVersion='5.6')
|
||||
len(option_group_options['OptionGroupOptions']).should.equal(1)
|
||||
conn.describe_option_group_options.when.called_with(EngineName='non-existent').should.throw(ClientError)
|
||||
conn.describe_option_group_options.when.called_with(EngineName='mysql', MajorEngineVersion='non-existent').should.throw(ClientError)
|
||||
conn.describe_option_group_options.when.called_with(
|
||||
EngineName='non-existent').should.throw(ClientError)
|
||||
conn.describe_option_group_options.when.called_with(
|
||||
EngineName='mysql', MajorEngineVersion='non-existent').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_modify_option_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_option_group(OptionGroupName='test', EngineName='mysql', MajorEngineVersion='5.6', OptionGroupDescription='test option group')
|
||||
conn.create_option_group(OptionGroupName='test', EngineName='mysql',
|
||||
MajorEngineVersion='5.6', OptionGroupDescription='test option group')
|
||||
# TODO: create option and validate before deleting.
|
||||
# if Someone can tell me how the hell to use this function
|
||||
# to add options to an option_group, I can finish coding this.
|
||||
result = conn.modify_option_group(OptionGroupName='test', OptionsToInclude=[], OptionsToRemove=['MEMCACHED'], ApplyImmediately=True)
|
||||
result = conn.modify_option_group(OptionGroupName='test', OptionsToInclude=[
|
||||
], OptionsToRemove=['MEMCACHED'], ApplyImmediately=True)
|
||||
result['OptionGroup']['EngineName'].should.equal('mysql')
|
||||
result['OptionGroup']['Options'].should.equal([])
|
||||
result['OptionGroup']['OptionGroupName'].should.equal('test')
|
||||
|
|
@ -277,36 +296,42 @@ def test_modify_option_group():
|
|||
@mock_rds2
|
||||
def test_modify_option_group_no_options():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_option_group(OptionGroupName='test', EngineName='mysql', MajorEngineVersion='5.6', OptionGroupDescription='test option group')
|
||||
conn.modify_option_group.when.called_with(OptionGroupName='test').should.throw(ClientError)
|
||||
conn.create_option_group(OptionGroupName='test', EngineName='mysql',
|
||||
MajorEngineVersion='5.6', OptionGroupDescription='test option group')
|
||||
conn.modify_option_group.when.called_with(
|
||||
OptionGroupName='test').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_modify_non_existant_option_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.modify_option_group.when.called_with(OptionGroupName='non-existant', OptionsToInclude=[('OptionName', 'Port', 'DBSecurityGroupMemberships', 'VpcSecurityGroupMemberships', 'OptionSettings')]).should.throw(ParamValidationError)
|
||||
conn.modify_option_group.when.called_with(OptionGroupName='non-existant', OptionsToInclude=[(
|
||||
'OptionName', 'Port', 'DBSecurityGroupMemberships', 'VpcSecurityGroupMemberships', 'OptionSettings')]).should.throw(ParamValidationError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_delete_non_existant_database():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.delete_db_instance.when.called_with(DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
conn.delete_db_instance.when.called_with(
|
||||
DBInstanceIdentifier="not-a-db").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_list_tags_invalid_arn():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.list_tags_for_resource.when.called_with(ResourceName='arn:aws:rds:bad-arn').should.throw(ClientError)
|
||||
conn.list_tags_for_resource.when.called_with(
|
||||
ResourceName='arn:aws:rds:bad-arn').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_list_tags_db():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:foo')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:foo')
|
||||
result['TagList'].should.equal([])
|
||||
conn.create_db_instance(DBInstanceIdentifier='db-with-tags',
|
||||
AllocatedStorage=10,
|
||||
|
|
@ -326,11 +351,12 @@ def test_list_tags_db():
|
|||
'Value': 'bar1',
|
||||
},
|
||||
])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
result['TagList'].should.equal([{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -355,7 +381,8 @@ def test_add_tags_db():
|
|||
'Value': 'bar1',
|
||||
},
|
||||
])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-without-tags')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-without-tags')
|
||||
list(result['TagList']).should.have.length_of(2)
|
||||
conn.add_tags_to_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-without-tags',
|
||||
Tags=[
|
||||
|
|
@ -368,7 +395,8 @@ def test_add_tags_db():
|
|||
'Value': 'bar2',
|
||||
},
|
||||
])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-without-tags')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-without-tags')
|
||||
list(result['TagList']).should.have.length_of(3)
|
||||
|
||||
|
||||
|
|
@ -394,10 +422,13 @@ def test_remove_tags_db():
|
|||
'Value': 'bar1',
|
||||
},
|
||||
])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
list(result['TagList']).should.have.length_of(2)
|
||||
conn.remove_tags_from_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags', TagKeys=['foo'])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
conn.remove_tags_from_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags', TagKeys=['foo'])
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:db:db-with-tags')
|
||||
len(result['TagList']).should.equal(1)
|
||||
|
||||
|
||||
|
|
@ -409,7 +440,8 @@ def test_add_tags_option_group():
|
|||
EngineName='mysql',
|
||||
MajorEngineVersion='5.6',
|
||||
OptionGroupDescription='test option group')
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
list(result['TagList']).should.have.length_of(0)
|
||||
conn.add_tags_to_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test',
|
||||
Tags=[
|
||||
|
|
@ -421,7 +453,8 @@ def test_add_tags_option_group():
|
|||
'Key': 'foo2',
|
||||
'Value': 'bar2',
|
||||
}])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
list(result['TagList']).should.have.length_of(2)
|
||||
|
||||
|
||||
|
|
@ -433,7 +466,8 @@ def test_remove_tags_option_group():
|
|||
EngineName='mysql',
|
||||
MajorEngineVersion='5.6',
|
||||
OptionGroupDescription='test option group')
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
conn.add_tags_to_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test',
|
||||
Tags=[
|
||||
{
|
||||
|
|
@ -444,11 +478,13 @@ def test_remove_tags_option_group():
|
|||
'Key': 'foo2',
|
||||
'Value': 'bar2',
|
||||
}])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
list(result['TagList']).should.have.length_of(2)
|
||||
conn.remove_tags_from_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test',
|
||||
TagKeys=['foo'])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:og:test')
|
||||
list(result['TagList']).should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
@ -457,9 +493,11 @@ def test_remove_tags_option_group():
|
|||
def test_create_database_security_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
|
||||
result = conn.create_db_security_group(DBSecurityGroupName='db_sg', DBSecurityGroupDescription='DB Security Group')
|
||||
result = conn.create_db_security_group(
|
||||
DBSecurityGroupName='db_sg', DBSecurityGroupDescription='DB Security Group')
|
||||
result['DBSecurityGroup']['DBSecurityGroupName'].should.equal("db_sg")
|
||||
result['DBSecurityGroup']['DBSecurityGroupDescription'].should.equal("DB Security Group")
|
||||
result['DBSecurityGroup'][
|
||||
'DBSecurityGroupDescription'].should.equal("DB Security Group")
|
||||
result['DBSecurityGroup']['IPRanges'].should.equal([])
|
||||
|
||||
|
||||
|
|
@ -471,8 +509,10 @@ def test_get_security_groups():
|
|||
result = conn.describe_db_security_groups()
|
||||
result['DBSecurityGroups'].should.have.length_of(0)
|
||||
|
||||
conn.create_db_security_group(DBSecurityGroupName='db_sg1', DBSecurityGroupDescription='DB Security Group')
|
||||
conn.create_db_security_group(DBSecurityGroupName='db_sg2', DBSecurityGroupDescription='DB Security Group')
|
||||
conn.create_db_security_group(
|
||||
DBSecurityGroupName='db_sg1', DBSecurityGroupDescription='DB Security Group')
|
||||
conn.create_db_security_group(
|
||||
DBSecurityGroupName='db_sg2', DBSecurityGroupDescription='DB Security Group')
|
||||
|
||||
result = conn.describe_db_security_groups()
|
||||
result['DBSecurityGroups'].should.have.length_of(2)
|
||||
|
|
@ -486,14 +526,16 @@ def test_get_security_groups():
|
|||
@mock_rds2
|
||||
def test_get_non_existant_security_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.describe_db_security_groups.when.called_with(DBSecurityGroupName="not-a-sg").should.throw(ClientError)
|
||||
conn.describe_db_security_groups.when.called_with(
|
||||
DBSecurityGroupName="not-a-sg").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_delete_database_security_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_db_security_group(DBSecurityGroupName='db_sg', DBSecurityGroupDescription='DB Security Group')
|
||||
conn.create_db_security_group(
|
||||
DBSecurityGroupName='db_sg', DBSecurityGroupDescription='DB Security Group')
|
||||
|
||||
result = conn.describe_db_security_groups()
|
||||
result['DBSecurityGroups'].should.have.length_of(1)
|
||||
|
|
@ -507,7 +549,8 @@ def test_delete_database_security_group():
|
|||
@mock_rds2
|
||||
def test_delete_non_existant_security_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.delete_db_security_group.when.called_with(DBSecurityGroupName="not-a-db").should.throw(ClientError)
|
||||
conn.delete_db_security_group.when.called_with(
|
||||
DBSecurityGroupName="not-a-db").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -518,13 +561,13 @@ def test_security_group_authorize():
|
|||
DBSecurityGroupDescription='DB Security Group')
|
||||
security_group['DBSecurityGroup']['IPRanges'].should.equal([])
|
||||
|
||||
|
||||
conn.authorize_db_security_group_ingress(DBSecurityGroupName='db_sg',
|
||||
CIDRIP='10.3.2.45/32')
|
||||
|
||||
result = conn.describe_db_security_groups(DBSecurityGroupName="db_sg")
|
||||
result['DBSecurityGroups'][0]['IPRanges'].should.have.length_of(1)
|
||||
result['DBSecurityGroups'][0]['IPRanges'].should.equal([{'Status': 'authorized', 'CIDRIP': '10.3.2.45/32'}])
|
||||
result['DBSecurityGroups'][0]['IPRanges'].should.equal(
|
||||
[{'Status': 'authorized', 'CIDRIP': '10.3.2.45/32'}])
|
||||
|
||||
conn.authorize_db_security_group_ingress(DBSecurityGroupName='db_sg',
|
||||
CIDRIP='10.3.2.46/32')
|
||||
|
|
@ -554,9 +597,10 @@ def test_add_security_group_to_database():
|
|||
conn.create_db_security_group(DBSecurityGroupName='db_sg',
|
||||
DBSecurityGroupDescription='DB Security Group')
|
||||
conn.modify_db_instance(DBInstanceIdentifier='db-master-1',
|
||||
DBSecurityGroups=['db_sg'])
|
||||
DBSecurityGroups=['db_sg'])
|
||||
result = conn.describe_db_instances()
|
||||
result['DBInstances'][0]['DBSecurityGroups'][0]['DBSecurityGroupName'].should.equal('db_sg')
|
||||
result['DBInstances'][0]['DBSecurityGroups'][0][
|
||||
'DBSecurityGroupName'].should.equal('db_sg')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -572,12 +616,13 @@ def test_list_tags_security_group():
|
|||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])['DBSecurityGroup']['DBSecurityGroupName']
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(security_group)
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(
|
||||
security_group)
|
||||
result = conn.list_tags_for_resource(ResourceName=resource)
|
||||
result['TagList'].should.equal([{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -590,7 +635,8 @@ def test_add_tags_security_group():
|
|||
security_group = conn.create_db_security_group(DBSecurityGroupName="db_sg",
|
||||
DBSecurityGroupDescription='DB Security Group')['DBSecurityGroup']['DBSecurityGroupName']
|
||||
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(security_group)
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(
|
||||
security_group)
|
||||
conn.add_tags_to_resource(ResourceName=resource,
|
||||
Tags=[{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
|
|
@ -600,8 +646,9 @@ def test_add_tags_security_group():
|
|||
result = conn.list_tags_for_resource(ResourceName=resource)
|
||||
result['TagList'].should.equal([{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
|
|
@ -617,7 +664,8 @@ def test_remove_tags_security_group():
|
|||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])['DBSecurityGroup']['DBSecurityGroupName']
|
||||
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(security_group)
|
||||
resource = 'arn:aws:rds:us-west-2:1234567890:secgrp:{0}'.format(
|
||||
security_group)
|
||||
conn.remove_tags_from_resource(ResourceName=resource, TagKeys=['foo'])
|
||||
|
||||
result = conn.list_tags_for_resource(ResourceName=resource)
|
||||
|
|
@ -630,8 +678,10 @@ def test_remove_tags_security_group():
|
|||
def test_create_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet1 = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet2 = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/26')['Subnet']
|
||||
subnet1 = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet2 = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/26')['Subnet']
|
||||
|
||||
subnet_ids = [subnet1['SubnetId'], subnet2['SubnetId']]
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
|
|
@ -639,9 +689,11 @@ def test_create_database_subnet_group():
|
|||
DBSubnetGroupDescription='my db subnet',
|
||||
SubnetIds=subnet_ids)
|
||||
result['DBSubnetGroup']['DBSubnetGroupName'].should.equal("db_subnet")
|
||||
result['DBSubnetGroup']['DBSubnetGroupDescription'].should.equal("my db subnet")
|
||||
result['DBSubnetGroup'][
|
||||
'DBSubnetGroupDescription'].should.equal("my db subnet")
|
||||
subnets = result['DBSubnetGroup']['Subnets']
|
||||
subnet_group_ids = [subnets[0]['SubnetIdentifier'], subnets[1]['SubnetIdentifier']]
|
||||
subnet_group_ids = [subnets[0]['SubnetIdentifier'],
|
||||
subnets[1]['SubnetIdentifier']]
|
||||
list(subnet_group_ids).should.equal(subnet_ids)
|
||||
|
||||
|
||||
|
|
@ -651,7 +703,8 @@ def test_create_database_subnet_group():
|
|||
def test_create_database_in_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_db_subnet_group(DBSubnetGroupName='db_subnet1',
|
||||
|
|
@ -666,7 +719,8 @@ def test_create_database_in_subnet_group():
|
|||
Port=1234,
|
||||
DBSubnetGroupName='db_subnet1')
|
||||
result = conn.describe_db_instances(DBInstanceIdentifier='db-master-1')
|
||||
result['DBInstances'][0]['DBSubnetGroup']['DBSubnetGroupName'].should.equal('db_subnet1')
|
||||
result['DBInstances'][0]['DBSubnetGroup'][
|
||||
'DBSubnetGroupName'].should.equal('db_subnet1')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -675,7 +729,8 @@ def test_create_database_in_subnet_group():
|
|||
def test_describe_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_db_subnet_group(DBSubnetGroupName="db_subnet1",
|
||||
|
|
@ -691,9 +746,11 @@ def test_describe_database_subnet_group():
|
|||
subnets = resp['DBSubnetGroups'][0]['Subnets']
|
||||
subnets.should.have.length_of(1)
|
||||
|
||||
list(conn.describe_db_subnet_groups(DBSubnetGroupName="db_subnet1")['DBSubnetGroups']).should.have.length_of(1)
|
||||
list(conn.describe_db_subnet_groups(DBSubnetGroupName="db_subnet1")
|
||||
['DBSubnetGroups']).should.have.length_of(1)
|
||||
|
||||
conn.describe_db_subnet_groups.when.called_with(DBSubnetGroupName="not-a-subnet").should.throw(ClientError)
|
||||
conn.describe_db_subnet_groups.when.called_with(
|
||||
DBSubnetGroupName="not-a-subnet").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -702,7 +759,8 @@ def test_describe_database_subnet_group():
|
|||
def test_delete_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
result = conn.describe_db_subnet_groups()
|
||||
|
|
@ -718,7 +776,8 @@ def test_delete_database_subnet_group():
|
|||
result = conn.describe_db_subnet_groups()
|
||||
result['DBSubnetGroups'].should.have.length_of(0)
|
||||
|
||||
conn.delete_db_subnet_group.when.called_with(DBSubnetGroupName="db_subnet1").should.throw(ClientError)
|
||||
conn.delete_db_subnet_group.when.called_with(
|
||||
DBSubnetGroupName="db_subnet1").should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -727,7 +786,8 @@ def test_delete_database_subnet_group():
|
|||
def test_list_tags_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
result = conn.describe_db_subnet_groups()
|
||||
|
|
@ -740,11 +800,13 @@ def test_list_tags_database_subnet_group():
|
|||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])['DBSubnetGroup']['DBSubnetGroupName']
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:subgrp:{0}'.format(subnet))
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:subgrp:{0}'.format(subnet))
|
||||
result['TagList'].should.equal([{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_ec2
|
||||
|
|
@ -752,7 +814,8 @@ def test_list_tags_database_subnet_group():
|
|||
def test_add_tags_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
result = conn.describe_db_subnet_groups()
|
||||
|
|
@ -773,8 +836,9 @@ def test_add_tags_database_subnet_group():
|
|||
result = conn.list_tags_for_resource(ResourceName=resource)
|
||||
result['TagList'].should.equal([{'Value': 'bar',
|
||||
'Key': 'foo'},
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
{'Value': 'bar1',
|
||||
'Key': 'foo1'}])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_ec2
|
||||
|
|
@ -782,7 +846,8 @@ def test_add_tags_database_subnet_group():
|
|||
def test_remove_tags_database_subnet_group():
|
||||
vpc_conn = boto3.client('ec2', 'us-west-2')
|
||||
vpc = vpc_conn.create_vpc(CidrBlock='10.0.0.0/16')['Vpc']
|
||||
subnet = vpc_conn.create_subnet(VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
subnet = vpc_conn.create_subnet(
|
||||
VpcId=vpc['VpcId'], CidrBlock='10.1.0.0/24')['Subnet']
|
||||
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
result = conn.describe_db_subnet_groups()
|
||||
|
|
@ -820,17 +885,22 @@ def test_create_database_replica():
|
|||
replica = conn.create_db_instance_read_replica(DBInstanceIdentifier="db-replica-1",
|
||||
SourceDBInstanceIdentifier="db-master-1",
|
||||
DBInstanceClass="db.m1.small")
|
||||
replica['DBInstance']['ReadReplicaSourceDBInstanceIdentifier'].should.equal('db-master-1')
|
||||
replica['DBInstance'][
|
||||
'ReadReplicaSourceDBInstanceIdentifier'].should.equal('db-master-1')
|
||||
replica['DBInstance']['DBInstanceClass'].should.equal('db.m1.small')
|
||||
replica['DBInstance']['DBInstanceIdentifier'].should.equal('db-replica-1')
|
||||
|
||||
master = conn.describe_db_instances(DBInstanceIdentifier="db-master-1")
|
||||
master['DBInstances'][0]['ReadReplicaDBInstanceIdentifiers'].should.equal(['db-replica-1'])
|
||||
master['DBInstances'][0]['ReadReplicaDBInstanceIdentifiers'].should.equal([
|
||||
'db-replica-1'])
|
||||
|
||||
conn.delete_db_instance(DBInstanceIdentifier="db-replica-1", SkipFinalSnapshot=True)
|
||||
conn.delete_db_instance(
|
||||
DBInstanceIdentifier="db-replica-1", SkipFinalSnapshot=True)
|
||||
|
||||
master = conn.describe_db_instances(DBInstanceIdentifier="db-master-1")
|
||||
master['DBInstances'][0]['ReadReplicaDBInstanceIdentifiers'].should.equal([])
|
||||
master['DBInstances'][0][
|
||||
'ReadReplicaDBInstanceIdentifiers'].should.equal([])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
|
|
@ -854,19 +924,25 @@ def test_create_database_with_encrypted_storage():
|
|||
KmsKeyId=key['KeyMetadata']['KeyId'])
|
||||
|
||||
database['DBInstance']['StorageEncrypted'].should.equal(True)
|
||||
database['DBInstance']['KmsKeyId'].should.equal(key['KeyMetadata']['KeyId'])
|
||||
database['DBInstance']['KmsKeyId'].should.equal(
|
||||
key['KeyMetadata']['KeyId'])
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_create_db_parameter_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
db_parameter_group = conn.create_db_parameter_group(DBParameterGroupName='test',
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group')
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group')
|
||||
|
||||
db_parameter_group['DBParameterGroup'][
|
||||
'DBParameterGroupName'].should.equal('test')
|
||||
db_parameter_group['DBParameterGroup'][
|
||||
'DBParameterGroupFamily'].should.equal('mysql5.6')
|
||||
db_parameter_group['DBParameterGroup'][
|
||||
'Description'].should.equal('test parameter group')
|
||||
|
||||
db_parameter_group['DBParameterGroup']['DBParameterGroupName'].should.equal('test')
|
||||
db_parameter_group['DBParameterGroup']['DBParameterGroupFamily'].should.equal('mysql5.6')
|
||||
db_parameter_group['DBParameterGroup']['Description'].should.equal('test parameter group')
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
|
|
@ -886,8 +962,11 @@ def test_create_db_instance_with_parameter_group():
|
|||
Port=1234)
|
||||
|
||||
len(database['DBInstance']['DBParameterGroups']).should.equal(1)
|
||||
database['DBInstance']['DBParameterGroups'][0]['DBParameterGroupName'].should.equal('test')
|
||||
database['DBInstance']['DBParameterGroups'][0]['ParameterApplyStatus'].should.equal('in-sync')
|
||||
database['DBInstance']['DBParameterGroups'][0][
|
||||
'DBParameterGroupName'].should.equal('test')
|
||||
database['DBInstance']['DBParameterGroups'][0][
|
||||
'ParameterApplyStatus'].should.equal('in-sync')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
|
|
@ -902,8 +981,10 @@ def test_modify_db_instance_with_parameter_group():
|
|||
Port=1234)
|
||||
|
||||
len(database['DBInstance']['DBParameterGroups']).should.equal(1)
|
||||
database['DBInstance']['DBParameterGroups'][0]['DBParameterGroupName'].should.equal('default.mysql5.6')
|
||||
database['DBInstance']['DBParameterGroups'][0]['ParameterApplyStatus'].should.equal('in-sync')
|
||||
database['DBInstance']['DBParameterGroups'][0][
|
||||
'DBParameterGroupName'].should.equal('default.mysql5.6')
|
||||
database['DBInstance']['DBParameterGroups'][0][
|
||||
'ParameterApplyStatus'].should.equal('in-sync')
|
||||
|
||||
db_parameter_group = conn.create_db_parameter_group(DBParameterGroupName='test',
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
|
|
@ -912,10 +993,13 @@ def test_modify_db_instance_with_parameter_group():
|
|||
DBParameterGroupName='test',
|
||||
ApplyImmediately=True)
|
||||
|
||||
database = conn.describe_db_instances(DBInstanceIdentifier='db-master-1')['DBInstances'][0]
|
||||
database = conn.describe_db_instances(
|
||||
DBInstanceIdentifier='db-master-1')['DBInstances'][0]
|
||||
len(database['DBParameterGroups']).should.equal(1)
|
||||
database['DBParameterGroups'][0]['DBParameterGroupName'].should.equal('test')
|
||||
database['DBParameterGroups'][0]['ParameterApplyStatus'].should.equal('in-sync')
|
||||
database['DBParameterGroups'][0][
|
||||
'DBParameterGroupName'].should.equal('test')
|
||||
database['DBParameterGroups'][0][
|
||||
'ParameterApplyStatus'].should.equal('in-sync')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
|
|
@ -946,15 +1030,18 @@ def test_describe_db_parameter_group():
|
|||
conn.create_db_parameter_group(DBParameterGroupName='test',
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(DBParameterGroupName='test')
|
||||
db_parameter_groups['DBParameterGroups'][0]['DBParameterGroupName'].should.equal('test')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(
|
||||
DBParameterGroupName='test')
|
||||
db_parameter_groups['DBParameterGroups'][0][
|
||||
'DBParameterGroupName'].should.equal('test')
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_describe_non_existant_db_parameter_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(DBParameterGroupName='test')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(
|
||||
DBParameterGroupName='test')
|
||||
len(db_parameter_groups['DBParameterGroups']).should.equal(0)
|
||||
|
||||
|
||||
|
|
@ -963,14 +1050,18 @@ def test_describe_non_existant_db_parameter_group():
|
|||
def test_delete_db_parameter_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.create_db_parameter_group(DBParameterGroupName='test',
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(DBParameterGroupName='test')
|
||||
db_parameter_groups['DBParameterGroups'][0]['DBParameterGroupName'].should.equal('test')
|
||||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(
|
||||
DBParameterGroupName='test')
|
||||
db_parameter_groups['DBParameterGroups'][0][
|
||||
'DBParameterGroupName'].should.equal('test')
|
||||
conn.delete_db_parameter_group(DBParameterGroupName='test')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(DBParameterGroupName='test')
|
||||
db_parameter_groups = conn.describe_db_parameter_groups(
|
||||
DBParameterGroupName='test')
|
||||
len(db_parameter_groups['DBParameterGroups']).should.equal(0)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
def test_modify_db_parameter_group():
|
||||
|
|
@ -986,7 +1077,7 @@ def test_modify_db_parameter_group():
|
|||
'Description': 'test param',
|
||||
'ApplyMethod': 'immediate'
|
||||
}]
|
||||
)
|
||||
)
|
||||
|
||||
modify_result['DBParameterGroupName'].should.equal('test')
|
||||
|
||||
|
|
@ -1001,7 +1092,9 @@ def test_modify_db_parameter_group():
|
|||
@mock_rds2
|
||||
def test_delete_non_existant_db_parameter_group():
|
||||
conn = boto3.client('rds', region_name='us-west-2')
|
||||
conn.delete_db_parameter_group.when.called_with(DBParameterGroupName='non-existant').should.throw(ClientError)
|
||||
conn.delete_db_parameter_group.when.called_with(
|
||||
DBParameterGroupName='non-existant').should.throw(ClientError)
|
||||
|
||||
|
||||
@disable_on_py3()
|
||||
@mock_rds2
|
||||
|
|
@ -1011,8 +1104,9 @@ def test_create_parameter_group_with_tags():
|
|||
DBParameterGroupFamily='mysql5.6',
|
||||
Description='test parameter group',
|
||||
Tags=[{
|
||||
'Key': 'foo',
|
||||
'Value': 'bar',
|
||||
'Key': 'foo',
|
||||
'Value': 'bar',
|
||||
}])
|
||||
result = conn.list_tags_for_resource(ResourceName='arn:aws:rds:us-west-2:1234567890:pg:test')
|
||||
result = conn.list_tags_for_resource(
|
||||
ResourceName='arn:aws:rds:us-west-2:1234567890:pg:test')
|
||||
result['TagList'].should.equal([{'Value': 'bar', 'Key': 'foo'}])
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ Test the different server responses
|
|||
|
||||
|
||||
#@mock_rds2
|
||||
#def test_list_databases():
|
||||
# def test_list_databases():
|
||||
# backend = server.create_backend_app("rds2")
|
||||
# test_client = backend.test_client()
|
||||
#
|
||||
|
|
|
|||
|
|
@ -35,18 +35,21 @@ def test_create_cluster():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters(cluster_identifier)
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
|
||||
cluster['ClusterIdentifier'].should.equal(cluster_identifier)
|
||||
cluster['NodeType'].should.equal("dw.hs1.xlarge")
|
||||
cluster['MasterUsername'].should.equal("username")
|
||||
cluster['DBName'].should.equal("my_db")
|
||||
cluster['ClusterSecurityGroups'][0]['ClusterSecurityGroupName'].should.equal("Default")
|
||||
cluster['ClusterSecurityGroups'][0][
|
||||
'ClusterSecurityGroupName'].should.equal("Default")
|
||||
cluster['VpcSecurityGroups'].should.equal([])
|
||||
cluster['ClusterSubnetGroupName'].should.equal(None)
|
||||
cluster['AvailabilityZone'].should.equal("us-east-1d")
|
||||
cluster['PreferredMaintenanceWindow'].should.equal("Mon:03:00-Mon:11:00")
|
||||
cluster['ClusterParameterGroups'][0]['ParameterGroupName'].should.equal("default.redshift-1.0")
|
||||
cluster['ClusterParameterGroups'][0][
|
||||
'ParameterGroupName'].should.equal("default.redshift-1.0")
|
||||
cluster['AutomatedSnapshotRetentionPeriod'].should.equal(10)
|
||||
cluster['Port'].should.equal(1234)
|
||||
cluster['ClusterVersion'].should.equal("1.0")
|
||||
|
|
@ -69,7 +72,8 @@ def test_create_single_node_cluster():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters(cluster_identifier)
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
|
||||
cluster['ClusterIdentifier'].should.equal(cluster_identifier)
|
||||
cluster['NodeType'].should.equal("dw.hs1.xlarge")
|
||||
|
|
@ -91,13 +95,15 @@ def test_default_cluster_attibutes():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters(cluster_identifier)
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
|
||||
cluster['DBName'].should.equal("dev")
|
||||
cluster['ClusterSubnetGroupName'].should.equal(None)
|
||||
assert "us-east-" in cluster['AvailabilityZone']
|
||||
cluster['PreferredMaintenanceWindow'].should.equal("Mon:03:00-Mon:03:30")
|
||||
cluster['ClusterParameterGroups'][0]['ParameterGroupName'].should.equal("default.redshift-1.0")
|
||||
cluster['ClusterParameterGroups'][0][
|
||||
'ParameterGroupName'].should.equal("default.redshift-1.0")
|
||||
cluster['AutomatedSnapshotRetentionPeriod'].should.equal(1)
|
||||
cluster['Port'].should.equal(5439)
|
||||
cluster['ClusterVersion'].should.equal("1.0")
|
||||
|
|
@ -127,7 +133,8 @@ def test_create_cluster_in_subnet_group():
|
|||
)
|
||||
|
||||
cluster_response = redshift_conn.describe_clusters("my_cluster")
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
cluster['ClusterSubnetGroupName'].should.equal('my_subnet_group')
|
||||
|
||||
|
||||
|
|
@ -153,8 +160,10 @@ def test_create_cluster_with_security_group():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters(cluster_identifier)
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
group_names = [group['ClusterSecurityGroupName'] for group in cluster['ClusterSecurityGroups']]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
group_names = [group['ClusterSecurityGroupName']
|
||||
for group in cluster['ClusterSecurityGroups']]
|
||||
set(group_names).should.equal(set(["security_group1", "security_group2"]))
|
||||
|
||||
|
||||
|
|
@ -165,7 +174,8 @@ def test_create_cluster_with_vpc_security_groups():
|
|||
ec2_conn = boto.connect_ec2()
|
||||
redshift_conn = boto.connect_redshift()
|
||||
vpc = vpc_conn.create_vpc("10.0.0.0/16")
|
||||
security_group = ec2_conn.create_security_group("vpc_security_group", "a group", vpc_id=vpc.id)
|
||||
security_group = ec2_conn.create_security_group(
|
||||
"vpc_security_group", "a group", vpc_id=vpc.id)
|
||||
|
||||
redshift_conn.create_cluster(
|
||||
"my_cluster",
|
||||
|
|
@ -176,8 +186,10 @@ def test_create_cluster_with_vpc_security_groups():
|
|||
)
|
||||
|
||||
cluster_response = redshift_conn.describe_clusters("my_cluster")
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
group_ids = [group['VpcSecurityGroupId'] for group in cluster['VpcSecurityGroups']]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
group_ids = [group['VpcSecurityGroupId']
|
||||
for group in cluster['VpcSecurityGroups']]
|
||||
list(group_ids).should.equal([security_group.id])
|
||||
|
||||
|
||||
|
|
@ -199,14 +211,17 @@ def test_create_cluster_with_parameter_group():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters("my_cluster")
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster['ClusterParameterGroups'][0]['ParameterGroupName'].should.equal("my_parameter_group")
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
cluster['ClusterParameterGroups'][0][
|
||||
'ParameterGroupName'].should.equal("my_parameter_group")
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
def test_describe_non_existant_cluster():
|
||||
conn = boto.redshift.connect_to_region("us-east-1")
|
||||
conn.describe_clusters.when.called_with("not-a-cluster").should.throw(ClusterNotFound)
|
||||
conn.describe_clusters.when.called_with(
|
||||
"not-a-cluster").should.throw(ClusterNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -221,16 +236,19 @@ def test_delete_cluster():
|
|||
master_user_password="password",
|
||||
)
|
||||
|
||||
clusters = conn.describe_clusters()['DescribeClustersResponse']['DescribeClustersResult']['Clusters']
|
||||
clusters = conn.describe_clusters()['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters']
|
||||
list(clusters).should.have.length_of(1)
|
||||
|
||||
conn.delete_cluster(cluster_identifier)
|
||||
|
||||
clusters = conn.describe_clusters()['DescribeClustersResponse']['DescribeClustersResult']['Clusters']
|
||||
clusters = conn.describe_clusters()['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters']
|
||||
list(clusters).should.have.length_of(0)
|
||||
|
||||
# Delete invalid id
|
||||
conn.delete_cluster.when.called_with("not-a-cluster").should.throw(ClusterNotFound)
|
||||
conn.delete_cluster.when.called_with(
|
||||
"not-a-cluster").should.throw(ClusterNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -269,13 +287,16 @@ def test_modify_cluster():
|
|||
)
|
||||
|
||||
cluster_response = conn.describe_clusters("new_identifier")
|
||||
cluster = cluster_response['DescribeClustersResponse']['DescribeClustersResult']['Clusters'][0]
|
||||
cluster = cluster_response['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters'][0]
|
||||
|
||||
cluster['ClusterIdentifier'].should.equal("new_identifier")
|
||||
cluster['NodeType'].should.equal("dw.hs1.xlarge")
|
||||
cluster['ClusterSecurityGroups'][0]['ClusterSecurityGroupName'].should.equal("security_group")
|
||||
cluster['ClusterSecurityGroups'][0][
|
||||
'ClusterSecurityGroupName'].should.equal("security_group")
|
||||
cluster['PreferredMaintenanceWindow'].should.equal("Tue:03:00-Tue:11:00")
|
||||
cluster['ClusterParameterGroups'][0]['ParameterGroupName'].should.equal("my_parameter_group")
|
||||
cluster['ClusterParameterGroups'][0][
|
||||
'ParameterGroupName'].should.equal("my_parameter_group")
|
||||
cluster['AutomatedSnapshotRetentionPeriod'].should.equal(7)
|
||||
cluster['AllowVersionUpgrade'].should.equal(False)
|
||||
cluster['NumberOfNodes'].should.equal(2)
|
||||
|
|
@ -297,12 +318,15 @@ def test_create_cluster_subnet_group():
|
|||
subnet_ids=[subnet1.id, subnet2.id],
|
||||
)
|
||||
|
||||
subnets_response = redshift_conn.describe_cluster_subnet_groups("my_subnet")
|
||||
my_subnet = subnets_response['DescribeClusterSubnetGroupsResponse']['DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups'][0]
|
||||
subnets_response = redshift_conn.describe_cluster_subnet_groups(
|
||||
"my_subnet")
|
||||
my_subnet = subnets_response['DescribeClusterSubnetGroupsResponse'][
|
||||
'DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups'][0]
|
||||
|
||||
my_subnet['ClusterSubnetGroupName'].should.equal("my_subnet")
|
||||
my_subnet['Description'].should.equal("This is my subnet group")
|
||||
subnet_ids = [subnet['SubnetIdentifier'] for subnet in my_subnet['Subnets']]
|
||||
subnet_ids = [subnet['SubnetIdentifier']
|
||||
for subnet in my_subnet['Subnets']]
|
||||
set(subnet_ids).should.equal(set([subnet1.id, subnet2.id]))
|
||||
|
||||
|
||||
|
|
@ -320,7 +344,8 @@ def test_create_invalid_cluster_subnet_group():
|
|||
@mock_redshift_deprecated
|
||||
def test_describe_non_existant_subnet_group():
|
||||
conn = boto.redshift.connect_to_region("us-east-1")
|
||||
conn.describe_cluster_subnet_groups.when.called_with("not-a-subnet-group").should.throw(ClusterSubnetGroupNotFound)
|
||||
conn.describe_cluster_subnet_groups.when.called_with(
|
||||
"not-a-subnet-group").should.throw(ClusterSubnetGroupNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -338,17 +363,20 @@ def test_delete_cluster_subnet_group():
|
|||
)
|
||||
|
||||
subnets_response = redshift_conn.describe_cluster_subnet_groups()
|
||||
subnets = subnets_response['DescribeClusterSubnetGroupsResponse']['DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups']
|
||||
subnets = subnets_response['DescribeClusterSubnetGroupsResponse'][
|
||||
'DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups']
|
||||
subnets.should.have.length_of(1)
|
||||
|
||||
redshift_conn.delete_cluster_subnet_group("my_subnet")
|
||||
|
||||
subnets_response = redshift_conn.describe_cluster_subnet_groups()
|
||||
subnets = subnets_response['DescribeClusterSubnetGroupsResponse']['DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups']
|
||||
subnets = subnets_response['DescribeClusterSubnetGroupsResponse'][
|
||||
'DescribeClusterSubnetGroupsResult']['ClusterSubnetGroups']
|
||||
subnets.should.have.length_of(0)
|
||||
|
||||
# Delete invalid id
|
||||
redshift_conn.delete_cluster_subnet_group.when.called_with("not-a-subnet-group").should.throw(ClusterSubnetGroupNotFound)
|
||||
redshift_conn.delete_cluster_subnet_group.when.called_with(
|
||||
"not-a-subnet-group").should.throw(ClusterSubnetGroupNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -359,8 +387,10 @@ def test_create_cluster_security_group():
|
|||
"This is my security group",
|
||||
)
|
||||
|
||||
groups_response = conn.describe_cluster_security_groups("my_security_group")
|
||||
my_group = groups_response['DescribeClusterSecurityGroupsResponse']['DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups'][0]
|
||||
groups_response = conn.describe_cluster_security_groups(
|
||||
"my_security_group")
|
||||
my_group = groups_response['DescribeClusterSecurityGroupsResponse'][
|
||||
'DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups'][0]
|
||||
|
||||
my_group['ClusterSecurityGroupName'].should.equal("my_security_group")
|
||||
my_group['Description'].should.equal("This is my security group")
|
||||
|
|
@ -370,7 +400,8 @@ def test_create_cluster_security_group():
|
|||
@mock_redshift_deprecated
|
||||
def test_describe_non_existant_security_group():
|
||||
conn = boto.redshift.connect_to_region("us-east-1")
|
||||
conn.describe_cluster_security_groups.when.called_with("not-a-security-group").should.throw(ClusterSecurityGroupNotFound)
|
||||
conn.describe_cluster_security_groups.when.called_with(
|
||||
"not-a-security-group").should.throw(ClusterSecurityGroupNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -382,17 +413,20 @@ def test_delete_cluster_security_group():
|
|||
)
|
||||
|
||||
groups_response = conn.describe_cluster_security_groups()
|
||||
groups = groups_response['DescribeClusterSecurityGroupsResponse']['DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups']
|
||||
groups = groups_response['DescribeClusterSecurityGroupsResponse'][
|
||||
'DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups']
|
||||
groups.should.have.length_of(2) # The default group already exists
|
||||
|
||||
conn.delete_cluster_security_group("my_security_group")
|
||||
|
||||
groups_response = conn.describe_cluster_security_groups()
|
||||
groups = groups_response['DescribeClusterSecurityGroupsResponse']['DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups']
|
||||
groups = groups_response['DescribeClusterSecurityGroupsResponse'][
|
||||
'DescribeClusterSecurityGroupsResult']['ClusterSecurityGroups']
|
||||
groups.should.have.length_of(1)
|
||||
|
||||
# Delete invalid id
|
||||
conn.delete_cluster_security_group.when.called_with("not-a-security-group").should.throw(ClusterSecurityGroupNotFound)
|
||||
conn.delete_cluster_security_group.when.called_with(
|
||||
"not-a-security-group").should.throw(ClusterSecurityGroupNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -404,8 +438,10 @@ def test_create_cluster_parameter_group():
|
|||
"This is my parameter group",
|
||||
)
|
||||
|
||||
groups_response = conn.describe_cluster_parameter_groups("my_parameter_group")
|
||||
my_group = groups_response['DescribeClusterParameterGroupsResponse']['DescribeClusterParameterGroupsResult']['ParameterGroups'][0]
|
||||
groups_response = conn.describe_cluster_parameter_groups(
|
||||
"my_parameter_group")
|
||||
my_group = groups_response['DescribeClusterParameterGroupsResponse'][
|
||||
'DescribeClusterParameterGroupsResult']['ParameterGroups'][0]
|
||||
|
||||
my_group['ParameterGroupName'].should.equal("my_parameter_group")
|
||||
my_group['ParameterGroupFamily'].should.equal("redshift-1.0")
|
||||
|
|
@ -415,7 +451,8 @@ def test_create_cluster_parameter_group():
|
|||
@mock_redshift_deprecated
|
||||
def test_describe_non_existant_parameter_group():
|
||||
conn = boto.redshift.connect_to_region("us-east-1")
|
||||
conn.describe_cluster_parameter_groups.when.called_with("not-a-parameter-group").should.throw(ClusterParameterGroupNotFound)
|
||||
conn.describe_cluster_parameter_groups.when.called_with(
|
||||
"not-a-parameter-group").should.throw(ClusterParameterGroupNotFound)
|
||||
|
||||
|
||||
@mock_redshift_deprecated
|
||||
|
|
@ -428,14 +465,17 @@ def test_delete_cluster_parameter_group():
|
|||
)
|
||||
|
||||
groups_response = conn.describe_cluster_parameter_groups()
|
||||
groups = groups_response['DescribeClusterParameterGroupsResponse']['DescribeClusterParameterGroupsResult']['ParameterGroups']
|
||||
groups = groups_response['DescribeClusterParameterGroupsResponse'][
|
||||
'DescribeClusterParameterGroupsResult']['ParameterGroups']
|
||||
groups.should.have.length_of(2) # The default group already exists
|
||||
|
||||
conn.delete_cluster_parameter_group("my_parameter_group")
|
||||
|
||||
groups_response = conn.describe_cluster_parameter_groups()
|
||||
groups = groups_response['DescribeClusterParameterGroupsResponse']['DescribeClusterParameterGroupsResult']['ParameterGroups']
|
||||
groups = groups_response['DescribeClusterParameterGroupsResponse'][
|
||||
'DescribeClusterParameterGroupsResult']['ParameterGroups']
|
||||
groups.should.have.length_of(1)
|
||||
|
||||
# Delete invalid id
|
||||
conn.delete_cluster_parameter_group.when.called_with("not-a-parameter-group").should.throw(ClusterParameterGroupNotFound)
|
||||
conn.delete_cluster_parameter_group.when.called_with(
|
||||
"not-a-parameter-group").should.throw(ClusterParameterGroupNotFound)
|
||||
|
|
|
|||
|
|
@ -19,5 +19,6 @@ def test_describe_clusters():
|
|||
res = test_client.get('/?Action=DescribeClusters')
|
||||
|
||||
json_data = json.loads(res.data.decode("utf-8"))
|
||||
clusters = json_data['DescribeClustersResponse']['DescribeClustersResult']['Clusters']
|
||||
clusters = json_data['DescribeClustersResponse'][
|
||||
'DescribeClustersResult']['Clusters']
|
||||
list(clusters).should.equal([])
|
||||
|
|
|
|||
|
|
@ -23,15 +23,18 @@ def test_hosted_zone():
|
|||
zones = conn.get_all_hosted_zones()
|
||||
len(zones["ListHostedZonesResponse"]["HostedZones"]).should.equal(2)
|
||||
|
||||
id1 = firstzone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
id1 = firstzone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
zone = conn.get_hosted_zone(id1)
|
||||
zone["GetHostedZoneResponse"]["HostedZone"]["Name"].should.equal("testdns.aws.com.")
|
||||
zone["GetHostedZoneResponse"]["HostedZone"][
|
||||
"Name"].should.equal("testdns.aws.com.")
|
||||
|
||||
conn.delete_hosted_zone(id1)
|
||||
zones = conn.get_all_hosted_zones()
|
||||
len(zones["ListHostedZonesResponse"]["HostedZones"]).should.equal(1)
|
||||
|
||||
conn.get_hosted_zone.when.called_with("abcd").should.throw(boto.route53.exception.DNSServerError, "404 Not Found")
|
||||
conn.get_hosted_zone.when.called_with("abcd").should.throw(
|
||||
boto.route53.exception.DNSServerError, "404 Not Found")
|
||||
|
||||
|
||||
@mock_route53_deprecated
|
||||
|
|
@ -42,7 +45,8 @@ def test_rrset():
|
|||
boto.route53.exception.DNSServerError, "404 Not Found")
|
||||
|
||||
zone = conn.create_hosted_zone("testdns.aws.com")
|
||||
zoneid = zone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
zoneid = zone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
changes = ResourceRecordSets(conn, zoneid)
|
||||
change = changes.add_change("CREATE", "foo.bar.testdns.aws.com", "A")
|
||||
|
|
@ -105,15 +109,18 @@ def test_rrset():
|
|||
rrsets = conn.get_all_rrsets(zoneid, type="A")
|
||||
rrsets.should.have.length_of(2)
|
||||
|
||||
rrsets = conn.get_all_rrsets(zoneid, name="foo.bar.testdns.aws.com", type="A")
|
||||
rrsets = conn.get_all_rrsets(
|
||||
zoneid, name="foo.bar.testdns.aws.com", type="A")
|
||||
rrsets.should.have.length_of(1)
|
||||
rrsets[0].resource_records[0].should.equal('1.2.3.4')
|
||||
|
||||
rrsets = conn.get_all_rrsets(zoneid, name="bar.foo.testdns.aws.com", type="A")
|
||||
rrsets = conn.get_all_rrsets(
|
||||
zoneid, name="bar.foo.testdns.aws.com", type="A")
|
||||
rrsets.should.have.length_of(1)
|
||||
rrsets[0].resource_records[0].should.equal('5.6.7.8')
|
||||
|
||||
rrsets = conn.get_all_rrsets(zoneid, name="foo.foo.testdns.aws.com", type="A")
|
||||
rrsets = conn.get_all_rrsets(
|
||||
zoneid, name="foo.foo.testdns.aws.com", type="A")
|
||||
rrsets.should.have.length_of(0)
|
||||
|
||||
|
||||
|
|
@ -121,7 +128,8 @@ def test_rrset():
|
|||
def test_rrset_with_multiple_values():
|
||||
conn = boto.connect_route53('the_key', 'the_secret')
|
||||
zone = conn.create_hosted_zone("testdns.aws.com")
|
||||
zoneid = zone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
zoneid = zone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
changes = ResourceRecordSets(conn, zoneid)
|
||||
change = changes.add_change("CREATE", "foo.bar.testdns.aws.com", "A")
|
||||
|
|
@ -138,11 +146,14 @@ def test_rrset_with_multiple_values():
|
|||
def test_alias_rrset():
|
||||
conn = boto.connect_route53('the_key', 'the_secret')
|
||||
zone = conn.create_hosted_zone("testdns.aws.com")
|
||||
zoneid = zone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
zoneid = zone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
changes = ResourceRecordSets(conn, zoneid)
|
||||
changes.add_change("CREATE", "foo.alias.testdns.aws.com", "A", alias_hosted_zone_id="Z3DG6IL3SJCGPX", alias_dns_name="foo.testdns.aws.com")
|
||||
changes.add_change("CREATE", "bar.alias.testdns.aws.com", "CNAME", alias_hosted_zone_id="Z3DG6IL3SJCGPX", alias_dns_name="bar.testdns.aws.com")
|
||||
changes.add_change("CREATE", "foo.alias.testdns.aws.com", "A",
|
||||
alias_hosted_zone_id="Z3DG6IL3SJCGPX", alias_dns_name="foo.testdns.aws.com")
|
||||
changes.add_change("CREATE", "bar.alias.testdns.aws.com", "CNAME",
|
||||
alias_hosted_zone_id="Z3DG6IL3SJCGPX", alias_dns_name="bar.testdns.aws.com")
|
||||
changes.commit()
|
||||
|
||||
rrsets = conn.get_all_rrsets(zoneid, type="A")
|
||||
|
|
@ -169,7 +180,8 @@ def test_create_health_check():
|
|||
)
|
||||
conn.create_health_check(check)
|
||||
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse']['HealthChecks']
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse'][
|
||||
'HealthChecks']
|
||||
list(checks).should.have.length_of(1)
|
||||
check = checks[0]
|
||||
config = check['HealthCheckConfig']
|
||||
|
|
@ -195,12 +207,14 @@ def test_delete_health_check():
|
|||
)
|
||||
conn.create_health_check(check)
|
||||
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse']['HealthChecks']
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse'][
|
||||
'HealthChecks']
|
||||
list(checks).should.have.length_of(1)
|
||||
health_check_id = checks[0]['Id']
|
||||
|
||||
conn.delete_health_check(health_check_id)
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse']['HealthChecks']
|
||||
checks = conn.get_list_health_checks()['ListHealthChecksResponse'][
|
||||
'HealthChecks']
|
||||
list(checks).should.have.length_of(0)
|
||||
|
||||
|
||||
|
|
@ -214,14 +228,17 @@ def test_use_health_check_in_resource_record_set():
|
|||
hc_type="HTTP",
|
||||
resource_path="/",
|
||||
)
|
||||
check = conn.create_health_check(check)['CreateHealthCheckResponse']['HealthCheck']
|
||||
check = conn.create_health_check(
|
||||
check)['CreateHealthCheckResponse']['HealthCheck']
|
||||
check_id = check['Id']
|
||||
|
||||
zone = conn.create_hosted_zone("testdns.aws.com")
|
||||
zone_id = zone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
zone_id = zone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
changes = ResourceRecordSets(conn, zone_id)
|
||||
change = changes.add_change("CREATE", "foo.bar.testdns.aws.com", "A", health_check=check_id)
|
||||
change = changes.add_change(
|
||||
"CREATE", "foo.bar.testdns.aws.com", "A", health_check=check_id)
|
||||
change.add_value("1.2.3.4")
|
||||
changes.commit()
|
||||
|
||||
|
|
@ -233,14 +250,18 @@ def test_use_health_check_in_resource_record_set():
|
|||
def test_hosted_zone_comment_preserved():
|
||||
conn = boto.connect_route53('the_key', 'the_secret')
|
||||
|
||||
firstzone = conn.create_hosted_zone("testdns.aws.com.", comment="test comment")
|
||||
zone_id = firstzone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
firstzone = conn.create_hosted_zone(
|
||||
"testdns.aws.com.", comment="test comment")
|
||||
zone_id = firstzone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
hosted_zone = conn.get_hosted_zone(zone_id)
|
||||
hosted_zone["GetHostedZoneResponse"]["HostedZone"]["Config"]["Comment"].should.equal("test comment")
|
||||
hosted_zone["GetHostedZoneResponse"]["HostedZone"][
|
||||
"Config"]["Comment"].should.equal("test comment")
|
||||
|
||||
hosted_zones = conn.get_all_hosted_zones()
|
||||
hosted_zones["ListHostedZonesResponse"]["HostedZones"][0]["Config"]["Comment"].should.equal("test comment")
|
||||
hosted_zones["ListHostedZonesResponse"]["HostedZones"][
|
||||
0]["Config"]["Comment"].should.equal("test comment")
|
||||
|
||||
zone = conn.get_zone("testdns.aws.com.")
|
||||
zone.config["Comment"].should.equal("test comment")
|
||||
|
|
@ -253,16 +274,20 @@ def test_deleting_weighted_route():
|
|||
conn.create_hosted_zone("testdns.aws.com.")
|
||||
zone = conn.get_zone("testdns.aws.com.")
|
||||
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com", identifier=('success-test-foo', '50'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com", identifier=('success-test-bar', '50'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com",
|
||||
identifier=('success-test-foo', '50'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com",
|
||||
identifier=('success-test-bar', '50'))
|
||||
|
||||
cnames = zone.get_cname('cname.testdns.aws.com.', all=True)
|
||||
cnames.should.have.length_of(2)
|
||||
foo_cname = [cname for cname in cnames if cname.identifier == 'success-test-foo'][0]
|
||||
foo_cname = [cname for cname in cnames if cname.identifier ==
|
||||
'success-test-foo'][0]
|
||||
|
||||
zone.delete_record(foo_cname)
|
||||
cname = zone.get_cname('cname.testdns.aws.com.', all=True)
|
||||
# When get_cname only had one result, it returns just that result instead of a list.
|
||||
# When get_cname only had one result, it returns just that result instead
|
||||
# of a list.
|
||||
cname.identifier.should.equal('success-test-bar')
|
||||
|
||||
|
||||
|
|
@ -273,17 +298,21 @@ def test_deleting_latency_route():
|
|||
conn.create_hosted_zone("testdns.aws.com.")
|
||||
zone = conn.get_zone("testdns.aws.com.")
|
||||
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com", identifier=('success-test-foo', 'us-west-2'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com", identifier=('success-test-bar', 'us-west-1'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com",
|
||||
identifier=('success-test-foo', 'us-west-2'))
|
||||
zone.add_cname("cname.testdns.aws.com", "example.com",
|
||||
identifier=('success-test-bar', 'us-west-1'))
|
||||
|
||||
cnames = zone.get_cname('cname.testdns.aws.com.', all=True)
|
||||
cnames.should.have.length_of(2)
|
||||
foo_cname = [cname for cname in cnames if cname.identifier == 'success-test-foo'][0]
|
||||
foo_cname = [cname for cname in cnames if cname.identifier ==
|
||||
'success-test-foo'][0]
|
||||
foo_cname.region.should.equal('us-west-2')
|
||||
|
||||
zone.delete_record(foo_cname)
|
||||
cname = zone.get_cname('cname.testdns.aws.com.', all=True)
|
||||
# When get_cname only had one result, it returns just that result instead of a list.
|
||||
# When get_cname only had one result, it returns just that result instead
|
||||
# of a list.
|
||||
cname.identifier.should.equal('success-test-bar')
|
||||
cname.region.should.equal('us-west-1')
|
||||
|
||||
|
|
@ -292,15 +321,19 @@ def test_deleting_latency_route():
|
|||
def test_hosted_zone_private_zone_preserved():
|
||||
conn = boto.connect_route53('the_key', 'the_secret')
|
||||
|
||||
firstzone = conn.create_hosted_zone("testdns.aws.com.", private_zone=True, vpc_id='vpc-fake', vpc_region='us-east-1')
|
||||
zone_id = firstzone["CreateHostedZoneResponse"]["HostedZone"]["Id"].split("/")[-1]
|
||||
firstzone = conn.create_hosted_zone(
|
||||
"testdns.aws.com.", private_zone=True, vpc_id='vpc-fake', vpc_region='us-east-1')
|
||||
zone_id = firstzone["CreateHostedZoneResponse"][
|
||||
"HostedZone"]["Id"].split("/")[-1]
|
||||
|
||||
hosted_zone = conn.get_hosted_zone(zone_id)
|
||||
# in (original) boto, these bools returned as strings.
|
||||
hosted_zone["GetHostedZoneResponse"]["HostedZone"]["Config"]["PrivateZone"].should.equal('True')
|
||||
hosted_zone["GetHostedZoneResponse"]["HostedZone"][
|
||||
"Config"]["PrivateZone"].should.equal('True')
|
||||
|
||||
hosted_zones = conn.get_all_hosted_zones()
|
||||
hosted_zones["ListHostedZonesResponse"]["HostedZones"][0]["Config"]["PrivateZone"].should.equal('True')
|
||||
hosted_zones["ListHostedZonesResponse"]["HostedZones"][
|
||||
0]["Config"]["PrivateZone"].should.equal('True')
|
||||
|
||||
zone = conn.get_zone("testdns.aws.com.")
|
||||
zone.config["PrivateZone"].should.equal('True')
|
||||
|
|
@ -331,6 +364,7 @@ def test_hosted_zone_private_zone_preserved_boto3():
|
|||
# zone = conn.list_hosted_zones_by_name(DNSName="testdns.aws.com.")
|
||||
# zone.config["PrivateZone"].should.equal(True)
|
||||
|
||||
|
||||
@mock_route53
|
||||
def test_list_or_change_tags_for_resource_request():
|
||||
conn = boto3.client('route53', region_name='us-east-1')
|
||||
|
|
@ -359,7 +393,8 @@ def test_list_or_change_tags_for_resource_request():
|
|||
)
|
||||
|
||||
# Check to make sure that the response has the 'ResourceTagSet' key
|
||||
response = conn.list_tags_for_resource(ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response = conn.list_tags_for_resource(
|
||||
ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response.should.contain('ResourceTagSet')
|
||||
|
||||
# Validate that each key was added
|
||||
|
|
@ -376,7 +411,8 @@ def test_list_or_change_tags_for_resource_request():
|
|||
)
|
||||
|
||||
# Check to make sure that the response has the 'ResourceTagSet' key
|
||||
response = conn.list_tags_for_resource(ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response = conn.list_tags_for_resource(
|
||||
ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response.should.contain('ResourceTagSet')
|
||||
response['ResourceTagSet']['Tags'].should_not.contain(tag1)
|
||||
response['ResourceTagSet']['Tags'].should.contain(tag2)
|
||||
|
|
@ -388,7 +424,8 @@ def test_list_or_change_tags_for_resource_request():
|
|||
RemoveTagKeys=[tag2['Key']]
|
||||
)
|
||||
|
||||
response = conn.list_tags_for_resource(ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response = conn.list_tags_for_resource(
|
||||
ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response['ResourceTagSet']['Tags'].should_not.contain(tag2)
|
||||
|
||||
# Re-add the tags
|
||||
|
|
@ -405,5 +442,6 @@ def test_list_or_change_tags_for_resource_request():
|
|||
RemoveTagKeys=[tag1['Key'], tag2['Key']]
|
||||
)
|
||||
|
||||
response = conn.list_tags_for_resource(ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response = conn.list_tags_for_resource(
|
||||
ResourceType='healthcheck', ResourceId=healthcheck_id)
|
||||
response['ResourceTagSet']['Tags'].should.be.empty
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ def reduced_min_part_size(f):
|
|||
|
||||
|
||||
class MyModel(object):
|
||||
|
||||
def __init__(self, name, value):
|
||||
self.name = name
|
||||
self.value = value
|
||||
|
|
@ -67,7 +68,8 @@ def test_my_model_save():
|
|||
model_instance = MyModel('steve', 'is awesome')
|
||||
model_instance.save()
|
||||
|
||||
body = conn.Object('mybucket', 'steve').get()['Body'].read().decode("utf-8")
|
||||
body = conn.Object('mybucket', 'steve').get()[
|
||||
'Body'].read().decode("utf-8")
|
||||
|
||||
assert body == b'is awesome'
|
||||
|
||||
|
|
@ -110,7 +112,8 @@ def test_multipart_upload():
|
|||
multipart.upload_part_from_file(BytesIO(part2), 2)
|
||||
multipart.complete_upload()
|
||||
# we should get both parts as the key contents
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -127,7 +130,8 @@ def test_multipart_upload_out_of_order():
|
|||
multipart.upload_part_from_file(BytesIO(part1), 2)
|
||||
multipart.complete_upload()
|
||||
# we should get both parts as the key contents
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -136,7 +140,8 @@ def test_multipart_upload_with_headers():
|
|||
conn = boto.connect_s3('the_key', 'the_secret')
|
||||
bucket = conn.create_bucket("foobar")
|
||||
|
||||
multipart = bucket.initiate_multipart_upload("the-key", metadata={"foo": "bar"})
|
||||
multipart = bucket.initiate_multipart_upload(
|
||||
"the-key", metadata={"foo": "bar"})
|
||||
part1 = b'0' * 10
|
||||
multipart.upload_part_from_file(BytesIO(part1), 1)
|
||||
multipart.complete_upload()
|
||||
|
|
@ -159,7 +164,8 @@ def test_multipart_upload_with_copy_key():
|
|||
multipart.upload_part_from_file(BytesIO(part1), 1)
|
||||
multipart.copy_part_from_key("foobar", "original-key", 2, 0, 3)
|
||||
multipart.complete_upload()
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(part1 + b"key_")
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(part1 + b"key_")
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -229,7 +235,8 @@ def test_multipart_duplicate_upload():
|
|||
multipart.upload_part_from_file(BytesIO(part2), 2)
|
||||
multipart.complete_upload()
|
||||
# We should get only one copy of part 1.
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(part1 + part2)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -260,7 +267,8 @@ def test_key_save_to_missing_bucket():
|
|||
|
||||
key = Key(bucket)
|
||||
key.key = "the-key"
|
||||
key.set_contents_from_string.when.called_with("foobar").should.throw(S3ResponseError)
|
||||
key.set_contents_from_string.when.called_with(
|
||||
"foobar").should.throw(S3ResponseError)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -275,7 +283,8 @@ def test_missing_key_urllib2():
|
|||
conn = boto.connect_s3('the_key', 'the_secret')
|
||||
conn.create_bucket("foobar")
|
||||
|
||||
urlopen.when.called_with("http://foobar.s3.amazonaws.com/the-key").should.throw(HTTPError)
|
||||
urlopen.when.called_with(
|
||||
"http://foobar.s3.amazonaws.com/the-key").should.throw(HTTPError)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -315,7 +324,8 @@ def test_large_key_save():
|
|||
key.key = "the-key"
|
||||
key.set_contents_from_string("foobar" * 100000)
|
||||
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(b'foobar' * 100000)
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(b'foobar' * 100000)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -328,8 +338,10 @@ def test_copy_key():
|
|||
|
||||
bucket.copy_key('new-key', 'foobar', 'the-key')
|
||||
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key("new-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key(
|
||||
"new-key").get_contents_as_string().should.equal(b"some value")
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -344,8 +356,10 @@ def test_copy_key_with_version():
|
|||
|
||||
bucket.copy_key('new-key', 'foobar', 'the-key', src_version_id='0')
|
||||
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(b"another value")
|
||||
bucket.get_key("new-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(b"another value")
|
||||
bucket.get_key(
|
||||
"new-key").get_contents_as_string().should.equal(b"some value")
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -373,7 +387,8 @@ def test_copy_key_replace_metadata():
|
|||
metadata={'momd': 'Mometadatastring'})
|
||||
|
||||
bucket.get_key("new-key").get_metadata('md').should.be.none
|
||||
bucket.get_key("new-key").get_metadata('momd').should.equal('Mometadatastring')
|
||||
bucket.get_key(
|
||||
"new-key").get_metadata('momd').should.equal('Mometadatastring')
|
||||
|
||||
|
||||
@freeze_time("2012-01-01 12:00:00")
|
||||
|
|
@ -389,7 +404,8 @@ def test_last_modified():
|
|||
rs = bucket.get_all_keys()
|
||||
rs[0].last_modified.should.equal('2012-01-01T12:00:00.000Z')
|
||||
|
||||
bucket.get_key("the-key").last_modified.should.equal('Sun, 01 Jan 2012 12:00:00 GMT')
|
||||
bucket.get_key(
|
||||
"the-key").last_modified.should.equal('Sun, 01 Jan 2012 12:00:00 GMT')
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -401,7 +417,8 @@ def test_missing_bucket():
|
|||
@mock_s3_deprecated
|
||||
def test_bucket_with_dash():
|
||||
conn = boto.connect_s3('the_key', 'the_secret')
|
||||
conn.get_bucket.when.called_with('mybucket-test').should.throw(S3ResponseError)
|
||||
conn.get_bucket.when.called_with(
|
||||
'mybucket-test').should.throw(S3ResponseError)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -432,7 +449,8 @@ def test_create_existing_bucket_in_us_east_1():
|
|||
|
||||
@mock_s3_deprecated
|
||||
def test_other_region():
|
||||
conn = S3Connection('key', 'secret', host='s3-website-ap-southeast-2.amazonaws.com')
|
||||
conn = S3Connection(
|
||||
'key', 'secret', host='s3-website-ap-southeast-2.amazonaws.com')
|
||||
conn.create_bucket("foobar")
|
||||
list(conn.get_bucket("foobar").get_all_keys()).should.equal([])
|
||||
|
||||
|
|
@ -613,7 +631,8 @@ def test_bucket_key_listing_order():
|
|||
|
||||
delimiter = None
|
||||
keys = [x.name for x in bucket.list(prefix + 'x', delimiter)]
|
||||
keys.should.equal([u'toplevel/x/key', u'toplevel/x/y/key', u'toplevel/x/y/z/key'])
|
||||
keys.should.equal(
|
||||
[u'toplevel/x/key', u'toplevel/x/y/key', u'toplevel/x/y/z/key'])
|
||||
|
||||
delimiter = '/'
|
||||
keys = [x.name for x in bucket.list(prefix + 'x', delimiter)]
|
||||
|
|
@ -640,7 +659,8 @@ def test_copy_key_reduced_redundancy():
|
|||
key.key = "the-key"
|
||||
key.set_contents_from_string("some value")
|
||||
|
||||
bucket.copy_key('new-key', 'foobar', 'the-key', storage_class='REDUCED_REDUNDANCY')
|
||||
bucket.copy_key('new-key', 'foobar', 'the-key',
|
||||
storage_class='REDUCED_REDUNDANCY')
|
||||
|
||||
# we use the bucket iterator because of:
|
||||
# https:/github.com/boto/boto/issues/1173
|
||||
|
|
@ -886,34 +906,54 @@ def test_ranged_get():
|
|||
key.set_contents_from_string(rep * 10)
|
||||
|
||||
# Implicitly bounded range requests.
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=50-'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=99-'}).should.equal(b'9')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=50-'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=99-'}).should.equal(b'9')
|
||||
|
||||
# Explicitly bounded range requests starting from the first byte.
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-0'}).should.equal(b'0')
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-49'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-99'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-100'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=0-700'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-0'}).should.equal(b'0')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-49'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-99'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-100'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=0-700'}).should.equal(rep * 10)
|
||||
|
||||
# Explicitly bounded range requests starting from the / a middle byte.
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=50-54'}).should.equal(rep[:5])
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=50-99'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=50-100'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=50-700'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=50-54'}).should.equal(rep[:5])
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=50-99'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=50-100'}).should.equal(rep * 5)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=50-700'}).should.equal(rep * 5)
|
||||
|
||||
# Explicitly bounded range requests starting from the last byte.
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=99-99'}).should.equal(b'9')
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=99-100'}).should.equal(b'9')
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=99-700'}).should.equal(b'9')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=99-99'}).should.equal(b'9')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=99-100'}).should.equal(b'9')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=99-700'}).should.equal(b'9')
|
||||
|
||||
# Suffix range requests.
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=-1'}).should.equal(b'9')
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=-60'}).should.equal(rep * 6)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=-100'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=-101'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(headers={'Range': 'bytes=-700'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=-1'}).should.equal(b'9')
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=-60'}).should.equal(rep * 6)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=-100'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=-101'}).should.equal(rep * 10)
|
||||
key.get_contents_as_string(
|
||||
headers={'Range': 'bytes=-700'}).should.equal(rep * 10)
|
||||
|
||||
key.size.should.equal(100)
|
||||
|
||||
|
|
@ -1006,6 +1046,7 @@ def test_boto3_key_etag():
|
|||
resp = s3.get_object(Bucket='mybucket', Key='steve')
|
||||
resp['ETag'].should.equal('"d32bda93738f7e03adb22e66c90fbc04"')
|
||||
|
||||
|
||||
@mock_s3
|
||||
def test_boto3_list_keys_xml_escaped():
|
||||
s3 = boto3.client('s3', region_name='us-east-1')
|
||||
|
|
@ -1045,13 +1086,13 @@ def test_boto3_list_objects_v2_truncated_response():
|
|||
assert resp['IsTruncated'] == True
|
||||
assert 'Delimiter' not in resp
|
||||
assert 'StartAfter' not in resp
|
||||
assert 'Owner' not in listed_object # owner info was not requested
|
||||
assert 'Owner' not in listed_object # owner info was not requested
|
||||
|
||||
next_token = resp['NextContinuationToken']
|
||||
|
||||
|
||||
# Second list
|
||||
resp = s3.list_objects_v2(Bucket='mybucket', MaxKeys=1, ContinuationToken=next_token)
|
||||
resp = s3.list_objects_v2(
|
||||
Bucket='mybucket', MaxKeys=1, ContinuationToken=next_token)
|
||||
listed_object = resp['Contents'][0]
|
||||
|
||||
assert listed_object['Key'] == 'three'
|
||||
|
|
@ -1065,9 +1106,9 @@ def test_boto3_list_objects_v2_truncated_response():
|
|||
|
||||
next_token = resp['NextContinuationToken']
|
||||
|
||||
|
||||
# Third list
|
||||
resp = s3.list_objects_v2(Bucket='mybucket', MaxKeys=1, ContinuationToken=next_token)
|
||||
resp = s3.list_objects_v2(
|
||||
Bucket='mybucket', MaxKeys=1, ContinuationToken=next_token)
|
||||
listed_object = resp['Contents'][0]
|
||||
|
||||
assert listed_object['Key'] == 'two'
|
||||
|
|
@ -1107,7 +1148,7 @@ def test_boto3_list_objects_v2_truncated_response_start_after():
|
|||
# Second list
|
||||
# The ContinuationToken must take precedence over StartAfter.
|
||||
resp = s3.list_objects_v2(Bucket='mybucket', MaxKeys=1, StartAfter='one',
|
||||
ContinuationToken=next_token)
|
||||
ContinuationToken=next_token)
|
||||
listed_object = resp['Contents'][0]
|
||||
|
||||
assert listed_object['Key'] == 'two'
|
||||
|
|
@ -1143,7 +1184,8 @@ def test_boto3_bucket_create():
|
|||
|
||||
s3.Object('blah', 'hello.txt').put(Body="some text")
|
||||
|
||||
s3.Object('blah', 'hello.txt').get()['Body'].read().decode("utf-8").should.equal("some text")
|
||||
s3.Object('blah', 'hello.txt').get()['Body'].read().decode(
|
||||
"utf-8").should.equal("some text")
|
||||
|
||||
|
||||
@mock_s3
|
||||
|
|
@ -1153,7 +1195,8 @@ def test_boto3_bucket_create_eu_central():
|
|||
|
||||
s3.Object('blah', 'hello.txt').put(Body="some text")
|
||||
|
||||
s3.Object('blah', 'hello.txt').get()['Body'].read().decode("utf-8").should.equal("some text")
|
||||
s3.Object('blah', 'hello.txt').get()['Body'].read().decode(
|
||||
"utf-8").should.equal("some text")
|
||||
|
||||
|
||||
@mock_s3
|
||||
|
|
@ -1163,10 +1206,12 @@ def test_boto3_head_object():
|
|||
|
||||
s3.Object('blah', 'hello.txt').put(Body="some text")
|
||||
|
||||
s3.Object('blah', 'hello.txt').meta.client.head_object(Bucket='blah', Key='hello.txt')
|
||||
s3.Object('blah', 'hello.txt').meta.client.head_object(
|
||||
Bucket='blah', Key='hello.txt')
|
||||
|
||||
with assert_raises(ClientError):
|
||||
s3.Object('blah', 'hello2.txt').meta.client.head_object(Bucket='blah', Key='hello_bad.txt')
|
||||
s3.Object('blah', 'hello2.txt').meta.client.head_object(
|
||||
Bucket='blah', Key='hello_bad.txt')
|
||||
|
||||
|
||||
@mock_s3
|
||||
|
|
@ -1176,7 +1221,8 @@ def test_boto3_get_object():
|
|||
|
||||
s3.Object('blah', 'hello.txt').put(Body="some text")
|
||||
|
||||
s3.Object('blah', 'hello.txt').meta.client.head_object(Bucket='blah', Key='hello.txt')
|
||||
s3.Object('blah', 'hello.txt').meta.client.head_object(
|
||||
Bucket='blah', Key='hello.txt')
|
||||
|
||||
with assert_raises(ClientError) as e:
|
||||
s3.Object('blah', 'hello2.txt').get()
|
||||
|
|
|
|||
|
|
@ -56,9 +56,9 @@ def test_lifecycle_multi():
|
|||
lifecycle.add_rule("2", "2/", "Enabled", Expiration(days=2))
|
||||
lifecycle.add_rule("3", "3/", "Enabled", Expiration(date=date))
|
||||
lifecycle.add_rule("4", "4/", "Enabled", None,
|
||||
Transition(days=4, storage_class=sc))
|
||||
Transition(days=4, storage_class=sc))
|
||||
lifecycle.add_rule("5", "5/", "Enabled", None,
|
||||
Transition(date=date, storage_class=sc))
|
||||
Transition(date=date, storage_class=sc))
|
||||
|
||||
bucket.configure_lifecycle(lifecycle)
|
||||
# read the lifecycle back
|
||||
|
|
|
|||
|
|
@ -8,11 +8,14 @@ def test_base_url():
|
|||
|
||||
|
||||
def test_localhost_bucket():
|
||||
expect(bucket_name_from_url('https://wfoobar.localhost:5000/abc')).should.equal("wfoobar")
|
||||
expect(bucket_name_from_url('https://wfoobar.localhost:5000/abc')
|
||||
).should.equal("wfoobar")
|
||||
|
||||
|
||||
def test_localhost_without_bucket():
|
||||
expect(bucket_name_from_url('https://www.localhost:5000/def')).should.equal(None)
|
||||
expect(bucket_name_from_url(
|
||||
'https://www.localhost:5000/def')).should.equal(None)
|
||||
|
||||
|
||||
def test_versioned_key_store():
|
||||
d = _VersionedKeyStore()
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@ def test_s3_server_bucket_create():
|
|||
res.status_code.should.equal(200)
|
||||
res.data.should.contain(b"ListBucketResult")
|
||||
|
||||
res = test_client.put('/bar', 'http://foobaz.localhost:5000/', data='test value')
|
||||
res = test_client.put(
|
||||
'/bar', 'http://foobaz.localhost:5000/', data='test value')
|
||||
res.status_code.should.equal(200)
|
||||
|
||||
res = test_client.get('/bar', 'http://foobaz.localhost:5000/')
|
||||
|
|
@ -45,7 +46,8 @@ def test_s3_server_bucket_versioning():
|
|||
|
||||
# Just enough XML to enable versioning
|
||||
body = '<Status>Enabled</Status>'
|
||||
res = test_client.put('/?versioning', 'http://foobaz.localhost:5000', data=body)
|
||||
res = test_client.put(
|
||||
'/?versioning', 'http://foobaz.localhost:5000', data=body)
|
||||
res.status_code.should.equal(200)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -44,7 +44,8 @@ def test_s3_server_bucket_create():
|
|||
res = test_client.get('/missing-bucket', 'http://localhost:5000')
|
||||
res.status_code.should.equal(404)
|
||||
|
||||
res = test_client.put('/foobar/bar', 'http://localhost:5000', data='test value')
|
||||
res = test_client.put(
|
||||
'/foobar/bar', 'http://localhost:5000', data='test value')
|
||||
res.status_code.should.equal(200)
|
||||
|
||||
res = test_client.get('/foobar/bar', 'http://localhost:5000')
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ def create_connection(key=None, secret=None):
|
|||
|
||||
|
||||
class MyModel(object):
|
||||
|
||||
def __init__(self, name, value):
|
||||
self.name = name
|
||||
self.value = value
|
||||
|
|
@ -42,7 +43,8 @@ def test_my_model_save():
|
|||
model_instance = MyModel('steve', 'is awesome')
|
||||
model_instance.save()
|
||||
|
||||
conn.get_bucket('mybucket').get_key('steve').get_contents_as_string().should.equal(b'is awesome')
|
||||
conn.get_bucket('mybucket').get_key(
|
||||
'steve').get_contents_as_string().should.equal(b'is awesome')
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -57,7 +59,8 @@ def test_missing_key_urllib2():
|
|||
conn = create_connection('the_key', 'the_secret')
|
||||
conn.create_bucket("foobar")
|
||||
|
||||
urlopen.when.called_with("http://s3.amazonaws.com/foobar/the-key").should.throw(HTTPError)
|
||||
urlopen.when.called_with(
|
||||
"http://s3.amazonaws.com/foobar/the-key").should.throw(HTTPError)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -93,7 +96,8 @@ def test_large_key_save():
|
|||
key.key = "the-key"
|
||||
key.set_contents_from_string("foobar" * 100000)
|
||||
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(b'foobar' * 100000)
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(b'foobar' * 100000)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -106,8 +110,10 @@ def test_copy_key():
|
|||
|
||||
bucket.copy_key('new-key', 'foobar', 'the-key')
|
||||
|
||||
bucket.get_key("the-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key("new-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key(
|
||||
"the-key").get_contents_as_string().should.equal(b"some value")
|
||||
bucket.get_key(
|
||||
"new-key").get_contents_as_string().should.equal(b"some value")
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -135,7 +141,8 @@ def test_last_modified():
|
|||
rs = bucket.get_all_keys()
|
||||
rs[0].last_modified.should.equal('2012-01-01T12:00:00.000Z')
|
||||
|
||||
bucket.get_key("the-key").last_modified.should.equal('Sun, 01 Jan 2012 12:00:00 GMT')
|
||||
bucket.get_key(
|
||||
"the-key").last_modified.should.equal('Sun, 01 Jan 2012 12:00:00 GMT')
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -147,7 +154,8 @@ def test_missing_bucket():
|
|||
@mock_s3_deprecated
|
||||
def test_bucket_with_dash():
|
||||
conn = create_connection('the_key', 'the_secret')
|
||||
conn.get_bucket.when.called_with('mybucket-test').should.throw(S3ResponseError)
|
||||
conn.get_bucket.when.called_with(
|
||||
'mybucket-test').should.throw(S3ResponseError)
|
||||
|
||||
|
||||
@mock_s3_deprecated
|
||||
|
|
@ -268,7 +276,8 @@ def test_bucket_key_listing_order():
|
|||
|
||||
delimiter = None
|
||||
keys = [x.name for x in bucket.list(prefix + 'x', delimiter)]
|
||||
keys.should.equal(['toplevel/x/key', 'toplevel/x/y/key', 'toplevel/x/y/z/key'])
|
||||
keys.should.equal(
|
||||
['toplevel/x/key', 'toplevel/x/y/key', 'toplevel/x/y/z/key'])
|
||||
|
||||
delimiter = '/'
|
||||
keys = [x.name for x in bucket.list(prefix + 'x', delimiter)]
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ def test_base_url():
|
|||
|
||||
|
||||
def test_localhost_bucket():
|
||||
expect(bucket_name_from_url('https://localhost:5000/wfoobar/abc')).should.equal("wfoobar")
|
||||
expect(bucket_name_from_url('https://localhost:5000/wfoobar/abc')
|
||||
).should.equal("wfoobar")
|
||||
|
||||
|
||||
def test_localhost_without_bucket():
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ def test_verify_email_identity():
|
|||
conn.verify_email_identity("test@example.com")
|
||||
|
||||
identities = conn.list_identities()
|
||||
address = identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'][0]
|
||||
address = identities['ListIdentitiesResponse'][
|
||||
'ListIdentitiesResult']['Identities'][0]
|
||||
address.should.equal('test@example.com')
|
||||
|
||||
|
||||
|
|
@ -27,7 +28,8 @@ def test_domain_verify():
|
|||
conn.verify_domain_identity("domain2.com")
|
||||
|
||||
identities = conn.list_identities()
|
||||
domains = list(identities['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'])
|
||||
domains = list(identities['ListIdentitiesResponse'][
|
||||
'ListIdentitiesResult']['Identities'])
|
||||
domains.should.equal(['domain1.com', 'domain2.com'])
|
||||
|
||||
|
||||
|
|
@ -36,9 +38,11 @@ def test_delete_identity():
|
|||
conn = boto.connect_ses('the_key', 'the_secret')
|
||||
conn.verify_email_identity("test@example.com")
|
||||
|
||||
conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(1)
|
||||
conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult'][
|
||||
'Identities'].should.have.length_of(1)
|
||||
conn.delete_identity("test@example.com")
|
||||
conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult']['Identities'].should.have.length_of(0)
|
||||
conn.list_identities()['ListIdentitiesResponse']['ListIdentitiesResult'][
|
||||
'Identities'].should.have.length_of(0)
|
||||
|
||||
|
||||
@mock_ses_deprecated
|
||||
|
|
@ -50,12 +54,15 @@ def test_send_email():
|
|||
"test body", "test_to@example.com").should.throw(BotoServerError)
|
||||
|
||||
conn.verify_email_identity("test@example.com")
|
||||
conn.send_email("test@example.com", "test subject", "test body", "test_to@example.com")
|
||||
conn.send_email("test@example.com", "test subject",
|
||||
"test body", "test_to@example.com")
|
||||
|
||||
send_quota = conn.get_send_quota()
|
||||
sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count = int(send_quota['GetSendQuotaResponse'][
|
||||
'GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count.should.equal(1)
|
||||
|
||||
|
||||
@mock_ses_deprecated
|
||||
def test_send_html_email():
|
||||
conn = boto.connect_ses('the_key', 'the_secret')
|
||||
|
|
@ -65,12 +72,15 @@ def test_send_html_email():
|
|||
"<span>test body</span>", "test_to@example.com", format="html").should.throw(BotoServerError)
|
||||
|
||||
conn.verify_email_identity("test@example.com")
|
||||
conn.send_email("test@example.com", "test subject", "<span>test body</span>", "test_to@example.com", format="html")
|
||||
conn.send_email("test@example.com", "test subject",
|
||||
"<span>test body</span>", "test_to@example.com", format="html")
|
||||
|
||||
send_quota = conn.get_send_quota()
|
||||
sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count = int(send_quota['GetSendQuotaResponse'][
|
||||
'GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count.should.equal(1)
|
||||
|
||||
|
||||
@mock_ses_deprecated
|
||||
def test_send_raw_email():
|
||||
conn = boto.connect_ses('the_key', 'the_secret')
|
||||
|
|
@ -101,5 +111,6 @@ def test_send_raw_email():
|
|||
)
|
||||
|
||||
send_quota = conn.get_send_quota()
|
||||
sent_count = int(send_quota['GetSendQuotaResponse']['GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count = int(send_quota['GetSendQuotaResponse'][
|
||||
'GetSendQuotaResult']['SentLast24Hours'])
|
||||
sent_count.should.equal(1)
|
||||
|
|
|
|||
|
|
@ -17,8 +17,10 @@ def test_create_platform_application():
|
|||
"PlatformPrincipal": "platform_principal",
|
||||
},
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn.should.equal('arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn.should.equal(
|
||||
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
|
|
@ -32,8 +34,10 @@ def test_get_platform_application_attributes():
|
|||
"PlatformPrincipal": "platform_principal",
|
||||
},
|
||||
)
|
||||
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
|
||||
arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
|
||||
'GetPlatformApplicationAttributesResult']['Attributes']
|
||||
attributes.should.equal({
|
||||
"PlatformCredential": "platform_credential",
|
||||
"PlatformPrincipal": "platform_principal",
|
||||
|
|
@ -43,7 +47,8 @@ def test_get_platform_application_attributes():
|
|||
@mock_sns_deprecated
|
||||
def test_get_missing_platform_application_attributes():
|
||||
conn = boto.connect_sns()
|
||||
conn.get_platform_application_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
|
||||
conn.get_platform_application_attributes.when.called_with(
|
||||
"a-fake-arn").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
|
|
@ -57,11 +62,13 @@ def test_set_platform_application_attributes():
|
|||
"PlatformPrincipal": "platform_principal",
|
||||
},
|
||||
)
|
||||
arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
conn.set_platform_application_attributes(arn,
|
||||
{"PlatformPrincipal": "other"}
|
||||
)
|
||||
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse']['GetPlatformApplicationAttributesResult']['Attributes']
|
||||
{"PlatformPrincipal": "other"}
|
||||
)
|
||||
attributes = conn.get_platform_application_attributes(arn)['GetPlatformApplicationAttributesResponse'][
|
||||
'GetPlatformApplicationAttributesResult']['Attributes']
|
||||
attributes.should.equal({
|
||||
"PlatformCredential": "platform_credential",
|
||||
"PlatformPrincipal": "other",
|
||||
|
|
@ -81,7 +88,8 @@ def test_list_platform_applications():
|
|||
)
|
||||
|
||||
applications_repsonse = conn.list_platform_applications()
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse'][
|
||||
'ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications.should.have.length_of(2)
|
||||
|
||||
|
||||
|
|
@ -98,14 +106,16 @@ def test_delete_platform_application():
|
|||
)
|
||||
|
||||
applications_repsonse = conn.list_platform_applications()
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse'][
|
||||
'ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications.should.have.length_of(2)
|
||||
|
||||
application_arn = applications[0]['PlatformApplicationArn']
|
||||
conn.delete_platform_application(application_arn)
|
||||
|
||||
applications_repsonse = conn.list_platform_applications()
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse']['ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications = applications_repsonse['ListPlatformApplicationsResponse'][
|
||||
'ListPlatformApplicationsResult']['PlatformApplications']
|
||||
applications.should.have.length_of(1)
|
||||
|
||||
|
||||
|
|
@ -116,7 +126,8 @@ def test_create_platform_endpoint():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -127,8 +138,10 @@ def test_create_platform_endpoint():
|
|||
},
|
||||
)
|
||||
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn.should.contain("arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn.should.contain(
|
||||
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
|
|
@ -138,7 +151,8 @@ def test_get_list_endpoints_by_platform_application():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -148,7 +162,8 @@ def test_get_list_endpoints_by_platform_application():
|
|||
"CustomUserData": "some data",
|
||||
},
|
||||
)
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
|
||||
endpoint_list = conn.list_endpoints_by_platform_application(
|
||||
platform_application_arn=application_arn
|
||||
|
|
@ -166,7 +181,8 @@ def test_get_endpoint_attributes():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -177,9 +193,11 @@ def test_get_endpoint_attributes():
|
|||
"CustomUserData": "some data",
|
||||
},
|
||||
)
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
|
||||
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
|
||||
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
|
||||
'GetEndpointAttributesResult']['Attributes']
|
||||
attributes.should.equal({
|
||||
"Token": "some_unique_id",
|
||||
"Enabled": 'False',
|
||||
|
|
@ -190,7 +208,8 @@ def test_get_endpoint_attributes():
|
|||
@mock_sns_deprecated
|
||||
def test_get_missing_endpoint_attributes():
|
||||
conn = boto.connect_sns()
|
||||
conn.get_endpoint_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
|
||||
conn.get_endpoint_attributes.when.called_with(
|
||||
"a-fake-arn").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
|
|
@ -200,7 +219,8 @@ def test_set_endpoint_attributes():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -211,12 +231,14 @@ def test_set_endpoint_attributes():
|
|||
"CustomUserData": "some data",
|
||||
},
|
||||
)
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
|
||||
conn.set_endpoint_attributes(endpoint_arn,
|
||||
{"CustomUserData": "other data"}
|
||||
)
|
||||
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse']['GetEndpointAttributesResult']['Attributes']
|
||||
{"CustomUserData": "other data"}
|
||||
)
|
||||
attributes = conn.get_endpoint_attributes(endpoint_arn)['GetEndpointAttributesResponse'][
|
||||
'GetEndpointAttributesResult']['Attributes']
|
||||
attributes.should.equal({
|
||||
"Token": "some_unique_id",
|
||||
"Enabled": 'False',
|
||||
|
|
@ -231,7 +253,8 @@ def test_delete_endpoint():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -242,7 +265,8 @@ def test_delete_endpoint():
|
|||
"CustomUserData": "some data",
|
||||
},
|
||||
)
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
|
||||
endpoint_list = conn.list_endpoints_by_platform_application(
|
||||
platform_application_arn=application_arn
|
||||
|
|
@ -265,7 +289,8 @@ def test_publish_to_platform_endpoint():
|
|||
name="my-application",
|
||||
platform="APNS",
|
||||
)
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse']['CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
application_arn = platform_application['CreatePlatformApplicationResponse'][
|
||||
'CreatePlatformApplicationResult']['PlatformApplicationArn']
|
||||
|
||||
endpoint = conn.create_platform_endpoint(
|
||||
platform_application_arn=application_arn,
|
||||
|
|
@ -276,6 +301,8 @@ def test_publish_to_platform_endpoint():
|
|||
},
|
||||
)
|
||||
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
|
||||
endpoint_arn = endpoint['CreatePlatformEndpointResponse'][
|
||||
'CreatePlatformEndpointResult']['EndpointArn']
|
||||
|
||||
conn.publish(message="some message", message_structure="json", target_arn=endpoint_arn)
|
||||
conn.publish(message="some message", message_structure="json",
|
||||
target_arn=endpoint_arn)
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ def test_create_platform_application():
|
|||
},
|
||||
)
|
||||
application_arn = response['PlatformApplicationArn']
|
||||
application_arn.should.equal('arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
|
||||
application_arn.should.equal(
|
||||
'arn:aws:sns:us-east-1:123456789012:app/APNS/my-application')
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -33,7 +34,8 @@ def test_get_platform_application_attributes():
|
|||
},
|
||||
)
|
||||
arn = platform_application['PlatformApplicationArn']
|
||||
attributes = conn.get_platform_application_attributes(PlatformApplicationArn=arn)['Attributes']
|
||||
attributes = conn.get_platform_application_attributes(
|
||||
PlatformApplicationArn=arn)['Attributes']
|
||||
attributes.should.equal({
|
||||
"PlatformCredential": "platform_credential",
|
||||
"PlatformPrincipal": "platform_principal",
|
||||
|
|
@ -43,7 +45,8 @@ def test_get_platform_application_attributes():
|
|||
@mock_sns
|
||||
def test_get_missing_platform_application_attributes():
|
||||
conn = boto3.client('sns', region_name='us-east-1')
|
||||
conn.get_platform_application_attributes.when.called_with(PlatformApplicationArn="a-fake-arn").should.throw(ClientError)
|
||||
conn.get_platform_application_attributes.when.called_with(
|
||||
PlatformApplicationArn="a-fake-arn").should.throw(ClientError)
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -59,9 +62,11 @@ def test_set_platform_application_attributes():
|
|||
)
|
||||
arn = platform_application['PlatformApplicationArn']
|
||||
conn.set_platform_application_attributes(PlatformApplicationArn=arn,
|
||||
Attributes={"PlatformPrincipal": "other"}
|
||||
)
|
||||
attributes = conn.get_platform_application_attributes(PlatformApplicationArn=arn)['Attributes']
|
||||
Attributes={
|
||||
"PlatformPrincipal": "other"}
|
||||
)
|
||||
attributes = conn.get_platform_application_attributes(
|
||||
PlatformApplicationArn=arn)['Attributes']
|
||||
attributes.should.equal({
|
||||
"PlatformCredential": "platform_credential",
|
||||
"PlatformPrincipal": "other",
|
||||
|
|
@ -133,7 +138,8 @@ def test_create_platform_endpoint():
|
|||
)
|
||||
|
||||
endpoint_arn = endpoint['EndpointArn']
|
||||
endpoint_arn.should.contain("arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
|
||||
endpoint_arn.should.contain(
|
||||
"arn:aws:sns:us-east-1:123456789012:endpoint/APNS/my-application/")
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -186,7 +192,8 @@ def test_get_endpoint_attributes():
|
|||
)
|
||||
endpoint_arn = endpoint['EndpointArn']
|
||||
|
||||
attributes = conn.get_endpoint_attributes(EndpointArn=endpoint_arn)['Attributes']
|
||||
attributes = conn.get_endpoint_attributes(
|
||||
EndpointArn=endpoint_arn)['Attributes']
|
||||
attributes.should.equal({
|
||||
"Token": "some_unique_id",
|
||||
"Enabled": 'false',
|
||||
|
|
@ -197,7 +204,8 @@ def test_get_endpoint_attributes():
|
|||
@mock_sns
|
||||
def test_get_missing_endpoint_attributes():
|
||||
conn = boto3.client('sns', region_name='us-east-1')
|
||||
conn.get_endpoint_attributes.when.called_with(EndpointArn="a-fake-arn").should.throw(ClientError)
|
||||
conn.get_endpoint_attributes.when.called_with(
|
||||
EndpointArn="a-fake-arn").should.throw(ClientError)
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -222,9 +230,10 @@ def test_set_endpoint_attributes():
|
|||
endpoint_arn = endpoint['EndpointArn']
|
||||
|
||||
conn.set_endpoint_attributes(EndpointArn=endpoint_arn,
|
||||
Attributes={"CustomUserData": "other data"}
|
||||
)
|
||||
attributes = conn.get_endpoint_attributes(EndpointArn=endpoint_arn)['Attributes']
|
||||
Attributes={"CustomUserData": "other data"}
|
||||
)
|
||||
attributes = conn.get_endpoint_attributes(
|
||||
EndpointArn=endpoint_arn)['Attributes']
|
||||
attributes.should.equal({
|
||||
"Token": "some_unique_id",
|
||||
"Enabled": 'false',
|
||||
|
|
@ -253,4 +262,5 @@ def test_publish_to_platform_endpoint():
|
|||
|
||||
endpoint_arn = endpoint['EndpointArn']
|
||||
|
||||
conn.publish(Message="some message", MessageStructure="json", TargetArn=endpoint_arn)
|
||||
conn.publish(Message="some message",
|
||||
MessageStructure="json", TargetArn=endpoint_arn)
|
||||
|
|
|
|||
|
|
@ -15,12 +15,14 @@ def test_publish_to_sqs():
|
|||
conn = boto.connect_sns()
|
||||
conn.create_topic("some-topic")
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
|
||||
sqs_conn = boto.connect_sqs()
|
||||
sqs_conn.create_queue("test-queue")
|
||||
|
||||
conn.subscribe(topic_arn, "sqs", "arn:aws:sqs:us-east-1:123456789012:test-queue")
|
||||
conn.subscribe(topic_arn, "sqs",
|
||||
"arn:aws:sqs:us-east-1:123456789012:test-queue")
|
||||
|
||||
conn.publish(topic=topic_arn, message="my message")
|
||||
|
||||
|
|
@ -35,12 +37,14 @@ def test_publish_to_sqs_in_different_region():
|
|||
conn = boto.sns.connect_to_region("us-west-1")
|
||||
conn.create_topic("some-topic")
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
|
||||
sqs_conn = boto.sqs.connect_to_region("us-west-2")
|
||||
sqs_conn.create_queue("test-queue")
|
||||
|
||||
conn.subscribe(topic_arn, "sqs", "arn:aws:sqs:us-west-2:123456789012:test-queue")
|
||||
conn.subscribe(topic_arn, "sqs",
|
||||
"arn:aws:sqs:us-west-2:123456789012:test-queue")
|
||||
|
||||
conn.publish(topic=topic_arn, message="my message")
|
||||
|
||||
|
|
@ -61,9 +65,11 @@ def test_publish_to_http():
|
|||
conn = boto.connect_sns()
|
||||
conn.create_topic("some-topic")
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
|
||||
conn.subscribe(topic_arn, "http", "http://example.com/foobar")
|
||||
|
||||
response = conn.publish(topic=topic_arn, message="my message", subject="my subject")
|
||||
response = conn.publish(
|
||||
topic=topic_arn, message="my message", subject="my subject")
|
||||
message_id = response['PublishResponse']['PublishResult']['MessageId']
|
||||
|
|
|
|||
|
|
@ -70,5 +70,6 @@ def test_publish_to_http():
|
|||
Protocol="http",
|
||||
Endpoint="http://example.com/foobar")
|
||||
|
||||
response = conn.publish(TopicArn=topic_arn, Message="my message", Subject="my subject")
|
||||
response = conn.publish(
|
||||
TopicArn=topic_arn, Message="my message", Subject="my subject")
|
||||
message_id = response['MessageId']
|
||||
|
|
|
|||
|
|
@ -15,8 +15,10 @@ def test_sns_server_get():
|
|||
|
||||
topic_data = test_client.action_data("CreateTopic", Name="test topic")
|
||||
topic_data.should.contain("CreateTopicResult")
|
||||
topic_data.should.contain("<TopicArn>arn:aws:sns:us-east-1:123456789012:test topic</TopicArn>")
|
||||
topic_data.should.contain(
|
||||
"<TopicArn>arn:aws:sns:us-east-1:123456789012:test topic</TopicArn>")
|
||||
|
||||
topics_data = test_client.action_data("ListTopics")
|
||||
topics_data.should.contain("ListTopicsResult")
|
||||
topic_data.should.contain("<TopicArn>arn:aws:sns:us-east-1:123456789012:test topic</TopicArn>")
|
||||
topic_data.should.contain(
|
||||
"<TopicArn>arn:aws:sns:us-east-1:123456789012:test topic</TopicArn>")
|
||||
|
|
|
|||
|
|
@ -12,11 +12,13 @@ def test_creating_subscription():
|
|||
conn = boto.connect_sns()
|
||||
conn.create_topic("some-topic")
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
|
||||
conn.subscribe(topic_arn, "http", "http://example.com/")
|
||||
|
||||
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
|
||||
"ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions.should.have.length_of(1)
|
||||
subscription = subscriptions[0]
|
||||
subscription["TopicArn"].should.equal(topic_arn)
|
||||
|
|
@ -28,7 +30,8 @@ def test_creating_subscription():
|
|||
conn.unsubscribe(subscription["SubscriptionArn"])
|
||||
|
||||
# And there should be zero subscriptions left
|
||||
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions = conn.get_all_subscriptions()["ListSubscriptionsResponse"][
|
||||
"ListSubscriptionsResult"]["Subscriptions"]
|
||||
subscriptions.should.have.length_of(0)
|
||||
|
||||
|
||||
|
|
@ -46,7 +49,8 @@ def test_getting_subscriptions_by_topic():
|
|||
conn.subscribe(topic1_arn, "http", "http://example1.com/")
|
||||
conn.subscribe(topic2_arn, "http", "http://example2.com/")
|
||||
|
||||
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"]
|
||||
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)[
|
||||
"ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"]
|
||||
topic1_subscriptions.should.have.length_of(1)
|
||||
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
|
||||
|
||||
|
|
@ -63,25 +67,36 @@ def test_subscription_paging():
|
|||
topic2_arn = topics[1]['TopicArn']
|
||||
|
||||
for index in range(DEFAULT_PAGE_SIZE + int(DEFAULT_PAGE_SIZE / 3)):
|
||||
conn.subscribe(topic1_arn, 'email', 'email_' + str(index) + '@test.com')
|
||||
conn.subscribe(topic2_arn, 'email', 'email_' + str(index) + '@test.com')
|
||||
conn.subscribe(topic1_arn, 'email', 'email_' +
|
||||
str(index) + '@test.com')
|
||||
conn.subscribe(topic2_arn, 'email', 'email_' +
|
||||
str(index) + '@test.com')
|
||||
|
||||
all_subscriptions = conn.get_all_subscriptions()
|
||||
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
|
||||
next_token = all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["NextToken"]
|
||||
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
|
||||
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
|
||||
next_token = all_subscriptions["ListSubscriptionsResponse"][
|
||||
"ListSubscriptionsResult"]["NextToken"]
|
||||
next_token.should.equal(DEFAULT_PAGE_SIZE)
|
||||
|
||||
all_subscriptions = conn.get_all_subscriptions(next_token=next_token * 2)
|
||||
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE * 2 / 3))
|
||||
next_token = all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"]["NextToken"]
|
||||
all_subscriptions["ListSubscriptionsResponse"]["ListSubscriptionsResult"][
|
||||
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE * 2 / 3))
|
||||
next_token = all_subscriptions["ListSubscriptionsResponse"][
|
||||
"ListSubscriptionsResult"]["NextToken"]
|
||||
next_token.should.equal(None)
|
||||
|
||||
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn)
|
||||
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
|
||||
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["NextToken"]
|
||||
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
|
||||
"Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
|
||||
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
|
||||
"ListSubscriptionsByTopicResult"]["NextToken"]
|
||||
next_token.should.equal(DEFAULT_PAGE_SIZE)
|
||||
|
||||
topic1_subscriptions = conn.get_all_subscriptions_by_topic(topic1_arn, next_token=next_token)
|
||||
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
|
||||
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"]["NextToken"]
|
||||
topic1_subscriptions = conn.get_all_subscriptions_by_topic(
|
||||
topic1_arn, next_token=next_token)
|
||||
topic1_subscriptions["ListSubscriptionsByTopicResponse"]["ListSubscriptionsByTopicResult"][
|
||||
"Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
|
||||
next_token = topic1_subscriptions["ListSubscriptionsByTopicResponse"][
|
||||
"ListSubscriptionsByTopicResult"]["NextToken"]
|
||||
next_token.should.equal(None)
|
||||
|
|
|
|||
|
|
@ -52,7 +52,8 @@ def test_getting_subscriptions_by_topic():
|
|||
Protocol="http",
|
||||
Endpoint="http://example2.com/")
|
||||
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn)["Subscriptions"]
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn)[
|
||||
"Subscriptions"]
|
||||
topic1_subscriptions.should.have.length_of(1)
|
||||
topic1_subscriptions[0]['Endpoint'].should.equal("http://example1.com/")
|
||||
|
||||
|
|
@ -77,14 +78,19 @@ def test_subscription_paging():
|
|||
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
|
||||
|
||||
all_subscriptions = conn.list_subscriptions(NextToken=next_token)
|
||||
all_subscriptions["Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
|
||||
all_subscriptions["Subscriptions"].should.have.length_of(
|
||||
int(DEFAULT_PAGE_SIZE / 3))
|
||||
all_subscriptions.shouldnt.have("NextToken")
|
||||
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn)
|
||||
topic1_subscriptions["Subscriptions"].should.have.length_of(DEFAULT_PAGE_SIZE)
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(
|
||||
TopicArn=topic1_arn)
|
||||
topic1_subscriptions["Subscriptions"].should.have.length_of(
|
||||
DEFAULT_PAGE_SIZE)
|
||||
next_token = topic1_subscriptions["NextToken"]
|
||||
next_token.should.equal(str(DEFAULT_PAGE_SIZE))
|
||||
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(TopicArn=topic1_arn, NextToken=next_token)
|
||||
topic1_subscriptions["Subscriptions"].should.have.length_of(int(DEFAULT_PAGE_SIZE / 3))
|
||||
topic1_subscriptions = conn.list_subscriptions_by_topic(
|
||||
TopicArn=topic1_arn, NextToken=next_token)
|
||||
topic1_subscriptions["Subscriptions"].should.have.length_of(
|
||||
int(DEFAULT_PAGE_SIZE / 3))
|
||||
topic1_subscriptions.shouldnt.have("NextToken")
|
||||
|
|
|
|||
|
|
@ -34,7 +34,8 @@ def test_create_and_delete_topic():
|
|||
@mock_sns_deprecated
|
||||
def test_get_missing_topic():
|
||||
conn = boto.connect_sns()
|
||||
conn.get_topic_attributes.when.called_with("a-fake-arn").should.throw(BotoServerError)
|
||||
conn.get_topic_attributes.when.called_with(
|
||||
"a-fake-arn").should.throw(BotoServerError)
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
|
|
@ -42,7 +43,9 @@ def test_create_topic_in_multiple_regions():
|
|||
for region in ['us-west-1', 'us-west-2']:
|
||||
conn = boto.sns.connect_to_region(region)
|
||||
conn.create_topic("some-topic")
|
||||
list(conn.get_all_topics()["ListTopicsResponse"]["ListTopicsResult"]["Topics"]).should.have.length_of(1)
|
||||
list(conn.get_all_topics()["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"]).should.have.length_of(1)
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
def test_topic_corresponds_to_region():
|
||||
|
|
@ -50,8 +53,11 @@ def test_topic_corresponds_to_region():
|
|||
conn = boto.sns.connect_to_region(region)
|
||||
conn.create_topic("some-topic")
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn.should.equal("arn:aws:sns:{0}:123456789012:some-topic".format(region))
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn.should.equal(
|
||||
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
def test_topic_attributes():
|
||||
|
|
@ -59,9 +65,11 @@ def test_topic_attributes():
|
|||
conn.create_topic("some-topic")
|
||||
|
||||
topics_json = conn.get_all_topics()
|
||||
topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
topic_arn = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"][0]['TopicArn']
|
||||
|
||||
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse']['GetTopicAttributesResult']['Attributes']
|
||||
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
|
||||
'GetTopicAttributesResult']['Attributes']
|
||||
attributes["TopicArn"].should.equal(
|
||||
"arn:aws:sns:{0}:123456789012:some-topic"
|
||||
.format(conn.region.name)
|
||||
|
|
@ -73,7 +81,8 @@ def test_topic_attributes():
|
|||
attributes["SubscriptionsConfirmed"].should.equal(0)
|
||||
attributes["SubscriptionsDeleted"].should.equal(0)
|
||||
attributes["DeliveryPolicy"].should.equal("")
|
||||
attributes["EffectiveDeliveryPolicy"].should.equal(DEFAULT_EFFECTIVE_DELIVERY_POLICY)
|
||||
attributes["EffectiveDeliveryPolicy"].should.equal(
|
||||
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
|
||||
|
||||
# boto can't handle prefix-mandatory strings:
|
||||
# i.e. unicode on Python 2 -- u"foobar"
|
||||
|
|
@ -90,10 +99,13 @@ def test_topic_attributes():
|
|||
conn.set_topic_attributes(topic_arn, "DisplayName", displayname)
|
||||
conn.set_topic_attributes(topic_arn, "DeliveryPolicy", delivery)
|
||||
|
||||
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse']['GetTopicAttributesResult']['Attributes']
|
||||
attributes = conn.get_topic_attributes(topic_arn)['GetTopicAttributesResponse'][
|
||||
'GetTopicAttributesResult']['Attributes']
|
||||
attributes["Policy"].should.equal("{'foo': 'bar'}")
|
||||
attributes["DisplayName"].should.equal("My display name")
|
||||
attributes["DeliveryPolicy"].should.equal("{'http': {'defaultHealthyRetryPolicy': {'numRetries': 5}}}")
|
||||
attributes["DeliveryPolicy"].should.equal(
|
||||
"{'http': {'defaultHealthyRetryPolicy': {'numRetries': 5}}}")
|
||||
|
||||
|
||||
@mock_sns_deprecated
|
||||
def test_topic_paging():
|
||||
|
|
@ -102,15 +114,19 @@ def test_topic_paging():
|
|||
conn.create_topic("some-topic_" + str(index))
|
||||
|
||||
topics_json = conn.get_all_topics()
|
||||
topics_list = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
|
||||
next_token = topics_json["ListTopicsResponse"]["ListTopicsResult"]["NextToken"]
|
||||
topics_list = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"]
|
||||
next_token = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["NextToken"]
|
||||
|
||||
len(topics_list).should.equal(DEFAULT_PAGE_SIZE)
|
||||
next_token.should.equal(DEFAULT_PAGE_SIZE)
|
||||
|
||||
topics_json = conn.get_all_topics(next_token=next_token)
|
||||
topics_list = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"]
|
||||
next_token = topics_json["ListTopicsResponse"]["ListTopicsResult"]["NextToken"]
|
||||
topics_list = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["Topics"]
|
||||
next_token = topics_json["ListTopicsResponse"][
|
||||
"ListTopicsResult"]["NextToken"]
|
||||
|
||||
topics_list.should.have.length_of(int(DEFAULT_PAGE_SIZE / 2))
|
||||
next_token.should.equal(None)
|
||||
|
|
|
|||
|
|
@ -35,7 +35,8 @@ def test_create_and_delete_topic():
|
|||
@mock_sns
|
||||
def test_get_missing_topic():
|
||||
conn = boto3.client("sns", region_name="us-east-1")
|
||||
conn.get_topic_attributes.when.called_with(TopicArn="a-fake-arn").should.throw(ClientError)
|
||||
conn.get_topic_attributes.when.called_with(
|
||||
TopicArn="a-fake-arn").should.throw(ClientError)
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -53,7 +54,8 @@ def test_topic_corresponds_to_region():
|
|||
conn.create_topic(Name="some-topic")
|
||||
topics_json = conn.list_topics()
|
||||
topic_arn = topics_json["Topics"][0]['TopicArn']
|
||||
topic_arn.should.equal("arn:aws:sns:{0}:123456789012:some-topic".format(region))
|
||||
topic_arn.should.equal(
|
||||
"arn:aws:sns:{0}:123456789012:some-topic".format(region))
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
@ -76,7 +78,8 @@ def test_topic_attributes():
|
|||
attributes["SubscriptionsConfirmed"].should.equal('0')
|
||||
attributes["SubscriptionsDeleted"].should.equal('0')
|
||||
attributes["DeliveryPolicy"].should.equal("")
|
||||
attributes["EffectiveDeliveryPolicy"].should.equal(DEFAULT_EFFECTIVE_DELIVERY_POLICY)
|
||||
attributes["EffectiveDeliveryPolicy"].should.equal(
|
||||
DEFAULT_EFFECTIVE_DELIVERY_POLICY)
|
||||
|
||||
# boto can't handle prefix-mandatory strings:
|
||||
# i.e. unicode on Python 2 -- u"foobar"
|
||||
|
|
@ -84,11 +87,13 @@ def test_topic_attributes():
|
|||
if six.PY2:
|
||||
policy = json.dumps({b"foo": b"bar"})
|
||||
displayname = b"My display name"
|
||||
delivery = json.dumps({b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}})
|
||||
delivery = json.dumps(
|
||||
{b"http": {b"defaultHealthyRetryPolicy": {b"numRetries": 5}}})
|
||||
else:
|
||||
policy = json.dumps({u"foo": u"bar"})
|
||||
displayname = u"My display name"
|
||||
delivery = json.dumps({u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}})
|
||||
delivery = json.dumps(
|
||||
{u"http": {u"defaultHealthyRetryPolicy": {u"numRetries": 5}}})
|
||||
conn.set_topic_attributes(TopicArn=topic_arn,
|
||||
AttributeName="Policy",
|
||||
AttributeValue=policy)
|
||||
|
|
@ -102,7 +107,8 @@ def test_topic_attributes():
|
|||
attributes = conn.get_topic_attributes(TopicArn=topic_arn)['Attributes']
|
||||
attributes["Policy"].should.equal('{"foo": "bar"}')
|
||||
attributes["DisplayName"].should.equal("My display name")
|
||||
attributes["DeliveryPolicy"].should.equal('{"http": {"defaultHealthyRetryPolicy": {"numRetries": 5}}}')
|
||||
attributes["DeliveryPolicy"].should.equal(
|
||||
'{"http": {"defaultHealthyRetryPolicy": {"numRetries": 5}}}')
|
||||
|
||||
|
||||
@mock_sns
|
||||
|
|
|
|||
|
|
@ -31,7 +31,8 @@ def test_sqs_list_identities():
|
|||
res = test_client.get(
|
||||
'/123/testqueue?Action=ReceiveMessage&MaxNumberOfMessages=1')
|
||||
|
||||
message = re.search("<Body>(.*?)</Body>", res.data.decode('utf-8')).groups()[0]
|
||||
message = re.search("<Body>(.*?)</Body>",
|
||||
res.data.decode('utf-8')).groups()[0]
|
||||
message.should.equal('test-message')
|
||||
|
||||
|
||||
|
|
@ -58,7 +59,8 @@ def test_messages_polling():
|
|||
msg_res = test_client.get(
|
||||
'/123/testqueue?Action=ReceiveMessage&MaxNumberOfMessages=1&WaitTimeSeconds=5'
|
||||
)
|
||||
new_msgs = re.findall("<Body>(.*?)</Body>", msg_res.data.decode('utf-8'))
|
||||
new_msgs = re.findall("<Body>(.*?)</Body>",
|
||||
msg_res.data.decode('utf-8'))
|
||||
count += len(new_msgs)
|
||||
messages.append(new_msgs)
|
||||
|
||||
|
|
@ -71,5 +73,6 @@ def test_messages_polling():
|
|||
get_messages_thread.join()
|
||||
insert_messages_thread.join()
|
||||
|
||||
# got each message in a separate call to ReceiveMessage, despite the long WaitTimeSeconds
|
||||
# got each message in a separate call to ReceiveMessage, despite the long
|
||||
# WaitTimeSeconds
|
||||
assert len(messages) == 5
|
||||
|
|
|
|||
|
|
@ -34,7 +34,8 @@ def test_create_queue():
|
|||
@mock_sqs
|
||||
def test_get_inexistent_queue():
|
||||
sqs = boto3.resource('sqs', region_name='us-east-1')
|
||||
sqs.get_queue_by_name.when.called_with(QueueName='nonexisting-queue').should.throw(botocore.exceptions.ClientError)
|
||||
sqs.get_queue_by_name.when.called_with(
|
||||
QueueName='nonexisting-queue').should.throw(botocore.exceptions.ClientError)
|
||||
|
||||
|
||||
@mock_sqs
|
||||
|
|
@ -43,8 +44,10 @@ def test_message_send():
|
|||
queue = sqs.create_queue(QueueName="blah")
|
||||
msg = queue.send_message(MessageBody="derp")
|
||||
|
||||
msg.get('MD5OfMessageBody').should.equal('58fd9edd83341c29f1aebba81c31e257')
|
||||
msg.get('ResponseMetadata', {}).get('RequestId').should.equal('27daac76-34dd-47df-bd01-1f6e873584a0')
|
||||
msg.get('MD5OfMessageBody').should.equal(
|
||||
'58fd9edd83341c29f1aebba81c31e257')
|
||||
msg.get('ResponseMetadata', {}).get('RequestId').should.equal(
|
||||
'27daac76-34dd-47df-bd01-1f6e873584a0')
|
||||
msg.get('MessageId').should_not.contain(' \n')
|
||||
|
||||
messages = queue.receive_messages()
|
||||
|
|
@ -73,7 +76,8 @@ def test_create_queues_in_multiple_region():
|
|||
list(west1_conn.list_queues()['QueueUrls']).should.have.length_of(1)
|
||||
list(west2_conn.list_queues()['QueueUrls']).should.have.length_of(1)
|
||||
|
||||
west1_conn.list_queues()['QueueUrls'][0].should.equal('http://sqs.us-west-1.amazonaws.com/123456789012/blah')
|
||||
west1_conn.list_queues()['QueueUrls'][0].should.equal(
|
||||
'http://sqs.us-west-1.amazonaws.com/123456789012/blah')
|
||||
|
||||
|
||||
@mock_sqs
|
||||
|
|
@ -87,14 +91,16 @@ def test_get_queue_with_prefix():
|
|||
|
||||
queue = conn.list_queues(QueueNamePrefix="test-")['QueueUrls']
|
||||
queue.should.have.length_of(1)
|
||||
queue[0].should.equal("http://sqs.us-west-1.amazonaws.com/123456789012/test-queue")
|
||||
queue[0].should.equal(
|
||||
"http://sqs.us-west-1.amazonaws.com/123456789012/test-queue")
|
||||
|
||||
|
||||
@mock_sqs
|
||||
def test_delete_queue():
|
||||
sqs = boto3.resource('sqs', region_name='us-east-1')
|
||||
conn = boto3.client("sqs", region_name='us-east-1')
|
||||
conn.create_queue(QueueName="test-queue", Attributes={"VisibilityTimeout": "60"})
|
||||
conn.create_queue(QueueName="test-queue",
|
||||
Attributes={"VisibilityTimeout": "60"})
|
||||
queue = sqs.Queue('test-queue')
|
||||
|
||||
conn.list_queues()['QueueUrls'].should.have.length_of(1)
|
||||
|
|
@ -110,7 +116,8 @@ def test_delete_queue():
|
|||
def test_set_queue_attribute():
|
||||
sqs = boto3.resource('sqs', region_name='us-east-1')
|
||||
conn = boto3.client("sqs", region_name='us-east-1')
|
||||
conn.create_queue(QueueName="test-queue", Attributes={"VisibilityTimeout": '60'})
|
||||
conn.create_queue(QueueName="test-queue",
|
||||
Attributes={"VisibilityTimeout": '60'})
|
||||
|
||||
queue = sqs.Queue("test-queue")
|
||||
queue.attributes['VisibilityTimeout'].should.equal('60')
|
||||
|
|
@ -133,7 +140,8 @@ def test_send_message():
|
|||
response = queue.send_message(MessageBody=body_one)
|
||||
response = queue.send_message(MessageBody=body_two)
|
||||
|
||||
messages = conn.receive_message(QueueUrl=queue.url, MaxNumberOfMessages=2)['Messages']
|
||||
messages = conn.receive_message(
|
||||
QueueUrl=queue.url, MaxNumberOfMessages=2)['Messages']
|
||||
|
||||
messages[0]['Body'].should.equal(body_one)
|
||||
messages[1]['Body'].should.equal(body_two)
|
||||
|
|
@ -244,13 +252,15 @@ def test_receive_message_with_explicit_visibility_timeout():
|
|||
queue.write(queue.new_message(body_one))
|
||||
|
||||
queue.count().should.equal(1)
|
||||
messages = conn.receive_message(queue, number_messages=1, visibility_timeout=0)
|
||||
messages = conn.receive_message(
|
||||
queue, number_messages=1, visibility_timeout=0)
|
||||
|
||||
assert len(messages) == 1
|
||||
|
||||
# Message should remain visible
|
||||
queue.count().should.equal(1)
|
||||
|
||||
|
||||
@mock_sqs_deprecated
|
||||
def test_change_message_visibility():
|
||||
conn = boto.connect_sqs('the_key', 'the_secret')
|
||||
|
|
@ -381,7 +391,8 @@ def test_send_batch_operation_with_message_attributes():
|
|||
queue = conn.create_queue("test-queue", visibility_timeout=60)
|
||||
queue.set_message_class(RawMessage)
|
||||
|
||||
message_tuple = ("my_first_message", 'test message 1', 0, {'name1': {'data_type': 'String', 'string_value': 'foo'}})
|
||||
message_tuple = ("my_first_message", 'test message 1', 0, {
|
||||
'name1': {'data_type': 'String', 'string_value': 'foo'}})
|
||||
queue.write_batch([message_tuple])
|
||||
|
||||
messages = queue.get_messages()
|
||||
|
|
@ -415,7 +426,8 @@ def test_queue_attributes():
|
|||
queue_name = 'test-queue'
|
||||
visibility_timeout = 60
|
||||
|
||||
queue = conn.create_queue(queue_name, visibility_timeout=visibility_timeout)
|
||||
queue = conn.create_queue(
|
||||
queue_name, visibility_timeout=visibility_timeout)
|
||||
|
||||
attributes = queue.get_attributes()
|
||||
|
||||
|
|
@ -462,7 +474,8 @@ def test_change_message_visibility_on_invalid_receipt():
|
|||
|
||||
assert len(messages) == 1
|
||||
|
||||
original_message.change_visibility.when.called_with(100).should.throw(SQSError)
|
||||
original_message.change_visibility.when.called_with(
|
||||
100).should.throw(SQSError)
|
||||
|
||||
|
||||
@mock_sqs_deprecated
|
||||
|
|
@ -485,7 +498,8 @@ def test_change_message_visibility_on_visible_message():
|
|||
|
||||
queue.count().should.equal(1)
|
||||
|
||||
original_message.change_visibility.when.called_with(100).should.throw(SQSError)
|
||||
original_message.change_visibility.when.called_with(
|
||||
100).should.throw(SQSError)
|
||||
|
||||
|
||||
@mock_sqs_deprecated
|
||||
|
|
@ -505,7 +519,8 @@ def test_purge_action():
|
|||
def test_delete_message_after_visibility_timeout():
|
||||
VISIBILITY_TIMEOUT = 1
|
||||
conn = boto.sqs.connect_to_region("us-east-1")
|
||||
new_queue = conn.create_queue('new-queue', visibility_timeout=VISIBILITY_TIMEOUT)
|
||||
new_queue = conn.create_queue(
|
||||
'new-queue', visibility_timeout=VISIBILITY_TIMEOUT)
|
||||
|
||||
m1 = Message()
|
||||
m1.set_body('Message 1!')
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ def test_get_session_token():
|
|||
token = conn.get_session_token(duration=123)
|
||||
|
||||
token.expiration.should.equal('2012-01-01T12:02:03.000Z')
|
||||
token.session_token.should.equal("AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE")
|
||||
token.session_token.should.equal(
|
||||
"AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE")
|
||||
token.access_key.should.equal("AKIAIOSFODNN7EXAMPLE")
|
||||
token.secret_key.should.equal("wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY")
|
||||
|
||||
|
|
@ -28,10 +29,13 @@ def test_get_federation_token():
|
|||
token = conn.get_federation_token(duration=123, name="Bob")
|
||||
|
||||
token.credentials.expiration.should.equal('2012-01-01T12:02:03.000Z')
|
||||
token.credentials.session_token.should.equal("AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==")
|
||||
token.credentials.session_token.should.equal(
|
||||
"AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==")
|
||||
token.credentials.access_key.should.equal("AKIAIOSFODNN7EXAMPLE")
|
||||
token.credentials.secret_key.should.equal("wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY")
|
||||
token.federated_user_arn.should.equal("arn:aws:sts::123456789012:federated-user/Bob")
|
||||
token.credentials.secret_key.should.equal(
|
||||
"wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY")
|
||||
token.federated_user_arn.should.equal(
|
||||
"arn:aws:sts::123456789012:federated-user/Bob")
|
||||
token.federated_user_id.should.equal("123456789012:Bob")
|
||||
|
||||
|
||||
|
|
@ -55,20 +59,25 @@ def test_assume_role():
|
|||
]
|
||||
})
|
||||
s3_role = "arn:aws:iam::123456789012:role/test-role"
|
||||
role = conn.assume_role(s3_role, "session-name", policy, duration_seconds=123)
|
||||
role = conn.assume_role(s3_role, "session-name",
|
||||
policy, duration_seconds=123)
|
||||
|
||||
credentials = role.credentials
|
||||
credentials.expiration.should.equal('2012-01-01T12:02:03.000Z')
|
||||
credentials.session_token.should.equal("BQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE")
|
||||
credentials.session_token.should.equal(
|
||||
"BQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE")
|
||||
credentials.access_key.should.equal("AKIAIOSFODNN7EXAMPLE")
|
||||
credentials.secret_key.should.equal("aJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY")
|
||||
credentials.secret_key.should.equal(
|
||||
"aJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY")
|
||||
|
||||
role.user.arn.should.equal("arn:aws:iam::123456789012:role/test-role")
|
||||
role.user.assume_role_id.should.contain("session-name")
|
||||
|
||||
|
||||
@mock_sts
|
||||
def test_get_caller_identity():
|
||||
identity = boto3.client("sts", region_name='us-east-1').get_caller_identity()
|
||||
identity = boto3.client(
|
||||
"sts", region_name='us-east-1').get_caller_identity()
|
||||
|
||||
identity['Arn'].should.equal('arn:aws:sts::123456789012:user/moto')
|
||||
identity['UserId'].should.equal('AKIAIOSFODNN7EXAMPLE')
|
||||
|
|
|
|||
|
|
@ -147,6 +147,7 @@ def test_activity_task_cannot_change_state_on_closed_workflow_execution():
|
|||
)
|
||||
wfe.complete(123)
|
||||
|
||||
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw(SWFWorkflowExecutionClosedError)
|
||||
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw(
|
||||
SWFWorkflowExecutionClosedError)
|
||||
task.complete.when.called_with().should.throw(SWFWorkflowExecutionClosedError)
|
||||
task.fail.when.called_with().should.throw(SWFWorkflowExecutionClosedError)
|
||||
|
|
|
|||
|
|
@ -75,5 +75,6 @@ def test_decision_task_cannot_change_state_on_closed_workflow_execution():
|
|||
|
||||
wfe.complete(123)
|
||||
|
||||
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw(SWFWorkflowExecutionClosedError)
|
||||
task.timeout.when.called_with(Timeout(task, 0, "foo")).should.throw(
|
||||
SWFWorkflowExecutionClosedError)
|
||||
task.complete.when.called_with().should.throw(SWFWorkflowExecutionClosedError)
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ WorkflowExecution = namedtuple(
|
|||
|
||||
def test_domain_short_dict_representation():
|
||||
domain = Domain("foo", "52")
|
||||
domain.to_short_dict().should.equal({"name": "foo", "status": "REGISTERED"})
|
||||
domain.to_short_dict().should.equal(
|
||||
{"name": "foo", "status": "REGISTERED"})
|
||||
|
||||
domain.description = "foo bar"
|
||||
domain.to_short_dict()["description"].should.equal("foo bar")
|
||||
|
|
@ -67,16 +68,23 @@ def test_domain_decision_tasks():
|
|||
def test_domain_get_workflow_execution():
|
||||
domain = Domain("my-domain", "60")
|
||||
|
||||
wfe1 = WorkflowExecution(workflow_id="wf-id-1", run_id="run-id-1", execution_status="OPEN", open=True)
|
||||
wfe2 = WorkflowExecution(workflow_id="wf-id-1", run_id="run-id-2", execution_status="CLOSED", open=False)
|
||||
wfe3 = WorkflowExecution(workflow_id="wf-id-2", run_id="run-id-3", execution_status="OPEN", open=True)
|
||||
wfe4 = WorkflowExecution(workflow_id="wf-id-3", run_id="run-id-4", execution_status="CLOSED", open=False)
|
||||
wfe1 = WorkflowExecution(
|
||||
workflow_id="wf-id-1", run_id="run-id-1", execution_status="OPEN", open=True)
|
||||
wfe2 = WorkflowExecution(
|
||||
workflow_id="wf-id-1", run_id="run-id-2", execution_status="CLOSED", open=False)
|
||||
wfe3 = WorkflowExecution(
|
||||
workflow_id="wf-id-2", run_id="run-id-3", execution_status="OPEN", open=True)
|
||||
wfe4 = WorkflowExecution(
|
||||
workflow_id="wf-id-3", run_id="run-id-4", execution_status="CLOSED", open=False)
|
||||
domain.workflow_executions = [wfe1, wfe2, wfe3, wfe4]
|
||||
|
||||
# get workflow execution through workflow_id and run_id
|
||||
domain.get_workflow_execution("wf-id-1", run_id="run-id-1").should.equal(wfe1)
|
||||
domain.get_workflow_execution("wf-id-1", run_id="run-id-2").should.equal(wfe2)
|
||||
domain.get_workflow_execution("wf-id-3", run_id="run-id-4").should.equal(wfe4)
|
||||
domain.get_workflow_execution(
|
||||
"wf-id-1", run_id="run-id-1").should.equal(wfe1)
|
||||
domain.get_workflow_execution(
|
||||
"wf-id-1", run_id="run-id-2").should.equal(wfe2)
|
||||
domain.get_workflow_execution(
|
||||
"wf-id-3", run_id="run-id-4").should.equal(wfe4)
|
||||
|
||||
domain.get_workflow_execution.when.called_with(
|
||||
"wf-id-1", run_id="non-existent"
|
||||
|
|
@ -98,7 +106,8 @@ def test_domain_get_workflow_execution():
|
|||
)
|
||||
|
||||
# raise_if_closed attribute
|
||||
domain.get_workflow_execution("wf-id-1", run_id="run-id-1", raise_if_closed=True).should.equal(wfe1)
|
||||
domain.get_workflow_execution(
|
||||
"wf-id-1", run_id="run-id-1", raise_if_closed=True).should.equal(wfe1)
|
||||
domain.get_workflow_execution.when.called_with(
|
||||
"wf-id-3", run_id="run-id-4", raise_if_closed=True
|
||||
).should.throw(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from moto.swf.models import GenericType
|
|||
|
||||
# Tests for GenericType (ActivityType, WorkflowType)
|
||||
class FooType(GenericType):
|
||||
|
||||
@property
|
||||
def kind(self):
|
||||
return "foo"
|
||||
|
|
@ -38,10 +39,12 @@ def test_type_full_dict_representation():
|
|||
_type.to_full_dict()["configuration"].should.equal({})
|
||||
|
||||
_type.task_list = "foo"
|
||||
_type.to_full_dict()["configuration"]["defaultTaskList"].should.equal({"name": "foo"})
|
||||
_type.to_full_dict()["configuration"][
|
||||
"defaultTaskList"].should.equal({"name": "foo"})
|
||||
|
||||
_type.just_an_example_timeout = "60"
|
||||
_type.to_full_dict()["configuration"]["justAnExampleTimeout"].should.equal("60")
|
||||
_type.to_full_dict()["configuration"][
|
||||
"justAnExampleTimeout"].should.equal("60")
|
||||
|
||||
_type.non_whitelisted_property = "34"
|
||||
keys = _type.to_full_dict()["configuration"].keys()
|
||||
|
|
@ -50,4 +53,5 @@ def test_type_full_dict_representation():
|
|||
|
||||
def test_type_string_representation():
|
||||
_type = FooType("test-foo", "v1.0")
|
||||
str(_type).should.equal("FooType(name: test-foo, version: v1.0, status: REGISTERED)")
|
||||
str(_type).should.equal(
|
||||
"FooType(name: test-foo, version: v1.0, status: REGISTERED)")
|
||||
|
|
|
|||
|
|
@ -240,8 +240,10 @@ def test_workflow_execution_schedule_activity_task():
|
|||
wfe.open_counts["openActivityTasks"].should.equal(1)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ActivityTaskScheduled")
|
||||
last_event.event_attributes["decisionTaskCompletedEventId"].should.equal(123)
|
||||
last_event.event_attributes["taskList"]["name"].should.equal("task-list-name")
|
||||
last_event.event_attributes[
|
||||
"decisionTaskCompletedEventId"].should.equal(123)
|
||||
last_event.event_attributes["taskList"][
|
||||
"name"].should.equal("task-list-name")
|
||||
|
||||
wfe.activity_tasks.should.have.length_of(1)
|
||||
task = wfe.activity_tasks[0]
|
||||
|
|
@ -288,43 +290,50 @@ def test_workflow_execution_schedule_activity_task_should_fail_if_wrong_attribut
|
|||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DOES_NOT_EXIST")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"ACTIVITY_TYPE_DOES_NOT_EXIST")
|
||||
|
||||
hsh["activityType"]["name"] = "test-activity"
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("ACTIVITY_TYPE_DEPRECATED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"ACTIVITY_TYPE_DEPRECATED")
|
||||
|
||||
hsh["activityType"]["version"] = "v1.2"
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("DEFAULT_TASK_LIST_UNDEFINED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"DEFAULT_TASK_LIST_UNDEFINED")
|
||||
|
||||
hsh["taskList"] = {"name": "foobar"}
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED")
|
||||
|
||||
hsh["scheduleToStartTimeout"] = "600"
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"DEFAULT_SCHEDULE_TO_CLOSE_TIMEOUT_UNDEFINED")
|
||||
|
||||
hsh["scheduleToCloseTimeout"] = "600"
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED")
|
||||
|
||||
hsh["startToCloseTimeout"] = "600"
|
||||
wfe.schedule_activity_task(123, hsh)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"DEFAULT_HEARTBEAT_TIMEOUT_UNDEFINED")
|
||||
|
||||
wfe.open_counts["openActivityTasks"].should.equal(0)
|
||||
wfe.activity_tasks.should.have.length_of(0)
|
||||
|
|
@ -393,7 +402,8 @@ def test_workflow_execution_schedule_activity_task_with_same_activity_id():
|
|||
wfe.open_counts["openActivityTasks"].should.equal(1)
|
||||
last_event = wfe.events()[-1]
|
||||
last_event.event_type.should.equal("ScheduleActivityTaskFailed")
|
||||
last_event.event_attributes["cause"].should.equal("ACTIVITY_ID_ALREADY_IN_USE")
|
||||
last_event.event_attributes["cause"].should.equal(
|
||||
"ACTIVITY_ID_ALREADY_IN_USE")
|
||||
|
||||
|
||||
def test_workflow_execution_start_activity_task():
|
||||
|
|
@ -456,7 +466,8 @@ def test_first_timeout():
|
|||
wfe.first_timeout().should.be.a(Timeout)
|
||||
|
||||
|
||||
# See moto/swf/models/workflow_execution.py "_process_timeouts()" for more details
|
||||
# See moto/swf/models/workflow_execution.py "_process_timeouts()" for more
|
||||
# details
|
||||
def test_timeouts_are_processed_in_order_and_reevaluated():
|
||||
# Let's make a Workflow Execution with the following properties:
|
||||
# - execution start to close timeout of 8 mins
|
||||
|
|
|
|||
|
|
@ -11,15 +11,18 @@ from ..utils import setup_workflow, SCHEDULE_ACTIVITY_TASK_DECISION
|
|||
@mock_swf_deprecated
|
||||
def test_poll_for_activity_task_when_one():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
resp = conn.poll_for_activity_task("test-domain", "activity-task-list", identity="surprise")
|
||||
resp = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list", identity="surprise")
|
||||
resp["activityId"].should.equal("my-activity-001")
|
||||
resp["taskToken"].should_not.be.none
|
||||
|
||||
resp = conn.get_workflow_execution_history("test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp = conn.get_workflow_execution_history(
|
||||
"test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp["events"][-1]["eventType"].should.equal("ActivityTaskStarted")
|
||||
resp["events"][-1]["activityTaskStartedEventAttributes"].should.equal(
|
||||
{"identity": "surprise", "scheduledEventId": 5}
|
||||
|
|
@ -44,12 +47,14 @@ def test_poll_for_activity_task_on_non_existent_queue():
|
|||
@mock_swf_deprecated
|
||||
def test_count_pending_activity_tasks():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
|
||||
resp = conn.count_pending_activity_tasks("test-domain", "activity-task-list")
|
||||
resp = conn.count_pending_activity_tasks(
|
||||
"test-domain", "activity-task-list")
|
||||
resp.should.equal({"count": 1, "truncated": False})
|
||||
|
||||
|
||||
|
|
@ -64,16 +69,20 @@ def test_count_pending_decision_tasks_on_non_existent_task_list():
|
|||
@mock_swf_deprecated
|
||||
def test_respond_activity_task_completed():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
resp = conn.respond_activity_task_completed(activity_token, result="result of the task")
|
||||
resp = conn.respond_activity_task_completed(
|
||||
activity_token, result="result of the task")
|
||||
resp.should.be.none
|
||||
|
||||
resp = conn.get_workflow_execution_history("test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp = conn.get_workflow_execution_history(
|
||||
"test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp["events"][-2]["eventType"].should.equal("ActivityTaskCompleted")
|
||||
resp["events"][-2]["activityTaskCompletedEventAttributes"].should.equal(
|
||||
{"result": "result of the task", "scheduledEventId": 5, "startedEventId": 6}
|
||||
|
|
@ -83,13 +92,16 @@ def test_respond_activity_task_completed():
|
|||
@mock_swf_deprecated
|
||||
def test_respond_activity_task_completed_on_closed_workflow_execution():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
# bad: we're closing workflow execution manually, but endpoints are not coded for now..
|
||||
# bad: we're closing workflow execution manually, but endpoints are not
|
||||
# coded for now..
|
||||
wfe = swf_backend.domains[0].workflow_executions[-1]
|
||||
wfe.execution_status = "CLOSED"
|
||||
# /bad
|
||||
|
|
@ -102,11 +114,13 @@ def test_respond_activity_task_completed_on_closed_workflow_execution():
|
|||
@mock_swf_deprecated
|
||||
def test_respond_activity_task_completed_with_task_already_completed():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
conn.respond_activity_task_completed(activity_token)
|
||||
|
||||
|
|
@ -119,18 +133,21 @@ def test_respond_activity_task_completed_with_task_already_completed():
|
|||
@mock_swf_deprecated
|
||||
def test_respond_activity_task_failed():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
resp = conn.respond_activity_task_failed(activity_token,
|
||||
reason="short reason",
|
||||
details="long details")
|
||||
resp.should.be.none
|
||||
|
||||
resp = conn.get_workflow_execution_history("test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp = conn.get_workflow_execution_history(
|
||||
"test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp["events"][-2]["eventType"].should.equal("ActivityTaskFailed")
|
||||
resp["events"][-2]["activityTaskFailedEventAttributes"].should.equal(
|
||||
{"reason": "short reason", "details": "long details",
|
||||
|
|
@ -144,7 +161,8 @@ def test_respond_activity_task_completed_with_wrong_token():
|
|||
# because the safeguards are shared with RespondActivityTaskCompleted, so
|
||||
# no need to retest everything end-to-end.
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
|
|
@ -158,11 +176,13 @@ def test_respond_activity_task_completed_with_wrong_token():
|
|||
@mock_swf_deprecated
|
||||
def test_record_activity_task_heartbeat():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
resp = conn.record_activity_task_heartbeat(activity_token)
|
||||
resp.should.equal({"cancelRequested": False})
|
||||
|
|
@ -171,11 +191,13 @@ def test_record_activity_task_heartbeat():
|
|||
@mock_swf_deprecated
|
||||
def test_record_activity_task_heartbeat_with_wrong_token():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
|
||||
conn.record_activity_task_heartbeat.when.called_with(
|
||||
"bad-token", details="some progress details"
|
||||
|
|
@ -185,17 +207,21 @@ def test_record_activity_task_heartbeat_with_wrong_token():
|
|||
@mock_swf_deprecated
|
||||
def test_record_activity_task_heartbeat_sets_details_in_case_of_timeout():
|
||||
conn = setup_workflow()
|
||||
decision_token = conn.poll_for_decision_task("test-domain", "queue")["taskToken"]
|
||||
decision_token = conn.poll_for_decision_task(
|
||||
"test-domain", "queue")["taskToken"]
|
||||
conn.respond_decision_task_completed(decision_token, decisions=[
|
||||
SCHEDULE_ACTIVITY_TASK_DECISION
|
||||
])
|
||||
with freeze_time("2015-01-01 12:00:00"):
|
||||
activity_token = conn.poll_for_activity_task("test-domain", "activity-task-list")["taskToken"]
|
||||
conn.record_activity_task_heartbeat(activity_token, details="some progress details")
|
||||
activity_token = conn.poll_for_activity_task(
|
||||
"test-domain", "activity-task-list")["taskToken"]
|
||||
conn.record_activity_task_heartbeat(
|
||||
activity_token, details="some progress details")
|
||||
|
||||
with freeze_time("2015-01-01 12:05:30"):
|
||||
# => Activity Task Heartbeat timeout reached!!
|
||||
resp = conn.get_workflow_execution_history("test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp = conn.get_workflow_execution_history(
|
||||
"test-domain", conn.run_id, "uid-abcd1234")
|
||||
resp["events"][-2]["eventType"].should.equal("ActivityTaskTimedOut")
|
||||
attrs = resp["events"][-2]["activityTaskTimedOutEventAttributes"]
|
||||
attrs["details"].should.equal("some progress details")
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue