Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Stephan Huber 2019-12-23 08:38:53 +01:00
commit 0527e88d46
541 changed files with 75504 additions and 51429 deletions

View file

@ -9,7 +9,8 @@ def rsa_check_private_key(private_key_material):
assert isinstance(private_key_material, six.string_types)
private_key = serialization.load_pem_private_key(
data=private_key_material.encode('ascii'),
data=private_key_material.encode("ascii"),
backend=default_backend(),
password=None)
password=None,
)
assert isinstance(private_key, rsa.RSAPrivateKey)

View file

@ -6,39 +6,32 @@ import sure # noqa
@mock_ec2
def test_describe_account_attributes():
conn = boto3.client('ec2', region_name='us-east-1')
conn = boto3.client("ec2", region_name="us-east-1")
response = conn.describe_account_attributes()
expected_attribute_values = [{
'AttributeValues': [{
'AttributeValue': '5'
}],
'AttributeName': 'vpc-max-security-groups-per-interface'
}, {
'AttributeValues': [{
'AttributeValue': '20'
}],
'AttributeName': 'max-instances'
}, {
'AttributeValues': [{
'AttributeValue': 'EC2'
}, {
'AttributeValue': 'VPC'
}],
'AttributeName': 'supported-platforms'
}, {
'AttributeValues': [{
'AttributeValue': 'none'
}],
'AttributeName': 'default-vpc'
}, {
'AttributeValues': [{
'AttributeValue': '5'
}],
'AttributeName': 'max-elastic-ips'
}, {
'AttributeValues': [{
'AttributeValue': '5'
}],
'AttributeName': 'vpc-max-elastic-ips'
}]
response['AccountAttributes'].should.equal(expected_attribute_values)
expected_attribute_values = [
{
"AttributeValues": [{"AttributeValue": "5"}],
"AttributeName": "vpc-max-security-groups-per-interface",
},
{
"AttributeValues": [{"AttributeValue": "20"}],
"AttributeName": "max-instances",
},
{
"AttributeValues": [{"AttributeValue": "EC2"}, {"AttributeValue": "VPC"}],
"AttributeName": "supported-platforms",
},
{
"AttributeValues": [{"AttributeValue": "none"}],
"AttributeName": "default-vpc",
},
{
"AttributeValues": [{"AttributeValue": "5"}],
"AttributeName": "max-elastic-ips",
},
{
"AttributeValues": [{"AttributeValue": "5"}],
"AttributeName": "vpc-max-elastic-ips",
},
]
response["AccountAttributes"].should.equal(expected_attribute_values)

File diff suppressed because it is too large Load diff

View file

@ -1,54 +1,54 @@
from __future__ import unicode_literals
import boto
import boto.ec2
import boto3
import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
@mock_ec2_deprecated
def test_describe_regions():
conn = boto.connect_ec2('the_key', 'the_secret')
regions = conn.get_all_regions()
regions.should.have.length_of(16)
for region in regions:
region.endpoint.should.contain(region.name)
@mock_ec2_deprecated
def test_availability_zones():
conn = boto.connect_ec2('the_key', 'the_secret')
regions = conn.get_all_regions()
for region in regions:
conn = boto.ec2.connect_to_region(region.name)
if conn is None:
continue
for zone in conn.get_all_zones():
zone.name.should.contain(region.name)
@mock_ec2
def test_boto3_describe_regions():
ec2 = boto3.client('ec2', 'us-east-1')
resp = ec2.describe_regions()
resp['Regions'].should.have.length_of(16)
for rec in resp['Regions']:
rec['Endpoint'].should.contain(rec['RegionName'])
test_region = 'us-east-1'
resp = ec2.describe_regions(RegionNames=[test_region])
resp['Regions'].should.have.length_of(1)
resp['Regions'][0].should.have.key('RegionName').which.should.equal(test_region)
@mock_ec2
def test_boto3_availability_zones():
ec2 = boto3.client('ec2', 'us-east-1')
resp = ec2.describe_regions()
regions = [r['RegionName'] for r in resp['Regions']]
for region in regions:
conn = boto3.client('ec2', region)
resp = conn.describe_availability_zones()
for rec in resp['AvailabilityZones']:
rec['ZoneName'].should.contain(region)
from __future__ import unicode_literals
import boto
import boto.ec2
import boto3
import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
@mock_ec2_deprecated
def test_describe_regions():
conn = boto.connect_ec2("the_key", "the_secret")
regions = conn.get_all_regions()
regions.should.have.length_of(16)
for region in regions:
region.endpoint.should.contain(region.name)
@mock_ec2_deprecated
def test_availability_zones():
conn = boto.connect_ec2("the_key", "the_secret")
regions = conn.get_all_regions()
for region in regions:
conn = boto.ec2.connect_to_region(region.name)
if conn is None:
continue
for zone in conn.get_all_zones():
zone.name.should.contain(region.name)
@mock_ec2
def test_boto3_describe_regions():
ec2 = boto3.client("ec2", "us-east-1")
resp = ec2.describe_regions()
resp["Regions"].should.have.length_of(16)
for rec in resp["Regions"]:
rec["Endpoint"].should.contain(rec["RegionName"])
test_region = "us-east-1"
resp = ec2.describe_regions(RegionNames=[test_region])
resp["Regions"].should.have.length_of(1)
resp["Regions"][0].should.have.key("RegionName").which.should.equal(test_region)
@mock_ec2
def test_boto3_availability_zones():
ec2 = boto3.client("ec2", "us-east-1")
resp = ec2.describe_regions()
regions = [r["RegionName"] for r in resp["Regions"]]
for region in regions:
conn = boto3.client("ec2", region)
resp = conn.describe_availability_zones()
for rec in resp["AvailabilityZones"]:
rec["ZoneName"].should.contain(region)

View file

@ -1,52 +1,49 @@
from __future__ import unicode_literals
import boto
import sure # noqa
from nose.tools import assert_raises
from nose.tools import assert_false
from boto.exception import EC2ResponseError
from moto import mock_ec2_deprecated
@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.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)
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.should_not.be.none
cgws = conn.get_all_customer_gateways()
cgws[0].id.should.match(customer_gateway.id)
deleted = conn.delete_customer_gateway(customer_gateway.id)
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')
with assert_raises(EC2ResponseError) as cm:
conn.delete_customer_gateway('cgw-0123abcd')
from __future__ import unicode_literals
import boto
import sure # noqa
from nose.tools import assert_raises
from nose.tools import assert_false
from boto.exception import EC2ResponseError
from moto import mock_ec2_deprecated
@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.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)
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.should_not.be.none
cgws = conn.get_all_customer_gateways()
cgws[0].id.should.match(customer_gateway.id)
deleted = conn.delete_customer_gateway(customer_gateway.id)
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")
with assert_raises(EC2ResponseError) as cm:
conn.delete_customer_gateway("cgw-0123abcd")

View file

@ -1,333 +1,337 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto3
import boto
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
SAMPLE_DOMAIN_NAME = u'example.com'
SAMPLE_NAME_SERVERS = [u'10.0.0.6', u'10.0.0.7']
@mock_ec2_deprecated
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)
vpc = conn.create_vpc("10.0.0.0/16")
rval = conn.associate_dhcp_options(dhcp_options.id, vpc.id)
rval.should.be.equal(True)
@mock_ec2_deprecated
def test_dhcp_options_associate_invalid_dhcp_id():
""" associate dhcp option bad dhcp options id """
conn = boto.connect_vpc('the_key', 'the_secret')
vpc = conn.create_vpc("10.0.0.0/16")
with assert_raises(EC2ResponseError) as cm:
conn.associate_dhcp_options("foo", vpc.id)
cm.exception.code.should.equal('InvalidDhcpOptionID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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)
with assert_raises(EC2ResponseError) as cm:
conn.associate_dhcp_options(dhcp_options.id, "foo")
cm.exception.code.should.equal('InvalidVpcID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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_id = dhcp_options.id
vpc = conn.create_vpc("10.0.0.0/16")
rval = conn.associate_dhcp_options(dhcp_options_id, vpc.id)
rval.should.be.equal(True)
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options(dhcp_options_id)
cm.exception.code.should.equal('DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
vpc.delete()
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options([dhcp_options_id])
cm.exception.code.should.equal('InvalidDhcpOptionID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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.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])
@mock_ec2_deprecated
def test_create_dhcp_options_invalid_options():
"""Create invalid dhcp options"""
conn = boto.connect_vpc('the_key', 'the_secret')
servers = ["f", "f", "f", "f", "f"]
with assert_raises(EC2ResponseError) as cm:
conn.create_dhcp_options(ntp_servers=servers)
cm.exception.code.should.equal('InvalidParameterValue')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
with assert_raises(EC2ResponseError) as cm:
conn.create_dhcp_options(netbios_node_type="0")
cm.exception.code.should.equal('InvalidParameterValue')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_describe_dhcp_options():
"""Test dhcp options lookup by id"""
conn = boto.connect_vpc('the_key', 'the_secret')
dhcp_option = conn.create_dhcp_options()
dhcp_options = conn.get_all_dhcp_options([dhcp_option.id])
dhcp_options.should.be.length_of(1)
dhcp_options = conn.get_all_dhcp_options()
dhcp_options.should.be.length_of(1)
@mock_ec2_deprecated
def test_describe_dhcp_options_invalid_id():
"""get error on invalid dhcp_option_id lookup"""
conn = boto.connect_vpc('the_key', 'the_secret')
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options(["1"])
cm.exception.code.should.equal('InvalidDhcpOptionID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options():
"""delete dhcp option"""
conn = boto.connect_vpc('the_key', 'the_secret')
dhcp_option = conn.create_dhcp_options()
dhcp_options = conn.get_all_dhcp_options([dhcp_option.id])
dhcp_options.should.be.length_of(1)
conn.delete_dhcp_options(dhcp_option.id) # .should.be.equal(True)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options([dhcp_option.id])
cm.exception.code.should.equal('InvalidDhcpOptionID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options_invalid_id():
conn = boto.connect_vpc('the_key', 'the_secret')
conn.create_dhcp_options()
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options("dopt-abcd1234")
cm.exception.code.should.equal('InvalidDhcpOptionID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options_malformed_id():
conn = boto.connect_vpc('the_key', 'the_secret')
conn.create_dhcp_options()
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options("foo-abcd1234")
cm.exception.code.should.equal('InvalidDhcpOptionsId.Malformed')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_dhcp_tagging():
conn = boto.connect_vpc('the_key', 'the_secret')
dhcp_option = conn.create_dhcp_options()
dhcp_option.add_tag("a key", "some value")
tag = conn.get_all_tags()[0]
tag.name.should.equal("a key")
tag.value.should.equal("some value")
# Refresh the DHCP options
dhcp_option = conn.get_all_dhcp_options()[0]
dhcp_option.tags.should.have.length_of(1)
dhcp_option.tags["a key"].should.equal("some value")
@mock_ec2_deprecated
def test_dhcp_options_get_by_tag():
conn = boto.connect_vpc('the_key', 'the_secret')
dhcp1 = conn.create_dhcp_options('example.com', ['10.0.10.2'])
dhcp1.add_tag('Name', 'TestDhcpOptions1')
dhcp1.add_tag('test-tag', 'test-value')
dhcp2 = conn.create_dhcp_options('example.com', ['10.0.20.2'])
dhcp2.add_tag('Name', 'TestDhcpOptions2')
dhcp2.add_tag('test-tag', 'test-value')
filters = {'tag:Name': 'TestDhcpOptions1', 'tag:test-tag': 'test-value'}
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].tags['Name'].should.equal('TestDhcpOptions1')
dhcp_options_sets[0].tags['test-tag'].should.equal('test-value')
filters = {'tag:Name': 'TestDhcpOptions2', 'tag:test-tag': 'test-value'}
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].tags['Name'].should.equal('TestDhcpOptions2')
dhcp_options_sets[0].tags['test-tag'].should.equal('test-value')
filters = {'tag:test-tag': 'test-value'}
dhcp_options_sets = conn.get_all_dhcp_options(filters=filters)
dhcp_options_sets.should.have.length_of(2)
@mock_ec2_deprecated
def test_dhcp_options_get_by_id():
conn = boto.connect_vpc('the_key', 'the_secret')
dhcp1 = conn.create_dhcp_options('test1.com', ['10.0.10.2'])
dhcp1.add_tag('Name', 'TestDhcpOptions1')
dhcp1.add_tag('test-tag', 'test-value')
dhcp1_id = dhcp1.id
dhcp2 = conn.create_dhcp_options('test2.com', ['10.0.20.2'])
dhcp2.add_tag('Name', 'TestDhcpOptions2')
dhcp2.add_tag('test-tag', 'test-value')
dhcp2_id = dhcp2.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.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 = 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')
@mock_ec2
def test_dhcp_options_get_by_value_filter():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.10.2']}
])
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.20.2']}
])
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.30.2']}
])
filters = [{'Name': 'value', 'Values': ['10.0.10.2']}]
dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
dhcp_options_sets.should.have.length_of(1)
@mock_ec2
def test_dhcp_options_get_by_key_filter():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.10.2']}
])
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.20.2']}
])
ec2.create_dhcp_options(DhcpConfigurations=[
{'Key': 'domain-name', 'Values': ['example.com']},
{'Key': 'domain-name-servers', 'Values': ['10.0.30.2']}
])
filters = [{'Name': 'key', 'Values': ['domain-name']}]
dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
dhcp_options_sets.should.have.length_of(3)
@mock_ec2_deprecated
def test_dhcp_options_get_by_invalid_filter():
conn = boto.connect_vpc('the_key', 'the_secret')
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)
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto3
import boto
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
SAMPLE_DOMAIN_NAME = "example.com"
SAMPLE_NAME_SERVERS = ["10.0.0.6", "10.0.0.7"]
@mock_ec2_deprecated
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)
vpc = conn.create_vpc("10.0.0.0/16")
rval = conn.associate_dhcp_options(dhcp_options.id, vpc.id)
rval.should.be.equal(True)
@mock_ec2_deprecated
def test_dhcp_options_associate_invalid_dhcp_id():
""" associate dhcp option bad dhcp options id """
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
with assert_raises(EC2ResponseError) as cm:
conn.associate_dhcp_options("foo", vpc.id)
cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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)
with assert_raises(EC2ResponseError) as cm:
conn.associate_dhcp_options(dhcp_options.id, "foo")
cm.exception.code.should.equal("InvalidVpcID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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_id = dhcp_options.id
vpc = conn.create_vpc("10.0.0.0/16")
rval = conn.associate_dhcp_options(dhcp_options_id, vpc.id)
rval.should.be.equal(True)
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options(dhcp_options_id)
cm.exception.code.should.equal("DependencyViolation")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
vpc.delete()
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options([dhcp_options_id])
cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
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.options["domain-name"][0].should.be.equal(SAMPLE_DOMAIN_NAME)
dhcp_option.options["domain-name-servers"][0].should.be.equal(
SAMPLE_NAME_SERVERS[0]
)
dhcp_option.options["domain-name-servers"][1].should.be.equal(
SAMPLE_NAME_SERVERS[1]
)
@mock_ec2_deprecated
def test_create_dhcp_options_invalid_options():
"""Create invalid dhcp options"""
conn = boto.connect_vpc("the_key", "the_secret")
servers = ["f", "f", "f", "f", "f"]
with assert_raises(EC2ResponseError) as cm:
conn.create_dhcp_options(ntp_servers=servers)
cm.exception.code.should.equal("InvalidParameterValue")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
with assert_raises(EC2ResponseError) as cm:
conn.create_dhcp_options(netbios_node_type="0")
cm.exception.code.should.equal("InvalidParameterValue")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_describe_dhcp_options():
"""Test dhcp options lookup by id"""
conn = boto.connect_vpc("the_key", "the_secret")
dhcp_option = conn.create_dhcp_options()
dhcp_options = conn.get_all_dhcp_options([dhcp_option.id])
dhcp_options.should.be.length_of(1)
dhcp_options = conn.get_all_dhcp_options()
dhcp_options.should.be.length_of(1)
@mock_ec2_deprecated
def test_describe_dhcp_options_invalid_id():
"""get error on invalid dhcp_option_id lookup"""
conn = boto.connect_vpc("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options(["1"])
cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options():
"""delete dhcp option"""
conn = boto.connect_vpc("the_key", "the_secret")
dhcp_option = conn.create_dhcp_options()
dhcp_options = conn.get_all_dhcp_options([dhcp_option.id])
dhcp_options.should.be.length_of(1)
conn.delete_dhcp_options(dhcp_option.id) # .should.be.equal(True)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_dhcp_options([dhcp_option.id])
cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options_invalid_id():
conn = boto.connect_vpc("the_key", "the_secret")
conn.create_dhcp_options()
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options("dopt-abcd1234")
cm.exception.code.should.equal("InvalidDhcpOptionID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_delete_dhcp_options_malformed_id():
conn = boto.connect_vpc("the_key", "the_secret")
conn.create_dhcp_options()
with assert_raises(EC2ResponseError) as cm:
conn.delete_dhcp_options("foo-abcd1234")
cm.exception.code.should.equal("InvalidDhcpOptionsId.Malformed")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_dhcp_tagging():
conn = boto.connect_vpc("the_key", "the_secret")
dhcp_option = conn.create_dhcp_options()
dhcp_option.add_tag("a key", "some value")
tag = conn.get_all_tags()[0]
tag.name.should.equal("a key")
tag.value.should.equal("some value")
# Refresh the DHCP options
dhcp_option = conn.get_all_dhcp_options()[0]
dhcp_option.tags.should.have.length_of(1)
dhcp_option.tags["a key"].should.equal("some value")
@mock_ec2_deprecated
def test_dhcp_options_get_by_tag():
conn = boto.connect_vpc("the_key", "the_secret")
dhcp1 = conn.create_dhcp_options("example.com", ["10.0.10.2"])
dhcp1.add_tag("Name", "TestDhcpOptions1")
dhcp1.add_tag("test-tag", "test-value")
dhcp2 = conn.create_dhcp_options("example.com", ["10.0.20.2"])
dhcp2.add_tag("Name", "TestDhcpOptions2")
dhcp2.add_tag("test-tag", "test-value")
filters = {"tag:Name": "TestDhcpOptions1", "tag:test-tag": "test-value"}
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].tags["Name"].should.equal("TestDhcpOptions1")
dhcp_options_sets[0].tags["test-tag"].should.equal("test-value")
filters = {"tag:Name": "TestDhcpOptions2", "tag:test-tag": "test-value"}
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].tags["Name"].should.equal("TestDhcpOptions2")
dhcp_options_sets[0].tags["test-tag"].should.equal("test-value")
filters = {"tag:test-tag": "test-value"}
dhcp_options_sets = conn.get_all_dhcp_options(filters=filters)
dhcp_options_sets.should.have.length_of(2)
@mock_ec2_deprecated
def test_dhcp_options_get_by_id():
conn = boto.connect_vpc("the_key", "the_secret")
dhcp1 = conn.create_dhcp_options("test1.com", ["10.0.10.2"])
dhcp1.add_tag("Name", "TestDhcpOptions1")
dhcp1.add_tag("test-tag", "test-value")
dhcp1_id = dhcp1.id
dhcp2 = conn.create_dhcp_options("test2.com", ["10.0.20.2"])
dhcp2.add_tag("Name", "TestDhcpOptions2")
dhcp2.add_tag("test-tag", "test-value")
dhcp2_id = dhcp2.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.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 = 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")
@mock_ec2
def test_dhcp_options_get_by_value_filter():
ec2 = boto3.resource("ec2", region_name="us-west-1")
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.10.2"]},
]
)
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.20.2"]},
]
)
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.30.2"]},
]
)
filters = [{"Name": "value", "Values": ["10.0.10.2"]}]
dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
dhcp_options_sets.should.have.length_of(1)
@mock_ec2
def test_dhcp_options_get_by_key_filter():
ec2 = boto3.resource("ec2", region_name="us-west-1")
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.10.2"]},
]
)
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.20.2"]},
]
)
ec2.create_dhcp_options(
DhcpConfigurations=[
{"Key": "domain-name", "Values": ["example.com"]},
{"Key": "domain-name-servers", "Values": ["10.0.30.2"]},
]
)
filters = [{"Name": "key", "Values": ["domain-name"]}]
dhcp_options_sets = list(ec2.dhcp_options_sets.filter(Filters=filters))
dhcp_options_sets.should.have.length_of(3)
@mock_ec2_deprecated
def test_dhcp_options_get_by_invalid_filter():
conn = boto.connect_vpc("the_key", "the_secret")
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
)

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
@ -32,10 +33,11 @@ def test_create_and_delete_volume():
with assert_raises(EC2ResponseError) as ex:
volume.delete(dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the DeleteVolume operation: Request would have succeeded, but DryRun flag is set"
)
volume.delete()
@ -46,7 +48,7 @@ def test_create_and_delete_volume():
# Deleting something that was already deleted should throw an error
with assert_raises(EC2ResponseError) as cm:
volume.delete()
cm.exception.code.should.equal('InvalidVolume.NotFound')
cm.exception.code.should.equal("InvalidVolume.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -56,10 +58,11 @@ def test_create_encrypted_volume_dryrun():
conn = boto.ec2.connect_to_region("us-east-1")
with assert_raises(EC2ResponseError) as ex:
conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.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')
"An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set"
)
@mock_ec2_deprecated
@ -69,10 +72,11 @@ def test_create_encrypted_volume():
with assert_raises(EC2ResponseError) as ex:
conn.create_volume(80, "us-east-1a", encrypted=True, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.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')
"An error occurred (DryRunOperation) when calling the CreateVolume operation: Request would have succeeded, but DryRun flag is set"
)
all_volumes = [vol for vol in conn.get_all_volumes() if vol.id == volume.id]
all_volumes[0].encrypted.should.be(True)
@ -87,13 +91,13 @@ def test_filter_volume_by_id():
vol1 = conn.get_all_volumes(volume_ids=volume3.id)
vol1.should.have.length_of(1)
vol1[0].size.should.equal(20)
vol1[0].zone.should.equal('us-east-1c')
vol1[0].zone.should.equal("us-east-1c")
vol2 = conn.get_all_volumes(volume_ids=[volume1.id, volume2.id])
vol2.should.have.length_of(2)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_volumes(volume_ids=['vol-does_not_exist'])
cm.exception.code.should.equal('InvalidVolume.NotFound')
conn.get_all_volumes(volume_ids=["vol-does_not_exist"])
cm.exception.code.should.equal("InvalidVolume.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -102,7 +106,7 @@ def test_filter_volume_by_id():
def test_volume_filters():
conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances('ami-1234abcd')
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.update()
@ -111,142 +115,155 @@ def test_volume_filters():
volume2 = conn.create_volume(36, "us-east-1b", encrypted=False)
volume3 = conn.create_volume(20, "us-east-1c", encrypted=True)
snapshot = volume3.create_snapshot(description='testsnap')
snapshot = volume3.create_snapshot(description="testsnap")
volume4 = conn.create_volume(25, "us-east-1a", snapshot=snapshot)
conn.create_tags([volume1.id], {'testkey1': 'testvalue1'})
conn.create_tags([volume2.id], {'testkey2': 'testvalue2'})
conn.create_tags([volume1.id], {"testkey1": "testvalue1"})
conn.create_tags([volume2.id], {"testkey2": "testvalue2"})
volume1.update()
volume2.update()
volume3.update()
volume4.update()
block_mapping = instance.block_device_mapping['/dev/sda1']
block_mapping = instance.block_device_mapping["/dev/sda1"]
volume_ids = (volume1.id, volume2.id, volume3.id, volume4.id, 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({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({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({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({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({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({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({volume4.id})
volumes_by_status = conn.get_all_volumes(filters={'status': 'in-use'})
set([vol.id for vol in volumes_by_status]).should.equal(
{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({volume1.id})
volumes_by_tag_key = conn.get_all_volumes(filters={'tag-key': 'testkey1'})
set([vol.id for vol in volumes_by_tag_key]).should.equal({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({volume1.id})
volumes_by_tag = conn.get_all_volumes(
filters={'tag:testkey1': 'testvalue1'})
set([vol.id for vol in volumes_by_tag]).should.equal({volume1.id})
volumes_by_unencrypted = conn.get_all_volumes(
filters={'encrypted': 'false'})
set([vol.id for vol in volumes_by_unencrypted if vol.id in volume_ids]).should.equal(
{block_mapping.volume_id, volume2.id}
volume_ids = (
volume1.id,
volume2.id,
volume3.id,
volume4.id,
block_mapping.volume_id,
)
volumes_by_encrypted = conn.get_all_volumes(filters={'encrypted': 'true'})
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(
{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(
{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(
{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(
{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(
{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({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({volume4.id})
volumes_by_status = conn.get_all_volumes(filters={"status": "in-use"})
set([vol.id for vol in volumes_by_status]).should.equal({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({volume1.id})
volumes_by_tag_key = conn.get_all_volumes(filters={"tag-key": "testkey1"})
set([vol.id for vol in volumes_by_tag_key]).should.equal({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({volume1.id})
volumes_by_tag = conn.get_all_volumes(filters={"tag:testkey1": "testvalue1"})
set([vol.id for vol in volumes_by_tag]).should.equal({volume1.id})
volumes_by_unencrypted = conn.get_all_volumes(filters={"encrypted": "false"})
set(
[vol.id for vol in volumes_by_unencrypted if vol.id in volume_ids]
).should.equal({block_mapping.volume_id, volume2.id})
volumes_by_encrypted = conn.get_all_volumes(filters={"encrypted": "true"})
set([vol.id for vol in volumes_by_encrypted if vol.id in volume_ids]).should.equal(
{volume1.id, volume3.id, volume4.id}
)
volumes_by_availability_zone = conn.get_all_volumes(filters={'availability-zone': 'us-east-1b'})
set([vol.id for vol in volumes_by_availability_zone if vol.id in volume_ids]).should.equal(
{volume2.id}
volumes_by_availability_zone = conn.get_all_volumes(
filters={"availability-zone": "us-east-1b"}
)
set(
[vol.id for vol in volumes_by_availability_zone if vol.id in volume_ids]
).should.equal({volume2.id})
@mock_ec2_deprecated
def test_volume_attach_and_detach():
conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances('ami-1234abcd')
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
volume = conn.create_volume(80, "us-east-1a")
volume.update()
volume.volume_state().should.equal('available')
volume.volume_state().should.equal("available")
with assert_raises(EC2ResponseError) as ex:
volume.attach(instance.id, "/dev/sdh", dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the AttachVolume operation: Request would have succeeded, but DryRun flag is set"
)
volume.attach(instance.id, "/dev/sdh")
volume.update()
volume.volume_state().should.equal('in-use')
volume.attachment_state().should.equal('attached')
volume.volume_state().should.equal("in-use")
volume.attachment_state().should.equal("attached")
volume.attach_data.instance_id.should.equal(instance.id)
with assert_raises(EC2ResponseError) as ex:
volume.detach(dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the DetachVolume operation: Request would have succeeded, but DryRun flag is set"
)
volume.detach()
volume.update()
volume.volume_state().should.equal('available')
volume.volume_state().should.equal("available")
with assert_raises(EC2ResponseError) as cm1:
volume.attach('i-1234abcd', "/dev/sdh")
cm1.exception.code.should.equal('InvalidInstanceID.NotFound')
volume.attach("i-1234abcd", "/dev/sdh")
cm1.exception.code.should.equal("InvalidInstanceID.NotFound")
cm1.exception.status.should.equal(400)
cm1.exception.request_id.should_not.be.none
with assert_raises(EC2ResponseError) as cm2:
conn.detach_volume(volume.id, instance.id, "/dev/sdh")
cm2.exception.code.should.equal('InvalidAttachment.NotFound')
cm2.exception.code.should.equal("InvalidAttachment.NotFound")
cm2.exception.status.should.equal(400)
cm2.exception.request_id.should_not.be.none
with assert_raises(EC2ResponseError) as cm3:
conn.detach_volume(volume.id, 'i-1234abcd', "/dev/sdh")
cm3.exception.code.should.equal('InvalidInstanceID.NotFound')
conn.detach_volume(volume.id, "i-1234abcd", "/dev/sdh")
cm3.exception.code.should.equal("InvalidInstanceID.NotFound")
cm3.exception.status.should.equal(400)
cm3.exception.request_id.should_not.be.none
@ -257,19 +274,20 @@ def test_create_snapshot():
volume = conn.create_volume(80, "us-east-1a")
with assert_raises(EC2ResponseError) as ex:
snapshot = volume.create_snapshot('a dryrun snapshot', dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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 = volume.create_snapshot("a test snapshot")
snapshot.update()
snapshot.status.should.equal('completed')
snapshot.status.should.equal("completed")
snapshots = [snap for snap in conn.get_all_snapshots() if snap.id == snapshot.id]
snapshots.should.have.length_of(1)
snapshots[0].description.should.equal('a test snapshot')
snapshots[0].description.should.equal("a test snapshot")
snapshots[0].start_time.should_not.be.none
snapshots[0].encrypted.should.be(False)
@ -285,7 +303,7 @@ def test_create_snapshot():
# Deleting something that was already deleted should throw an error
with assert_raises(EC2ResponseError) as cm:
snapshot.delete()
cm.exception.code.should.equal('InvalidSnapshot.NotFound')
cm.exception.code.should.equal("InvalidSnapshot.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -294,13 +312,13 @@ def test_create_snapshot():
def test_create_encrypted_snapshot():
conn = boto.ec2.connect_to_region("us-east-1")
volume = conn.create_volume(80, "us-east-1a", encrypted=True)
snapshot = volume.create_snapshot('a test snapshot')
snapshot = volume.create_snapshot("a test snapshot")
snapshot.update()
snapshot.status.should.equal('completed')
snapshot.status.should.equal("completed")
snapshots = [snap for snap in conn.get_all_snapshots() if snap.id == snapshot.id]
snapshots.should.have.length_of(1)
snapshots[0].description.should.equal('a test snapshot')
snapshots[0].description.should.equal("a test snapshot")
snapshots[0].start_time.should_not.be.none
snapshots[0].encrypted.should.be(True)
@ -309,11 +327,11 @@ def test_create_encrypted_snapshot():
def test_filter_snapshot_by_id():
conn = boto.ec2.connect_to_region("us-east-1")
volume1 = conn.create_volume(36, "us-east-1a")
snap1 = volume1.create_snapshot('a test snapshot 1')
volume2 = conn.create_volume(42, 'us-east-1a')
snap2 = volume2.create_snapshot('a test snapshot 2')
volume3 = conn.create_volume(84, 'us-east-1a')
snap3 = volume3.create_snapshot('a test snapshot 3')
snap1 = volume1.create_snapshot("a test snapshot 1")
volume2 = conn.create_volume(42, "us-east-1a")
snap2 = volume2.create_snapshot("a test snapshot 2")
volume3 = conn.create_volume(84, "us-east-1a")
snap3 = volume3.create_snapshot("a test snapshot 3")
snapshots1 = conn.get_all_snapshots(snapshot_ids=snap2.id)
snapshots1.should.have.length_of(1)
snapshots1[0].volume_id.should.equal(volume2.id)
@ -326,8 +344,8 @@ def test_filter_snapshot_by_id():
s.region.name.should.equal(conn.region.name)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_snapshots(snapshot_ids=['snap-does_not_exist'])
cm.exception.code.should.equal('InvalidSnapshot.NotFound')
conn.get_all_snapshots(snapshot_ids=["snap-does_not_exist"])
cm.exception.code.should.equal("InvalidSnapshot.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -338,67 +356,62 @@ def test_snapshot_filters():
volume1 = conn.create_volume(20, "us-east-1a", encrypted=False)
volume2 = conn.create_volume(25, "us-east-1a", encrypted=True)
snapshot1 = volume1.create_snapshot(description='testsnapshot1')
snapshot2 = volume1.create_snapshot(description='testsnapshot2')
snapshot3 = volume2.create_snapshot(description='testsnapshot3')
snapshot1 = volume1.create_snapshot(description="testsnapshot1")
snapshot2 = volume1.create_snapshot(description="testsnapshot2")
snapshot3 = volume2.create_snapshot(description="testsnapshot3")
conn.create_tags([snapshot1.id], {'testkey1': 'testvalue1'})
conn.create_tags([snapshot2.id], {'testkey2': 'testvalue2'})
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({snapshot1.id})
filters={"description": "testsnapshot1"}
)
set([snap.id for snap in snapshots_by_description]).should.equal({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({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({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({snapshot1.start_time})
filters={"start-time": snapshot1.start_time}
)
set([snap.start_time for snap in snapshots_by_start_time]).should.equal(
{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({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(
{snapshot1.id, snapshot2.id}
)
snapshots_by_status = conn.get_all_snapshots(
filters={'status': 'completed'})
({snapshot1.id, snapshot2.id, snapshot3.id} -
{snap.id for snap in snapshots_by_status}).should.have.length_of(0)
snapshots_by_status = conn.get_all_snapshots(filters={"status": "completed"})
(
{snapshot1.id, snapshot2.id, snapshot3.id}
- {snap.id for snap in snapshots_by_status}
).should.have.length_of(0)
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({snapshot1.id, snapshot2.id})
filters={"volume-size": volume1.size}
)
set([snap.id for snap in snapshots_by_volume_size]).should.equal(
{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({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({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({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({snapshot1.id})
snapshots_by_tag = conn.get_all_snapshots(
filters={'tag:testkey1': 'testvalue1'})
set([snap.id for snap in snapshots_by_tag]
).should.equal({snapshot1.id})
snapshots_by_tag = conn.get_all_snapshots(filters={"tag:testkey1": "testvalue1"})
set([snap.id for snap in snapshots_by_tag]).should.equal({snapshot1.id})
snapshots_by_encrypted = conn.get_all_snapshots(
filters={'encrypted': 'true'})
set([snap.id for snap in snapshots_by_encrypted]
).should.equal({snapshot3.id})
snapshots_by_encrypted = conn.get_all_snapshots(filters={"encrypted": "true"})
set([snap.id for snap in snapshots_by_encrypted]).should.equal({snapshot3.id})
snapshots_by_owner_id = conn.get_all_snapshots(
filters={'owner-id': OWNER_ID})
set([snap.id for snap in snapshots_by_owner_id]
).should.equal({snapshot1.id, snapshot2.id, snapshot3.id})
snapshots_by_owner_id = conn.get_all_snapshots(filters={"owner-id": OWNER_ID})
set([snap.id for snap in snapshots_by_owner_id]).should.equal(
{snapshot1.id, snapshot2.id, snapshot3.id}
)
@mock_ec2_deprecated
@ -411,119 +424,139 @@ def test_snapshot_attribute():
# Baseline
attributes = conn.get_snapshot_attribute(
snapshot.id, attribute='createVolumePermission')
attributes.name.should.equal('create_volume_permission')
snapshot.id, attribute="createVolumePermission"
)
attributes.name.should.equal("create_volume_permission")
attributes.attrs.should.have.length_of(0)
ADD_GROUP_ARGS = {'snapshot_id': snapshot.id,
'attribute': 'createVolumePermission',
'operation': 'add',
'groups': 'all'}
ADD_GROUP_ARGS = {
"snapshot_id": snapshot.id,
"attribute": "createVolumePermission",
"operation": "add",
"groups": "all",
}
REMOVE_GROUP_ARGS = {'snapshot_id': snapshot.id,
'attribute': 'createVolumePermission',
'operation': 'remove',
'groups': 'all'}
REMOVE_GROUP_ARGS = {
"snapshot_id": snapshot.id,
"attribute": "createVolumePermission",
"operation": "remove",
"groups": "all",
}
# Add 'all' group and confirm
with assert_raises(EC2ResponseError) as ex:
conn.modify_snapshot_attribute(
**dict(ADD_GROUP_ARGS, **{'dry_run': True}))
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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.attrs['groups'].should.have.length_of(1)
attributes.attrs['groups'].should.equal(['all'])
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}))
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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')
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)
**REMOVE_GROUP_ARGS
).should_not.throw(EC2ResponseError)
# Error: Add with group != 'all'
with assert_raises(EC2ResponseError) as cm:
conn.modify_snapshot_attribute(snapshot.id,
attribute='createVolumePermission',
operation='add',
groups='everyone')
cm.exception.code.should.equal('InvalidAMIAttributeItemValue')
conn.modify_snapshot_attribute(
snapshot.id,
attribute="createVolumePermission",
operation="add",
groups="everyone",
)
cm.exception.code.should.equal("InvalidAMIAttributeItemValue")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
# Error: Add with invalid snapshot ID
with assert_raises(EC2ResponseError) as cm:
conn.modify_snapshot_attribute("snapshot-abcd1234",
attribute='createVolumePermission',
operation='add',
groups='all')
cm.exception.code.should.equal('InvalidSnapshot.NotFound')
conn.modify_snapshot_attribute(
"snapshot-abcd1234",
attribute="createVolumePermission",
operation="add",
groups="all",
)
cm.exception.code.should.equal("InvalidSnapshot.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
# Error: Remove with invalid snapshot ID
with assert_raises(EC2ResponseError) as cm:
conn.modify_snapshot_attribute("snapshot-abcd1234",
attribute='createVolumePermission',
operation='remove',
groups='all')
cm.exception.code.should.equal('InvalidSnapshot.NotFound')
conn.modify_snapshot_attribute(
"snapshot-abcd1234",
attribute="createVolumePermission",
operation="remove",
groups="all",
)
cm.exception.code.should.equal("InvalidSnapshot.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
# Error: Add or remove with user ID instead of group
conn.modify_snapshot_attribute.when.called_with(snapshot.id,
attribute='createVolumePermission',
operation='add',
user_ids=['user']).should.throw(NotImplementedError)
conn.modify_snapshot_attribute.when.called_with(snapshot.id,
attribute='createVolumePermission',
operation='remove',
user_ids=['user']).should.throw(NotImplementedError)
conn.modify_snapshot_attribute.when.called_with(
snapshot.id,
attribute="createVolumePermission",
operation="add",
user_ids=["user"],
).should.throw(NotImplementedError)
conn.modify_snapshot_attribute.when.called_with(
snapshot.id,
attribute="createVolumePermission",
operation="remove",
user_ids=["user"],
).should.throw(NotImplementedError)
@mock_ec2_deprecated
def test_create_volume_from_snapshot():
conn = boto.ec2.connect_to_region("us-east-1")
volume = conn.create_volume(80, "us-east-1a")
snapshot = volume.create_snapshot('a test snapshot')
snapshot = volume.create_snapshot("a test snapshot")
with assert_raises(EC2ResponseError) as ex:
snapshot = volume.create_snapshot('a test snapshot', dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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 = volume.create_snapshot("a test snapshot")
snapshot.update()
snapshot.status.should.equal('completed')
snapshot.status.should.equal("completed")
new_volume = snapshot.create_volume('us-east-1a')
new_volume = snapshot.create_volume("us-east-1a")
new_volume.size.should.equal(80)
new_volume.snapshot_id.should.equal(snapshot.id)
@ -533,11 +566,11 @@ def test_create_volume_from_encrypted_snapshot():
conn = boto.ec2.connect_to_region("us-east-1")
volume = conn.create_volume(80, "us-east-1a", encrypted=True)
snapshot = volume.create_snapshot('a test snapshot')
snapshot = volume.create_snapshot("a test snapshot")
snapshot.update()
snapshot.status.should.equal('completed')
snapshot.status.should.equal("completed")
new_volume = snapshot.create_volume('us-east-1a')
new_volume = snapshot.create_volume("us-east-1a")
new_volume.size.should.equal(80)
new_volume.snapshot_id.should.equal(snapshot.id)
new_volume.encrypted.should.be(True)
@ -553,131 +586,133 @@ def test_modify_attribute_blockDeviceMapping():
"""
conn = boto.ec2.connect_to_region("us-east-1")
reservation = conn.run_instances('ami-1234abcd')
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
with assert_raises(EC2ResponseError) as ex:
instance.modify_attribute('blockDeviceMapping', {
'/dev/sda1': True}, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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.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.should.have.key("/dev/sda1")
instance.block_device_mapping["/dev/sda1"].delete_on_termination.should.be(True)
@mock_ec2_deprecated
def test_volume_tag_escaping():
conn = boto.ec2.connect_to_region("us-east-1")
vol = conn.create_volume(10, 'us-east-1a')
snapshot = conn.create_snapshot(vol.id, 'Desc')
vol = conn.create_volume(10, "us-east-1a")
snapshot = conn.create_snapshot(vol.id, "Desc")
with assert_raises(EC2ResponseError) as ex:
snapshot.add_tags({'key': '</closed>'}, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set"
)
snaps = [snap for snap in conn.get_all_snapshots() if snap.id == snapshot.id]
dict(snaps[0].tags).should_not.be.equal(
{'key': '</closed>'})
dict(snaps[0].tags).should_not.be.equal({"key": "</closed>"})
snapshot.add_tags({'key': '</closed>'})
snapshot.add_tags({"key": "</closed>"})
snaps = [snap for snap in conn.get_all_snapshots() if snap.id == snapshot.id]
dict(snaps[0].tags).should.equal({'key': '</closed>'})
dict(snaps[0].tags).should.equal({"key": "</closed>"})
@mock_ec2
def test_volume_property_hidden_when_no_tags_exist():
ec2_client = boto3.client('ec2', region_name='us-east-1')
ec2_client = boto3.client("ec2", region_name="us-east-1")
volume_response = ec2_client.create_volume(
Size=10,
AvailabilityZone='us-east-1a'
)
volume_response = ec2_client.create_volume(Size=10, AvailabilityZone="us-east-1a")
volume_response.get('Tags').should.equal(None)
volume_response.get("Tags").should.equal(None)
@freeze_time
@mock_ec2
def test_copy_snapshot():
ec2_client = boto3.client('ec2', region_name='eu-west-1')
dest_ec2_client = boto3.client('ec2', region_name='eu-west-2')
ec2_client = boto3.client("ec2", region_name="eu-west-1")
dest_ec2_client = boto3.client("ec2", region_name="eu-west-2")
volume_response = ec2_client.create_volume(
AvailabilityZone='eu-west-1a', Size=10
)
volume_response = ec2_client.create_volume(AvailabilityZone="eu-west-1a", Size=10)
create_snapshot_response = ec2_client.create_snapshot(
VolumeId=volume_response['VolumeId']
VolumeId=volume_response["VolumeId"]
)
copy_snapshot_response = dest_ec2_client.copy_snapshot(
SourceSnapshotId=create_snapshot_response['SnapshotId'],
SourceRegion="eu-west-1"
SourceSnapshotId=create_snapshot_response["SnapshotId"],
SourceRegion="eu-west-1",
)
ec2 = boto3.resource('ec2', region_name='eu-west-1')
dest_ec2 = boto3.resource('ec2', region_name='eu-west-2')
ec2 = boto3.resource("ec2", region_name="eu-west-1")
dest_ec2 = boto3.resource("ec2", region_name="eu-west-2")
source = ec2.Snapshot(create_snapshot_response['SnapshotId'])
dest = dest_ec2.Snapshot(copy_snapshot_response['SnapshotId'])
source = ec2.Snapshot(create_snapshot_response["SnapshotId"])
dest = dest_ec2.Snapshot(copy_snapshot_response["SnapshotId"])
attribs = ['data_encryption_key_id', 'encrypted',
'kms_key_id', 'owner_alias', 'owner_id',
'progress', 'state', 'state_message',
'tags', 'volume_id', 'volume_size']
attribs = [
"data_encryption_key_id",
"encrypted",
"kms_key_id",
"owner_alias",
"owner_id",
"progress",
"state",
"state_message",
"tags",
"volume_id",
"volume_size",
]
for attrib in attribs:
getattr(source, attrib).should.equal(getattr(dest, attrib))
# Copy from non-existent source ID.
with assert_raises(ClientError) as cm:
create_snapshot_error = ec2_client.create_snapshot(
VolumeId='vol-abcd1234'
)
cm.exception.response['Error']['Code'].should.equal('InvalidVolume.NotFound')
cm.exception.response['Error']['Message'].should.equal("The volume 'vol-abcd1234' does not exist.")
cm.exception.response['ResponseMetadata']['RequestId'].should_not.be.none
cm.exception.response['ResponseMetadata']['HTTPStatusCode'].should.equal(400)
create_snapshot_error = ec2_client.create_snapshot(VolumeId="vol-abcd1234")
cm.exception.response["Error"]["Code"].should.equal("InvalidVolume.NotFound")
cm.exception.response["Error"]["Message"].should.equal(
"The volume 'vol-abcd1234' does not exist."
)
cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none
cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
# Copy from non-existent source region.
with assert_raises(ClientError) as cm:
copy_snapshot_response = dest_ec2_client.copy_snapshot(
SourceSnapshotId=create_snapshot_response['SnapshotId'],
SourceRegion="eu-west-2"
SourceSnapshotId=create_snapshot_response["SnapshotId"],
SourceRegion="eu-west-2",
)
cm.exception.response['Error']['Code'].should.equal('InvalidSnapshot.NotFound')
cm.exception.response['Error']['Message'].should.be.none
cm.exception.response['ResponseMetadata']['RequestId'].should_not.be.none
cm.exception.response['ResponseMetadata']['HTTPStatusCode'].should.equal(400)
cm.exception.response["Error"]["Code"].should.equal("InvalidSnapshot.NotFound")
cm.exception.response["Error"]["Message"].should.be.none
cm.exception.response["ResponseMetadata"]["RequestId"].should_not.be.none
cm.exception.response["ResponseMetadata"]["HTTPStatusCode"].should.equal(400)
@mock_ec2
def test_search_for_many_snapshots():
ec2_client = boto3.client('ec2', region_name='eu-west-1')
ec2_client = boto3.client("ec2", region_name="eu-west-1")
volume_response = ec2_client.create_volume(
AvailabilityZone='eu-west-1a', Size=10
)
volume_response = ec2_client.create_volume(AvailabilityZone="eu-west-1a", Size=10)
snapshot_ids = []
for i in range(1, 20):
create_snapshot_response = ec2_client.create_snapshot(
VolumeId=volume_response['VolumeId']
VolumeId=volume_response["VolumeId"]
)
snapshot_ids.append(create_snapshot_response['SnapshotId'])
snapshot_ids.append(create_snapshot_response["SnapshotId"])
snapshots_response = ec2_client.describe_snapshots(
SnapshotIds=snapshot_ids
)
snapshots_response = ec2_client.describe_snapshots(SnapshotIds=snapshot_ids)
assert len(snapshots_response['Snapshots']) == len(snapshot_ids)
assert len(snapshots_response["Snapshots"]) == len(snapshot_ids)

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
@ -19,16 +20,17 @@ import json
@mock_ec2_deprecated
def test_elastic_network_interfaces():
conn = boto.connect_vpc('the_key', 'the_secret')
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")
with assert_raises(EC2ResponseError) as ex:
eni = conn.create_network_interface(subnet.id, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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)
@ -37,14 +39,15 @@ def test_elastic_network_interfaces():
eni = all_enis[0]
eni.groups.should.have.length_of(0)
eni.private_ip_addresses.should.have.length_of(1)
eni.private_ip_addresses[0].private_ip_address.startswith('10.').should.be.true
eni.private_ip_addresses[0].private_ip_address.startswith("10.").should.be.true
with assert_raises(EC2ResponseError) as ex:
conn.delete_network_interface(eni.id, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the DeleteNetworkInterface operation: Request would have succeeded, but DryRun flag is set"
)
conn.delete_network_interface(eni.id)
@ -53,25 +56,25 @@ def test_elastic_network_interfaces():
with assert_raises(EC2ResponseError) as cm:
conn.delete_network_interface(eni.id)
cm.exception.error_code.should.equal('InvalidNetworkInterfaceID.NotFound')
cm.exception.error_code.should.equal("InvalidNetworkInterfaceID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_elastic_network_interfaces_subnet_validation():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.create_network_interface("subnet-abcd1234")
cm.exception.error_code.should.equal('InvalidSubnetID.NotFound')
cm.exception.error_code.should.equal("InvalidSubnetID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_elastic_network_interfaces_with_private_ip():
conn = boto.connect_vpc('the_key', 'the_secret')
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")
private_ip = "54.0.0.1"
@ -89,15 +92,18 @@ def test_elastic_network_interfaces_with_private_ip():
@mock_ec2_deprecated
def test_elastic_network_interfaces_with_groups():
conn = boto.connect_vpc('the_key', 'the_secret')
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')
"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')
"test security group #2", "this is a test security group"
)
conn.create_network_interface(
subnet.id, groups=[security_group1.id, security_group2.id])
subnet.id, groups=[security_group1.id, security_group2.id]
)
all_enis = conn.get_all_network_interfaces()
all_enis.should.have.length_of(1)
@ -105,19 +111,22 @@ def test_elastic_network_interfaces_with_groups():
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([security_group1.id, security_group2.id])
)
@requires_boto_gte("2.12.0")
@mock_ec2_deprecated
def test_elastic_network_interfaces_modify_attribute():
conn = boto.connect_vpc('the_key', 'the_secret')
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')
"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')
"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()
@ -129,14 +138,15 @@ def test_elastic_network_interfaces_modify_attribute():
with assert_raises(EC2ResponseError) as ex:
conn.modify_network_interface_attribute(
eni.id, 'groupset', [security_group2.id], dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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)
@ -148,20 +158,22 @@ def test_elastic_network_interfaces_modify_attribute():
@mock_ec2_deprecated
def test_elastic_network_interfaces_filtering():
conn = boto.connect_vpc('the_key', 'the_secret')
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')
"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')
"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])
eni3 = conn.create_network_interface(subnet.id, description='test description')
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, description="test description")
all_enis = conn.get_all_network_interfaces()
all_enis.should.have.length_of(3)
@ -173,280 +185,322 @@ def test_elastic_network_interfaces_filtering():
# Filter by ENI ID
enis_by_id = conn.get_all_network_interfaces(
filters={'network-interface-id': eni1.id})
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})
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})
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]))
# Filter by Description
enis_by_description = conn.get_all_network_interfaces(
filters={'description': eni3.description })
filters={"description": eni3.description}
)
enis_by_description.should.have.length_of(1)
enis_by_description[0].description.should.equal(eni3.description)
# Unsupported filter
conn.get_all_network_interfaces.when.called_with(
filters={'not-implemented-filter': 'foobar'}).should.throw(NotImplementedError)
filters={"not-implemented-filter": "foobar"}
).should.throw(NotImplementedError)
@mock_ec2
def test_elastic_network_interfaces_get_by_tag_name():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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')
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')
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"
)
eni1.create_tags(Tags=[{'Key': 'Name', 'Value': 'eni1'}])
eni1.create_tags(Tags=[{"Key": "Name", "Value": "eni1"}])
# The status of the new interface should be 'available'
waiter = ec2_client.get_waiter('network_interface_available')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
filters = [{'Name': 'tag:Name', 'Values': ['eni1']}]
filters = [{"Name": "tag:Name", "Values": ["eni1"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'tag:Name', 'Values': ['wrong-name']}]
filters = [{"Name": "tag:Name", "Values": ["wrong-name"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_get_by_availability_zone():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
subnet1 = ec2.create_subnet(
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-2a')
VpcId=vpc.id, CidrBlock="10.0.0.0/24", AvailabilityZone="us-west-2a"
)
subnet2 = ec2.create_subnet(
VpcId=vpc.id, CidrBlock='10.0.1.0/24', AvailabilityZone='us-west-2b')
VpcId=vpc.id, CidrBlock="10.0.1.0/24", AvailabilityZone="us-west-2b"
)
eni1 = ec2.create_network_interface(
SubnetId=subnet1.id, PrivateIpAddress='10.0.0.15')
SubnetId=subnet1.id, PrivateIpAddress="10.0.0.15"
)
eni2 = ec2.create_network_interface(
SubnetId=subnet2.id, PrivateIpAddress='10.0.1.15')
SubnetId=subnet2.id, PrivateIpAddress="10.0.1.15"
)
# The status of the new interface should be 'available'
waiter = ec2_client.get_waiter('network_interface_available')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id, eni2.id])
filters = [{'Name': 'availability-zone', 'Values': ['us-west-2a']}]
filters = [{"Name": "availability-zone", "Values": ["us-west-2a"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'availability-zone', 'Values': ['us-west-2c']}]
filters = [{"Name": "availability-zone", "Values": ["us-west-2c"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_get_by_private_ip():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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')
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')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
filters = [{'Name': 'private-ip-address', 'Values': ['10.0.10.5']}]
filters = [{"Name": "private-ip-address", "Values": ["10.0.10.5"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'private-ip-address', 'Values': ['10.0.10.10']}]
filters = [{"Name": "private-ip-address", "Values": ["10.0.10.10"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
filters = [{'Name': 'addresses.private-ip-address', 'Values': ['10.0.10.5']}]
filters = [{"Name": "addresses.private-ip-address", "Values": ["10.0.10.5"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'addresses.private-ip-address', 'Values': ['10.0.10.10']}]
filters = [{"Name": "addresses.private-ip-address", "Values": ["10.0.10.10"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_get_by_vpc_id():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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')
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')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
filters = [{'Name': 'vpc-id', 'Values': [subnet.vpc_id]}]
filters = [{"Name": "vpc-id", "Values": [subnet.vpc_id]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'vpc-id', 'Values': ['vpc-aaaa1111']}]
filters = [{"Name": "vpc-id", "Values": ["vpc-aaaa1111"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_get_by_subnet_id():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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')
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')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
filters = [{'Name': 'subnet-id', 'Values': [subnet.id]}]
filters = [{"Name": "subnet-id", "Values": [subnet.id]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'subnet-id', 'Values': ['subnet-aaaa1111']}]
filters = [{"Name": "subnet-id", "Values": ["subnet-aaaa1111"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_get_by_description():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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', Description='test interface')
SubnetId=subnet.id, PrivateIpAddress="10.0.10.5", Description="test interface"
)
# The status of the new interface should be 'available'
waiter = ec2_client.get_waiter('network_interface_available')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
filters = [{'Name': 'description', 'Values': [eni1.description]}]
filters = [{"Name": "description", "Values": [eni1.description]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(1)
filters = [{'Name': 'description', 'Values': ['bad description']}]
filters = [{"Name": "description", "Values": ["bad description"]}]
enis = list(ec2.network_interfaces.filter(Filters=filters))
enis.should.have.length_of(0)
@mock_ec2
def test_elastic_network_interfaces_describe_network_interfaces_with_filter():
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2_client = boto3.client('ec2', region_name='us-west-2')
ec2 = boto3.resource("ec2", region_name="us-west-2")
ec2_client = boto3.client("ec2", region_name="us-west-2")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
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')
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', Description='test interface')
SubnetId=subnet.id, PrivateIpAddress="10.0.10.5", Description="test interface"
)
# The status of the new interface should be 'available'
waiter = ec2_client.get_waiter('network_interface_available')
waiter = ec2_client.get_waiter("network_interface_available")
waiter.wait(NetworkInterfaceIds=[eni1.id])
# Filter by network-interface-id
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'network-interface-id', 'Values': [eni1.id]}])
response['NetworkInterfaces'].should.have.length_of(1)
response['NetworkInterfaces'][0]['NetworkInterfaceId'].should.equal(eni1.id)
response['NetworkInterfaces'][0]['PrivateIpAddress'].should.equal(eni1.private_ip_address)
response['NetworkInterfaces'][0]['Description'].should.equal(eni1.description)
Filters=[{"Name": "network-interface-id", "Values": [eni1.id]}]
)
response["NetworkInterfaces"].should.have.length_of(1)
response["NetworkInterfaces"][0]["NetworkInterfaceId"].should.equal(eni1.id)
response["NetworkInterfaces"][0]["PrivateIpAddress"].should.equal(
eni1.private_ip_address
)
response["NetworkInterfaces"][0]["Description"].should.equal(eni1.description)
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'network-interface-id', 'Values': ['bad-id']}])
response['NetworkInterfaces'].should.have.length_of(0)
Filters=[{"Name": "network-interface-id", "Values": ["bad-id"]}]
)
response["NetworkInterfaces"].should.have.length_of(0)
# Filter by private-ip-address
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'private-ip-address', 'Values': [eni1.private_ip_address]}])
response['NetworkInterfaces'].should.have.length_of(1)
response['NetworkInterfaces'][0]['NetworkInterfaceId'].should.equal(eni1.id)
response['NetworkInterfaces'][0]['PrivateIpAddress'].should.equal(eni1.private_ip_address)
response['NetworkInterfaces'][0]['Description'].should.equal(eni1.description)
Filters=[{"Name": "private-ip-address", "Values": [eni1.private_ip_address]}]
)
response["NetworkInterfaces"].should.have.length_of(1)
response["NetworkInterfaces"][0]["NetworkInterfaceId"].should.equal(eni1.id)
response["NetworkInterfaces"][0]["PrivateIpAddress"].should.equal(
eni1.private_ip_address
)
response["NetworkInterfaces"][0]["Description"].should.equal(eni1.description)
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'private-ip-address', 'Values': ['11.11.11.11']}])
response['NetworkInterfaces'].should.have.length_of(0)
Filters=[{"Name": "private-ip-address", "Values": ["11.11.11.11"]}]
)
response["NetworkInterfaces"].should.have.length_of(0)
# Filter by sunet-id
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'subnet-id', 'Values': [eni1.subnet.id]}])
response['NetworkInterfaces'].should.have.length_of(1)
response['NetworkInterfaces'][0]['NetworkInterfaceId'].should.equal(eni1.id)
response['NetworkInterfaces'][0]['PrivateIpAddress'].should.equal(eni1.private_ip_address)
response['NetworkInterfaces'][0]['Description'].should.equal(eni1.description)
Filters=[{"Name": "subnet-id", "Values": [eni1.subnet.id]}]
)
response["NetworkInterfaces"].should.have.length_of(1)
response["NetworkInterfaces"][0]["NetworkInterfaceId"].should.equal(eni1.id)
response["NetworkInterfaces"][0]["PrivateIpAddress"].should.equal(
eni1.private_ip_address
)
response["NetworkInterfaces"][0]["Description"].should.equal(eni1.description)
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'subnet-id', 'Values': ['sn-bad-id']}])
response['NetworkInterfaces'].should.have.length_of(0)
Filters=[{"Name": "subnet-id", "Values": ["sn-bad-id"]}]
)
response["NetworkInterfaces"].should.have.length_of(0)
# Filter by description
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'description', 'Values': [eni1.description]}])
response['NetworkInterfaces'].should.have.length_of(1)
response['NetworkInterfaces'][0]['NetworkInterfaceId'].should.equal(eni1.id)
response['NetworkInterfaces'][0]['PrivateIpAddress'].should.equal(eni1.private_ip_address)
response['NetworkInterfaces'][0]['Description'].should.equal(eni1.description)
Filters=[{"Name": "description", "Values": [eni1.description]}]
)
response["NetworkInterfaces"].should.have.length_of(1)
response["NetworkInterfaces"][0]["NetworkInterfaceId"].should.equal(eni1.id)
response["NetworkInterfaces"][0]["PrivateIpAddress"].should.equal(
eni1.private_ip_address
)
response["NetworkInterfaces"][0]["Description"].should.equal(eni1.description)
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'description', 'Values': ['bad description']}])
response['NetworkInterfaces'].should.have.length_of(0)
Filters=[{"Name": "description", "Values": ["bad description"]}]
)
response["NetworkInterfaces"].should.have.length_of(0)
# Filter by multiple filters
response = ec2_client.describe_network_interfaces(
Filters=[{'Name': 'private-ip-address', 'Values': [eni1.private_ip_address]},
{'Name': 'network-interface-id', 'Values': [eni1.id]},
{'Name': 'subnet-id', 'Values': [eni1.subnet.id]}])
response['NetworkInterfaces'].should.have.length_of(1)
response['NetworkInterfaces'][0]['NetworkInterfaceId'].should.equal(eni1.id)
response['NetworkInterfaces'][0]['PrivateIpAddress'].should.equal(eni1.private_ip_address)
response['NetworkInterfaces'][0]['Description'].should.equal(eni1.description)
Filters=[
{"Name": "private-ip-address", "Values": [eni1.private_ip_address]},
{"Name": "network-interface-id", "Values": [eni1.id]},
{"Name": "subnet-id", "Values": [eni1.subnet.id]},
]
)
response["NetworkInterfaces"].should.have.length_of(1)
response["NetworkInterfaces"][0]["NetworkInterfaceId"].should.equal(eni1.id)
response["NetworkInterfaces"][0]["PrivateIpAddress"].should.equal(
eni1.private_ip_address
)
response["NetworkInterfaces"][0]["Description"].should.equal(eni1.description)
@mock_ec2_deprecated
@ -455,19 +509,19 @@ def test_elastic_network_interfaces_cloudformation():
template = vpc_eni.template
template_json = json.dumps(template)
conn = boto.cloudformation.connect_to_region("us-west-1")
conn.create_stack(
"test_stack",
template_body=template_json,
)
conn.create_stack("test_stack", template_body=template_json)
ec2_conn = boto.ec2.connect_to_region("us-west-1")
eni = ec2_conn.get_all_network_interfaces()[0]
eni.private_ip_addresses.should.have.length_of(1)
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)
outputs = {output.key: output.value for output in stack.outputs}
outputs['ENIIpAddress'].should.equal(eni.private_ip_addresses[0].private_ip_address)
outputs["ENIIpAddress"].should.equal(eni.private_ip_addresses[0].private_ip_address)

View file

@ -1,42 +1,41 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto
import boto3
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2_deprecated, mock_ec2
@mock_ec2_deprecated
def test_console_output():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
instance_id = reservation.instances[0].id
output = conn.get_console_output(instance_id)
output.output.should_not.equal(None)
@mock_ec2_deprecated
def test_console_output_without_instance():
conn = boto.connect_ec2('the_key', 'the_secret')
with assert_raises(EC2ResponseError) as cm:
conn.get_console_output('i-1234abcd')
cm.exception.code.should.equal('InvalidInstanceID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2
def test_console_output_boto3():
conn = boto3.resource('ec2', 'us-east-1')
instances = conn.create_instances(ImageId='ami-1234abcd',
MinCount=1,
MaxCount=1)
output = instances[0].console_output()
output.get('Output').should_not.equal(None)
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto
import boto3
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2_deprecated, mock_ec2
@mock_ec2_deprecated
def test_console_output():
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance_id = reservation.instances[0].id
output = conn.get_console_output(instance_id)
output.output.should_not.equal(None)
@mock_ec2_deprecated
def test_console_output_without_instance():
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.get_console_output("i-1234abcd")
cm.exception.code.should.equal("InvalidInstanceID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2
def test_console_output_boto3():
conn = boto3.resource("ec2", "us-east-1")
instances = conn.create_instances(ImageId="ami-1234abcd", MinCount=1, MaxCount=1)
output = instances[0].console_output()
output.get("Output").should_not.equal(None)

File diff suppressed because it is too large Load diff

View file

@ -1,269 +1,271 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import re
import boto
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2_deprecated
VPC_CIDR = "10.0.0.0/16"
BAD_VPC = "vpc-deadbeef"
BAD_IGW = "igw-deadbeef"
@mock_ec2_deprecated
def test_igw_create():
""" internet gateway create """
conn = boto.connect_vpc('the_key', 'the_secret')
conn.get_all_internet_gateways().should.have.length_of(0)
with assert_raises(EC2ResponseError) as ex:
igw = conn.create_internet_gateway(dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'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)
igw.id.should.match(r'igw-[0-9a-f]+')
igw = conn.get_all_internet_gateways()[0]
igw.attachments.should.have.length_of(0)
@mock_ec2_deprecated
def test_igw_attach():
""" internet gateway attach """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
with assert_raises(EC2ResponseError) as ex:
conn.attach_internet_gateway(igw.id, vpc.id, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'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 """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
with assert_raises(EC2ResponseError) as cm:
conn.attach_internet_gateway(igw.id, BAD_VPC)
cm.exception.code.should.equal('InvalidVpcID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_attach_twice():
""" internet gateway fail to attach twice """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc1 = conn.create_vpc(VPC_CIDR)
vpc2 = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc1.id)
with assert_raises(EC2ResponseError) as cm:
conn.attach_internet_gateway(igw.id, vpc2.id)
cm.exception.code.should.equal('Resource.AlreadyAssociated')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach():
""" internet gateway detach"""
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as ex:
conn.detach_internet_gateway(igw.id, vpc.id, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'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 """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc1 = conn.create_vpc(VPC_CIDR)
vpc2 = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc1.id)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, vpc2.id)
cm.exception.code.should.equal('Gateway.NotAttached')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach_invalid_vpc():
""" internet gateway fail to detach w/ invalid vpc """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, BAD_VPC)
cm.exception.code.should.equal('Gateway.NotAttached')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach_unattached():
""" internet gateway fail to detach unattached """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, vpc.id)
cm.exception.code.should.equal('Gateway.NotAttached')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_delete():
""" internet gateway delete"""
conn = boto.connect_vpc('the_key', 'the_secret')
vpc = conn.create_vpc(VPC_CIDR)
conn.get_all_internet_gateways().should.have.length_of(0)
igw = conn.create_internet_gateway()
conn.get_all_internet_gateways().should.have.length_of(1)
with assert_raises(EC2ResponseError) as ex:
conn.delete_internet_gateway(igw.id, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'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 """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal('DependencyViolation')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_desribe():
""" internet gateway fetch by id """
conn = boto.connect_vpc('the_key', 'the_secret')
igw = conn.create_internet_gateway()
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_describe_bad_id():
""" internet gateway fail to fetch by bad id """
conn = boto.connect_vpc('the_key', 'the_secret')
with assert_raises(EC2ResponseError) as cm:
conn.get_all_internet_gateways([BAD_IGW])
cm.exception.code.should.equal('InvalidInternetGatewayID.NotFound')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_filter_by_vpc_id():
""" internet gateway filter by vpc id """
conn = boto.connect_vpc('the_key', 'the_secret')
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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.should.have.length_of(1)
result[0].id.should.equal(igw1.id)
@mock_ec2_deprecated
def test_igw_filter_by_tags():
""" internet gateway filter by vpc id """
conn = boto.connect_vpc('the_key', 'the_secret')
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
igw1.add_tag("tests", "yes")
result = conn.get_all_internet_gateways(filters={"tag:tests": "yes"})
result.should.have.length_of(1)
result[0].id.should.equal(igw1.id)
@mock_ec2_deprecated
def test_igw_filter_by_internet_gateway_id():
""" internet gateway filter by internet gateway id """
conn = boto.connect_vpc('the_key', 'the_secret')
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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)
@mock_ec2_deprecated
def test_igw_filter_by_attachment_state():
""" internet gateway filter by attachment state """
conn = boto.connect_vpc('the_key', 'the_secret')
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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.should.have.length_of(1)
result[0].id.should.equal(igw1.id)
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import re
import boto
from boto.exception import EC2ResponseError
import sure # noqa
from moto import mock_ec2_deprecated
VPC_CIDR = "10.0.0.0/16"
BAD_VPC = "vpc-deadbeef"
BAD_IGW = "igw-deadbeef"
@mock_ec2_deprecated
def test_igw_create():
""" internet gateway create """
conn = boto.connect_vpc("the_key", "the_secret")
conn.get_all_internet_gateways().should.have.length_of(0)
with assert_raises(EC2ResponseError) as ex:
igw = conn.create_internet_gateway(dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"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)
igw.id.should.match(r"igw-[0-9a-f]+")
igw = conn.get_all_internet_gateways()[0]
igw.attachments.should.have.length_of(0)
@mock_ec2_deprecated
def test_igw_attach():
""" internet gateway attach """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
with assert_raises(EC2ResponseError) as ex:
conn.attach_internet_gateway(igw.id, vpc.id, dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"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 """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
with assert_raises(EC2ResponseError) as cm:
conn.attach_internet_gateway(igw.id, BAD_VPC)
cm.exception.code.should.equal("InvalidVpcID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_attach_twice():
""" internet gateway fail to attach twice """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc1 = conn.create_vpc(VPC_CIDR)
vpc2 = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc1.id)
with assert_raises(EC2ResponseError) as cm:
conn.attach_internet_gateway(igw.id, vpc2.id)
cm.exception.code.should.equal("Resource.AlreadyAssociated")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach():
""" internet gateway detach"""
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as ex:
conn.detach_internet_gateway(igw.id, vpc.id, dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"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 """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc1 = conn.create_vpc(VPC_CIDR)
vpc2 = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc1.id)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, vpc2.id)
cm.exception.code.should.equal("Gateway.NotAttached")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach_invalid_vpc():
""" internet gateway fail to detach w/ invalid vpc """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, BAD_VPC)
cm.exception.code.should.equal("Gateway.NotAttached")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_detach_unattached():
""" internet gateway fail to detach unattached """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
with assert_raises(EC2ResponseError) as cm:
conn.detach_internet_gateway(igw.id, vpc.id)
cm.exception.code.should.equal("Gateway.NotAttached")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_delete():
""" internet gateway delete"""
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc(VPC_CIDR)
conn.get_all_internet_gateways().should.have.length_of(0)
igw = conn.create_internet_gateway()
conn.get_all_internet_gateways().should.have.length_of(1)
with assert_raises(EC2ResponseError) as ex:
conn.delete_internet_gateway(igw.id, dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
"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 """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
vpc = conn.create_vpc(VPC_CIDR)
conn.attach_internet_gateway(igw.id, vpc.id)
with assert_raises(EC2ResponseError) as cm:
conn.delete_internet_gateway(igw.id)
cm.exception.code.should.equal("DependencyViolation")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_desribe():
""" internet gateway fetch by id """
conn = boto.connect_vpc("the_key", "the_secret")
igw = conn.create_internet_gateway()
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_describe_bad_id():
""" internet gateway fail to fetch by bad id """
conn = boto.connect_vpc("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.get_all_internet_gateways([BAD_IGW])
cm.exception.code.should.equal("InvalidInternetGatewayID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_igw_filter_by_vpc_id():
""" internet gateway filter by vpc id """
conn = boto.connect_vpc("the_key", "the_secret")
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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.should.have.length_of(1)
result[0].id.should.equal(igw1.id)
@mock_ec2_deprecated
def test_igw_filter_by_tags():
""" internet gateway filter by vpc id """
conn = boto.connect_vpc("the_key", "the_secret")
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
igw1.add_tag("tests", "yes")
result = conn.get_all_internet_gateways(filters={"tag:tests": "yes"})
result.should.have.length_of(1)
result[0].id.should.equal(igw1.id)
@mock_ec2_deprecated
def test_igw_filter_by_internet_gateway_id():
""" internet gateway filter by internet gateway id """
conn = boto.connect_vpc("the_key", "the_secret")
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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)
@mock_ec2_deprecated
def test_igw_filter_by_attachment_state():
""" internet gateway filter by attachment state """
conn = boto.connect_vpc("the_key", "the_secret")
igw1 = conn.create_internet_gateway()
igw2 = conn.create_internet_gateway()
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.should.have.length_of(1)
result[0].id.should.equal(igw1.id)

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
@ -47,116 +48,119 @@ moto@github.com"""
@mock_ec2_deprecated
def test_key_pairs_empty():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
assert len(conn.get_all_key_pairs()) == 0
@mock_ec2_deprecated
def test_key_pairs_invalid_id():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.get_all_key_pairs('foo')
cm.exception.code.should.equal('InvalidKeyPair.NotFound')
conn.get_all_key_pairs("foo")
cm.exception.code.should.equal("InvalidKeyPair.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_key_pairs_create():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as ex:
conn.create_key_pair('foo', dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"An error occurred (DryRunOperation) when calling the CreateKeyPair operation: Request would have succeeded, but DryRun flag is set"
)
kp = conn.create_key_pair('foo')
kp = conn.create_key_pair("foo")
rsa_check_private_key(kp.material)
kps = conn.get_all_key_pairs()
assert len(kps) == 1
assert kps[0].name == 'foo'
assert kps[0].name == "foo"
@mock_ec2_deprecated
def test_key_pairs_create_two():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
kp1 = conn.create_key_pair('foo')
kp1 = conn.create_key_pair("foo")
rsa_check_private_key(kp1.material)
kp2 = conn.create_key_pair('bar')
kp2 = conn.create_key_pair("bar")
rsa_check_private_key(kp2.material)
assert kp1.material != kp2.material
kps = conn.get_all_key_pairs()
kps.should.have.length_of(2)
assert {i.name for i in kps} == {'foo', 'bar'}
assert {i.name for i in kps} == {"foo", "bar"}
kps = conn.get_all_key_pairs('foo')
kps = conn.get_all_key_pairs("foo")
kps.should.have.length_of(1)
kps[0].name.should.equal('foo')
kps[0].name.should.equal("foo")
@mock_ec2_deprecated
def test_key_pairs_create_exist():
conn = boto.connect_ec2('the_key', 'the_secret')
conn.create_key_pair('foo')
conn = boto.connect_ec2("the_key", "the_secret")
conn.create_key_pair("foo")
assert len(conn.get_all_key_pairs()) == 1
with assert_raises(EC2ResponseError) as cm:
conn.create_key_pair('foo')
cm.exception.code.should.equal('InvalidKeyPair.Duplicate')
conn.create_key_pair("foo")
cm.exception.code.should.equal("InvalidKeyPair.Duplicate")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_key_pairs_delete_no_exist():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
assert len(conn.get_all_key_pairs()) == 0
r = conn.delete_key_pair('foo')
r = conn.delete_key_pair("foo")
r.should.be.ok
@mock_ec2_deprecated
def test_key_pairs_delete_exist():
conn = boto.connect_ec2('the_key', 'the_secret')
conn.create_key_pair('foo')
conn = boto.connect_ec2("the_key", "the_secret")
conn.create_key_pair("foo")
with assert_raises(EC2ResponseError) as ex:
r = conn.delete_key_pair('foo', dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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 = conn.delete_key_pair("foo")
r.should.be.ok
assert len(conn.get_all_key_pairs()) == 0
@mock_ec2_deprecated
def test_key_pairs_import():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as ex:
conn.import_key_pair('foo', RSA_PUBLIC_KEY_OPENSSH, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
conn.import_key_pair("foo", RSA_PUBLIC_KEY_OPENSSH, dry_run=True)
ex.exception.error_code.should.equal("DryRunOperation")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'An error occurred (DryRunOperation) when calling the ImportKeyPair operation: Request would have succeeded, but DryRun flag is set')
"An error occurred (DryRunOperation) when calling the ImportKeyPair operation: Request would have succeeded, but DryRun flag is set"
)
kp1 = conn.import_key_pair('foo', RSA_PUBLIC_KEY_OPENSSH)
assert kp1.name == 'foo'
kp1 = conn.import_key_pair("foo", RSA_PUBLIC_KEY_OPENSSH)
assert kp1.name == "foo"
assert kp1.fingerprint == RSA_PUBLIC_KEY_FINGERPRINT
kp2 = conn.import_key_pair('foo2', RSA_PUBLIC_KEY_RFC4716)
assert kp2.name == 'foo2'
kp2 = conn.import_key_pair("foo2", RSA_PUBLIC_KEY_RFC4716)
assert kp2.name == "foo2"
assert kp2.fingerprint == RSA_PUBLIC_KEY_FINGERPRINT
kps = conn.get_all_key_pairs()
@ -167,58 +171,51 @@ def test_key_pairs_import():
@mock_ec2_deprecated
def test_key_pairs_import_exist():
conn = boto.connect_ec2('the_key', 'the_secret')
kp = conn.import_key_pair('foo', RSA_PUBLIC_KEY_OPENSSH)
assert kp.name == 'foo'
conn = boto.connect_ec2("the_key", "the_secret")
kp = conn.import_key_pair("foo", RSA_PUBLIC_KEY_OPENSSH)
assert kp.name == "foo"
assert len(conn.get_all_key_pairs()) == 1
with assert_raises(EC2ResponseError) as cm:
conn.create_key_pair('foo')
cm.exception.code.should.equal('InvalidKeyPair.Duplicate')
conn.create_key_pair("foo")
cm.exception.code.should.equal("InvalidKeyPair.Duplicate")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_key_pairs_invalid():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as ex:
conn.import_key_pair('foo', b'')
ex.exception.error_code.should.equal('InvalidKeyPair.Format')
conn.import_key_pair("foo", b"")
ex.exception.error_code.should.equal("InvalidKeyPair.Format")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'Key is not in valid OpenSSH public key format')
ex.exception.message.should.equal("Key is not in valid OpenSSH public key format")
with assert_raises(EC2ResponseError) as ex:
conn.import_key_pair('foo', b'garbage')
ex.exception.error_code.should.equal('InvalidKeyPair.Format')
conn.import_key_pair("foo", b"garbage")
ex.exception.error_code.should.equal("InvalidKeyPair.Format")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'Key is not in valid OpenSSH public key format')
ex.exception.message.should.equal("Key is not in valid OpenSSH public key format")
with assert_raises(EC2ResponseError) as ex:
conn.import_key_pair('foo', DSA_PUBLIC_KEY_OPENSSH)
ex.exception.error_code.should.equal('InvalidKeyPair.Format')
conn.import_key_pair("foo", DSA_PUBLIC_KEY_OPENSSH)
ex.exception.error_code.should.equal("InvalidKeyPair.Format")
ex.exception.status.should.equal(400)
ex.exception.message.should.equal(
'Key is not in valid OpenSSH public key format')
ex.exception.message.should.equal("Key is not in valid OpenSSH public key format")
@mock_ec2_deprecated
def test_key_pair_filters():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
_ = conn.create_key_pair('kpfltr1')
kp2 = conn.create_key_pair('kpfltr2')
kp3 = conn.create_key_pair('kpfltr3')
_ = conn.create_key_pair("kpfltr1")
kp2 = conn.create_key_pair("kpfltr2")
kp3 = conn.create_key_pair("kpfltr3")
kp_by_name = conn.get_all_key_pairs(
filters={'key-name': 'kpfltr2'})
set([kp.name for kp in kp_by_name]
).should.equal(set([kp2.name]))
kp_by_name = conn.get_all_key_pairs(filters={"key-name": "kpfltr2"})
set([kp.name for kp in kp_by_name]).should.equal(set([kp2.name]))
kp_by_name = conn.get_all_key_pairs(
filters={'fingerprint': kp3.fingerprint})
set([kp.name for kp in kp_by_name]
).should.equal(set([kp3.name]))
kp_by_name = conn.get_all_key_pairs(filters={"fingerprint": kp3.fingerprint})
set([kp.name for kp in kp_by_name]).should.equal(set([kp3.name]))

View file

@ -13,16 +13,14 @@ def test_launch_template_create():
resp = cli.create_launch_template(
LaunchTemplateName="test-template",
# the absolute minimum needed to create a template without other resources
LaunchTemplateData={
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{
"Key": "test",
"Value": "value",
}],
}],
"TagSpecifications": [
{
"ResourceType": "instance",
"Tags": [{"Key": "test", "Value": "value"}],
}
]
},
)
@ -36,18 +34,18 @@ def test_launch_template_create():
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{
"Key": "test",
"Value": "value",
}],
}],
"TagSpecifications": [
{
"ResourceType": "instance",
"Tags": [{"Key": "test", "Value": "value"}],
}
]
},
)
str(ex.exception).should.equal(
'An error occurred (InvalidLaunchTemplateName.AlreadyExistsException) when calling the CreateLaunchTemplate operation: Launch template name already in use.')
"An error occurred (InvalidLaunchTemplateName.AlreadyExistsException) when calling the CreateLaunchTemplate operation: Launch template name already in use."
)
@mock_ec2
@ -55,29 +53,22 @@ def test_describe_launch_template_versions():
template_data = {
"ImageId": "ami-abc123",
"DisableApiTermination": False,
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{
"Key": "test",
"Value": "value",
}],
}],
"SecurityGroupIds": [
"sg-1234",
"sg-ab5678",
"TagSpecifications": [
{"ResourceType": "instance", "Tags": [{"Key": "test", "Value": "value"}]}
],
"SecurityGroupIds": ["sg-1234", "sg-ab5678"],
}
cli = boto3.client("ec2", region_name="us-east-1")
create_resp = cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData=template_data)
LaunchTemplateName="test-template", LaunchTemplateData=template_data
)
# test using name
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
Versions=['1'])
LaunchTemplateName="test-template", Versions=["1"]
)
templ = resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]
templ.should.equal(template_data)
@ -85,7 +76,8 @@ def test_describe_launch_template_versions():
# test using id
resp = cli.describe_launch_template_versions(
LaunchTemplateId=create_resp["LaunchTemplate"]["LaunchTemplateId"],
Versions=['1'])
Versions=["1"],
)
templ = resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]
templ.should.equal(template_data)
@ -96,22 +88,21 @@ def test_create_launch_template_version():
cli = boto3.client("ec2", region_name="us-east-1")
create_resp = cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
version_resp = cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
version_resp.should.have.key("LaunchTemplateVersion")
version = version_resp["LaunchTemplateVersion"]
version["DefaultVersion"].should.equal(False)
version["LaunchTemplateId"].should.equal(create_resp["LaunchTemplate"]["LaunchTemplateId"])
version["LaunchTemplateId"].should.equal(
create_resp["LaunchTemplate"]["LaunchTemplateId"]
)
version["VersionDescription"].should.equal("new ami")
version["VersionNumber"].should.equal(2)
@ -121,22 +112,21 @@ def test_create_launch_template_version_by_id():
cli = boto3.client("ec2", region_name="us-east-1")
create_resp = cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
version_resp = cli.create_launch_template_version(
LaunchTemplateId=create_resp["LaunchTemplate"]["LaunchTemplateId"],
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
version_resp.should.have.key("LaunchTemplateVersion")
version = version_resp["LaunchTemplateVersion"]
version["DefaultVersion"].should.equal(False)
version["LaunchTemplateId"].should.equal(create_resp["LaunchTemplate"]["LaunchTemplateId"])
version["LaunchTemplateId"].should.equal(
create_resp["LaunchTemplate"]["LaunchTemplateId"]
)
version["VersionDescription"].should.equal("new ami")
version["VersionNumber"].should.equal(2)
@ -146,24 +136,24 @@ def test_describe_launch_template_versions_with_multiple_versions():
cli = boto3.client("ec2", region_name="us-east-1")
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template")
resp = cli.describe_launch_template_versions(LaunchTemplateName="test-template")
resp["LaunchTemplateVersions"].should.have.length_of(2)
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal("ami-abc123")
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal("ami-def456")
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-abc123"
)
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-def456"
)
@mock_ec2
@ -171,32 +161,32 @@ def test_describe_launch_template_versions_with_versions_option():
cli = boto3.client("ec2", region_name="us-east-1")
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-hij789"
},
VersionDescription="new ami, again")
LaunchTemplateData={"ImageId": "ami-hij789"},
VersionDescription="new ami, again",
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
Versions=["2", "3"])
LaunchTemplateName="test-template", Versions=["2", "3"]
)
resp["LaunchTemplateVersions"].should.have.length_of(2)
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal("ami-def456")
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal("ami-hij789")
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-def456"
)
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-hij789"
)
@mock_ec2
@ -204,32 +194,32 @@ def test_describe_launch_template_versions_with_min():
cli = boto3.client("ec2", region_name="us-east-1")
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-hij789"
},
VersionDescription="new ami, again")
LaunchTemplateData={"ImageId": "ami-hij789"},
VersionDescription="new ami, again",
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
MinVersion="2")
LaunchTemplateName="test-template", MinVersion="2"
)
resp["LaunchTemplateVersions"].should.have.length_of(2)
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal("ami-def456")
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal("ami-hij789")
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-def456"
)
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-hij789"
)
@mock_ec2
@ -237,32 +227,32 @@ def test_describe_launch_template_versions_with_max():
cli = boto3.client("ec2", region_name="us-east-1")
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-hij789"
},
VersionDescription="new ami, again")
LaunchTemplateData={"ImageId": "ami-hij789"},
VersionDescription="new ami, again",
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
MaxVersion="2")
LaunchTemplateName="test-template", MaxVersion="2"
)
resp["LaunchTemplateVersions"].should.have.length_of(2)
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal("ami-abc123")
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal("ami-def456")
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-abc123"
)
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-def456"
)
@mock_ec2
@ -270,40 +260,38 @@ def test_describe_launch_template_versions_with_min_and_max():
cli = boto3.client("ec2", region_name="us-east-1")
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-def456"
},
VersionDescription="new ami")
LaunchTemplateData={"ImageId": "ami-def456"},
VersionDescription="new ami",
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-hij789"
},
VersionDescription="new ami, again")
LaunchTemplateData={"ImageId": "ami-hij789"},
VersionDescription="new ami, again",
)
cli.create_launch_template_version(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-345abc"
},
VersionDescription="new ami, because why not")
LaunchTemplateData={"ImageId": "ami-345abc"},
VersionDescription="new ami, because why not",
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
MinVersion="2",
MaxVersion="3")
LaunchTemplateName="test-template", MinVersion="2", MaxVersion="3"
)
resp["LaunchTemplateVersions"].should.have.length_of(2)
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal("ami-def456")
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal("ami-hij789")
resp["LaunchTemplateVersions"][0]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-def456"
)
resp["LaunchTemplateVersions"][1]["LaunchTemplateData"]["ImageId"].should.equal(
"ami-hij789"
)
@mock_ec2
@ -312,17 +300,14 @@ def test_describe_launch_templates():
lt_ids = []
r = cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
lt_ids.append(r["LaunchTemplate"]["LaunchTemplateId"])
r = cli.create_launch_template(
LaunchTemplateName="test-template2",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateData={"ImageId": "ami-abc123"},
)
lt_ids.append(r["LaunchTemplate"]["LaunchTemplateId"])
# general call, all templates
@ -334,7 +319,8 @@ def test_describe_launch_templates():
# filter by names
resp = cli.describe_launch_templates(
LaunchTemplateNames=["test-template2", "test-template"])
LaunchTemplateNames=["test-template2", "test-template"]
)
resp.should.have.key("LaunchTemplates")
resp["LaunchTemplates"].should.have.length_of(2)
resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template2")
@ -353,34 +339,31 @@ def test_describe_launch_templates_with_filters():
cli = boto3.client("ec2", region_name="us-east-1")
r = cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="test-template", LaunchTemplateData={"ImageId": "ami-abc123"}
)
cli.create_tags(
Resources=[r["LaunchTemplate"]["LaunchTemplateId"]],
Tags=[
{"Key": "tag1", "Value": "a value"},
{"Key": "another-key", "Value": "this value"},
])
],
)
cli.create_launch_template(
LaunchTemplateName="no-tags",
LaunchTemplateData={
"ImageId": "ami-abc123"
})
LaunchTemplateName="no-tags", LaunchTemplateData={"ImageId": "ami-abc123"}
)
resp = cli.describe_launch_templates(Filters=[{
"Name": "tag:tag1", "Values": ["a value"]
}])
resp = cli.describe_launch_templates(
Filters=[{"Name": "tag:tag1", "Values": ["a value"]}]
)
resp["LaunchTemplates"].should.have.length_of(1)
resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("test-template")
resp = cli.describe_launch_templates(Filters=[{
"Name": "launch-template-name", "Values": ["no-tags"]
}])
resp = cli.describe_launch_templates(
Filters=[{"Name": "launch-template-name", "Values": ["no-tags"]}]
)
resp["LaunchTemplates"].should.have.length_of(1)
resp["LaunchTemplates"][0]["LaunchTemplateName"].should.equal("no-tags")
@ -392,24 +375,18 @@ def test_create_launch_template_with_tag_spec():
cli.create_launch_template(
LaunchTemplateName="test-template",
LaunchTemplateData={"ImageId": "ami-abc123"},
TagSpecifications=[{
"ResourceType": "instance",
"Tags": [
{"Key": "key", "Value": "value"}
]
}],
TagSpecifications=[
{"ResourceType": "instance", "Tags": [{"Key": "key", "Value": "value"}]}
],
)
resp = cli.describe_launch_template_versions(
LaunchTemplateName="test-template",
Versions=["1"])
LaunchTemplateName="test-template", Versions=["1"]
)
version = resp["LaunchTemplateVersions"][0]
version["LaunchTemplateData"].should.have.key("TagSpecifications")
version["LaunchTemplateData"]["TagSpecifications"].should.have.length_of(1)
version["LaunchTemplateData"]["TagSpecifications"][0].should.equal({
"ResourceType": "instance",
"Tags": [
{"Key": "key", "Value": "value"}
]
})
version["LaunchTemplateData"]["TagSpecifications"][0].should.equal(
{"ResourceType": "instance", "Tags": [{"Key": "key", "Value": "value"}]}
)

View file

@ -1,109 +1,225 @@
from __future__ import unicode_literals
import boto3
import sure # noqa
from moto import mock_ec2
@mock_ec2
def test_describe_nat_gateways():
conn = boto3.client('ec2', 'us-east-1')
response = conn.describe_nat_gateways()
response['NatGateways'].should.have.length_of(0)
@mock_ec2
def test_create_nat_gateway():
conn = boto3.client('ec2', 'us-east-1')
vpc = conn.create_vpc(CidrBlock='10.0.0.0/16')
vpc_id = vpc['Vpc']['VpcId']
subnet = conn.create_subnet(
VpcId=vpc_id,
CidrBlock='10.0.1.0/27',
AvailabilityZone='us-east-1a',
)
allocation_id = conn.allocate_address(Domain='vpc')['AllocationId']
subnet_id = subnet['Subnet']['SubnetId']
response = conn.create_nat_gateway(
SubnetId=subnet_id,
AllocationId=allocation_id,
)
response['NatGateway']['VpcId'].should.equal(vpc_id)
response['NatGateway']['SubnetId'].should.equal(subnet_id)
response['NatGateway']['State'].should.equal('available')
@mock_ec2
def test_delete_nat_gateway():
conn = boto3.client('ec2', 'us-east-1')
vpc = conn.create_vpc(CidrBlock='10.0.0.0/16')
vpc_id = vpc['Vpc']['VpcId']
subnet = conn.create_subnet(
VpcId=vpc_id,
CidrBlock='10.0.1.0/27',
AvailabilityZone='us-east-1a',
)
allocation_id = conn.allocate_address(Domain='vpc')['AllocationId']
subnet_id = subnet['Subnet']['SubnetId']
nat_gateway = conn.create_nat_gateway(
SubnetId=subnet_id,
AllocationId=allocation_id,
)
nat_gateway_id = nat_gateway['NatGateway']['NatGatewayId']
response = conn.delete_nat_gateway(NatGatewayId=nat_gateway_id)
# 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,
'ResponseMetadata': {
'HTTPStatusCode': 200,
'RequestId': '741fc8ab-6ebe-452b-b92b-example'
}
})
@mock_ec2
def test_create_and_describe_nat_gateway():
conn = boto3.client('ec2', 'us-east-1')
vpc = conn.create_vpc(CidrBlock='10.0.0.0/16')
vpc_id = vpc['Vpc']['VpcId']
subnet = conn.create_subnet(
VpcId=vpc_id,
CidrBlock='10.0.1.0/27',
AvailabilityZone='us-east-1a',
)
allocation_id = conn.allocate_address(Domain='vpc')['AllocationId']
subnet_id = subnet['Subnet']['SubnetId']
create_response = conn.create_nat_gateway(
SubnetId=subnet_id,
AllocationId=allocation_id,
)
nat_gateway_id = create_response['NatGateway']['NatGatewayId']
describe_response = conn.describe_nat_gateways()
enis = conn.describe_network_interfaces()['NetworkInterfaces']
eni_id = enis[0]['NetworkInterfaceId']
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]['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)
from __future__ import unicode_literals
import boto3
import sure # noqa
from moto import mock_ec2
@mock_ec2
def test_describe_nat_gateways():
conn = boto3.client("ec2", "us-east-1")
response = conn.describe_nat_gateways()
response["NatGateways"].should.have.length_of(0)
@mock_ec2
def test_create_nat_gateway():
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
allocation_id = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id = subnet["Subnet"]["SubnetId"]
response = conn.create_nat_gateway(SubnetId=subnet_id, AllocationId=allocation_id)
response["NatGateway"]["VpcId"].should.equal(vpc_id)
response["NatGateway"]["SubnetId"].should.equal(subnet_id)
response["NatGateway"]["State"].should.equal("available")
@mock_ec2
def test_delete_nat_gateway():
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
allocation_id = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id = subnet["Subnet"]["SubnetId"]
nat_gateway = conn.create_nat_gateway(
SubnetId=subnet_id, AllocationId=allocation_id
)
nat_gateway_id = nat_gateway["NatGateway"]["NatGatewayId"]
response = conn.delete_nat_gateway(NatGatewayId=nat_gateway_id)
# 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,
"ResponseMetadata": {
"HTTPStatusCode": 200,
"RequestId": "741fc8ab-6ebe-452b-b92b-example",
},
}
)
@mock_ec2
def test_create_and_describe_nat_gateway():
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
allocation_id = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id = subnet["Subnet"]["SubnetId"]
create_response = conn.create_nat_gateway(
SubnetId=subnet_id, AllocationId=allocation_id
)
nat_gateway_id = create_response["NatGateway"]["NatGatewayId"]
describe_response = conn.describe_nat_gateways()
enis = conn.describe_network_interfaces()["NetworkInterfaces"]
eni_id = enis[0]["NetworkInterfaceId"]
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]["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)
@mock_ec2
def test_describe_nat_gateway_filter_by_net_gateway_id_and_state():
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
allocation_id = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id = subnet["Subnet"]["SubnetId"]
create_response = conn.create_nat_gateway(
SubnetId=subnet_id, AllocationId=allocation_id
)
nat_gateway_id = create_response["NatGateway"]["NatGatewayId"]
describe_response = conn.describe_nat_gateways(
Filters=[
{"Name": "nat-gateway-id", "Values": ["non-existent-id"]},
{"Name": "state", "Values": ["available"]},
]
)
describe_response["NatGateways"].should.have.length_of(0)
describe_response = conn.describe_nat_gateways(
Filters=[
{"Name": "nat-gateway-id", "Values": [nat_gateway_id]},
{"Name": "state", "Values": ["available"]},
]
)
describe_response["NatGateways"].should.have.length_of(1)
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)
@mock_ec2
def test_describe_nat_gateway_filter_by_subnet_id():
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id = vpc["Vpc"]["VpcId"]
subnet_1 = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
subnet_2 = conn.create_subnet(
VpcId=vpc_id, CidrBlock="10.0.2.0/27", AvailabilityZone="us-east-1a"
)
allocation_id_1 = conn.allocate_address(Domain="vpc")["AllocationId"]
allocation_id_2 = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id_1 = subnet_1["Subnet"]["SubnetId"]
subnet_id_2 = subnet_2["Subnet"]["SubnetId"]
create_response_1 = conn.create_nat_gateway(
SubnetId=subnet_id_1, AllocationId=allocation_id_1
)
# create_response_2 =
conn.create_nat_gateway(SubnetId=subnet_id_2, AllocationId=allocation_id_2)
nat_gateway_id_1 = create_response_1["NatGateway"]["NatGatewayId"]
# nat_gateway_id_2 = create_response_2["NatGateway"]["NatGatewayId"]
describe_response = conn.describe_nat_gateways()
describe_response["NatGateways"].should.have.length_of(2)
describe_response = conn.describe_nat_gateways(
Filters=[{"Name": "subnet-id", "Values": [subnet_id_1]}]
)
describe_response["NatGateways"].should.have.length_of(1)
describe_response["NatGateways"][0]["NatGatewayId"].should.equal(nat_gateway_id_1)
describe_response["NatGateways"][0]["State"].should.equal("available")
describe_response["NatGateways"][0]["SubnetId"].should.equal(subnet_id_1)
describe_response["NatGateways"][0]["VpcId"].should.equal(vpc_id)
describe_response["NatGateways"][0]["NatGatewayAddresses"][0][
"AllocationId"
].should.equal(allocation_id_1)
@mock_ec2
def test_describe_nat_gateway_filter_vpc_id():
conn = boto3.client("ec2", "us-east-1")
vpc_1 = conn.create_vpc(CidrBlock="10.0.0.0/16")
vpc_id_1 = vpc_1["Vpc"]["VpcId"]
vpc_2 = conn.create_vpc(CidrBlock="10.1.0.0/16")
vpc_id_2 = vpc_2["Vpc"]["VpcId"]
subnet_1 = conn.create_subnet(
VpcId=vpc_id_1, CidrBlock="10.0.1.0/27", AvailabilityZone="us-east-1a"
)
subnet_2 = conn.create_subnet(
VpcId=vpc_id_2, CidrBlock="10.1.1.0/27", AvailabilityZone="us-east-1a"
)
allocation_id_1 = conn.allocate_address(Domain="vpc")["AllocationId"]
allocation_id_2 = conn.allocate_address(Domain="vpc")["AllocationId"]
subnet_id_1 = subnet_1["Subnet"]["SubnetId"]
subnet_id_2 = subnet_2["Subnet"]["SubnetId"]
create_response_1 = conn.create_nat_gateway(
SubnetId=subnet_id_1, AllocationId=allocation_id_1
)
conn.create_nat_gateway(SubnetId=subnet_id_2, AllocationId=allocation_id_2)
nat_gateway_id_1 = create_response_1["NatGateway"]["NatGatewayId"]
describe_response = conn.describe_nat_gateways()
describe_response["NatGateways"].should.have.length_of(2)
describe_response = conn.describe_nat_gateways(
Filters=[{"Name": "vpc-id", "Values": [vpc_id_1]}]
)
describe_response["NatGateways"].should.have.length_of(1)
describe_response["NatGateways"][0]["NatGatewayId"].should.equal(nat_gateway_id_1)
describe_response["NatGateways"][0]["State"].should.equal("available")
describe_response["NatGateways"][0]["SubnetId"].should.equal(subnet_id_1)
describe_response["NatGateways"][0]["VpcId"].should.equal(vpc_id_1)
describe_response["NatGateways"][0]["NatGatewayAddresses"][0][
"AllocationId"
].should.equal(allocation_id_1)

View file

@ -10,7 +10,7 @@ from moto import mock_ec2_deprecated, mock_ec2
@mock_ec2_deprecated
def test_default_network_acl_created_with_vpc():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
all_network_acls = conn.get_all_network_acls()
all_network_acls.should.have.length_of(2)
@ -18,7 +18,7 @@ def test_default_network_acl_created_with_vpc():
@mock_ec2_deprecated
def test_network_acls():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
network_acl = conn.create_network_acl(vpc.id)
all_network_acls = conn.get_all_network_acls()
@ -27,7 +27,7 @@ def test_network_acls():
@mock_ec2_deprecated
def test_new_subnet_associates_with_default_network_acl():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.get_all_vpcs()[0]
subnet = conn.create_subnet(vpc.id, "172.31.112.0/20")
@ -41,88 +41,100 @@ def test_new_subnet_associates_with_default_network_acl():
@mock_ec2_deprecated
def test_network_acl_entries():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
network_acl = conn.create_network_acl(vpc.id)
network_acl_entry = conn.create_network_acl_entry(
network_acl.id, 110, 6,
'ALLOW', '0.0.0.0/0', False,
port_range_from='443',
port_range_to='443'
network_acl.id,
110,
6,
"ALLOW",
"0.0.0.0/0",
False,
port_range_from="443",
port_range_to="443",
)
all_network_acls = conn.get_all_network_acls()
all_network_acls.should.have.length_of(3)
test_network_acl = next(na for na in all_network_acls
if na.id == network_acl.id)
test_network_acl = next(na for na in all_network_acls if na.id == network_acl.id)
entries = test_network_acl.network_acl_entries
entries.should.have.length_of(1)
entries[0].rule_number.should.equal('110')
entries[0].protocol.should.equal('6')
entries[0].rule_action.should.equal('ALLOW')
entries[0].rule_number.should.equal("110")
entries[0].protocol.should.equal("6")
entries[0].rule_action.should.equal("ALLOW")
@mock_ec2_deprecated
def test_delete_network_acl_entry():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
network_acl = conn.create_network_acl(vpc.id)
conn.create_network_acl_entry(
network_acl.id, 110, 6,
'ALLOW', '0.0.0.0/0', False,
port_range_from='443',
port_range_to='443'
)
conn.delete_network_acl_entry(
network_acl.id, 110, False
network_acl.id,
110,
6,
"ALLOW",
"0.0.0.0/0",
False,
port_range_from="443",
port_range_to="443",
)
conn.delete_network_acl_entry(network_acl.id, 110, False)
all_network_acls = conn.get_all_network_acls()
test_network_acl = next(na for na in all_network_acls
if na.id == network_acl.id)
test_network_acl = next(na for na in all_network_acls if na.id == network_acl.id)
entries = test_network_acl.network_acl_entries
entries.should.have.length_of(0)
@mock_ec2_deprecated
def test_replace_network_acl_entry():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
network_acl = conn.create_network_acl(vpc.id)
conn.create_network_acl_entry(
network_acl.id, 110, 6,
'ALLOW', '0.0.0.0/0', False,
port_range_from='443',
port_range_to='443'
network_acl.id,
110,
6,
"ALLOW",
"0.0.0.0/0",
False,
port_range_from="443",
port_range_to="443",
)
conn.replace_network_acl_entry(
network_acl.id, 110, -1,
'DENY', '0.0.0.0/0', False,
port_range_from='22',
port_range_to='22'
network_acl.id,
110,
-1,
"DENY",
"0.0.0.0/0",
False,
port_range_from="22",
port_range_to="22",
)
all_network_acls = conn.get_all_network_acls()
test_network_acl = next(na for na in all_network_acls
if na.id == network_acl.id)
test_network_acl = next(na for na in all_network_acls if na.id == network_acl.id)
entries = test_network_acl.network_acl_entries
entries.should.have.length_of(1)
entries[0].rule_number.should.equal('110')
entries[0].protocol.should.equal('-1')
entries[0].rule_action.should.equal('DENY')
entries[0].rule_number.should.equal("110")
entries[0].protocol.should.equal("-1")
entries[0].rule_action.should.equal("DENY")
@mock_ec2_deprecated
def test_associate_new_network_acl_with_subnet():
conn = boto.connect_vpc('the_key', 'the secret')
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")
network_acl = conn.create_network_acl(vpc.id)
@ -132,8 +144,7 @@ def test_associate_new_network_acl_with_subnet():
all_network_acls = conn.get_all_network_acls()
all_network_acls.should.have.length_of(3)
test_network_acl = next(na for na in all_network_acls
if na.id == network_acl.id)
test_network_acl = next(na for na in all_network_acls if na.id == network_acl.id)
test_network_acl.associations.should.have.length_of(1)
test_network_acl.associations[0].subnet_id.should.equal(subnet.id)
@ -141,7 +152,7 @@ def test_associate_new_network_acl_with_subnet():
@mock_ec2_deprecated
def test_delete_network_acl():
conn = boto.connect_vpc('the_key', 'the secret')
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")
network_acl = conn.create_network_acl(vpc.id)
@ -161,7 +172,7 @@ def test_delete_network_acl():
@mock_ec2_deprecated
def test_network_acl_tagging():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
network_acl = conn.create_network_acl(vpc.id)
@ -172,46 +183,45 @@ def test_network_acl_tagging():
tag.value.should.equal("some value")
all_network_acls = conn.get_all_network_acls()
test_network_acl = next(na for na in all_network_acls
if na.id == network_acl.id)
test_network_acl = next(na for na in all_network_acls if na.id == network_acl.id)
test_network_acl.tags.should.have.length_of(1)
test_network_acl.tags["a key"].should.equal("some value")
@mock_ec2
def test_new_subnet_in_new_vpc_associates_with_default_network_acl():
ec2 = boto3.resource('ec2', region_name='us-west-1')
new_vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
ec2 = boto3.resource("ec2", region_name="us-west-1")
new_vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
new_vpc.reload()
subnet = ec2.create_subnet(VpcId=new_vpc.id, CidrBlock='10.0.0.0/24')
subnet = ec2.create_subnet(VpcId=new_vpc.id, CidrBlock="10.0.0.0/24")
subnet.reload()
new_vpcs_default_network_acl = next(iter(new_vpc.network_acls.all()), None)
new_vpcs_default_network_acl.reload()
new_vpcs_default_network_acl.vpc_id.should.equal(new_vpc.id)
new_vpcs_default_network_acl.associations.should.have.length_of(1)
new_vpcs_default_network_acl.associations[0]['SubnetId'].should.equal(subnet.id)
new_vpcs_default_network_acl.associations[0]["SubnetId"].should.equal(subnet.id)
@mock_ec2
def test_default_network_acl_default_entries():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
default_network_acl = next(iter(ec2.network_acls.all()), None)
default_network_acl.is_default.should.be.ok
default_network_acl.entries.should.have.length_of(4)
unique_entries = []
for entry in default_network_acl.entries:
entry['CidrBlock'].should.equal('0.0.0.0/0')
entry['Protocol'].should.equal('-1')
entry['RuleNumber'].should.be.within([100, 32767])
entry['RuleAction'].should.be.within(['allow', 'deny'])
assert type(entry['Egress']) is bool
if entry['RuleAction'] == 'allow':
entry['RuleNumber'].should.be.equal(100)
entry["CidrBlock"].should.equal("0.0.0.0/0")
entry["Protocol"].should.equal("-1")
entry["RuleNumber"].should.be.within([100, 32767])
entry["RuleAction"].should.be.within(["allow", "deny"])
assert type(entry["Egress"]) is bool
if entry["RuleAction"] == "allow":
entry["RuleNumber"].should.be.equal(100)
else:
entry['RuleNumber'].should.be.equal(32767)
entry["RuleNumber"].should.be.equal(32767)
if entry not in unique_entries:
unique_entries.append(entry)
@ -220,33 +230,48 @@ def test_default_network_acl_default_entries():
@mock_ec2
def test_delete_default_network_acl_default_entry():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
default_network_acl = next(iter(ec2.network_acls.all()), None)
default_network_acl.is_default.should.be.ok
default_network_acl.entries.should.have.length_of(4)
first_default_network_acl_entry = default_network_acl.entries[0]
default_network_acl.delete_entry(Egress=first_default_network_acl_entry['Egress'],
RuleNumber=first_default_network_acl_entry['RuleNumber'])
default_network_acl.delete_entry(
Egress=first_default_network_acl_entry["Egress"],
RuleNumber=first_default_network_acl_entry["RuleNumber"],
)
default_network_acl.entries.should.have.length_of(3)
@mock_ec2
def test_duplicate_network_acl_entry():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
default_network_acl = next(iter(ec2.network_acls.all()), None)
default_network_acl.is_default.should.be.ok
rule_number = 200
egress = True
default_network_acl.create_entry(CidrBlock="0.0.0.0/0", Egress=egress, Protocol="-1", RuleAction="allow", RuleNumber=rule_number)
default_network_acl.create_entry(
CidrBlock="0.0.0.0/0",
Egress=egress,
Protocol="-1",
RuleAction="allow",
RuleNumber=rule_number,
)
with assert_raises(ClientError) as ex:
default_network_acl.create_entry(CidrBlock="10.0.0.0/0", Egress=egress, Protocol="-1", RuleAction="deny", RuleNumber=rule_number)
default_network_acl.create_entry(
CidrBlock="10.0.0.0/0",
Egress=egress,
Protocol="-1",
RuleAction="deny",
RuleNumber=rule_number,
)
str(ex.exception).should.equal(
"An error occurred (NetworkAclEntryAlreadyExists) when calling the CreateNetworkAclEntry "
"operation: The network acl entry identified by {} already exists.".format(rule_number))
"operation: The network acl entry identified by {} already exists.".format(
rule_number
)
)

View file

@ -7,38 +7,41 @@ from moto import mock_ec2_deprecated, mock_autoscaling_deprecated, mock_elb_depr
from moto.ec2 import ec2_backends
def test_use_boto_regions():
boto_regions = {r.name for r in boto.ec2.regions()}
moto_regions = set(ec2_backends)
moto_regions.should.equal(boto_regions)
def add_servers_to_region(ami_id, count, region):
conn = boto.ec2.connect_to_region(region)
for index in range(count):
conn.run_instances(ami_id)
@mock_ec2_deprecated
def test_add_servers_to_a_single_region():
region = 'ap-northeast-1'
add_servers_to_region('ami-1234abcd', 1, region)
add_servers_to_region('ami-5678efgh', 1, region)
region = "ap-northeast-1"
add_servers_to_region("ami-1234abcd", 1, region)
add_servers_to_region("ami-5678efgh", 1, region)
conn = boto.ec2.connect_to_region(region)
reservations = conn.get_all_instances()
len(reservations).should.equal(2)
reservations.sort(key=lambda x: x.instances[0].image_id)
reservations[0].instances[0].image_id.should.equal('ami-1234abcd')
reservations[1].instances[0].image_id.should.equal('ami-5678efgh')
reservations[0].instances[0].image_id.should.equal("ami-1234abcd")
reservations[1].instances[0].image_id.should.equal("ami-5678efgh")
@mock_ec2_deprecated
def test_add_servers_to_multiple_regions():
region1 = 'us-east-1'
region2 = 'ap-northeast-1'
add_servers_to_region('ami-1234abcd', 1, region1)
add_servers_to_region('ami-5678efgh', 1, region2)
region1 = "us-east-1"
region2 = "ap-northeast-1"
add_servers_to_region("ami-1234abcd", 1, region1)
add_servers_to_region("ami-5678efgh", 1, region2)
us_conn = boto.ec2.connect_to_region(region1)
ap_conn = boto.ec2.connect_to_region(region2)
@ -48,33 +51,35 @@ def test_add_servers_to_multiple_regions():
len(us_reservations).should.equal(1)
len(ap_reservations).should.equal(1)
us_reservations[0].instances[0].image_id.should.equal('ami-1234abcd')
ap_reservations[0].instances[0].image_id.should.equal('ami-5678efgh')
us_reservations[0].instances[0].image_id.should.equal("ami-1234abcd")
ap_reservations[0].instances[0].image_id.should.equal("ami-5678efgh")
@mock_autoscaling_deprecated
@mock_elb_deprecated
def test_create_autoscaling_group():
elb_conn = boto.ec2.elb.connect_to_region('us-east-1')
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 = boto.ec2.elb.connect_to_region('ap-northeast-1')
"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')])
"ap_test_lb", zones=[], listeners=[(80, 8080, "http")]
)
us_conn = boto.ec2.autoscale.connect_to_region('us-east-1')
us_conn = boto.ec2.autoscale.connect_to_region("us-east-1")
config = boto.ec2.autoscale.LaunchConfiguration(
name='us_tester',
image_id='ami-abcd1234',
instance_type='m1.small',
name="us_tester", image_id="ami-abcd1234", instance_type="m1.small"
)
x = us_conn.create_launch_configuration(config)
us_subnet_id = list(ec2_backends['us-east-1'].subnets['us-east-1c'].keys())[0]
ap_subnet_id = list(ec2_backends['ap-northeast-1'].subnets['ap-northeast-1a'].keys())[0]
us_subnet_id = list(ec2_backends["us-east-1"].subnets["us-east-1c"].keys())[0]
ap_subnet_id = list(
ec2_backends["ap-northeast-1"].subnets["ap-northeast-1a"].keys()
)[0]
group = boto.ec2.autoscale.AutoScalingGroup(
name='us_tester_group',
availability_zones=['us-east-1c'],
name="us_tester_group",
availability_zones=["us-east-1c"],
default_cooldown=60,
desired_capacity=2,
health_check_period=100,
@ -89,17 +94,15 @@ def test_create_autoscaling_group():
)
us_conn.create_auto_scaling_group(group)
ap_conn = boto.ec2.autoscale.connect_to_region('ap-northeast-1')
ap_conn = boto.ec2.autoscale.connect_to_region("ap-northeast-1")
config = boto.ec2.autoscale.LaunchConfiguration(
name='ap_tester',
image_id='ami-efgh5678',
instance_type='m1.small',
name="ap_tester", image_id="ami-efgh5678", instance_type="m1.small"
)
ap_conn.create_launch_configuration(config)
group = boto.ec2.autoscale.AutoScalingGroup(
name='ap_tester_group',
availability_zones=['ap-northeast-1a'],
name="ap_tester_group",
availability_zones=["ap-northeast-1a"],
default_cooldown=60,
desired_capacity=2,
health_check_period=100,
@ -118,33 +121,35 @@ def test_create_autoscaling_group():
len(ap_conn.get_all_groups()).should.equal(1)
us_group = us_conn.get_all_groups()[0]
us_group.name.should.equal('us_tester_group')
list(us_group.availability_zones).should.equal(['us-east-1c'])
us_group.name.should.equal("us_tester_group")
list(us_group.availability_zones).should.equal(["us-east-1c"])
us_group.desired_capacity.should.equal(2)
us_group.max_size.should.equal(2)
us_group.min_size.should.equal(2)
us_group.vpc_zone_identifier.should.equal(us_subnet_id)
us_group.launch_config_name.should.equal('us_tester')
us_group.launch_config_name.should.equal("us_tester")
us_group.default_cooldown.should.equal(60)
us_group.health_check_period.should.equal(100)
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"])
["OldestInstance", "NewestInstance"]
)
ap_group = ap_conn.get_all_groups()[0]
ap_group.name.should.equal('ap_tester_group')
list(ap_group.availability_zones).should.equal(['ap-northeast-1a'])
ap_group.name.should.equal("ap_tester_group")
list(ap_group.availability_zones).should.equal(["ap-northeast-1a"])
ap_group.desired_capacity.should.equal(2)
ap_group.max_size.should.equal(2)
ap_group.min_size.should.equal(2)
ap_group.vpc_zone_identifier.should.equal(ap_subnet_id)
ap_group.launch_config_name.should.equal('ap_tester')
ap_group.launch_config_name.should.equal("ap_tester")
ap_group.default_cooldown.should.equal(60)
ap_group.health_check_period.should.equal(100)
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"])
["OldestInstance", "NewestInstance"]
)

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
@ -15,10 +16,10 @@ from tests.helpers import requires_boto_gte
@mock_ec2_deprecated
def test_route_tables_defaults():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id})
all_route_tables = conn.get_all_route_tables(filters={"vpc-id": vpc.id})
all_route_tables.should.have.length_of(1)
main_route_table = all_route_tables[0]
@ -28,23 +29,23 @@ def test_route_tables_defaults():
routes.should.have.length_of(1)
local_route = routes[0]
local_route.gateway_id.should.equal('local')
local_route.state.should.equal('active')
local_route.gateway_id.should.equal("local")
local_route.state.should.equal("active")
local_route.destination_cidr_block.should.equal(vpc.cidr_block)
vpc.delete()
all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id})
all_route_tables = conn.get_all_route_tables(filters={"vpc-id": vpc.id})
all_route_tables.should.have.length_of(0)
@mock_ec2_deprecated
def test_route_tables_additional():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
route_table = conn.create_route_table(vpc.id)
all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id})
all_route_tables = conn.get_all_route_tables(filters={"vpc-id": vpc.id})
all_route_tables.should.have.length_of(2)
all_route_tables[0].vpc_id.should.equal(vpc.id)
all_route_tables[1].vpc_id.should.equal(vpc.id)
@ -56,31 +57,31 @@ def test_route_tables_additional():
routes.should.have.length_of(1)
local_route = routes[0]
local_route.gateway_id.should.equal('local')
local_route.state.should.equal('active')
local_route.gateway_id.should.equal("local")
local_route.state.should.equal("active")
local_route.destination_cidr_block.should.equal(vpc.cidr_block)
with assert_raises(EC2ResponseError) as cm:
conn.delete_vpc(vpc.id)
cm.exception.code.should.equal('DependencyViolation')
cm.exception.code.should.equal("DependencyViolation")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
conn.delete_route_table(route_table.id)
all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id})
all_route_tables = conn.get_all_route_tables(filters={"vpc-id": vpc.id})
all_route_tables.should.have.length_of(1)
with assert_raises(EC2ResponseError) as cm:
conn.delete_route_table("rtb-1234abcd")
cm.exception.code.should.equal('InvalidRouteTableID.NotFound')
cm.exception.code.should.equal("InvalidRouteTableID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_route_tables_filters_standard():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc1 = conn.create_vpc("10.0.0.0/16")
route_table1 = conn.create_route_table(vpc1.id)
@ -92,39 +93,39 @@ 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})
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]
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)
filters={"not-implemented-filter": "foobar"}
).should.throw(NotImplementedError)
@mock_ec2_deprecated
def test_route_tables_filters_associations():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
subnet1 = conn.create_subnet(vpc.id, "10.0.0.0/24")
@ -142,21 +143,24 @@ def test_route_tables_filters_associations():
# Filter by association ID
association1_route_tables = conn.get_all_route_tables(
filters={'association.route-table-association-id': association_id1})
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})
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})
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)
@ -164,7 +168,7 @@ def test_route_tables_filters_associations():
@mock_ec2_deprecated
def test_route_table_associations():
conn = boto.connect_vpc('the_key', 'the_secret')
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")
route_table = conn.create_route_table(vpc.id)
@ -189,14 +193,13 @@ 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.
with assert_raises(EC2ResponseError) as cm:
conn.delete_route_table(route_table.id)
cm.exception.code.should.equal('DependencyViolation')
cm.exception.code.should.equal("DependencyViolation")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -210,21 +213,21 @@ def test_route_table_associations():
# Error: Disassociate with invalid association ID
with assert_raises(EC2ResponseError) as cm:
conn.disassociate_route_table(association_id)
cm.exception.code.should.equal('InvalidAssociationID.NotFound')
cm.exception.code.should.equal("InvalidAssociationID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
# Error: Associate with invalid subnet ID
with assert_raises(EC2ResponseError) as cm:
conn.associate_route_table(route_table.id, "subnet-1234abcd")
cm.exception.code.should.equal('InvalidSubnetID.NotFound')
cm.exception.code.should.equal("InvalidSubnetID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
# Error: Associate with invalid route table ID
with assert_raises(EC2ResponseError) as cm:
conn.associate_route_table("rtb-1234abcd", subnet.id)
cm.exception.code.should.equal('InvalidRouteTableID.NotFound')
cm.exception.code.should.equal("InvalidRouteTableID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -236,7 +239,7 @@ def test_route_table_replace_route_table_association():
Note: Boto has deprecated replace_route_table_assocation (which returns status)
and now uses replace_route_table_assocation_with_assoc (which returns association ID).
"""
conn = boto.connect_vpc('the_key', 'the_secret')
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")
route_table1 = conn.create_route_table(vpc.id)
@ -267,7 +270,8 @@ def test_route_table_replace_route_table_association():
# Replace Association
association_id2 = conn.replace_route_table_association_with_assoc(
association_id1, route_table2.id)
association_id1, route_table2.id
)
# Refresh
route_table1 = conn.get_all_route_tables(route_table1.id)[0]
@ -284,120 +288,128 @@ def test_route_table_replace_route_table_association():
# Replace Association is idempotent
association_id_idempotent = conn.replace_route_table_association_with_assoc(
association_id2, route_table2.id)
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)
cm.exception.code.should.equal('InvalidAssociationID.NotFound')
"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")
cm.exception.code.should.equal('InvalidRouteTableID.NotFound')
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
@mock_ec2_deprecated
def test_route_table_get_by_tag():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc('10.0.0.0/16')
vpc = conn.create_vpc("10.0.0.0/16")
route_table = conn.create_route_table(vpc.id)
route_table.add_tag('Name', 'TestRouteTable')
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)
route_tables[0].id.should.equal(route_table.id)
route_tables[0].tags.should.have.length_of(1)
route_tables[0].tags['Name'].should.equal('TestRouteTable')
route_tables[0].tags["Name"].should.equal("TestRouteTable")
@mock_ec2
def test_route_table_get_by_tag_boto3():
ec2 = boto3.resource('ec2', region_name='eu-central-1')
ec2 = boto3.resource("ec2", region_name="eu-central-1")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
route_table = ec2.create_route_table(VpcId=vpc.id)
route_table.create_tags(Tags=[{'Key': 'Name', 'Value': 'TestRouteTable'}])
route_table.create_tags(Tags=[{"Key": "Name", "Value": "TestRouteTable"}])
filters = [{'Name': 'tag:Name', 'Values': ['TestRouteTable']}]
filters = [{"Name": "tag:Name", "Values": ["TestRouteTable"]}]
route_tables = list(ec2.route_tables.filter(Filters=filters))
route_tables.should.have.length_of(1)
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
def test_routes_additional():
conn = boto.connect_vpc('the_key', 'the_secret')
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={'vpc-id': vpc.id})[0]
main_route_table = conn.get_all_route_tables(filters={"vpc-id": vpc.id})[0]
local_route = main_route_table.routes[0]
igw = conn.create_internet_gateway()
ROUTE_CIDR = "10.0.0.4/24"
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]
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]
new_route.gateway_id.should.equal(igw.id)
new_route.instance_id.should.be.none
new_route.state.should.equal('active')
new_route.state.should.equal("active")
new_route.destination_cidr_block.should.equal(ROUTE_CIDR)
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]
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:
conn.delete_route(main_route_table.id, ROUTE_CIDR)
cm.exception.code.should.equal('InvalidRoute.NotFound')
cm.exception.code.should.equal("InvalidRoute.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_routes_replace():
conn = boto.connect_vpc('the_key', 'the_secret')
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]
filters={"association.main": "true", "vpc-id": vpc.id}
)[0]
local_route = main_route_table.routes[0]
ROUTE_CIDR = "10.0.0.4/24"
# Various route targets
igw = conn.create_internet_gateway()
reservation = conn.run_instances('ami-1234abcd')
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
# Create initial route
@ -407,17 +419,19 @@ def test_routes_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]
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
target_route.instance_id.should.equal(instance.id)
target_route.state.should.equal('active')
target_route.state.should.equal("active")
target_route.destination_cidr_block.should.equal(ROUTE_CIDR)
conn.replace_route(main_route_table.id, ROUTE_CIDR, gateway_id=igw.id)
@ -425,12 +439,12 @@ def test_routes_replace():
target_route = get_target_route()
target_route.gateway_id.should.equal(igw.id)
target_route.instance_id.should.be.none
target_route.state.should.equal('active')
target_route.state.should.equal("active")
target_route.destination_cidr_block.should.equal(ROUTE_CIDR)
with assert_raises(EC2ResponseError) as cm:
conn.replace_route('rtb-1234abcd', ROUTE_CIDR, gateway_id=igw.id)
cm.exception.code.should.equal('InvalidRouteTableID.NotFound')
conn.replace_route("rtb-1234abcd", ROUTE_CIDR, gateway_id=igw.id)
cm.exception.code.should.equal("InvalidRouteTableID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -438,7 +452,7 @@ def test_routes_replace():
@requires_boto_gte("2.19.0")
@mock_ec2_deprecated
def test_routes_not_supported():
conn = boto.connect_vpc('the_key', 'the_secret')
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()[0]
local_route = main_route_table.routes[0]
@ -447,42 +461,49 @@ def test_routes_not_supported():
# Create
conn.create_route.when.called_with(
main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError)
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)
main_route_table.id, ROUTE_CIDR, interface_id="eni-1234abcd"
).should.throw(NotImplementedError)
@requires_boto_gte("2.34.0")
@mock_ec2_deprecated
def test_routes_vpc_peering_connection():
conn = boto.connect_vpc('the_key', 'the_secret')
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]
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]
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]
new_route.gateway_id.should.be.none
new_route.instance_id.should.be.none
new_route.vpc_peering_connection_id.should.equal(vpc_pcx.id)
new_route.state.should.equal('blackhole')
new_route.state.should.equal("blackhole")
new_route.destination_cidr_block.should.equal(ROUTE_CIDR)
@ -490,10 +511,11 @@ def test_routes_vpc_peering_connection():
@mock_ec2_deprecated
def test_routes_vpn_gateway():
conn = boto.connect_vpc('the_key', 'the_secret')
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]
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")
@ -502,7 +524,10 @@ def test_routes_vpn_gateway():
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]
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]
@ -514,7 +539,7 @@ def test_routes_vpn_gateway():
@mock_ec2_deprecated
def test_network_acl_tagging():
conn = boto.connect_vpc('the_key', 'the secret')
conn = boto.connect_vpc("the_key", "the secret")
vpc = conn.create_vpc("10.0.0.0/16")
route_table = conn.create_route_table(vpc.id)
@ -525,17 +550,16 @@ def test_network_acl_tagging():
tag.value.should.equal("some value")
all_route_tables = conn.get_all_route_tables()
test_route_table = next(na for na in all_route_tables
if na.id == route_table.id)
test_route_table = next(na for na in all_route_tables if na.id == route_table.id)
test_route_table.tags.should.have.length_of(1)
test_route_table.tags["a key"].should.equal("some value")
@mock_ec2
def test_create_route_with_invalid_destination_cidr_block_parameter():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc.reload()
vpc.is_default.shouldnt.be.ok
@ -546,9 +570,51 @@ def test_create_route_with_invalid_destination_cidr_block_parameter():
vpc.attach_internet_gateway(InternetGatewayId=internet_gateway.id)
internet_gateway.reload()
destination_cidr_block = '1000.1.0.0/20'
destination_cidr_block = "1000.1.0.0/20"
with assert_raises(ClientError) as ex:
route = route_table.create_route(DestinationCidrBlock=destination_cidr_block, GatewayId=internet_gateway.id)
route = route_table.create_route(
DestinationCidrBlock=destination_cidr_block, GatewayId=internet_gateway.id
)
str(ex.exception).should.equal(
"An error occurred (InvalidParameterValue) when calling the CreateRoute "
"operation: Value ({}) for parameter destinationCidrBlock is invalid. This is not a valid CIDR block.".format(destination_cidr_block))
"operation: Value ({}) for parameter destinationCidrBlock is invalid. This is not a valid CIDR block.".format(
destination_cidr_block
)
)
@mock_ec2
def test_describe_route_tables_with_nat_gateway():
ec2 = boto3.client("ec2", region_name="us-west-1")
vpc_id = ec2.create_vpc(CidrBlock="192.168.0.0/23")["Vpc"]["VpcId"]
igw_id = ec2.create_internet_gateway()["InternetGateway"]["InternetGatewayId"]
ec2.attach_internet_gateway(VpcId=vpc_id, InternetGatewayId=igw_id)
az = ec2.describe_availability_zones()["AvailabilityZones"][0]["ZoneName"]
sn_id = ec2.create_subnet(
AvailabilityZone=az, CidrBlock="192.168.0.0/24", VpcId=vpc_id
)["Subnet"]["SubnetId"]
route_table_id = ec2.create_route_table(VpcId=vpc_id)["RouteTable"]["RouteTableId"]
ec2.associate_route_table(SubnetId=sn_id, RouteTableId=route_table_id)
alloc_id = ec2.allocate_address(Domain="vpc")["AllocationId"]
nat_gw_id = ec2.create_nat_gateway(SubnetId=sn_id, AllocationId=alloc_id)[
"NatGateway"
]["NatGatewayId"]
ec2.create_route(
DestinationCidrBlock="0.0.0.0/0",
NatGatewayId=nat_gw_id,
RouteTableId=route_table_id,
)
route_table = ec2.describe_route_tables(
Filters=[{"Name": "route-table-id", "Values": [route_table_id]}]
)["RouteTables"][0]
nat_gw_routes = [
route
for route in route_table["Routes"]
if route["DestinationCidrBlock"] == "0.0.0.0/0"
]
nat_gw_routes.should.have.length_of(1)
nat_gw_routes[0]["DestinationCidrBlock"].should.equal("0.0.0.0/0")
nat_gw_routes[0]["NatGatewayId"].should.equal(nat_gw_id)
nat_gw_routes[0]["State"].should.equal("active")

File diff suppressed because it is too large Load diff

View file

@ -1,26 +1,25 @@
from __future__ import unicode_literals
import re
import sure # noqa
import moto.server as server
'''
Test the different server responses
'''
def test_ec2_server_get():
backend = server.create_backend_app("ec2")
test_client = backend.test_client()
res = test_client.get(
'/?Action=RunInstances&ImageId=ami-60a54009',
headers={"Host": "ec2.us-east-1.amazonaws.com"}
)
groups = re.search("<instanceId>(.*)</instanceId>",
res.data.decode('utf-8'))
instance_id = groups.groups()[0]
res = test_client.get('/?Action=DescribeInstances')
res.data.decode('utf-8').should.contain(instance_id)
from __future__ import unicode_literals
import re
import sure # noqa
import moto.server as server
"""
Test the different server responses
"""
def test_ec2_server_get():
backend = server.create_backend_app("ec2")
test_client = backend.test_client()
res = test_client.get(
"/?Action=RunInstances&ImageId=ami-60a54009",
headers={"Host": "ec2.us-east-1.amazonaws.com"},
)
groups = re.search("<instanceId>(.*)</instanceId>", res.data.decode("utf-8"))
instance_id = groups.groups()[0]
res = test_client.get("/?Action=DescribeInstances")
res.data.decode("utf-8").should.contain(instance_id)

View file

@ -4,384 +4,376 @@ import boto3
import sure # noqa
from moto import mock_ec2
from moto.core import ACCOUNT_ID
def get_subnet_id(conn):
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")['Vpc']
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]
subnet = conn.create_subnet(
VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
subnet_id = subnet['SubnetId']
VpcId=vpc["VpcId"], CidrBlock="10.0.0.0/16", AvailabilityZone="us-east-1a"
)["Subnet"]
subnet_id = subnet["SubnetId"]
return subnet_id
def spot_config(subnet_id, allocation_strategy="lowestPrice"):
return {
'ClientToken': 'string',
'SpotPrice': '0.12',
'TargetCapacity': 6,
'IamFleetRole': 'arn:aws:iam::123456789012:role/fleet',
'LaunchSpecifications': [{
'ImageId': 'ami-123',
'KeyName': 'my-key',
'SecurityGroups': [
{
'GroupId': 'sg-123'
},
],
'UserData': 'some user data',
'InstanceType': 't2.small',
'BlockDeviceMappings': [
{
'VirtualName': 'string',
'DeviceName': 'string',
'Ebs': {
'SnapshotId': 'string',
'VolumeSize': 123,
'DeleteOnTermination': True | False,
'VolumeType': 'standard',
'Iops': 123,
'Encrypted': True | False
"ClientToken": "string",
"SpotPrice": "0.12",
"TargetCapacity": 6,
"IamFleetRole": "arn:aws:iam::{}:role/fleet".format(ACCOUNT_ID),
"LaunchSpecifications": [
{
"ImageId": "ami-123",
"KeyName": "my-key",
"SecurityGroups": [{"GroupId": "sg-123"}],
"UserData": "some user data",
"InstanceType": "t2.small",
"BlockDeviceMappings": [
{
"VirtualName": "string",
"DeviceName": "string",
"Ebs": {
"SnapshotId": "string",
"VolumeSize": 123,
"DeleteOnTermination": True | False,
"VolumeType": "standard",
"Iops": 123,
"Encrypted": True | False,
},
'NoDevice': 'string'
"NoDevice": "string",
}
],
"Monitoring": {"Enabled": True},
"SubnetId": subnet_id,
"IamInstanceProfile": {
"Arn": "arn:aws:iam::{}:role/fleet".format(ACCOUNT_ID)
},
],
'Monitoring': {
'Enabled': True
"EbsOptimized": False,
"WeightedCapacity": 2.0,
"SpotPrice": "0.13",
},
'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'
{
"ImageId": "ami-123",
"KeyName": "my-key",
"SecurityGroups": [{"GroupId": "sg-123"}],
"UserData": "some user data",
"InstanceType": "t2.large",
"Monitoring": {"Enabled": True},
"SubnetId": subnet_id,
"IamInstanceProfile": {
"Arn": "arn:aws:iam::{}:role/fleet".format(ACCOUNT_ID)
},
],
'UserData': 'some user data',
'InstanceType': 't2.large',
'Monitoring': {
'Enabled': True
"EbsOptimized": False,
"WeightedCapacity": 4.0,
"SpotPrice": "10.00",
},
'SubnetId': subnet_id,
'IamInstanceProfile': {
'Arn': 'arn:aws:iam::123456789012:role/fleet'
},
'EbsOptimized': False,
'WeightedCapacity': 4.0,
'SpotPrice': '10.00',
}],
'AllocationStrategy': allocation_strategy,
'FulfilledCapacity': 6,
],
"AllocationStrategy": allocation_strategy,
"FulfilledCapacity": 6,
}
@mock_ec2
def test_create_spot_fleet_with_lowest_price():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
spot_fleet_requests = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
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")
spot_fleet_config = spot_fleet_request['SpotFleetRequestConfig']
spot_fleet_request["SpotFleetRequestState"].should.equal("active")
spot_fleet_config = spot_fleet_request["SpotFleetRequestConfig"]
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['AllocationStrategy'].should.equal('lowestPrice')
spot_fleet_config['FulfilledCapacity'].should.equal(6.0)
spot_fleet_config["SpotPrice"].should.equal("0.12")
spot_fleet_config["TargetCapacity"].should.equal(6)
spot_fleet_config["IamFleetRole"].should.equal(
"arn:aws:iam::{}:role/fleet".format(ACCOUNT_ID)
)
spot_fleet_config["AllocationStrategy"].should.equal("lowestPrice")
spot_fleet_config["FulfilledCapacity"].should.equal(6.0)
len(spot_fleet_config['LaunchSpecifications']).should.equal(2)
launch_spec = spot_fleet_config['LaunchSpecifications'][0]
len(spot_fleet_config["LaunchSpecifications"]).should.equal(2)
launch_spec = spot_fleet_config["LaunchSpecifications"][0]
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['ImageId'].should.equal("ami-123")
launch_spec['InstanceType'].should.equal("t2.small")
launch_spec['KeyName'].should.equal("my-key")
launch_spec['Monitoring'].should.equal({"Enabled": True})
launch_spec['SpotPrice'].should.equal("0.13")
launch_spec['SubnetId'].should.equal(subnet_id)
launch_spec['UserData'].should.equal("some user data")
launch_spec['WeightedCapacity'].should.equal(2.0)
launch_spec["EbsOptimized"].should.equal(False)
launch_spec["SecurityGroups"].should.equal([{"GroupId": "sg-123"}])
launch_spec["IamInstanceProfile"].should.equal(
{"Arn": "arn:aws:iam::{}:role/fleet".format(ACCOUNT_ID)}
)
launch_spec["ImageId"].should.equal("ami-123")
launch_spec["InstanceType"].should.equal("t2.small")
launch_spec["KeyName"].should.equal("my-key")
launch_spec["Monitoring"].should.equal({"Enabled": True})
launch_spec["SpotPrice"].should.equal("0.13")
launch_spec["SubnetId"].should.equal(subnet_id)
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)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(3)
@mock_ec2
def test_create_diversified_spot_fleet():
conn = boto3.client("ec2", region_name='us-west-2')
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']
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)
instances = instance_res['ActiveInstances']
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])
instance_types = set([instance["InstanceType"] for instance in instances])
instance_types.should.equal(set(["t2.small", "t2.large"]))
instances[0]['InstanceId'].should.contain("i-")
instances[0]["InstanceId"].should.contain("i-")
@mock_ec2
def test_create_spot_fleet_request_with_tag_spec():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
tag_spec = [
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'tag-1',
'Value': 'foo',
},
{
'Key': 'tag-2',
'Value': 'bar',
},
]
},
"ResourceType": "instance",
"Tags": [
{"Key": "tag-1", "Value": "foo"},
{"Key": "tag-2", "Value": "bar"},
],
}
]
config = spot_config(subnet_id)
config['LaunchSpecifications'][0]['TagSpecifications'] = tag_spec
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=config
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
config["LaunchSpecifications"][0]["TagSpecifications"] = tag_spec
spot_fleet_res = conn.request_spot_fleet(SpotFleetRequestConfig=config)
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
spot_fleet_requests = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
spot_fleet_config = spot_fleet_requests[0]['SpotFleetRequestConfig']
spot_fleet_config['LaunchSpecifications'][0]['TagSpecifications'][0][
'ResourceType'].should.equal('instance')
for tag in tag_spec[0]['Tags']:
spot_fleet_config['LaunchSpecifications'][0]['TagSpecifications'][0]['Tags'].should.contain(tag)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"]
spot_fleet_config = spot_fleet_requests[0]["SpotFleetRequestConfig"]
spot_fleet_config["LaunchSpecifications"][0]["TagSpecifications"][0][
"ResourceType"
].should.equal("instance")
for tag in tag_spec[0]["Tags"]:
spot_fleet_config["LaunchSpecifications"][0]["TagSpecifications"][0][
"Tags"
].should.contain(tag)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = conn.describe_instances(InstanceIds=[i['InstanceId'] for i in instance_res['ActiveInstances']])
for instance in instances['Reservations'][0]['Instances']:
for tag in tag_spec[0]['Tags']:
instance['Tags'].should.contain(tag)
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = conn.describe_instances(
InstanceIds=[i["InstanceId"] for i in instance_res["ActiveInstances"]]
)
for instance in instances["Reservations"][0]["Instances"]:
for tag in tag_spec[0]["Tags"]:
instance["Tags"].should.contain(tag)
@mock_ec2
def test_cancel_spot_fleet_request():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.cancel_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id], TerminateInstances=True)
SpotFleetRequestIds=[spot_fleet_id], TerminateInstances=True
)
spot_fleet_requests = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"]
len(spot_fleet_requests).should.equal(0)
@mock_ec2
def test_modify_spot_fleet_request_up():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=20)
conn.modify_spot_fleet_request(SpotFleetRequestId=spot_fleet_id, TargetCapacity=20)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(10)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(20)
spot_fleet_config['FulfilledCapacity'].should.equal(20.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(20)
spot_fleet_config["FulfilledCapacity"].should.equal(20.0)
@mock_ec2
def test_modify_spot_fleet_request_up_diversified():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(
subnet_id, allocation_strategy='diversified'),
SpotFleetRequestConfig=spot_config(subnet_id, allocation_strategy="diversified")
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=19)
conn.modify_spot_fleet_request(SpotFleetRequestId=spot_fleet_id, TargetCapacity=19)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(7)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(19)
spot_fleet_config['FulfilledCapacity'].should.equal(20.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(19)
spot_fleet_config["FulfilledCapacity"].should.equal(20.0)
@mock_ec2
def test_modify_spot_fleet_request_down_no_terminate():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=1, ExcessCapacityTerminationPolicy="noTermination")
SpotFleetRequestId=spot_fleet_id,
TargetCapacity=1,
ExcessCapacityTerminationPolicy="noTermination",
)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(3)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(1)
spot_fleet_config['FulfilledCapacity'].should.equal(6.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(1)
spot_fleet_config["FulfilledCapacity"].should.equal(6.0)
@mock_ec2
def test_modify_spot_fleet_request_down_odd():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=7)
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=5)
conn.modify_spot_fleet_request(SpotFleetRequestId=spot_fleet_id, TargetCapacity=7)
conn.modify_spot_fleet_request(SpotFleetRequestId=spot_fleet_id, TargetCapacity=5)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(3)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(5)
spot_fleet_config['FulfilledCapacity'].should.equal(6.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(5)
spot_fleet_config["FulfilledCapacity"].should.equal(6.0)
@mock_ec2
def test_modify_spot_fleet_request_down():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=1)
conn.modify_spot_fleet_request(SpotFleetRequestId=spot_fleet_id, TargetCapacity=1)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(1)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(1)
spot_fleet_config['FulfilledCapacity'].should.equal(2.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(1)
spot_fleet_config["FulfilledCapacity"].should.equal(2.0)
@mock_ec2
def test_modify_spot_fleet_request_down_no_terminate_after_custom_terminate():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
spot_fleet_res = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config(subnet_id),
SpotFleetRequestConfig=spot_config(subnet_id)
)
spot_fleet_id = spot_fleet_res['SpotFleetRequestId']
spot_fleet_id = spot_fleet_res["SpotFleetRequestId"]
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
conn.terminate_instances(InstanceIds=[i['InstanceId'] for i in instances[1:]])
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
conn.terminate_instances(InstanceIds=[i["InstanceId"] for i in instances[1:]])
conn.modify_spot_fleet_request(
SpotFleetRequestId=spot_fleet_id, TargetCapacity=1, ExcessCapacityTerminationPolicy="noTermination")
SpotFleetRequestId=spot_fleet_id,
TargetCapacity=1,
ExcessCapacityTerminationPolicy="noTermination",
)
instance_res = conn.describe_spot_fleet_instances(
SpotFleetRequestId=spot_fleet_id)
instances = instance_res['ActiveInstances']
instance_res = conn.describe_spot_fleet_instances(SpotFleetRequestId=spot_fleet_id)
instances = instance_res["ActiveInstances"]
len(instances).should.equal(1)
spot_fleet_config = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs'][0]['SpotFleetRequestConfig']
spot_fleet_config['TargetCapacity'].should.equal(1)
spot_fleet_config['FulfilledCapacity'].should.equal(2.0)
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"][0]["SpotFleetRequestConfig"]
spot_fleet_config["TargetCapacity"].should.equal(1)
spot_fleet_config["FulfilledCapacity"].should.equal(2.0)
@mock_ec2
def test_create_spot_fleet_without_spot_price():
conn = boto3.client("ec2", region_name='us-west-2')
conn = boto3.client("ec2", region_name="us-west-2")
subnet_id = get_subnet_id(conn)
# remove prices to force a fallback to ondemand price
spot_config_without_price = spot_config(subnet_id)
del spot_config_without_price['SpotPrice']
for spec in spot_config_without_price['LaunchSpecifications']:
del spec['SpotPrice']
del spot_config_without_price["SpotPrice"]
for spec in spot_config_without_price["LaunchSpecifications"]:
del spec["SpotPrice"]
spot_fleet_id = conn.request_spot_fleet(SpotFleetRequestConfig=spot_config_without_price)['SpotFleetRequestId']
spot_fleet_id = conn.request_spot_fleet(
SpotFleetRequestConfig=spot_config_without_price
)["SpotFleetRequestId"]
spot_fleet_requests = conn.describe_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_id])['SpotFleetRequestConfigs']
SpotFleetRequestIds=[spot_fleet_id]
)["SpotFleetRequestConfigs"]
len(spot_fleet_requests).should.equal(1)
spot_fleet_request = spot_fleet_requests[0]
spot_fleet_config = spot_fleet_request['SpotFleetRequestConfig']
spot_fleet_config = spot_fleet_request["SpotFleetRequestConfig"]
len(spot_fleet_config['LaunchSpecifications']).should.equal(2)
launch_spec1 = spot_fleet_config['LaunchSpecifications'][0]
launch_spec2 = spot_fleet_config['LaunchSpecifications'][1]
len(spot_fleet_config["LaunchSpecifications"]).should.equal(2)
launch_spec1 = spot_fleet_config["LaunchSpecifications"][0]
launch_spec2 = spot_fleet_config["LaunchSpecifications"][1]
# AWS will figure out the price
assert 'SpotPrice' not in launch_spec1
assert 'SpotPrice' not in launch_spec2
assert "SpotPrice" not in launch_spec1
assert "SpotPrice" not in launch_spec2

View file

@ -16,14 +16,15 @@ from moto.core.utils import iso_8601_datetime_with_milliseconds
@mock_ec2
def test_request_spot_instances():
conn = boto3.client('ec2', 'us-east-1')
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")['Vpc']
conn = boto3.client("ec2", "us-east-1")
vpc = conn.create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]
subnet = conn.create_subnet(
VpcId=vpc['VpcId'], CidrBlock='10.0.0.0/16', AvailabilityZone='us-east-1a')['Subnet']
subnet_id = subnet['SubnetId']
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')
conn.create_security_group(GroupName='group2', Description='description')
conn.create_security_group(GroupName="group1", Description="description")
conn.create_security_group(GroupName="group2", Description="description")
start_dt = datetime.datetime(2013, 1, 1).replace(tzinfo=pytz.utc)
end_dt = datetime.datetime(2013, 1, 2).replace(tzinfo=pytz.utc)
@ -32,78 +33,79 @@ def test_request_spot_instances():
with assert_raises(ClientError) as ex:
request = conn.request_spot_instances(
SpotPrice="0.5", InstanceCount=1, Type='one-time',
ValidFrom=start, ValidUntil=end, LaunchGroup="the-group",
AvailabilityZoneGroup='my-group',
SpotPrice="0.5",
InstanceCount=1,
Type="one-time",
ValidFrom=start,
ValidUntil=end,
LaunchGroup="the-group",
AvailabilityZoneGroup="my-group",
LaunchSpecification={
"ImageId": 'ami-abcd1234',
"ImageId": "ami-abcd1234",
"KeyName": "test",
"SecurityGroups": ['group1', 'group2'],
"SecurityGroups": ["group1", "group2"],
"UserData": "some test data",
"InstanceType": 'm1.small',
"Placement": {
"AvailabilityZone": 'us-east-1c',
},
"InstanceType": "m1.small",
"Placement": {"AvailabilityZone": "us-east-1c"},
"KernelId": "test-kernel",
"RamdiskId": "test-ramdisk",
"Monitoring": {
"Enabled": True,
},
"Monitoring": {"Enabled": True},
"SubnetId": subnet_id,
},
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["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"
)
request = conn.request_spot_instances(
SpotPrice="0.5", InstanceCount=1, Type='one-time',
ValidFrom=start, ValidUntil=end, LaunchGroup="the-group",
AvailabilityZoneGroup='my-group',
SpotPrice="0.5",
InstanceCount=1,
Type="one-time",
ValidFrom=start,
ValidUntil=end,
LaunchGroup="the-group",
AvailabilityZoneGroup="my-group",
LaunchSpecification={
"ImageId": 'ami-abcd1234',
"ImageId": "ami-abcd1234",
"KeyName": "test",
"SecurityGroups": ['group1', 'group2'],
"SecurityGroups": ["group1", "group2"],
"UserData": "some test data",
"InstanceType": 'm1.small',
"Placement": {
"AvailabilityZone": 'us-east-1c',
},
"InstanceType": "m1.small",
"Placement": {"AvailabilityZone": "us-east-1c"},
"KernelId": "test-kernel",
"RamdiskId": "test-ramdisk",
"Monitoring": {
"Enabled": True,
},
"Monitoring": {"Enabled": True},
"SubnetId": subnet_id,
},
)
requests = conn.describe_spot_instance_requests()['SpotInstanceRequests']
requests = conn.describe_spot_instance_requests()["SpotInstanceRequests"]
requests.should.have.length_of(1)
request = requests[0]
request['State'].should.equal("open")
request['SpotPrice'].should.equal("0.5")
request['Type'].should.equal('one-time')
request['ValidFrom'].should.equal(start_dt)
request['ValidUntil'].should.equal(end_dt)
request['LaunchGroup'].should.equal("the-group")
request['AvailabilityZoneGroup'].should.equal('my-group')
request["State"].should.equal("open")
request["SpotPrice"].should.equal("0.5")
request["Type"].should.equal("one-time")
request["ValidFrom"].should.equal(start_dt)
request["ValidUntil"].should.equal(end_dt)
request["LaunchGroup"].should.equal("the-group")
request["AvailabilityZoneGroup"].should.equal("my-group")
launch_spec = request['LaunchSpecification']
security_group_names = [group['GroupName']
for group in launch_spec['SecurityGroups']]
set(security_group_names).should.equal(set(['group1', 'group2']))
launch_spec = request["LaunchSpecification"]
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')
launch_spec['KeyName'].should.equal("test")
launch_spec['InstanceType'].should.equal('m1.small')
launch_spec['KernelId'].should.equal("test-kernel")
launch_spec['RamdiskId'].should.equal("test-ramdisk")
launch_spec['SubnetId'].should.equal(subnet_id)
launch_spec["ImageId"].should.equal("ami-abcd1234")
launch_spec["KeyName"].should.equal("test")
launch_spec["InstanceType"].should.equal("m1.small")
launch_spec["KernelId"].should.equal("test-kernel")
launch_spec["RamdiskId"].should.equal("test-ramdisk")
launch_spec["SubnetId"].should.equal(subnet_id)
@mock_ec2
@ -111,58 +113,55 @@ def test_request_spot_instances_default_arguments():
"""
Test that moto set the correct default arguments
"""
conn = boto3.client('ec2', 'us-east-1')
conn = boto3.client("ec2", "us-east-1")
request = conn.request_spot_instances(
SpotPrice="0.5",
LaunchSpecification={
"ImageId": 'ami-abcd1234',
}
SpotPrice="0.5", LaunchSpecification={"ImageId": "ami-abcd1234"}
)
requests = conn.describe_spot_instance_requests()['SpotInstanceRequests']
requests = conn.describe_spot_instance_requests()["SpotInstanceRequests"]
requests.should.have.length_of(1)
request = requests[0]
request['State'].should.equal("open")
request['SpotPrice'].should.equal("0.5")
request['Type'].should.equal('one-time')
request.shouldnt.contain('ValidFrom')
request.shouldnt.contain('ValidUntil')
request.shouldnt.contain('LaunchGroup')
request.shouldnt.contain('AvailabilityZoneGroup')
request["State"].should.equal("open")
request["SpotPrice"].should.equal("0.5")
request["Type"].should.equal("one-time")
request.shouldnt.contain("ValidFrom")
request.shouldnt.contain("ValidUntil")
request.shouldnt.contain("LaunchGroup")
request.shouldnt.contain("AvailabilityZoneGroup")
launch_spec = request['LaunchSpecification']
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')
request.shouldnt.contain('KeyName')
launch_spec['InstanceType'].should.equal('m1.small')
request.shouldnt.contain('KernelId')
request.shouldnt.contain('RamdiskId')
request.shouldnt.contain('SubnetId')
launch_spec["ImageId"].should.equal("ami-abcd1234")
request.shouldnt.contain("KeyName")
launch_spec["InstanceType"].should.equal("m1.small")
request.shouldnt.contain("KernelId")
request.shouldnt.contain("RamdiskId")
request.shouldnt.contain("SubnetId")
@mock_ec2_deprecated
def test_cancel_spot_instance_request():
conn = boto.connect_ec2()
conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
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.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')
"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])
@ -177,9 +176,7 @@ def test_request_spot_instances_fulfilled():
"""
conn = boto.ec2.connect_to_region("us-east-1")
request = conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
request = conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
requests = conn.get_all_spot_instance_requests()
requests.should.have.length_of(1)
@ -187,7 +184,7 @@ def test_request_spot_instances_fulfilled():
request.state.should.equal("open")
get_model('SpotInstanceRequest', 'us-east-1')[0].state = 'active'
get_model("SpotInstanceRequest", "us-east-1")[0].state = "active"
requests = conn.get_all_spot_instance_requests()
requests.should.have.length_of(1)
@ -203,18 +200,16 @@ def test_tag_spot_instance_request():
"""
conn = boto.connect_ec2()
request = conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
request[0].add_tag('tag1', 'value1')
request[0].add_tag('tag2', 'value2')
request = conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
request[0].add_tag("tag1", "value1")
request[0].add_tag("tag2", "value2")
requests = conn.get_all_spot_instance_requests()
requests.should.have.length_of(1)
request = requests[0]
tag_dict = dict(request.tags)
tag_dict.should.equal({'tag1': 'value1', 'tag2': 'value2'})
tag_dict.should.equal({"tag1": "value1", "tag2": "value2"})
@mock_ec2_deprecated
@ -224,45 +219,38 @@ def test_get_all_spot_instance_requests_filtering():
"""
conn = boto.connect_ec2()
request1 = conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
request2 = conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234',
)
request1[0].add_tag('tag1', 'value1')
request1[0].add_tag('tag2', 'value2')
request2[0].add_tag('tag1', 'value1')
request2[0].add_tag('tag2', 'wrong')
request1 = conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
request2 = conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
request1[0].add_tag("tag1", "value1")
request1[0].add_tag("tag2", "value2")
request2[0].add_tag("tag1", "value1")
request2[0].add_tag("tag2", "wrong")
requests = conn.get_all_spot_instance_requests(filters={'state': 'active'})
requests = conn.get_all_spot_instance_requests(filters={"state": "active"})
requests.should.have.length_of(0)
requests = conn.get_all_spot_instance_requests(filters={'state': 'open'})
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'})
filters={"tag:tag1": "value1", "tag:tag2": "value2"}
)
requests.should.have.length_of(1)
@mock_ec2_deprecated
def test_request_spot_instances_setting_instance_id():
conn = boto.ec2.connect_to_region("us-east-1")
request = conn.request_spot_instances(
price=0.5, image_id='ami-abcd1234')
request = conn.request_spot_instances(price=0.5, image_id="ami-abcd1234")
req = get_model('SpotInstanceRequest', 'us-east-1')[0]
req.state = 'active'
req.instance_id = 'i-12345678'
req = get_model("SpotInstanceRequest", "us-east-1")[0]
req.state = "active"
req.instance_id = "i-12345678"
request = conn.get_all_spot_instance_requests()[0]
assert request.state == 'active'
assert request.instance_id == 'i-12345678'
assert request.state == "active"
assert request.instance_id == "i-12345678"

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises # noqa
from nose.tools import assert_raises
@ -10,14 +11,15 @@ from boto.exception import EC2ResponseError
from botocore.exceptions import ParamValidationError, ClientError
import json
import sure # noqa
import random
from moto import mock_cloudformation_deprecated, mock_ec2, mock_ec2_deprecated
@mock_ec2_deprecated
def test_subnets():
ec2 = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_vpc('the_key', 'the_secret')
ec2 = boto.connect_ec2("the_key", "the_secret")
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")
@ -31,25 +33,25 @@ def test_subnets():
with assert_raises(EC2ResponseError) as cm:
conn.delete_subnet(subnet.id)
cm.exception.code.should.equal('InvalidSubnetID.NotFound')
cm.exception.code.should.equal("InvalidSubnetID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_subnet_create_vpc_validation():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.create_subnet("vpc-abcd1234", "10.0.0.0/18")
cm.exception.code.should.equal('InvalidVpcID.NotFound')
cm.exception.code.should.equal("InvalidVpcID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_subnet_tagging():
conn = boto.connect_vpc('the_key', 'the_secret')
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")
@ -67,31 +69,31 @@ def test_subnet_tagging():
@mock_ec2_deprecated
def test_subnet_should_have_proper_availability_zone_set():
conn = boto.vpc.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-1b')
subnetA.availability_zone.should.equal('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")
@mock_ec2
def test_default_subnet():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
default_vpc = list(ec2.vpcs.all())[0]
default_vpc.cidr_block.should.equal('172.31.0.0/16')
default_vpc.cidr_block.should.equal("172.31.0.0/16")
default_vpc.reload()
default_vpc.is_default.should.be.ok
subnet = ec2.create_subnet(
VpcId=default_vpc.id, CidrBlock='172.31.48.0/20', AvailabilityZone='us-west-1a')
VpcId=default_vpc.id, CidrBlock="172.31.48.0/20", AvailabilityZone="us-west-1a"
)
subnet.reload()
subnet.map_public_ip_on_launch.shouldnt.be.ok
@mock_ec2_deprecated
def test_non_default_subnet():
vpc_cli = boto.vpc.connect_to_region('us-west-1')
vpc_cli = boto.vpc.connect_to_region("us-west-1")
# Create the non default VPC
vpc = vpc_cli.create_vpc("10.0.0.0/16")
@ -99,34 +101,36 @@ def test_non_default_subnet():
subnet = vpc_cli.create_subnet(vpc.id, "10.0.0.0/24")
subnet = vpc_cli.get_all_subnets(subnet_ids=[subnet.id])[0]
subnet.mapPublicIpOnLaunch.should.equal('false')
subnet.mapPublicIpOnLaunch.should.equal("false")
@mock_ec2
def test_boto3_non_default_subnet():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the non default VPC
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
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')
VpcId=vpc.id, CidrBlock="10.0.0.0/24", AvailabilityZone="us-west-1a"
)
subnet.reload()
subnet.map_public_ip_on_launch.shouldnt.be.ok
@mock_ec2
def test_modify_subnet_attribute_public_ip_on_launch():
ec2 = boto3.resource('ec2', region_name='us-west-1')
client = boto3.client('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
client = boto3.client("ec2", region_name="us-west-1")
# Get the default VPC
vpc = list(ec2.vpcs.all())[0]
subnet = ec2.create_subnet(
VpcId=vpc.id, CidrBlock="172.31.48.0/20", AvailabilityZone='us-west-1a')
VpcId=vpc.id, CidrBlock="172.31.48.0/20", AvailabilityZone="us-west-1a"
)
# 'map_public_ip_on_launch' is set when calling 'DescribeSubnets' action
subnet.reload()
@ -135,26 +139,29 @@ def test_modify_subnet_attribute_public_ip_on_launch():
subnet.map_public_ip_on_launch.shouldnt.be.ok
client.modify_subnet_attribute(
SubnetId=subnet.id, MapPublicIpOnLaunch={'Value': False})
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})
SubnetId=subnet.id, MapPublicIpOnLaunch={"Value": True}
)
subnet.reload()
subnet.map_public_ip_on_launch.should.be.ok
@mock_ec2
def test_modify_subnet_attribute_assign_ipv6_address_on_creation():
ec2 = boto3.resource('ec2', region_name='us-west-1')
client = boto3.client('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
client = boto3.client("ec2", region_name="us-west-1")
# Get the default VPC
vpc = list(ec2.vpcs.all())[0]
subnet = ec2.create_subnet(
VpcId=vpc.id, CidrBlock='172.31.112.0/20', AvailabilityZone='us-west-1a')
VpcId=vpc.id, CidrBlock="172.31.112.0/20", AvailabilityZone="us-west-1a"
)
# 'map_public_ip_on_launch' is set when calling 'DescribeSubnets' action
subnet.reload()
@ -163,41 +170,46 @@ def test_modify_subnet_attribute_assign_ipv6_address_on_creation():
subnet.assign_ipv6_address_on_creation.shouldnt.be.ok
client.modify_subnet_attribute(
SubnetId=subnet.id, AssignIpv6AddressOnCreation={'Value': False})
SubnetId=subnet.id, AssignIpv6AddressOnCreation={"Value": False}
)
subnet.reload()
subnet.assign_ipv6_address_on_creation.shouldnt.be.ok
client.modify_subnet_attribute(
SubnetId=subnet.id, AssignIpv6AddressOnCreation={'Value': True})
SubnetId=subnet.id, AssignIpv6AddressOnCreation={"Value": True}
)
subnet.reload()
subnet.assign_ipv6_address_on_creation.should.be.ok
@mock_ec2
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')
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')
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'})
SubnetId=subnet.id, MapPublicIpOnLaunch={"Value": "invalid"}
)
@mock_ec2_deprecated
def test_subnet_get_by_id():
ec2 = boto.ec2.connect_to_region('us-west-1')
conn = boto.vpc.connect_to_region('us-west-1')
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')
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')
vpcB.id, "10.0.1.0/24", availability_zone="us-west-1b"
)
subnets_by_id = conn.get_all_subnets(subnet_ids=[subnetA.id, subnetB1.id])
subnets_by_id.should.have.length_of(2)
@ -206,85 +218,91 @@ def test_subnet_get_by_id():
subnetB1.id.should.be.within(subnets_by_id)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_subnets(subnet_ids=['subnet-does_not_exist'])
cm.exception.code.should.equal('InvalidSubnetID.NotFound')
conn.get_all_subnets(subnet_ids=["subnet-does_not_exist"])
cm.exception.code.should.equal("InvalidSubnetID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_get_subnets_filtering():
ec2 = boto.ec2.connect_to_region('us-west-1')
conn = boto.vpc.connect_to_region('us-west-1')
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')
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')
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()))
# Filter by VPC ID
subnets_by_vpc = conn.get_all_subnets(filters={'vpc-id': vpcB.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([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 = 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"})
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})
subnets_by_id = conn.get_all_subnets(filters={"subnet-id": subnetA.id})
subnets_by_id.should.have.length_of(1)
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})
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
subnets_by_az = conn.get_all_subnets(filters={'defaultForAz': "true"})
subnets_by_az = conn.get_all_subnets(filters={"defaultForAz": "true"})
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)
filters={"not-implemented-filter": "foobar"}
).should.throw(NotImplementedError)
@mock_ec2_deprecated
@mock_cloudformation_deprecated
def test_subnet_tags_through_cloudformation():
vpc_conn = boto.vpc.connect_to_region('us-west-1')
vpc_conn = boto.vpc.connect_to_region("us-west-1")
vpc = vpc_conn.create_vpc("10.0.0.0/16")
subnet_template = {
@ -296,151 +314,288 @@ def test_subnet_tags_through_cloudformation():
"VpcId": vpc.id,
"CidrBlock": "10.0.0.0/24",
"AvailabilityZone": "us-west-1b",
"Tags": [{
"Key": "foo",
"Value": "bar",
}, {
"Key": "blah",
"Value": "baz",
}]
}
"Tags": [
{"Key": "foo", "Value": "bar"},
{"Key": "blah", "Value": "baz"},
],
},
}
}
},
}
cf_conn = boto.cloudformation.connect_to_region("us-west-1")
template_json = json.dumps(subnet_template)
cf_conn.create_stack(
"test_stack",
template_body=template_json,
)
cf_conn.create_stack("test_stack", template_body=template_json)
subnet = vpc_conn.get_all_subnets(filters={'cidrBlock': '10.0.0.0/24'})[0]
subnet = vpc_conn.get_all_subnets(filters={"cidrBlock": "10.0.0.0/24"})[0]
subnet.tags["foo"].should.equal("bar")
subnet.tags["blah"].should.equal("baz")
@mock_ec2
def test_create_subnet_response_fields():
ec2 = boto3.resource('ec2', region_name='us-west-1')
client = boto3.client('ec2', region_name='us-west-1')
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')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
subnet = client.create_subnet(
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')['Subnet']
VpcId=vpc.id, CidrBlock="10.0.0.0/24", AvailabilityZone="us-west-1a"
)["Subnet"]
subnet.should.have.key('AvailabilityZone')
subnet.should.have.key('AvailabilityZoneId')
subnet.should.have.key('AvailableIpAddressCount')
subnet.should.have.key('CidrBlock')
subnet.should.have.key('State')
subnet.should.have.key('SubnetId')
subnet.should.have.key('VpcId')
subnet.shouldnt.have.key('Tags')
subnet.should.have.key('DefaultForAz').which.should.equal(False)
subnet.should.have.key('MapPublicIpOnLaunch').which.should.equal(False)
subnet.should.have.key('OwnerId')
subnet.should.have.key('AssignIpv6AddressOnCreation').which.should.equal(False)
subnet.should.have.key("AvailabilityZone")
subnet.should.have.key("AvailabilityZoneId")
subnet.should.have.key("AvailableIpAddressCount")
subnet.should.have.key("CidrBlock")
subnet.should.have.key("State")
subnet.should.have.key("SubnetId")
subnet.should.have.key("VpcId")
subnet.shouldnt.have.key("Tags")
subnet.should.have.key("DefaultForAz").which.should.equal(False)
subnet.should.have.key("MapPublicIpOnLaunch").which.should.equal(False)
subnet.should.have.key("OwnerId")
subnet.should.have.key("AssignIpv6AddressOnCreation").which.should.equal(False)
subnet_arn = "arn:aws:ec2:{region}:{owner_id}:subnet/{subnet_id}".format(region=subnet['AvailabilityZone'][0:-1],
owner_id=subnet['OwnerId'],
subnet_id=subnet['SubnetId'])
subnet.should.have.key('SubnetArn').which.should.equal(subnet_arn)
subnet.should.have.key('Ipv6CidrBlockAssociationSet').which.should.equal([])
subnet_arn = "arn:aws:ec2:{region}:{owner_id}:subnet/{subnet_id}".format(
region=subnet["AvailabilityZone"][0:-1],
owner_id=subnet["OwnerId"],
subnet_id=subnet["SubnetId"],
)
subnet.should.have.key("SubnetArn").which.should.equal(subnet_arn)
subnet.should.have.key("Ipv6CidrBlockAssociationSet").which.should.equal([])
@mock_ec2
def test_describe_subnet_response_fields():
ec2 = boto3.resource('ec2', region_name='us-west-1')
client = boto3.client('ec2', region_name='us-west-1')
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')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
subnet_object = ec2.create_subnet(
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone='us-west-1a')
VpcId=vpc.id, CidrBlock="10.0.0.0/24", AvailabilityZone="us-west-1a"
)
subnets = client.describe_subnets(SubnetIds=[subnet_object.id])['Subnets']
subnets = client.describe_subnets(SubnetIds=[subnet_object.id])["Subnets"]
subnets.should.have.length_of(1)
subnet = subnets[0]
subnet.should.have.key('AvailabilityZone')
subnet.should.have.key('AvailabilityZoneId')
subnet.should.have.key('AvailableIpAddressCount')
subnet.should.have.key('CidrBlock')
subnet.should.have.key('State')
subnet.should.have.key('SubnetId')
subnet.should.have.key('VpcId')
subnet.shouldnt.have.key('Tags')
subnet.should.have.key('DefaultForAz').which.should.equal(False)
subnet.should.have.key('MapPublicIpOnLaunch').which.should.equal(False)
subnet.should.have.key('OwnerId')
subnet.should.have.key('AssignIpv6AddressOnCreation').which.should.equal(False)
subnet.should.have.key("AvailabilityZone")
subnet.should.have.key("AvailabilityZoneId")
subnet.should.have.key("AvailableIpAddressCount")
subnet.should.have.key("CidrBlock")
subnet.should.have.key("State")
subnet.should.have.key("SubnetId")
subnet.should.have.key("VpcId")
subnet.shouldnt.have.key("Tags")
subnet.should.have.key("DefaultForAz").which.should.equal(False)
subnet.should.have.key("MapPublicIpOnLaunch").which.should.equal(False)
subnet.should.have.key("OwnerId")
subnet.should.have.key("AssignIpv6AddressOnCreation").which.should.equal(False)
subnet_arn = "arn:aws:ec2:{region}:{owner_id}:subnet/{subnet_id}".format(region=subnet['AvailabilityZone'][0:-1],
owner_id=subnet['OwnerId'],
subnet_id=subnet['SubnetId'])
subnet.should.have.key('SubnetArn').which.should.equal(subnet_arn)
subnet.should.have.key('Ipv6CidrBlockAssociationSet').which.should.equal([])
subnet_arn = "arn:aws:ec2:{region}:{owner_id}:subnet/{subnet_id}".format(
region=subnet["AvailabilityZone"][0:-1],
owner_id=subnet["OwnerId"],
subnet_id=subnet["SubnetId"],
)
subnet.should.have.key("SubnetArn").which.should.equal(subnet_arn)
subnet.should.have.key("Ipv6CidrBlockAssociationSet").which.should.equal([])
@mock_ec2
def test_create_subnet_with_invalid_availability_zone():
ec2 = boto3.resource('ec2', region_name='us-west-1')
client = boto3.client('ec2', region_name='us-west-1')
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')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
subnet_availability_zone = 'asfasfas'
subnet_availability_zone = "asfasfas"
with assert_raises(ClientError) as ex:
subnet = client.create_subnet(
VpcId=vpc.id, CidrBlock='10.0.0.0/24', AvailabilityZone=subnet_availability_zone)
VpcId=vpc.id,
CidrBlock="10.0.0.0/24",
AvailabilityZone=subnet_availability_zone,
)
assert str(ex.exception).startswith(
"An error occurred (InvalidParameterValue) when calling the CreateSubnet "
"operation: Value ({}) for parameter availabilityZone is invalid. Subnets can currently only be created in the following availability zones: ".format(subnet_availability_zone))
"operation: Value ({}) for parameter availabilityZone is invalid. Subnets can currently only be created in the following availability zones: ".format(
subnet_availability_zone
)
)
@mock_ec2
def test_create_subnet_with_invalid_cidr_range():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc.reload()
vpc.is_default.shouldnt.be.ok
subnet_cidr_block = '10.1.0.0/20'
subnet_cidr_block = "10.1.0.0/20"
with assert_raises(ClientError) as ex:
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block)
str(ex.exception).should.equal(
"An error occurred (InvalidSubnet.Range) when calling the CreateSubnet "
"operation: The CIDR '{}' is invalid.".format(subnet_cidr_block))
"operation: The CIDR '{}' is invalid.".format(subnet_cidr_block)
)
@mock_ec2
def test_create_subnet_with_invalid_cidr_block_parameter():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc.reload()
vpc.is_default.shouldnt.be.ok
subnet_cidr_block = '1000.1.0.0/20'
subnet_cidr_block = "1000.1.0.0/20"
with assert_raises(ClientError) as ex:
subnet = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block)
str(ex.exception).should.equal(
"An error occurred (InvalidParameterValue) when calling the CreateSubnet "
"operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format(subnet_cidr_block))
"operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format(
subnet_cidr_block
)
)
@mock_ec2
def test_create_subnets_with_overlapping_cidr_blocks():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc.reload()
vpc.is_default.shouldnt.be.ok
subnet_cidr_block = '10.0.0.0/24'
subnet_cidr_block = "10.0.0.0/24"
with assert_raises(ClientError) as ex:
subnet1 = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block)
subnet2 = ec2.create_subnet(VpcId=vpc.id, CidrBlock=subnet_cidr_block)
str(ex.exception).should.equal(
"An error occurred (InvalidSubnet.Conflict) when calling the CreateSubnet "
"operation: The CIDR '{}' conflicts with another subnet".format(subnet_cidr_block))
"operation: The CIDR '{}' conflicts with another subnet".format(
subnet_cidr_block
)
)
@mock_ec2
def test_available_ip_addresses_in_subnet():
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")
cidr_range_addresses = [
("10.0.0.0/16", 65531),
("10.0.0.0/17", 32763),
("10.0.0.0/18", 16379),
("10.0.0.0/19", 8187),
("10.0.0.0/20", 4091),
("10.0.0.0/21", 2043),
("10.0.0.0/22", 1019),
("10.0.0.0/23", 507),
("10.0.0.0/24", 251),
("10.0.0.0/25", 123),
("10.0.0.0/26", 59),
("10.0.0.0/27", 27),
("10.0.0.0/28", 11),
]
for (cidr, expected_count) in cidr_range_addresses:
validate_subnet_details(client, vpc, cidr, expected_count)
@mock_ec2
def test_available_ip_addresses_in_subnet_with_enis():
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")
# Verify behaviour for various CIDR ranges (...)
# Don't try to assign ENIs to /27 and /28, as there are not a lot of IP addresses to go around
cidr_range_addresses = [
("10.0.0.0/16", 65531),
("10.0.0.0/17", 32763),
("10.0.0.0/18", 16379),
("10.0.0.0/19", 8187),
("10.0.0.0/20", 4091),
("10.0.0.0/21", 2043),
("10.0.0.0/22", 1019),
("10.0.0.0/23", 507),
("10.0.0.0/24", 251),
("10.0.0.0/25", 123),
("10.0.0.0/26", 59),
]
for (cidr, expected_count) in cidr_range_addresses:
validate_subnet_details_after_creating_eni(client, vpc, cidr, expected_count)
def validate_subnet_details(client, vpc, cidr, expected_ip_address_count):
subnet = client.create_subnet(
VpcId=vpc.id, CidrBlock=cidr, AvailabilityZone="us-west-1b"
)["Subnet"]
subnet["AvailableIpAddressCount"].should.equal(expected_ip_address_count)
client.delete_subnet(SubnetId=subnet["SubnetId"])
def validate_subnet_details_after_creating_eni(
client, vpc, cidr, expected_ip_address_count
):
subnet = client.create_subnet(
VpcId=vpc.id, CidrBlock=cidr, AvailabilityZone="us-west-1b"
)["Subnet"]
# Create a random number of Elastic Network Interfaces
nr_of_eni_to_create = random.randint(0, 5)
ip_addresses_assigned = 0
enis_created = []
for i in range(0, nr_of_eni_to_create):
# Create a random number of IP addresses per ENI
nr_of_ip_addresses = random.randint(1, 5)
if nr_of_ip_addresses == 1:
# Pick the first available IP address (First 4 are reserved by AWS)
private_address = "10.0.0." + str(ip_addresses_assigned + 4)
eni = client.create_network_interface(
SubnetId=subnet["SubnetId"], PrivateIpAddress=private_address
)["NetworkInterface"]
enis_created.append(eni)
ip_addresses_assigned = ip_addresses_assigned + 1
else:
# Assign a list of IP addresses
private_addresses = [
"10.0.0." + str(4 + ip_addresses_assigned + i)
for i in range(0, nr_of_ip_addresses)
]
eni = client.create_network_interface(
SubnetId=subnet["SubnetId"],
PrivateIpAddresses=[
{"PrivateIpAddress": address} for address in private_addresses
],
)["NetworkInterface"]
enis_created.append(eni)
ip_addresses_assigned = ip_addresses_assigned + nr_of_ip_addresses + 1 #
# Verify that the nr of available IP addresses takes these ENIs into account
updated_subnet = client.describe_subnets(SubnetIds=[subnet["SubnetId"]])["Subnets"][
0
]
private_addresses = [
eni["PrivateIpAddress"] for eni in enis_created if eni["PrivateIpAddress"]
]
for eni in enis_created:
private_addresses.extend(
[address["PrivateIpAddress"] for address in eni["PrivateIpAddresses"]]
)
error_msg = (
"Nr of IP addresses for Subnet with CIDR {0} is incorrect. Expected: {1}, Actual: {2}. "
"Addresses: {3}"
)
with sure.ensure(
error_msg,
cidr,
str(expected_ip_address_count),
updated_subnet["AvailableIpAddressCount"],
str(private_addresses),
):
updated_subnet["AvailableIpAddressCount"].should.equal(
expected_ip_address_count - ip_addresses_assigned
)
# Clean up, as we have to create a few more subnets that shouldn't interfere with each other
for eni in enis_created:
client.delete_network_interface(NetworkInterfaceId=eni["NetworkInterfaceId"])
client.delete_subnet(SubnetId=subnet["SubnetId"])

View file

@ -16,21 +16,23 @@ from nose.tools import assert_raises
@mock_ec2_deprecated
def test_add_tag():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
with assert_raises(EC2ResponseError) as ex:
instance.add_tag("a key", "some value", dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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()]))
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")
@ -38,8 +40,8 @@ def test_add_tag():
@mock_ec2_deprecated
def test_remove_tag():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("a key", "some value")
@ -51,10 +53,11 @@ def test_remove_tag():
with assert_raises(EC2ResponseError) as ex:
instance.remove_tag("a key", dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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)
@ -66,8 +69,8 @@ def test_remove_tag():
@mock_ec2_deprecated
def test_get_all_tags():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("a key", "some value")
@ -80,8 +83,8 @@ def test_get_all_tags():
@mock_ec2_deprecated
def test_get_all_tags_with_special_characters():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("a key", "some<> value")
@ -94,47 +97,50 @@ def test_get_all_tags_with_special_characters():
@mock_ec2_deprecated
def test_create_tags():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
tag_dict = {'a key': 'some value',
'another key': 'some other value',
'blank key': ''}
tag_dict = {
"a key": "some value",
"another key": "some other value",
"blank key": "",
}
with assert_raises(EC2ResponseError) as ex:
conn.create_tags(instance.id, tag_dict, dry_run=True)
ex.exception.error_code.should.equal('DryRunOperation')
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')
"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([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([tag.value for tag in tags])
)
@mock_ec2_deprecated
def test_tag_limit_exceeded():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
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)
cm.exception.code.should.equal('TagLimitExceeded')
cm.exception.code.should.equal("TagLimitExceeded")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
instance.add_tag("a key", "a value")
with assert_raises(EC2ResponseError) as cm:
conn.create_tags(instance.id, tag_dict)
cm.exception.code.should.equal('TagLimitExceeded')
cm.exception.code.should.equal("TagLimitExceeded")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -147,158 +153,158 @@ def test_tag_limit_exceeded():
@mock_ec2_deprecated
def test_invalid_parameter_tag_null():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
with assert_raises(EC2ResponseError) as cm:
instance.add_tag("a key", None)
cm.exception.code.should.equal('InvalidParameterValue')
cm.exception.code.should.equal("InvalidParameterValue")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_invalid_id():
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
with assert_raises(EC2ResponseError) as cm:
conn.create_tags('ami-blah', {'key': 'tag'})
cm.exception.code.should.equal('InvalidID')
conn.create_tags("ami-blah", {"key": "tag"})
cm.exception.code.should.equal("InvalidID")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
with assert_raises(EC2ResponseError) as cm:
conn.create_tags('blah-blah', {'key': 'tag'})
cm.exception.code.should.equal('InvalidID')
conn.create_tags("blah-blah", {"key": "tag"})
cm.exception.code.should.equal("InvalidID")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_get_all_tags_resource_id_filter():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("an instance key", "some value")
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
image = conn.get_image(image_id)
image.add_tag("an image key", "some value")
tags = conn.get_all_tags(filters={'resource-id': instance.id})
tags = conn.get_all_tags(filters={"resource-id": instance.id})
tag = tags[0]
tags.should.have.length_of(1)
tag.res_id.should.equal(instance.id)
tag.res_type.should.equal('instance')
tag.res_type.should.equal("instance")
tag.name.should.equal("an instance key")
tag.value.should.equal("some value")
tags = conn.get_all_tags(filters={'resource-id': image_id})
tags = conn.get_all_tags(filters={"resource-id": image_id})
tag = tags[0]
tags.should.have.length_of(1)
tag.res_id.should.equal(image_id)
tag.res_type.should.equal('image')
tag.res_type.should.equal("image")
tag.name.should.equal("an image key")
tag.value.should.equal("some value")
@mock_ec2_deprecated
def test_get_all_tags_resource_type_filter():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("an instance key", "some value")
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
image = conn.get_image(image_id)
image.add_tag("an image key", "some value")
tags = conn.get_all_tags(filters={'resource-type': 'instance'})
tags = conn.get_all_tags(filters={"resource-type": "instance"})
tag = tags[0]
tags.should.have.length_of(1)
tag.res_id.should.equal(instance.id)
tag.res_type.should.equal('instance')
tag.res_type.should.equal("instance")
tag.name.should.equal("an instance key")
tag.value.should.equal("some value")
tags = conn.get_all_tags(filters={'resource-type': 'image'})
tags = conn.get_all_tags(filters={"resource-type": "image"})
tag = tags[0]
tags.should.have.length_of(1)
tag.res_id.should.equal(image_id)
tag.res_type.should.equal('image')
tag.res_type.should.equal("image")
tag.name.should.equal("an image key")
tag.value.should.equal("some value")
@mock_ec2_deprecated
def test_get_all_tags_key_filter():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("an instance key", "some value")
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
image = conn.get_image(image_id)
image.add_tag("an image key", "some value")
tags = conn.get_all_tags(filters={'key': 'an instance key'})
tags = conn.get_all_tags(filters={"key": "an instance key"})
tag = tags[0]
tags.should.have.length_of(1)
tag.res_id.should.equal(instance.id)
tag.res_type.should.equal('instance')
tag.res_type.should.equal("instance")
tag.name.should.equal("an instance key")
tag.value.should.equal("some value")
@mock_ec2_deprecated
def test_get_all_tags_value_filter():
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
instance = reservation.instances[0]
instance.add_tag("an instance key", "some value")
reservation_b = conn.run_instances('ami-1234abcd')
reservation_b = conn.run_instances("ami-1234abcd")
instance_b = reservation_b.instances[0]
instance_b.add_tag("an instance key", "some other value")
reservation_c = conn.run_instances('ami-1234abcd')
reservation_c = conn.run_instances("ami-1234abcd")
instance_c = reservation_c.instances[0]
instance_c.add_tag("an instance key", "other value*")
reservation_d = conn.run_instances('ami-1234abcd')
reservation_d = conn.run_instances("ami-1234abcd")
instance_d = reservation_d.instances[0]
instance_d.add_tag("an instance key", "other value**")
reservation_e = conn.run_instances('ami-1234abcd')
reservation_e = conn.run_instances("ami-1234abcd")
instance_e = reservation_e.instances[0]
instance_e.add_tag("an instance key", "other value*?")
image_id = conn.create_image(instance.id, "test-ami", "this is a test ami")
image = conn.get_image(image_id)
image.add_tag("an image key", "some value")
tags = conn.get_all_tags(filters={'value': 'some value'})
tags = conn.get_all_tags(filters={"value": "some value"})
tags.should.have.length_of(2)
tags = conn.get_all_tags(filters={'value': 'some*value'})
tags = conn.get_all_tags(filters={"value": "some*value"})
tags.should.have.length_of(3)
tags = conn.get_all_tags(filters={'value': '*some*value'})
tags = conn.get_all_tags(filters={"value": "*some*value"})
tags.should.have.length_of(3)
tags = conn.get_all_tags(filters={'value': '*some*value*'})
tags = conn.get_all_tags(filters={"value": "*some*value*"})
tags.should.have.length_of(3)
tags = conn.get_all_tags(filters={'value': '*value\*'})
tags = conn.get_all_tags(filters={"value": "*value\*"})
tags.should.have.length_of(1)
tags = conn.get_all_tags(filters={'value': '*value\*\*'})
tags = conn.get_all_tags(filters={"value": "*value\*\*"})
tags.should.have.length_of(1)
tags = conn.get_all_tags(filters={'value': '*value\*\?'})
tags = conn.get_all_tags(filters={"value": "*value\*\?"})
tags.should.have.length_of(1)
@mock_ec2_deprecated
def test_retrieved_instances_must_contain_their_tags():
tag_key = 'Tag name'
tag_value = 'Tag value'
tag_key = "Tag name"
tag_value = "Tag value"
tags_to_be_set = {tag_key: tag_value}
conn = boto.connect_ec2('the_key', 'the_secret')
reservation = conn.run_instances('ami-1234abcd')
conn = boto.connect_ec2("the_key", "the_secret")
reservation = conn.run_instances("ami-1234abcd")
reservation.should.be.a(Reservation)
reservation.instances.should.have.length_of(1)
instance = reservation.instances[0]
@ -324,10 +330,10 @@ def test_retrieved_instances_must_contain_their_tags():
@mock_ec2_deprecated
def test_retrieved_volumes_must_contain_their_tags():
tag_key = 'Tag name'
tag_value = 'Tag value'
tag_key = "Tag name"
tag_value = "Tag value"
tags_to_be_set = {tag_key: tag_value}
conn = boto.connect_ec2('the_key', 'the_secret')
conn = boto.connect_ec2("the_key", "the_secret")
volume = conn.create_volume(80, "us-east-1a")
all_volumes = conn.get_all_volumes()
@ -347,11 +353,12 @@ def test_retrieved_volumes_must_contain_their_tags():
@mock_ec2_deprecated
def test_retrieved_snapshots_must_contain_their_tags():
tag_key = 'Tag name'
tag_value = 'Tag value'
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)
@ -370,113 +377,94 @@ 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')
reservation = conn.run_instances('ami-1234abcd')
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")
reservation_b = conn.run_instances('ami-1234abcd')
reservation_b = conn.run_instances("ami-1234abcd")
instance_b = reservation_b.instances[0]
instance_b.add_tag("Key1", "Value2")
reservations = conn.get_all_instances(filters={'tag:Key1': 'Value*'})
reservations = conn.get_all_instances(filters={"tag:Key1": "Value*"})
reservations.should.have.length_of(2)
reservations = conn.get_all_instances(filters={'tag-key': 'Key*'})
reservations = conn.get_all_instances(filters={"tag-key": "Key*"})
reservations.should.have.length_of(2)
reservations = conn.get_all_instances(filters={'tag-value': 'Value*'})
reservations = conn.get_all_instances(filters={"tag-value": "Value*"})
reservations.should.have.length_of(2)
@mock_ec2
def test_create_volume_with_tags():
client = boto3.client('ec2', 'us-west-2')
client = boto3.client("ec2", "us-west-2")
response = client.create_volume(
AvailabilityZone='us-west-2',
Encrypted=False,
Size=40,
TagSpecifications=[
{
'ResourceType': 'volume',
'Tags': [
{
'Key': 'TEST_TAG',
'Value': 'TEST_VALUE'
}
],
}
]
)
assert response['Tags'][0]['Key'] == 'TEST_TAG'
@mock_ec2
def test_create_snapshot_with_tags():
client = boto3.client('ec2', 'us-west-2')
volume_id = client.create_volume(
AvailabilityZone='us-west-2',
AvailabilityZone="us-west-2",
Encrypted=False,
Size=40,
TagSpecifications=[
{
'ResourceType': 'volume',
'Tags': [
{
'Key': 'TEST_TAG',
'Value': 'TEST_VALUE'
}
],
"ResourceType": "volume",
"Tags": [{"Key": "TEST_TAG", "Value": "TEST_VALUE"}],
}
]
)['VolumeId']
],
)
assert response["Tags"][0]["Key"] == "TEST_TAG"
@mock_ec2
def test_create_snapshot_with_tags():
client = boto3.client("ec2", "us-west-2")
volume_id = client.create_volume(
AvailabilityZone="us-west-2",
Encrypted=False,
Size=40,
TagSpecifications=[
{
"ResourceType": "volume",
"Tags": [{"Key": "TEST_TAG", "Value": "TEST_VALUE"}],
}
],
)["VolumeId"]
snapshot = client.create_snapshot(
VolumeId=volume_id,
TagSpecifications=[
{
'ResourceType': 'snapshot',
'Tags': [
{
'Key': 'TEST_SNAPSHOT_TAG',
'Value': 'TEST_SNAPSHOT_VALUE'
}
],
"ResourceType": "snapshot",
"Tags": [{"Key": "TEST_SNAPSHOT_TAG", "Value": "TEST_SNAPSHOT_VALUE"}],
}
]
],
)
expected_tags = [{
'Key': 'TEST_SNAPSHOT_TAG',
'Value': 'TEST_SNAPSHOT_VALUE'
}]
expected_tags = [{"Key": "TEST_SNAPSHOT_TAG", "Value": "TEST_SNAPSHOT_VALUE"}]
assert snapshot['Tags'] == expected_tags
assert snapshot["Tags"] == expected_tags
@mock_ec2
def test_create_tag_empty_resource():
# create ec2 client in us-west-1
client = boto3.client('ec2', region_name='us-west-1')
client = boto3.client("ec2", region_name="us-west-1")
# create tag with empty resource
with assert_raises(ClientError) as ex:
client.create_tags(
Resources=[],
Tags=[{'Key': 'Value'}]
)
ex.exception.response['Error']['Code'].should.equal('MissingParameter')
ex.exception.response['Error']['Message'].should.equal('The request must contain the parameter resourceIdSet')
client.create_tags(Resources=[], Tags=[{"Key": "Value"}])
ex.exception.response["Error"]["Code"].should.equal("MissingParameter")
ex.exception.response["Error"]["Message"].should.equal(
"The request must contain the parameter resourceIdSet"
)
@mock_ec2
def test_delete_tag_empty_resource():
# create ec2 client in us-west-1
client = boto3.client('ec2', region_name='us-west-1')
client = boto3.client("ec2", region_name="us-west-1")
# delete tag with empty resource
with assert_raises(ClientError) as ex:
client.delete_tags(
Resources=[],
Tags=[{'Key': 'Value'}]
)
ex.exception.response['Error']['Code'].should.equal('MissingParameter')
ex.exception.response['Error']['Message'].should.equal('The request must contain the parameter resourceIdSet')
client.delete_tags(Resources=[], Tags=[{"Key": "Value"}])
ex.exception.response["Error"]["Code"].should.equal("MissingParameter")
ex.exception.response["Error"]["Message"].should.equal(
"The request must contain the parameter resourceIdSet"
)

View file

@ -5,8 +5,8 @@ from .helpers import rsa_check_private_key
def test_random_key_pair():
key_pair = utils.random_key_pair()
rsa_check_private_key(key_pair['material'])
rsa_check_private_key(key_pair["material"])
# AWS uses MD5 fingerprints, which are 47 characters long, *not* SHA1
# fingerprints with 59 characters.
assert len(key_pair['fingerprint']) == 47
assert len(key_pair["fingerprint"]) == 47

View file

@ -7,54 +7,51 @@ from moto import mock_ec2_deprecated
@mock_ec2_deprecated
def test_virtual_private_gateways():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
vpn_gateway.should_not.be.none
vpn_gateway.id.should.match(r'vgw-\w+')
vpn_gateway.type.should.equal('ipsec.1')
vpn_gateway.state.should.equal('available')
vpn_gateway.availability_zone.should.equal('us-east-1a')
vpn_gateway.id.should.match(r"vgw-\w+")
vpn_gateway.type.should.equal("ipsec.1")
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')
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
conn = boto.connect_vpc("the_key", "the_secret")
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
vgws = conn.get_all_vpn_gateways()
vgws.should.have.length_of(1)
gateway = vgws[0]
gateway.id.should.match(r'vgw-\w+')
gateway.id.should.match(r"vgw-\w+")
gateway.id.should.equal(vpn_gateway.id)
vpn_gateway.type.should.equal('ipsec.1')
vpn_gateway.state.should.equal('available')
vpn_gateway.availability_zone.should.equal('us-east-1a')
vpn_gateway.type.should.equal("ipsec.1")
vpn_gateway.state.should.equal("available")
vpn_gateway.availability_zone.should.equal("us-east-1a")
@mock_ec2_deprecated
def test_vpn_gateway_vpc_attachment():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
conn.attach_vpn_gateway(
vpn_gateway_id=vpn_gateway.id,
vpc_id=vpc.id
)
conn.attach_vpn_gateway(vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id)
gateway = conn.get_all_vpn_gateways()[0]
attachments = gateway.attachments
attachments.should.have.length_of(1)
attachments[0].vpc_id.should.equal(vpc.id)
attachments[0].state.should.equal('attached')
attachments[0].state.should.equal("attached")
@mock_ec2_deprecated
def test_delete_vpn_gateway():
conn = boto.connect_vpc('the_key', 'the_secret')
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
conn = boto.connect_vpc("the_key", "the_secret")
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
conn.delete_vpn_gateway(vpn_gateway.id)
vgws = conn.get_all_vpn_gateways()
@ -63,8 +60,8 @@ def test_delete_vpn_gateway():
@mock_ec2_deprecated
def test_vpn_gateway_tagging():
conn = boto.connect_vpc('the_key', 'the_secret')
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
conn = boto.connect_vpc("the_key", "the_secret")
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
vpn_gateway.add_tag("a key", "some value")
tag = conn.get_all_tags()[0]
@ -80,25 +77,19 @@ def test_vpn_gateway_tagging():
@mock_ec2_deprecated
def test_detach_vpn_gateway():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a')
vpn_gateway = conn.create_vpn_gateway("ipsec.1", "us-east-1a")
conn.attach_vpn_gateway(
vpn_gateway_id=vpn_gateway.id,
vpc_id=vpc.id
)
conn.attach_vpn_gateway(vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id)
gateway = conn.get_all_vpn_gateways()[0]
attachments = gateway.attachments
attachments.should.have.length_of(1)
attachments[0].vpc_id.should.equal(vpc.id)
attachments[0].state.should.equal('attached')
attachments[0].state.should.equal("attached")
conn.detach_vpn_gateway(
vpn_gateway_id=vpn_gateway.id,
vpc_id=vpc.id
)
conn.detach_vpn_gateway(vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id)
gateway = conn.get_all_vpn_gateways()[0]
attachments = gateway.attachments

View file

@ -1,4 +1,5 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
@ -17,12 +18,12 @@ from tests.helpers import requires_boto_gte
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
peer_vpc = conn.create_vpc("11.0.0.0/16")
vpc_pcx = conn.create_vpc_peering_connection(vpc.id, peer_vpc.id)
vpc_pcx._status.code.should.equal('initiating-request')
vpc_pcx._status.code.should.equal("initiating-request")
return vpc_pcx
@ -30,39 +31,39 @@ def test_vpc_peering_connections():
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_get_all():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
vpc_pcx._status.code.should.equal('initiating-request')
vpc_pcx._status.code.should.equal("initiating-request")
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal('pending-acceptance')
all_vpc_pcxs[0]._status.code.should.equal("pending-acceptance")
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_accept():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
vpc_pcx = conn.accept_vpc_peering_connection(vpc_pcx.id)
vpc_pcx._status.code.should.equal('active')
vpc_pcx._status.code.should.equal("active")
with assert_raises(EC2ResponseError) as cm:
conn.reject_vpc_peering_connection(vpc_pcx.id)
cm.exception.code.should.equal('InvalidStateTransition')
cm.exception.code.should.equal("InvalidStateTransition")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal('active')
all_vpc_pcxs[0]._status.code.should.equal("active")
@requires_boto_gte("2.32.0")
@mock_ec2_deprecated
def test_vpc_peering_connections_reject():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
verdict = conn.reject_vpc_peering_connection(vpc_pcx.id)
@ -70,19 +71,19 @@ def test_vpc_peering_connections_reject():
with assert_raises(EC2ResponseError) as cm:
conn.accept_vpc_peering_connection(vpc_pcx.id)
cm.exception.code.should.equal('InvalidStateTransition')
cm.exception.code.should.equal("InvalidStateTransition")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal('rejected')
all_vpc_pcxs[0]._status.code.should.equal("rejected")
@requires_boto_gte("2.32.1")
@mock_ec2_deprecated
def test_vpc_peering_connections_delete():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc_pcx = test_vpc_peering_connections()
verdict = vpc_pcx.delete()
@ -90,11 +91,11 @@ def test_vpc_peering_connections_delete():
all_vpc_pcxs = conn.get_all_vpc_peering_connections()
all_vpc_pcxs.should.have.length_of(1)
all_vpc_pcxs[0]._status.code.should.equal('deleted')
all_vpc_pcxs[0]._status.code.should.equal("deleted")
with assert_raises(EC2ResponseError) as cm:
conn.delete_vpc_peering_connection("pcx-1234abcd")
cm.exception.code.should.equal('InvalidVpcPeeringConnectionId.NotFound')
cm.exception.code.should.equal("InvalidVpcPeeringConnectionId.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -102,17 +103,15 @@ def test_vpc_peering_connections_delete():
@mock_ec2
def test_vpc_peering_connections_cross_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
vpc_pcx_usw1.status['Code'].should.equal('initiating-request')
vpc_pcx_usw1.status["Code"].should.equal("initiating-request")
vpc_pcx_usw1.requester_vpc.id.should.equal(vpc_usw1.id)
vpc_pcx_usw1.accepter_vpc.id.should.equal(vpc_apn1.id)
# test cross region vpc peering connection exist
@ -125,35 +124,32 @@ def test_vpc_peering_connections_cross_region():
@mock_ec2
def test_vpc_peering_connections_cross_region_fail():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering wrong region with no vpc
with assert_raises(ClientError) as cm:
ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-2')
cm.exception.response['Error']['Code'].should.equal('InvalidVpcID.NotFound')
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-2"
)
cm.exception.response["Error"]["Code"].should.equal("InvalidVpcID.NotFound")
@mock_ec2
def test_vpc_peering_connections_cross_region_accept():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# accept peering from ap-northeast-1
ec2_apn1 = boto3.client('ec2', region_name='ap-northeast-1')
ec2_usw1 = boto3.client('ec2', region_name='us-west-1')
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
acp_pcx_apn1 = ec2_apn1.accept_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
@ -163,27 +159,25 @@ def test_vpc_peering_connections_cross_region_accept():
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
acp_pcx_apn1['VpcPeeringConnection']['Status']['Code'].should.equal('active')
des_pcx_apn1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('active')
des_pcx_usw1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('active')
acp_pcx_apn1["VpcPeeringConnection"]["Status"]["Code"].should.equal("active")
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("active")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("active")
@mock_ec2
def test_vpc_peering_connections_cross_region_reject():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject peering from ap-northeast-1
ec2_apn1 = boto3.client('ec2', region_name='ap-northeast-1')
ec2_usw1 = boto3.client('ec2', region_name='us-west-1')
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
rej_pcx_apn1 = ec2_apn1.reject_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
@ -193,27 +187,25 @@ def test_vpc_peering_connections_cross_region_reject():
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
rej_pcx_apn1['Return'].should.equal(True)
des_pcx_apn1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('rejected')
des_pcx_usw1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('rejected')
rej_pcx_apn1["Return"].should.equal(True)
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("rejected")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("rejected")
@mock_ec2
def test_vpc_peering_connections_cross_region_delete():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject peering from ap-northeast-1
ec2_apn1 = boto3.client('ec2', region_name='ap-northeast-1')
ec2_usw1 = boto3.client('ec2', region_name='us-west-1')
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
del_pcx_apn1 = ec2_apn1.delete_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
@ -223,61 +215,57 @@ def test_vpc_peering_connections_cross_region_delete():
des_pcx_usw1 = ec2_usw1.describe_vpc_peering_connections(
VpcPeeringConnectionIds=[vpc_pcx_usw1.id]
)
del_pcx_apn1['Return'].should.equal(True)
des_pcx_apn1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('deleted')
des_pcx_usw1['VpcPeeringConnections'][0]['Status']['Code'].should.equal('deleted')
del_pcx_apn1["Return"].should.equal(True)
des_pcx_apn1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("deleted")
des_pcx_usw1["VpcPeeringConnections"][0]["Status"]["Code"].should.equal("deleted")
@mock_ec2
def test_vpc_peering_connections_cross_region_accept_wrong_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# accept wrong peering from us-west-1 which will raise error
ec2_apn1 = boto3.client('ec2', region_name='ap-northeast-1')
ec2_usw1 = boto3.client('ec2', region_name='us-west-1')
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
with assert_raises(ClientError) as cm:
ec2_usw1.accept_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
cm.exception.response['Error']['Code'].should.equal('OperationNotPermitted')
exp_msg = 'Incorrect region ({0}) specified for this request.VPC ' \
'peering connection {1} must be ' \
'accepted in region {2}'.format('us-west-1', vpc_pcx_usw1.id, 'ap-northeast-1')
cm.exception.response['Error']['Message'].should.equal(exp_msg)
ec2_usw1.accept_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id)
cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted")
exp_msg = (
"Incorrect region ({0}) specified for this request.VPC "
"peering connection {1} must be "
"accepted in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1")
)
cm.exception.response["Error"]["Message"].should.equal(exp_msg)
@mock_ec2
def test_vpc_peering_connections_cross_region_reject_wrong_region():
# create vpc in us-west-1 and ap-northeast-1
ec2_usw1 = boto3.resource('ec2', region_name='us-west-1')
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock='10.90.0.0/16')
ec2_apn1 = boto3.resource('ec2', region_name='ap-northeast-1')
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock='10.20.0.0/16')
ec2_usw1 = boto3.resource("ec2", region_name="us-west-1")
vpc_usw1 = ec2_usw1.create_vpc(CidrBlock="10.90.0.0/16")
ec2_apn1 = boto3.resource("ec2", region_name="ap-northeast-1")
vpc_apn1 = ec2_apn1.create_vpc(CidrBlock="10.20.0.0/16")
# create peering
vpc_pcx_usw1 = ec2_usw1.create_vpc_peering_connection(
VpcId=vpc_usw1.id,
PeerVpcId=vpc_apn1.id,
PeerRegion='ap-northeast-1',
VpcId=vpc_usw1.id, PeerVpcId=vpc_apn1.id, PeerRegion="ap-northeast-1"
)
# reject wrong peering from us-west-1 which will raise error
ec2_apn1 = boto3.client('ec2', region_name='ap-northeast-1')
ec2_usw1 = boto3.client('ec2', region_name='us-west-1')
ec2_apn1 = boto3.client("ec2", region_name="ap-northeast-1")
ec2_usw1 = boto3.client("ec2", region_name="us-west-1")
with assert_raises(ClientError) as cm:
ec2_usw1.reject_vpc_peering_connection(
VpcPeeringConnectionId=vpc_pcx_usw1.id
)
cm.exception.response['Error']['Code'].should.equal('OperationNotPermitted')
exp_msg = 'Incorrect region ({0}) specified for this request.VPC ' \
'peering connection {1} must be accepted or ' \
'rejected in region {2}'.format('us-west-1', vpc_pcx_usw1.id, 'ap-northeast-1')
cm.exception.response['Error']['Message'].should.equal(exp_msg)
ec2_usw1.reject_vpc_peering_connection(VpcPeeringConnectionId=vpc_pcx_usw1.id)
cm.exception.response["Error"]["Code"].should.equal("OperationNotPermitted")
exp_msg = (
"Incorrect region ({0}) specified for this request.VPC "
"peering connection {1} must be accepted or "
"rejected in region {2}".format("us-west-1", vpc_pcx_usw1.id, "ap-northeast-1")
)
cm.exception.response["Error"]["Message"].should.equal(exp_msg)

View file

@ -1,6 +1,7 @@
from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises # flake8: noqa
import tests.backport_assert_raises # noqa
from nose.tools import assert_raises
from moto.ec2.exceptions import EC2ClientError
from botocore.exceptions import ClientError
@ -12,15 +13,15 @@ import sure # noqa
from moto import mock_ec2, mock_ec2_deprecated
SAMPLE_DOMAIN_NAME = u'example.com'
SAMPLE_NAME_SERVERS = [u'10.0.0.6', u'10.0.0.7']
SAMPLE_DOMAIN_NAME = "example.com"
SAMPLE_NAME_SERVERS = ["10.0.0.6", "10.0.0.7"]
@mock_ec2_deprecated
def test_vpcs():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
vpc.cidr_block.should.equal('10.0.0.0/16')
vpc.cidr_block.should.equal("10.0.0.0/16")
all_vpcs = conn.get_all_vpcs()
all_vpcs.should.have.length_of(2)
@ -32,58 +33,56 @@ def test_vpcs():
with assert_raises(EC2ResponseError) as cm:
conn.delete_vpc("vpc-1234abcd")
cm.exception.code.should.equal('InvalidVpcID.NotFound')
cm.exception.code.should.equal("InvalidVpcID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@mock_ec2_deprecated
def test_vpc_defaults():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
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():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
conn.get_all_vpcs(filters={'isDefault': 'true'}).should.have.length_of(1)
conn.get_all_vpcs(filters={"isDefault": "true"}).should.have.length_of(1)
vpc.delete()
conn.get_all_vpcs(filters={'isDefault': 'true'}).should.have.length_of(1)
conn.get_all_vpcs(filters={"isDefault": "true"}).should.have.length_of(1)
@mock_ec2_deprecated
def test_multiple_vpcs_default_filter():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
conn.create_vpc("10.8.0.0/16")
conn.create_vpc("10.0.0.0/16")
conn.create_vpc("192.168.0.0/16")
conn.get_all_vpcs().should.have.length_of(4)
vpc = conn.get_all_vpcs(filters={'isDefault': 'true'})
vpc = conn.get_all_vpcs(filters={"isDefault": "true"})
vpc.should.have.length_of(1)
vpc[0].cidr_block.should.equal('172.31.0.0/16')
vpc[0].cidr_block.should.equal("172.31.0.0/16")
@mock_ec2_deprecated
def test_vpc_state_available_filter():
conn = boto.connect_vpc('the_key', 'the_secret')
conn = boto.connect_vpc("the_key", "the_secret")
vpc = conn.create_vpc("10.0.0.0/16")
conn.create_vpc("10.1.0.0/16")
conn.get_all_vpcs(filters={'state': 'available'}).should.have.length_of(3)
conn.get_all_vpcs(filters={"state": "available"}).should.have.length_of(3)
vpc.delete()
conn.get_all_vpcs(filters={'state': 'available'}).should.have.length_of(2)
conn.get_all_vpcs(filters={"state": "available"}).should.have.length_of(2)
@mock_ec2_deprecated
@ -116,8 +115,8 @@ def test_vpc_get_by_id():
vpc2.id.should.be.within(vpc_ids)
with assert_raises(EC2ResponseError) as cm:
conn.get_all_vpcs(vpc_ids=['vpc-does_not_exist'])
cm.exception.code.should.equal('InvalidVpcID.NotFound')
conn.get_all_vpcs(vpc_ids=["vpc-does_not_exist"])
cm.exception.code.should.equal("InvalidVpcID.NotFound")
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
@ -129,7 +128,7 @@ def test_vpc_get_by_cidr_block():
vpc2 = conn.create_vpc("10.0.0.0/16")
conn.create_vpc("10.0.0.0/24")
vpcs = conn.get_all_vpcs(filters={'cidr': '10.0.0.0/16'})
vpcs = conn.get_all_vpcs(filters={"cidr": "10.0.0.0/16"})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -139,8 +138,7 @@ 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")
@ -148,7 +146,7 @@ def test_vpc_get_by_dhcp_options_id():
conn.associate_dhcp_options(dhcp_options.id, vpc1.id)
conn.associate_dhcp_options(dhcp_options.id, vpc2.id)
vpcs = conn.get_all_vpcs(filters={'dhcp-options-id': dhcp_options.id})
vpcs = conn.get_all_vpcs(filters={"dhcp-options-id": dhcp_options.id})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -162,11 +160,11 @@ def test_vpc_get_by_tag():
vpc2 = conn.create_vpc("10.0.0.0/16")
vpc3 = conn.create_vpc("10.0.0.0/24")
vpc1.add_tag('Name', 'TestVPC')
vpc2.add_tag('Name', 'TestVPC')
vpc3.add_tag('Name', 'TestVPC2')
vpc1.add_tag("Name", "TestVPC")
vpc2.add_tag("Name", "TestVPC")
vpc3.add_tag("Name", "TestVPC2")
vpcs = conn.get_all_vpcs(filters={'tag:Name': 'TestVPC'})
vpcs = conn.get_all_vpcs(filters={"tag:Name": "TestVPC"})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -180,13 +178,13 @@ def test_vpc_get_by_tag_key_superset():
vpc2 = conn.create_vpc("10.0.0.0/16")
vpc3 = conn.create_vpc("10.0.0.0/24")
vpc1.add_tag('Name', 'TestVPC')
vpc1.add_tag('Key', 'TestVPC2')
vpc2.add_tag('Name', 'TestVPC')
vpc2.add_tag('Key', 'TestVPC2')
vpc3.add_tag('Key', 'TestVPC2')
vpc1.add_tag("Name", "TestVPC")
vpc1.add_tag("Key", "TestVPC2")
vpc2.add_tag("Name", "TestVPC")
vpc2.add_tag("Key", "TestVPC2")
vpc3.add_tag("Key", "TestVPC2")
vpcs = conn.get_all_vpcs(filters={'tag-key': 'Name'})
vpcs = conn.get_all_vpcs(filters={"tag-key": "Name"})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -200,13 +198,13 @@ def test_vpc_get_by_tag_key_subset():
vpc2 = conn.create_vpc("10.0.0.0/16")
vpc3 = conn.create_vpc("10.0.0.0/24")
vpc1.add_tag('Name', 'TestVPC')
vpc1.add_tag('Key', 'TestVPC2')
vpc2.add_tag('Name', 'TestVPC')
vpc2.add_tag('Key', 'TestVPC2')
vpc3.add_tag('Test', 'TestVPC2')
vpc1.add_tag("Name", "TestVPC")
vpc1.add_tag("Key", "TestVPC2")
vpc2.add_tag("Name", "TestVPC")
vpc2.add_tag("Key", "TestVPC2")
vpc3.add_tag("Test", "TestVPC2")
vpcs = conn.get_all_vpcs(filters={'tag-key': ['Name', 'Key']})
vpcs = conn.get_all_vpcs(filters={"tag-key": ["Name", "Key"]})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -220,13 +218,13 @@ def test_vpc_get_by_tag_value_superset():
vpc2 = conn.create_vpc("10.0.0.0/16")
vpc3 = conn.create_vpc("10.0.0.0/24")
vpc1.add_tag('Name', 'TestVPC')
vpc1.add_tag('Key', 'TestVPC2')
vpc2.add_tag('Name', 'TestVPC')
vpc2.add_tag('Key', 'TestVPC2')
vpc3.add_tag('Key', 'TestVPC2')
vpc1.add_tag("Name", "TestVPC")
vpc1.add_tag("Key", "TestVPC2")
vpc2.add_tag("Name", "TestVPC")
vpc2.add_tag("Key", "TestVPC2")
vpc3.add_tag("Key", "TestVPC2")
vpcs = conn.get_all_vpcs(filters={'tag-value': 'TestVPC'})
vpcs = conn.get_all_vpcs(filters={"tag-value": "TestVPC"})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -240,12 +238,12 @@ def test_vpc_get_by_tag_value_subset():
vpc2 = conn.create_vpc("10.0.0.0/16")
conn.create_vpc("10.0.0.0/24")
vpc1.add_tag('Name', 'TestVPC')
vpc1.add_tag('Key', 'TestVPC2')
vpc2.add_tag('Name', 'TestVPC')
vpc2.add_tag('Key', 'TestVPC2')
vpc1.add_tag("Name", "TestVPC")
vpc1.add_tag("Key", "TestVPC2")
vpc2.add_tag("Name", "TestVPC")
vpc2.add_tag("Key", "TestVPC2")
vpcs = conn.get_all_vpcs(filters={'tag-value': ['TestVPC', 'TestVPC2']})
vpcs = conn.get_all_vpcs(filters={"tag-value": ["TestVPC", "TestVPC2"]})
vpcs.should.have.length_of(2)
vpc_ids = tuple(map(lambda v: v.id, vpcs))
vpc1.id.should.be.within(vpc_ids)
@ -254,117 +252,116 @@ def test_vpc_get_by_tag_value_subset():
@mock_ec2
def test_default_vpc():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the default VPC
default_vpc = list(ec2.vpcs.all())[0]
default_vpc.cidr_block.should.equal('172.31.0.0/16')
default_vpc.instance_tenancy.should.equal('default')
default_vpc.cidr_block.should.equal("172.31.0.0/16")
default_vpc.instance_tenancy.should.equal("default")
default_vpc.reload()
default_vpc.is_default.should.be.ok
# Test default values for VPC attributes
response = default_vpc.describe_attribute(Attribute='enableDnsSupport')
attr = response.get('EnableDnsSupport')
attr.get('Value').should.be.ok
response = default_vpc.describe_attribute(Attribute="enableDnsSupport")
attr = response.get("EnableDnsSupport")
attr.get("Value").should.be.ok
response = default_vpc.describe_attribute(Attribute='enableDnsHostnames')
attr = response.get('EnableDnsHostnames')
attr.get('Value').should.be.ok
response = default_vpc.describe_attribute(Attribute="enableDnsHostnames")
attr = response.get("EnableDnsHostnames")
attr.get("Value").should.be.ok
@mock_ec2
def test_non_default_vpc():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the default VPC - this already exists when backend instantiated!
#ec2.create_vpc(CidrBlock='172.31.0.0/16')
# ec2.create_vpc(CidrBlock='172.31.0.0/16')
# Create the non default VPC
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
vpc.reload()
vpc.is_default.shouldnt.be.ok
# Test default instance_tenancy
vpc.instance_tenancy.should.equal('default')
vpc.instance_tenancy.should.equal("default")
# Test default values for VPC attributes
response = vpc.describe_attribute(Attribute='enableDnsSupport')
attr = response.get('EnableDnsSupport')
attr.get('Value').should.be.ok
response = vpc.describe_attribute(Attribute="enableDnsSupport")
attr = response.get("EnableDnsSupport")
attr.get("Value").should.be.ok
response = vpc.describe_attribute(Attribute='enableDnsHostnames')
attr = response.get('EnableDnsHostnames')
attr.get('Value').shouldnt.be.ok
response = vpc.describe_attribute(Attribute="enableDnsHostnames")
attr = response.get("EnableDnsHostnames")
attr.get("Value").shouldnt.be.ok
# Check Primary CIDR Block Associations
cidr_block_association_set = next(iter(vpc.cidr_block_association_set), None)
cidr_block_association_set['CidrBlockState']['State'].should.equal('associated')
cidr_block_association_set['CidrBlock'].should.equal(vpc.cidr_block)
cidr_block_association_set['AssociationId'].should.contain('vpc-cidr-assoc')
cidr_block_association_set["CidrBlockState"]["State"].should.equal("associated")
cidr_block_association_set["CidrBlock"].should.equal(vpc.cidr_block)
cidr_block_association_set["AssociationId"].should.contain("vpc-cidr-assoc")
@mock_ec2
def test_vpc_dedicated_tenancy():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the default VPC
ec2.create_vpc(CidrBlock='172.31.0.0/16')
ec2.create_vpc(CidrBlock="172.31.0.0/16")
# Create the non default VPC
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='dedicated')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16", InstanceTenancy="dedicated")
vpc.reload()
vpc.is_default.shouldnt.be.ok
vpc.instance_tenancy.should.equal('dedicated')
vpc.instance_tenancy.should.equal("dedicated")
@mock_ec2
def test_vpc_modify_enable_dns_support():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the default VPC
ec2.create_vpc(CidrBlock='172.31.0.0/16')
ec2.create_vpc(CidrBlock="172.31.0.0/16")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
# Test default values for VPC attributes
response = vpc.describe_attribute(Attribute='enableDnsSupport')
attr = response.get('EnableDnsSupport')
attr.get('Value').should.be.ok
response = vpc.describe_attribute(Attribute="enableDnsSupport")
attr = response.get("EnableDnsSupport")
attr.get("Value").should.be.ok
vpc.modify_attribute(EnableDnsSupport={'Value': False})
vpc.modify_attribute(EnableDnsSupport={"Value": False})
response = vpc.describe_attribute(Attribute='enableDnsSupport')
attr = response.get('EnableDnsSupport')
attr.get('Value').shouldnt.be.ok
response = vpc.describe_attribute(Attribute="enableDnsSupport")
attr = response.get("EnableDnsSupport")
attr.get("Value").shouldnt.be.ok
@mock_ec2
def test_vpc_modify_enable_dns_hostnames():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create the default VPC
ec2.create_vpc(CidrBlock='172.31.0.0/16')
ec2.create_vpc(CidrBlock="172.31.0.0/16")
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
# Test default values for VPC attributes
response = vpc.describe_attribute(Attribute='enableDnsHostnames')
attr = response.get('EnableDnsHostnames')
attr.get('Value').shouldnt.be.ok
response = vpc.describe_attribute(Attribute="enableDnsHostnames")
attr = response.get("EnableDnsHostnames")
attr.get("Value").shouldnt.be.ok
vpc.modify_attribute(EnableDnsHostnames={'Value': True})
vpc.modify_attribute(EnableDnsHostnames={"Value": True})
response = vpc.describe_attribute(Attribute='enableDnsHostnames')
attr = response.get('EnableDnsHostnames')
attr.get('Value').should.be.ok
response = vpc.describe_attribute(Attribute="enableDnsHostnames")
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)
@ -375,117 +372,206 @@ def test_vpc_associate_dhcp_options():
@mock_ec2
def test_associate_vpc_ipv4_cidr_block():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.10.42.0/24')
vpc = ec2.create_vpc(CidrBlock="10.10.42.0/24")
# Associate/Extend vpc CIDR range up to 5 ciders
for i in range(43, 47):
response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, CidrBlock='10.10.{}.0/24'.format(i))
response['CidrBlockAssociation']['CidrBlockState']['State'].should.equal('associating')
response['CidrBlockAssociation']['CidrBlock'].should.equal('10.10.{}.0/24'.format(i))
response['CidrBlockAssociation']['AssociationId'].should.contain('vpc-cidr-assoc')
response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc.id, CidrBlock="10.10.{}.0/24".format(i)
)
response["CidrBlockAssociation"]["CidrBlockState"]["State"].should.equal(
"associating"
)
response["CidrBlockAssociation"]["CidrBlock"].should.equal(
"10.10.{}.0/24".format(i)
)
response["CidrBlockAssociation"]["AssociationId"].should.contain(
"vpc-cidr-assoc"
)
# Check all associations exist
vpc = ec2.Vpc(vpc.id)
vpc.cidr_block_association_set.should.have.length_of(5)
vpc.cidr_block_association_set[2]['CidrBlockState']['State'].should.equal('associated')
vpc.cidr_block_association_set[4]['CidrBlockState']['State'].should.equal('associated')
vpc.cidr_block_association_set[2]["CidrBlockState"]["State"].should.equal(
"associated"
)
vpc.cidr_block_association_set[4]["CidrBlockState"]["State"].should.equal(
"associated"
)
# Check error on adding 6th association.
with assert_raises(ClientError) as ex:
response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, CidrBlock='10.10.50.0/22')
response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc.id, CidrBlock="10.10.50.0/22"
)
str(ex.exception).should.equal(
"An error occurred (CidrLimitExceeded) when calling the AssociateVpcCidrBlock "
"operation: This network '{}' has met its maximum number of allowed CIDRs: 5".format(vpc.id))
"operation: This network '{}' has met its maximum number of allowed CIDRs: 5".format(
vpc.id
)
)
@mock_ec2
def test_disassociate_vpc_ipv4_cidr_block():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc = ec2.create_vpc(CidrBlock='10.10.42.0/24')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, CidrBlock='10.10.43.0/24')
vpc = ec2.create_vpc(CidrBlock="10.10.42.0/24")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, CidrBlock="10.10.43.0/24")
# Remove an extended cidr block
vpc = ec2.Vpc(vpc.id)
non_default_assoc_cidr_block = next(iter([x for x in vpc.cidr_block_association_set if vpc.cidr_block != x['CidrBlock']]), None)
response = ec2.meta.client.disassociate_vpc_cidr_block(AssociationId=non_default_assoc_cidr_block['AssociationId'])
response['CidrBlockAssociation']['CidrBlockState']['State'].should.equal('disassociating')
response['CidrBlockAssociation']['CidrBlock'].should.equal(non_default_assoc_cidr_block['CidrBlock'])
response['CidrBlockAssociation']['AssociationId'].should.equal(non_default_assoc_cidr_block['AssociationId'])
non_default_assoc_cidr_block = next(
iter(
[
x
for x in vpc.cidr_block_association_set
if vpc.cidr_block != x["CidrBlock"]
]
),
None,
)
response = ec2.meta.client.disassociate_vpc_cidr_block(
AssociationId=non_default_assoc_cidr_block["AssociationId"]
)
response["CidrBlockAssociation"]["CidrBlockState"]["State"].should.equal(
"disassociating"
)
response["CidrBlockAssociation"]["CidrBlock"].should.equal(
non_default_assoc_cidr_block["CidrBlock"]
)
response["CidrBlockAssociation"]["AssociationId"].should.equal(
non_default_assoc_cidr_block["AssociationId"]
)
# Error attempting to delete a non-existent CIDR_BLOCK association
with assert_raises(ClientError) as ex:
response = ec2.meta.client.disassociate_vpc_cidr_block(AssociationId='vpc-cidr-assoc-BORING123')
response = ec2.meta.client.disassociate_vpc_cidr_block(
AssociationId="vpc-cidr-assoc-BORING123"
)
str(ex.exception).should.equal(
"An error occurred (InvalidVpcCidrBlockAssociationIdError.NotFound) when calling the "
"DisassociateVpcCidrBlock operation: The vpc CIDR block association ID "
"'vpc-cidr-assoc-BORING123' does not exist")
"'vpc-cidr-assoc-BORING123' does not exist"
)
# Error attempting to delete Primary CIDR BLOCK association
vpc_base_cidr_assoc_id = next(iter([x for x in vpc.cidr_block_association_set
if vpc.cidr_block == x['CidrBlock']]), {})['AssociationId']
vpc_base_cidr_assoc_id = next(
iter(
[
x
for x in vpc.cidr_block_association_set
if vpc.cidr_block == x["CidrBlock"]
]
),
{},
)["AssociationId"]
with assert_raises(ClientError) as ex:
response = ec2.meta.client.disassociate_vpc_cidr_block(AssociationId=vpc_base_cidr_assoc_id)
response = ec2.meta.client.disassociate_vpc_cidr_block(
AssociationId=vpc_base_cidr_assoc_id
)
str(ex.exception).should.equal(
"An error occurred (OperationNotPermitted) when calling the DisassociateVpcCidrBlock operation: "
"The vpc CIDR block with association ID {} may not be disassociated. It is the primary "
"IPv4 CIDR block of the VPC".format(vpc_base_cidr_assoc_id))
"IPv4 CIDR block of the VPC".format(vpc_base_cidr_assoc_id)
)
@mock_ec2
def test_cidr_block_association_filters():
ec2 = boto3.resource('ec2', region_name='us-west-1')
vpc1 = ec2.create_vpc(CidrBlock='10.90.0.0/16')
vpc2 = ec2.create_vpc(CidrBlock='10.91.0.0/16')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc2.id, CidrBlock='10.10.0.0/19')
vpc3 = ec2.create_vpc(CidrBlock='10.92.0.0/24')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock='10.92.1.0/24')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock='10.92.2.0/24')
vpc3_assoc_response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock='10.92.3.0/24')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc1 = ec2.create_vpc(CidrBlock="10.90.0.0/16")
vpc2 = ec2.create_vpc(CidrBlock="10.91.0.0/16")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc2.id, CidrBlock="10.10.0.0/19")
vpc3 = ec2.create_vpc(CidrBlock="10.92.0.0/24")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock="10.92.1.0/24")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock="10.92.2.0/24")
vpc3_assoc_response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc3.id, CidrBlock="10.92.3.0/24"
)
# Test filters for a cidr-block in all VPCs cidr-block-associations
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'cidr-block-association.cidr-block',
'Values': ['10.10.0.0/19']}]))
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{
"Name": "cidr-block-association.cidr-block",
"Values": ["10.10.0.0/19"],
}
]
)
)
filtered_vpcs.should.be.length_of(1)
filtered_vpcs[0].id.should.equal(vpc2.id)
# Test filter for association id in VPCs
association_id = vpc3_assoc_response['CidrBlockAssociation']['AssociationId']
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'cidr-block-association.association-id',
'Values': [association_id]}]))
association_id = vpc3_assoc_response["CidrBlockAssociation"]["AssociationId"]
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{
"Name": "cidr-block-association.association-id",
"Values": [association_id],
}
]
)
)
filtered_vpcs.should.be.length_of(1)
filtered_vpcs[0].id.should.equal(vpc3.id)
# Test filter for association state in VPC - this will never show anything in this test
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'cidr-block-association.association-id',
'Values': ['failing']}]))
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{"Name": "cidr-block-association.association-id", "Values": ["failing"]}
]
)
)
filtered_vpcs.should.be.length_of(0)
@mock_ec2
def test_vpc_associate_ipv6_cidr_block():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Test create VPC with IPV6 cidr range
vpc = ec2.create_vpc(CidrBlock='10.10.42.0/24', AmazonProvidedIpv6CidrBlock=True)
ipv6_cidr_block_association_set = next(iter(vpc.ipv6_cidr_block_association_set), None)
ipv6_cidr_block_association_set['Ipv6CidrBlockState']['State'].should.equal('associated')
ipv6_cidr_block_association_set['Ipv6CidrBlock'].should.contain('::/56')
ipv6_cidr_block_association_set['AssociationId'].should.contain('vpc-cidr-assoc')
vpc = ec2.create_vpc(CidrBlock="10.10.42.0/24", AmazonProvidedIpv6CidrBlock=True)
ipv6_cidr_block_association_set = next(
iter(vpc.ipv6_cidr_block_association_set), None
)
ipv6_cidr_block_association_set["Ipv6CidrBlockState"]["State"].should.equal(
"associated"
)
ipv6_cidr_block_association_set["Ipv6CidrBlock"].should.contain("::/56")
ipv6_cidr_block_association_set["AssociationId"].should.contain("vpc-cidr-assoc")
# Test Fail on adding 2nd IPV6 association - AWS only allows 1 at this time!
with assert_raises(ClientError) as ex:
response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True)
response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True
)
str(ex.exception).should.equal(
"An error occurred (CidrLimitExceeded) when calling the AssociateVpcCidrBlock "
"operation: This network '{}' has met its maximum number of allowed CIDRs: 1".format(vpc.id))
"operation: This network '{}' has met its maximum number of allowed CIDRs: 1".format(
vpc.id
)
)
# Test associate ipv6 cidr block after vpc created
vpc = ec2.create_vpc(CidrBlock='10.10.50.0/24')
response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True)
response['Ipv6CidrBlockAssociation']['Ipv6CidrBlockState']['State'].should.equal('associating')
response['Ipv6CidrBlockAssociation']['Ipv6CidrBlock'].should.contain('::/56')
response['Ipv6CidrBlockAssociation']['AssociationId'].should.contain('vpc-cidr-assoc-')
vpc = ec2.create_vpc(CidrBlock="10.10.50.0/24")
response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc.id, AmazonProvidedIpv6CidrBlock=True
)
response["Ipv6CidrBlockAssociation"]["Ipv6CidrBlockState"]["State"].should.equal(
"associating"
)
response["Ipv6CidrBlockAssociation"]["Ipv6CidrBlock"].should.contain("::/56")
response["Ipv6CidrBlockAssociation"]["AssociationId"].should.contain(
"vpc-cidr-assoc-"
)
# Check on describe vpc that has ipv6 cidr block association
vpc = ec2.Vpc(vpc.id)
@ -494,72 +580,248 @@ def test_vpc_associate_ipv6_cidr_block():
@mock_ec2
def test_vpc_disassociate_ipv6_cidr_block():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Test create VPC with IPV6 cidr range
vpc = ec2.create_vpc(CidrBlock='10.10.42.0/24', AmazonProvidedIpv6CidrBlock=True)
vpc = ec2.create_vpc(CidrBlock="10.10.42.0/24", AmazonProvidedIpv6CidrBlock=True)
# Test disassociating the only IPV6
assoc_id = vpc.ipv6_cidr_block_association_set[0]['AssociationId']
assoc_id = vpc.ipv6_cidr_block_association_set[0]["AssociationId"]
response = ec2.meta.client.disassociate_vpc_cidr_block(AssociationId=assoc_id)
response['Ipv6CidrBlockAssociation']['Ipv6CidrBlockState']['State'].should.equal('disassociating')
response['Ipv6CidrBlockAssociation']['Ipv6CidrBlock'].should.contain('::/56')
response['Ipv6CidrBlockAssociation']['AssociationId'].should.equal(assoc_id)
response["Ipv6CidrBlockAssociation"]["Ipv6CidrBlockState"]["State"].should.equal(
"disassociating"
)
response["Ipv6CidrBlockAssociation"]["Ipv6CidrBlock"].should.contain("::/56")
response["Ipv6CidrBlockAssociation"]["AssociationId"].should.equal(assoc_id)
@mock_ec2
def test_ipv6_cidr_block_association_filters():
ec2 = boto3.resource('ec2', region_name='us-west-1')
vpc1 = ec2.create_vpc(CidrBlock='10.90.0.0/16')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc1 = ec2.create_vpc(CidrBlock="10.90.0.0/16")
vpc2 = ec2.create_vpc(CidrBlock='10.91.0.0/16', AmazonProvidedIpv6CidrBlock=True)
vpc2_assoc_ipv6_assoc_id = vpc2.ipv6_cidr_block_association_set[0]['AssociationId']
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc2.id, CidrBlock='10.10.0.0/19')
vpc2 = ec2.create_vpc(CidrBlock="10.91.0.0/16", AmazonProvidedIpv6CidrBlock=True)
vpc2_assoc_ipv6_assoc_id = vpc2.ipv6_cidr_block_association_set[0]["AssociationId"]
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc2.id, CidrBlock="10.10.0.0/19")
vpc3 = ec2.create_vpc(CidrBlock='10.92.0.0/24')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock='10.92.1.0/24')
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock='10.92.2.0/24')
response = ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, AmazonProvidedIpv6CidrBlock=True)
vpc3_ipv6_cidr_block = response['Ipv6CidrBlockAssociation']['Ipv6CidrBlock']
vpc3 = ec2.create_vpc(CidrBlock="10.92.0.0/24")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock="10.92.1.0/24")
ec2.meta.client.associate_vpc_cidr_block(VpcId=vpc3.id, CidrBlock="10.92.2.0/24")
response = ec2.meta.client.associate_vpc_cidr_block(
VpcId=vpc3.id, AmazonProvidedIpv6CidrBlock=True
)
vpc3_ipv6_cidr_block = response["Ipv6CidrBlockAssociation"]["Ipv6CidrBlock"]
vpc4 = ec2.create_vpc(CidrBlock='10.95.0.0/16') # Here for its looks
vpc4 = ec2.create_vpc(CidrBlock="10.95.0.0/16") # Here for its looks
# Test filters for an ipv6 cidr-block in all VPCs cidr-block-associations
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'ipv6-cidr-block-association.ipv6-cidr-block',
'Values': [vpc3_ipv6_cidr_block]}]))
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{
"Name": "ipv6-cidr-block-association.ipv6-cidr-block",
"Values": [vpc3_ipv6_cidr_block],
}
]
)
)
filtered_vpcs.should.be.length_of(1)
filtered_vpcs[0].id.should.equal(vpc3.id)
# Test filter for association id in VPCs
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'ipv6-cidr-block-association.association-id',
'Values': [vpc2_assoc_ipv6_assoc_id]}]))
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{
"Name": "ipv6-cidr-block-association.association-id",
"Values": [vpc2_assoc_ipv6_assoc_id],
}
]
)
)
filtered_vpcs.should.be.length_of(1)
filtered_vpcs[0].id.should.equal(vpc2.id)
# Test filter for association state in VPC - this will never show anything in this test
filtered_vpcs = list(ec2.vpcs.filter(Filters=[{'Name': 'ipv6-cidr-block-association.state',
'Values': ['associated']}]))
filtered_vpcs.should.be.length_of(2) # 2 of 4 VPCs
filtered_vpcs = list(
ec2.vpcs.filter(
Filters=[
{"Name": "ipv6-cidr-block-association.state", "Values": ["associated"]}
]
)
)
filtered_vpcs.should.be.length_of(2) # 2 of 4 VPCs
@mock_ec2
def test_create_vpc_with_invalid_cidr_block_parameter():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc_cidr_block = '1000.1.0.0/20'
vpc_cidr_block = "1000.1.0.0/20"
with assert_raises(ClientError) as ex:
vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block)
str(ex.exception).should.equal(
"An error occurred (InvalidParameterValue) when calling the CreateVpc "
"operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format(vpc_cidr_block))
"operation: Value ({}) for parameter cidrBlock is invalid. This is not a valid CIDR block.".format(
vpc_cidr_block
)
)
@mock_ec2
def test_create_vpc_with_invalid_cidr_range():
ec2 = boto3.resource('ec2', region_name='us-west-1')
ec2 = boto3.resource("ec2", region_name="us-west-1")
vpc_cidr_block = '10.1.0.0/29'
vpc_cidr_block = "10.1.0.0/29"
with assert_raises(ClientError) as ex:
vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block)
str(ex.exception).should.equal(
"An error occurred (InvalidVpc.Range) when calling the CreateVpc "
"operation: The CIDR '{}' is invalid.".format(vpc_cidr_block))
"operation: The CIDR '{}' is invalid.".format(vpc_cidr_block)
)
@mock_ec2
def test_enable_vpc_classic_link():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.1.0.0/16")
response = ec2.meta.client.enable_vpc_classic_link(VpcId=vpc.id)
assert response.get("Return").should.be.true
@mock_ec2
def test_enable_vpc_classic_link_failure():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.90.0.0/16")
response = ec2.meta.client.enable_vpc_classic_link(VpcId=vpc.id)
assert response.get("Return").should.be.false
@mock_ec2
def test_disable_vpc_classic_link():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link(VpcId=vpc.id)
response = ec2.meta.client.disable_vpc_classic_link(VpcId=vpc.id)
assert response.get("Return").should.be.false
@mock_ec2
def test_describe_classic_link_enabled():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link(VpcId=vpc.id)
response = ec2.meta.client.describe_vpc_classic_link(VpcIds=[vpc.id])
assert response.get("Vpcs")[0].get("ClassicLinkEnabled").should.be.true
@mock_ec2
def test_describe_classic_link_disabled():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.90.0.0/16")
response = ec2.meta.client.describe_vpc_classic_link(VpcIds=[vpc.id])
assert response.get("Vpcs")[0].get("ClassicLinkEnabled").should.be.false
@mock_ec2
def test_describe_classic_link_multiple():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc1 = ec2.create_vpc(CidrBlock="10.90.0.0/16")
vpc2 = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link(VpcId=vpc2.id)
response = ec2.meta.client.describe_vpc_classic_link(VpcIds=[vpc1.id, vpc2.id])
expected = [
{"VpcId": vpc1.id, "ClassicLinkDnsSupported": False},
{"VpcId": vpc2.id, "ClassicLinkDnsSupported": True},
]
# Ensure response is sorted, because they can come in random order
assert response.get("Vpcs").sort(key=lambda x: x["VpcId"]) == expected.sort(
key=lambda x: x["VpcId"]
)
@mock_ec2
def test_enable_vpc_classic_link_dns_support():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.1.0.0/16")
response = ec2.meta.client.enable_vpc_classic_link_dns_support(VpcId=vpc.id)
assert response.get("Return").should.be.true
@mock_ec2
def test_disable_vpc_classic_link_dns_support():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link_dns_support(VpcId=vpc.id)
response = ec2.meta.client.disable_vpc_classic_link_dns_support(VpcId=vpc.id)
assert response.get("Return").should.be.false
@mock_ec2
def test_describe_classic_link_dns_support_enabled():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link_dns_support(VpcId=vpc.id)
response = ec2.meta.client.describe_vpc_classic_link_dns_support(VpcIds=[vpc.id])
assert response.get("Vpcs")[0].get("ClassicLinkDnsSupported").should.be.true
@mock_ec2
def test_describe_classic_link_dns_support_disabled():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc = ec2.create_vpc(CidrBlock="10.90.0.0/16")
response = ec2.meta.client.describe_vpc_classic_link_dns_support(VpcIds=[vpc.id])
assert response.get("Vpcs")[0].get("ClassicLinkDnsSupported").should.be.false
@mock_ec2
def test_describe_classic_link_dns_support_multiple():
ec2 = boto3.resource("ec2", region_name="us-west-1")
# Create VPC
vpc1 = ec2.create_vpc(CidrBlock="10.90.0.0/16")
vpc2 = ec2.create_vpc(CidrBlock="10.0.0.0/16")
ec2.meta.client.enable_vpc_classic_link_dns_support(VpcId=vpc2.id)
response = ec2.meta.client.describe_vpc_classic_link_dns_support(
VpcIds=[vpc1.id, vpc2.id]
)
expected = [
{"VpcId": vpc1.id, "ClassicLinkDnsSupported": False},
{"VpcId": vpc2.id, "ClassicLinkDnsSupported": True},
]
# Ensure response is sorted, because they can come in random order
assert response.get("Vpcs").sort(key=lambda x: x["VpcId"]) == expected.sort(
key=lambda x: x["VpcId"]
)

View file

@ -1,51 +1,53 @@
from __future__ import unicode_literals
import boto
from nose.tools import assert_raises
import sure # noqa
from boto.exception import EC2ResponseError
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.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')
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')
list_of_vpn_connections = conn.get_all_vpn_connections()
list_of_vpn_connections.should.have.length_of(0)
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)
vpn = conn.create_vpn_connection('ipsec.1', 'vgw-1234abcd', 'cgw-1234abcd')
list_of_vpn_connections = conn.get_all_vpn_connections()
list_of_vpn_connections.should.have.length_of(2)
list_of_vpn_connections = conn.get_all_vpn_connections(vpn.id)
list_of_vpn_connections.should.have.length_of(1)
from __future__ import unicode_literals
import boto
from nose.tools import assert_raises
import sure # noqa
from boto.exception import EC2ResponseError
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.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"
)
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")
list_of_vpn_connections = conn.get_all_vpn_connections()
list_of_vpn_connections.should.have.length_of(0)
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)
vpn = conn.create_vpn_connection("ipsec.1", "vgw-1234abcd", "cgw-1234abcd")
list_of_vpn_connections = conn.get_all_vpn_connections()
list_of_vpn_connections.should.have.length_of(2)
list_of_vpn_connections = conn.get_all_vpn_connections(vpn.id)
list_of_vpn_connections.should.have.length_of(1)