Techdebt: Replace sure with regular asserts in CloudFront (#6485)

This commit is contained in:
Bert Blommers 2023-07-05 22:49:24 +00:00 committed by GitHub
parent acc3ca5f64
commit 435519ff7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 344 additions and 487 deletions

View File

@ -1,41 +1,8 @@
from collections.abc import Iterable, Mapping
from uuid import UUID from uuid import UUID
from sure import assertion from sure import assertion
@assertion
def containing_item_with_attributes(context, **kwargs):
contains = False
if kwargs and isinstance(context.obj, Iterable):
for item in context.obj:
if not isinstance(item, dict):
continue
for k, v in kwargs.items():
if k not in item or item[k] != v:
break
else:
contains = True
if context.negative:
assert not contains, f"{context.obj} contains matching item {kwargs}"
else:
assert contains, f"{context.obj} does not contain matching item {kwargs}"
return True
@assertion
def match_dict(context, dict_value):
assert isinstance(dict_value, Mapping), f"Invalid match target value: {dict_value}"
assert isinstance(
context.obj, Mapping
), f"Expected dict like object, but got: {context.obj}"
for k, v in dict_value.items():
assert k in context.obj, f"No such key '{k}' in {context.obj}"
context.obj[k].should.equal(v)
return True
@assertion @assertion
def match_uuid4(context): def match_uuid4(context):
try: try:

View File

@ -3,7 +3,6 @@ import pytest
import boto3 import boto3
from botocore.exceptions import ClientError, ParamValidationError from botocore.exceptions import ClientError, ParamValidationError
from moto import mock_cloudfront from moto import mock_cloudfront
import sure # noqa # pylint: disable=unused-import
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from . import cloudfront_test_scaffolding as scaffold from . import cloudfront_test_scaffolding as scaffold
@ -26,122 +25,100 @@ def test_update_distribution():
dist_config["Origins"]["Items"][0]["OriginPath"] = "/updated" dist_config["Origins"]["Items"][0]["OriginPath"] = "/updated"
dist_config["Aliases"] = {"Quantity": len(aliases), "Items": aliases} dist_config["Aliases"] = {"Quantity": len(aliases), "Items": aliases}
resp = client.update_distribution( dist = client.update_distribution(
DistributionConfig=dist_config, Id=dist_id, IfMatch=dist_etag DistributionConfig=dist_config, Id=dist_id, IfMatch=dist_etag
) )["Distribution"]
assert dist["ARN"] == f"arn:aws:cloudfront:{ACCOUNT_ID}:distribution/{dist['Id']}"
assert dist["Status"] == "Deployed"
assert "LastModifiedTime" in dist
assert dist["InProgressInvalidationBatches"] == 0
assert ".cloudfront.net" in dist["DomainName"]
resp.should.have.key("Distribution") assert dist["ActiveTrustedSigners"] == {
distribution = resp["Distribution"] "Enabled": False,
distribution.should.have.key("Id") "Items": [],
distribution.should.have.key("ARN").equals( "Quantity": 0,
f"arn:aws:cloudfront:{ACCOUNT_ID}:distribution/{distribution['Id']}" }
)
distribution.should.have.key("Status").equals("Deployed")
distribution.should.have.key("LastModifiedTime")
distribution.should.have.key("InProgressInvalidationBatches").equals(0)
distribution.should.have.key("DomainName").should.contain(".cloudfront.net")
distribution.should.have.key("ActiveTrustedSigners") assert dist["ActiveTrustedKeyGroups"] == {
signers = distribution["ActiveTrustedSigners"] "Enabled": False,
signers.should.have.key("Enabled").equals(False) "Items": [],
signers.should.have.key("Quantity").equals(0) "Quantity": 0,
}
distribution.should.have.key("ActiveTrustedKeyGroups") config = dist["DistributionConfig"]
key_groups = distribution["ActiveTrustedKeyGroups"] assert config["CallerReference"] == "ref"
key_groups.should.have.key("Enabled").equals(False)
key_groups.should.have.key("Quantity").equals(0)
distribution.should.have.key("DistributionConfig") assert config["Aliases"] == dist_config["Aliases"]
config = distribution["DistributionConfig"]
config.should.have.key("CallerReference").should.equal("ref")
config.should.have.key("Aliases")
config["Aliases"].should.equal(dist_config["Aliases"])
config.should.have.key("Origins")
origins = config["Origins"] origins = config["Origins"]
origins.should.have.key("Quantity").equals(1) assert origins["Quantity"] == 1
origins.should.have.key("Items").length_of(1) assert len(origins["Items"]) == 1
origin = origins["Items"][0] origin = origins["Items"][0]
origin.should.have.key("Id").equals("origin1") assert origin["Id"] == "origin1"
origin.should.have.key("DomainName").equals("asdf.s3.us-east-1.amazonaws.com") assert origin["DomainName"] == "asdf.s3.us-east-1.amazonaws.com"
origin.should.have.key("OriginPath").equals("/updated") assert origin["OriginPath"] == "/updated"
origin.should.have.key("CustomHeaders") assert origin["CustomHeaders"]["Quantity"] == 0
origin["CustomHeaders"].should.have.key("Quantity").equals(0)
origin.should.have.key("ConnectionAttempts").equals(3) assert origin["ConnectionAttempts"] == 3
origin.should.have.key("ConnectionTimeout").equals(10) assert origin["ConnectionTimeout"] == 10
origin.should.have.key("OriginShield").equals( assert origin["OriginShield"] == {"Enabled": False, "OriginShieldRegion": "None"}
{"Enabled": False, "OriginShieldRegion": "None"}
)
config.should.have.key("OriginGroups").equals({"Quantity": 0}) assert config["OriginGroups"] == {"Quantity": 0}
config.should.have.key("DefaultCacheBehavior")
default_cache = config["DefaultCacheBehavior"] default_cache = config["DefaultCacheBehavior"]
default_cache.should.have.key("TargetOriginId").should.equal("origin1") assert default_cache["TargetOriginId"] == "origin1"
default_cache.should.have.key("TrustedSigners")
signers = default_cache["TrustedSigners"] signers = default_cache["TrustedSigners"]
signers.should.have.key("Enabled").equals(False) assert signers["Enabled"] is False
signers.should.have.key("Quantity").equals(0) assert signers["Quantity"] == 0
default_cache.should.have.key("TrustedKeyGroups")
groups = default_cache["TrustedKeyGroups"] groups = default_cache["TrustedKeyGroups"]
groups.should.have.key("Enabled").equals(False) assert groups["Enabled"] is False
groups.should.have.key("Quantity").equals(0) assert groups["Quantity"] == 0
default_cache.should.have.key("ViewerProtocolPolicy").equals("allow-all") assert default_cache["ViewerProtocolPolicy"] == "allow-all"
default_cache.should.have.key("AllowedMethods")
methods = default_cache["AllowedMethods"] methods = default_cache["AllowedMethods"]
methods.should.have.key("Quantity").equals(2) assert methods["Quantity"] == 2
methods.should.have.key("Items") assert set(methods["Items"]) == {"HEAD", "GET"}
set(methods["Items"]).should.equal({"HEAD", "GET"})
methods.should.have.key("CachedMethods")
cached_methods = methods["CachedMethods"] cached_methods = methods["CachedMethods"]
cached_methods.should.have.key("Quantity").equals(2) assert cached_methods["Quantity"] == 2
set(cached_methods["Items"]).should.equal({"HEAD", "GET"}) assert set(cached_methods["Items"]) == {"HEAD", "GET"}
default_cache.should.have.key("SmoothStreaming").equals(False) assert default_cache["SmoothStreaming"] is False
default_cache.should.have.key("Compress").equals(True) assert default_cache["Compress"] is True
default_cache.should.have.key("LambdaFunctionAssociations").equals({"Quantity": 0}) assert default_cache["LambdaFunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FunctionAssociations").equals({"Quantity": 0}) assert default_cache["FunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FieldLevelEncryptionId").equals("") assert default_cache["FieldLevelEncryptionId"] == ""
default_cache.should.have.key("CachePolicyId") assert "CachePolicyId" in default_cache
config.should.have.key("CacheBehaviors").equals({"Quantity": 0}) assert config["CacheBehaviors"] == {"Quantity": 0}
config.should.have.key("CustomErrorResponses").equals({"Quantity": 0}) assert config["CustomErrorResponses"] == {"Quantity": 0}
config.should.have.key("Comment").equals( assert config["Comment"] == "an optional comment that's not actually optional"
"an optional comment that's not actually optional"
)
config.should.have.key("Logging")
logging = config["Logging"] logging = config["Logging"]
logging.should.have.key("Enabled").equals(False) assert logging["Enabled"] is False
logging.should.have.key("IncludeCookies").equals(False) assert logging["IncludeCookies"] is False
logging.should.have.key("Bucket").equals("") assert logging["Bucket"] == ""
logging.should.have.key("Prefix").equals("") assert logging["Prefix"] == ""
config.should.have.key("PriceClass").equals("PriceClass_All") assert config["PriceClass"] == "PriceClass_All"
config.should.have.key("Enabled").equals(False) assert config["Enabled"] is False
config.should.have.key("WebACLId") assert "WebACLId" in config
config.should.have.key("HttpVersion").equals("http2") assert config["HttpVersion"] == "http2"
config.should.have.key("IsIPV6Enabled").equals(True) assert config["IsIPV6Enabled"] is True
config.should.have.key("ViewerCertificate")
cert = config["ViewerCertificate"] cert = config["ViewerCertificate"]
cert.should.have.key("CloudFrontDefaultCertificate").equals(True) assert cert["CloudFrontDefaultCertificate"] is True
cert.should.have.key("MinimumProtocolVersion").equals("TLSv1") assert cert["MinimumProtocolVersion"] == "TLSv1"
cert.should.have.key("CertificateSource").equals("cloudfront") assert cert["CertificateSource"] == "cloudfront"
config.should.have.key("Restrictions")
config["Restrictions"].should.have.key("GeoRestriction")
restriction = config["Restrictions"]["GeoRestriction"] restriction = config["Restrictions"]["GeoRestriction"]
restriction.should.have.key("RestrictionType").equals("none") assert restriction["RestrictionType"] == "none"
restriction.should.have.key("Quantity").equals(0) assert restriction["Quantity"] == 0
@mock_cloudfront @mock_cloudfront
@ -166,10 +143,10 @@ def test_update_distribution_no_such_distId():
) )
metadata = error.value.response["ResponseMetadata"] metadata = error.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(404) assert metadata["HTTPStatusCode"] == 404
err = error.value.response["Error"] err = error.value.response["Error"]
err["Code"].should.equal("NoSuchDistribution") assert err["Code"] == "NoSuchDistribution"
err["Message"].should.equal("The specified distribution does not exist.") assert err["Message"] == "The specified distribution does not exist."
@mock_cloudfront @mock_cloudfront
@ -194,9 +171,9 @@ def test_update_distribution_distId_is_None():
) )
typename = error.typename typename = error.typename
typename.should.equal("ParamValidationError") assert typename == "ParamValidationError"
error_str = "botocore.exceptions.ParamValidationError: Parameter validation failed:\nInvalid type for parameter Id, value: None, type: <class 'NoneType'>, valid types: <class 'str'>" error_str = "botocore.exceptions.ParamValidationError: Parameter validation failed:\nInvalid type for parameter Id, value: None, type: <class 'NoneType'>, valid types: <class 'str'>"
error.exconly().should.equal(error_str) assert error.exconly() == error_str
@mock_cloudfront @mock_cloudfront
@ -220,11 +197,11 @@ def test_update_distribution_IfMatch_not_set():
) )
metadata = error.value.response["ResponseMetadata"] metadata = error.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(400) assert metadata["HTTPStatusCode"] == 400
err = error.value.response["Error"] err = error.value.response["Error"]
err["Code"].should.equal("InvalidIfMatchVersion") assert err["Code"] == "InvalidIfMatchVersion"
msg = "The If-Match version is missing or not valid for the resource." msg = "The If-Match version is missing or not valid for the resource."
err["Message"].should.equal(msg) assert err["Message"] == msg
@mock_cloudfront @mock_cloudfront
@ -243,6 +220,6 @@ def test_update_distribution_dist_config_not_set():
client.update_distribution(Id=dist_id, IfMatch=dist_etag) client.update_distribution(Id=dist_id, IfMatch=dist_etag)
typename = error.typename typename = error.typename
typename.should.equal("ParamValidationError") assert typename == "ParamValidationError"
error_str = 'botocore.exceptions.ParamValidationError: Parameter validation failed:\nMissing required parameter in input: "DistributionConfig"' error_str = 'botocore.exceptions.ParamValidationError: Parameter validation failed:\nMissing required parameter in input: "DistributionConfig"'
error.exconly().should.equal(error_str) assert error.exconly() == error_str

View File

@ -1,7 +1,6 @@
import boto3 import boto3
from moto import mock_cloudfront from moto import mock_cloudfront
from . import cloudfront_test_scaffolding as scaffold from . import cloudfront_test_scaffolding as scaffold
import sure # noqa # pylint: disable=unused-import
@mock_cloudfront @mock_cloudfront
@ -12,13 +11,11 @@ def test_create_distribution_with_tags():
config = {"DistributionConfig": config, "Tags": tags} config = {"DistributionConfig": config, "Tags": tags}
resp = client.create_distribution_with_tags(DistributionConfigWithTags=config) resp = client.create_distribution_with_tags(DistributionConfigWithTags=config)
resp.should.have.key("Distribution")
resp = client.list_tags_for_resource(Resource=resp["Distribution"]["ARN"]) resp = client.list_tags_for_resource(Resource=resp["Distribution"]["ARN"])
resp.should.have.key("Tags") assert len(resp["Tags"]["Items"]) == 2
resp["Tags"].should.have.key("Items").length_of(2) assert {"Key": "k1", "Value": "v1"} in resp["Tags"]["Items"]
resp["Tags"]["Items"].should.contain({"Key": "k1", "Value": "v1"}) assert {"Key": "k2", "Value": "v2"} in resp["Tags"]["Items"]
resp["Tags"]["Items"].should.contain({"Key": "k2", "Value": "v2"})
@mock_cloudfront @mock_cloudfront
@ -29,9 +26,7 @@ def test_create_distribution_with_tags_only_one_tag():
config = {"DistributionConfig": config, "Tags": tags} config = {"DistributionConfig": config, "Tags": tags}
resp = client.create_distribution_with_tags(DistributionConfigWithTags=config) resp = client.create_distribution_with_tags(DistributionConfigWithTags=config)
resp.should.have.key("Distribution")
resp = client.list_tags_for_resource(Resource=resp["Distribution"]["ARN"]) resp = client.list_tags_for_resource(Resource=resp["Distribution"]["ARN"])
resp.should.have.key("Tags") assert len(resp["Tags"]["Items"]) == 1
resp["Tags"].should.have.key("Items").length_of(1) assert {"Key": "k1", "Value": "v1"} in resp["Tags"]["Items"]
resp["Tags"]["Items"].should.contain({"Key": "k1", "Value": "v1"})

View File

@ -4,7 +4,6 @@ from moto import mock_cloudfront
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from . import cloudfront_test_scaffolding as scaffold from . import cloudfront_test_scaffolding as scaffold
import pytest import pytest
import sure # noqa # pylint: disable=unused-import
@mock_cloudfront @mock_cloudfront
@ -12,121 +11,110 @@ def test_create_distribution_s3_minimum():
client = boto3.client("cloudfront", region_name="us-west-1") client = boto3.client("cloudfront", region_name="us-west-1")
config = scaffold.example_distribution_config("ref") config = scaffold.example_distribution_config("ref")
resp = client.create_distribution(DistributionConfig=config) dist = client.create_distribution(DistributionConfig=config)["Distribution"]
resp.should.have.key("Distribution") assert dist["ARN"] == f"arn:aws:cloudfront:{ACCOUNT_ID}:distribution/{dist['Id']}"
assert dist["Status"] == "InProgress"
assert "LastModifiedTime" in dist
assert dist["InProgressInvalidationBatches"] == 0
assert ".cloudfront.net" in dist["DomainName"]
distribution = resp["Distribution"] assert dist["ActiveTrustedSigners"] == {
distribution.should.have.key("Id") "Enabled": False,
distribution.should.have.key("ARN").equals( "Items": [],
f"arn:aws:cloudfront:{ACCOUNT_ID}:distribution/{distribution['Id']}" "Quantity": 0,
) }
distribution.should.have.key("Status").equals("InProgress")
distribution.should.have.key("LastModifiedTime")
distribution.should.have.key("InProgressInvalidationBatches").equals(0)
distribution.should.have.key("DomainName").should.contain(".cloudfront.net")
distribution.should.have.key("ActiveTrustedSigners") assert dist["ActiveTrustedKeyGroups"] == {
signers = distribution["ActiveTrustedSigners"] "Enabled": False,
signers.should.have.key("Enabled").equals(False) "Items": [],
signers.should.have.key("Quantity").equals(0) "Quantity": 0,
}
distribution.should.have.key("ActiveTrustedKeyGroups") config = dist["DistributionConfig"]
key_groups = distribution["ActiveTrustedKeyGroups"] assert config["CallerReference"] == "ref"
key_groups.should.have.key("Enabled").equals(False)
key_groups.should.have.key("Quantity").equals(0)
distribution.should.have.key("DistributionConfig") assert config["Aliases"]["Quantity"] == 0
config = distribution["DistributionConfig"]
config.should.have.key("CallerReference").should.equal("ref")
config.should.have.key("Aliases")
config["Aliases"].should.have.key("Quantity").equals(0)
config.should.have.key("Origins")
origins = config["Origins"] origins = config["Origins"]
origins.should.have.key("Quantity").equals(1) assert origins["Quantity"] == 1
origins.should.have.key("Items").length_of(1) assert len(origins["Items"]) == 1
origin = origins["Items"][0] origin = origins["Items"][0]
origin.should.have.key("Id").equals("origin1") assert origin["Id"] == "origin1"
origin.should.have.key("DomainName").equals("asdf.s3.us-east-1.amazonaws.com") assert origin["DomainName"] == "asdf.s3.us-east-1.amazonaws.com"
origin.should.have.key("OriginPath").equals("/example") assert origin["OriginPath"] == "/example"
origin.should.have.key("CustomHeaders") assert origin["CustomHeaders"]["Quantity"] == 0
origin["CustomHeaders"].should.have.key("Quantity").equals(0)
origin.should.have.key("ConnectionAttempts").equals(3) assert origin["ConnectionAttempts"] == 3
origin.should.have.key("ConnectionTimeout").equals(10) assert origin["ConnectionTimeout"] == 10
origin.should.have.key("OriginShield").equals({"Enabled": False}) assert origin["OriginShield"] == {"Enabled": False}
config.should.have.key("OriginGroups").equals({"Quantity": 0}) assert config["OriginGroups"] == {"Quantity": 0}
config.should.have.key("DefaultCacheBehavior")
default_cache = config["DefaultCacheBehavior"] default_cache = config["DefaultCacheBehavior"]
default_cache.should.have.key("TargetOriginId").should.equal("origin1") assert default_cache["TargetOriginId"] == "origin1"
default_cache.should.have.key("TrustedSigners")
signers = default_cache["TrustedSigners"] assert default_cache["TrustedSigners"] == {
signers.should.have.key("Enabled").equals(False) "Enabled": False,
signers.should.have.key("Quantity").equals(0) "Items": [],
"Quantity": 0,
}
default_cache.should.have.key("TrustedKeyGroups") assert default_cache["TrustedKeyGroups"] == {
groups = default_cache["TrustedKeyGroups"] "Enabled": False,
groups.should.have.key("Enabled").equals(False) "Items": [],
groups.should.have.key("Quantity").equals(0) "Quantity": 0,
}
default_cache.should.have.key("ViewerProtocolPolicy").equals("allow-all") assert default_cache["ViewerProtocolPolicy"] == "allow-all"
default_cache.should.have.key("AllowedMethods")
methods = default_cache["AllowedMethods"] methods = default_cache["AllowedMethods"]
methods.should.have.key("Quantity").equals(2) assert methods["Quantity"] == 2
methods.should.have.key("Items") assert set(methods["Items"]) == {"HEAD", "GET"}
set(methods["Items"]).should.equal({"HEAD", "GET"})
methods.should.have.key("CachedMethods")
cached_methods = methods["CachedMethods"] cached_methods = methods["CachedMethods"]
cached_methods.should.have.key("Quantity").equals(2) assert cached_methods["Quantity"] == 2
set(cached_methods["Items"]).should.equal({"HEAD", "GET"}) assert set(cached_methods["Items"]) == {"HEAD", "GET"}
default_cache.should.have.key("SmoothStreaming").equals(False) assert default_cache["SmoothStreaming"] is False
default_cache.should.have.key("Compress").equals(True) assert default_cache["Compress"] is True
default_cache.should.have.key("LambdaFunctionAssociations").equals({"Quantity": 0}) assert default_cache["LambdaFunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FunctionAssociations").equals({"Quantity": 0}) assert default_cache["FunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FieldLevelEncryptionId").equals("") assert default_cache["FieldLevelEncryptionId"] == ""
default_cache.should.have.key("CachePolicyId") assert "CachePolicyId" in default_cache
config.should.have.key("CacheBehaviors").equals({"Quantity": 0}) assert config["CacheBehaviors"] == {"Quantity": 0}
config.should.have.key("CustomErrorResponses").equals({"Quantity": 0}) assert config["CustomErrorResponses"] == {"Quantity": 0}
config.should.have.key("Comment").equals( assert config["Comment"] == "an optional comment that's not actually optional"
"an optional comment that's not actually optional"
)
config.should.have.key("Logging") assert config["Logging"] == {
logging = config["Logging"] "Bucket": "",
logging.should.have.key("Enabled").equals(False) "Enabled": False,
logging.should.have.key("IncludeCookies").equals(False) "IncludeCookies": False,
logging.should.have.key("Bucket").equals("") "Prefix": "",
logging.should.have.key("Prefix").equals("") }
config.should.have.key("PriceClass").equals("PriceClass_All") assert config["PriceClass"] == "PriceClass_All"
config.should.have.key("Enabled").equals(False) assert config["Enabled"] is False
config.should.have.key("WebACLId") assert "WebACLId" in config
config.should.have.key("HttpVersion").equals("http2") assert config["HttpVersion"] == "http2"
config.should.have.key("IsIPV6Enabled").equals(True) assert config["IsIPV6Enabled"] is True
config.should.have.key("ViewerCertificate") assert config["ViewerCertificate"] == {
cert = config["ViewerCertificate"] "ACMCertificateArn": "",
cert.should.have.key("CloudFrontDefaultCertificate").equals(True) "Certificate": "",
cert.should.have.key("MinimumProtocolVersion").equals("TLSv1") "CertificateSource": "cloudfront",
cert.should.have.key("CertificateSource").equals("cloudfront") "CloudFrontDefaultCertificate": True,
"IAMCertificateId": "",
"MinimumProtocolVersion": "TLSv1",
"SSLSupportMethod": "",
}
config.should.have.key("Restrictions")
config["Restrictions"].should.have.key("GeoRestriction")
restriction = config["Restrictions"]["GeoRestriction"] restriction = config["Restrictions"]["GeoRestriction"]
restriction.should.have.key("RestrictionType").equals("none") assert restriction["RestrictionType"] == "none"
restriction.should.have.key("Quantity").equals(0) assert restriction["Quantity"] == 0
config.should.have.key("WebACLId") assert config["WebACLId"] == ""
config.should.have.key("WebACLId").equals("")
@mock_cloudfront @mock_cloudfront
@ -141,19 +129,14 @@ def test_create_distribution_with_logging():
} }
resp = client.create_distribution(DistributionConfig=config) resp = client.create_distribution(DistributionConfig=config)
resp.should.have.key("Distribution") config = resp["Distribution"]["DistributionConfig"]
distribution = resp["Distribution"] assert config["Logging"] == {
"Bucket": "logging-bucket",
distribution.should.have.key("DistributionConfig") "Enabled": True,
config = distribution["DistributionConfig"] "IncludeCookies": True,
"Prefix": "logging-bucket",
config.should.have.key("Logging") }
logging = config["Logging"]
logging.should.have.key("Enabled").equals(True)
logging.should.have.key("IncludeCookies").equals(True)
logging.should.have.key("Bucket").equals("logging-bucket")
logging.should.have.key("Prefix").equals("logging-bucket")
@mock_cloudfront @mock_cloudfront
@ -163,15 +146,9 @@ def test_create_distribution_with_web_acl():
config["WebACLId"] = "test-web-acl" config["WebACLId"] = "test-web-acl"
resp = client.create_distribution(DistributionConfig=config) resp = client.create_distribution(DistributionConfig=config)
resp.should.have.key("Distribution") config = resp["Distribution"]["DistributionConfig"]
distribution = resp["Distribution"] assert config["WebACLId"] == "test-web-acl"
distribution.should.have.key("DistributionConfig")
config = distribution["DistributionConfig"]
config.should.have.key("WebACLId")
config.should.have.key("WebACLId").equals("test-web-acl")
@mock_cloudfront @mock_cloudfront
@ -183,23 +160,12 @@ def test_create_distribution_with_field_level_encryption_and_real_time_log_confi
config["DefaultCacheBehavior"]["FieldLevelEncryptionId"] = "K3D5EWEUDCCXON" config["DefaultCacheBehavior"]["FieldLevelEncryptionId"] = "K3D5EWEUDCCXON"
resp = client.create_distribution(DistributionConfig=config) resp = client.create_distribution(DistributionConfig=config)
resp.should.have.key("Distribution")
distribution = resp["Distribution"] config = resp["Distribution"]["DistributionConfig"]
distribution.should.have.key("DistributionConfig")
config = distribution["DistributionConfig"]
config.should.have.key("DefaultCacheBehavior")
default_cache = config["DefaultCacheBehavior"] default_cache = config["DefaultCacheBehavior"]
default_cache.should.have.key("FieldLevelEncryptionId") assert default_cache["FieldLevelEncryptionId"] == "K3D5EWEUDCCXON"
default_cache.should.have.key("FieldLevelEncryptionId").equals("K3D5EWEUDCCXON") assert default_cache["RealtimeLogConfigArn"] == real_time_log_config_arn
default_cache.should.have.key("RealtimeLogConfigArn")
default_cache.should.have.key("RealtimeLogConfigArn").equals(
real_time_log_config_arn
)
@mock_cloudfront @mock_cloudfront
@ -215,20 +181,13 @@ def test_create_distribution_with_georestriction():
} }
resp = client.create_distribution(DistributionConfig=config) resp = client.create_distribution(DistributionConfig=config)
resp.should.have.key("Distribution") config = resp["Distribution"]["DistributionConfig"]
distribution = resp["Distribution"]
distribution.should.have.key("DistributionConfig")
config = distribution["DistributionConfig"]
config.should.have.key("Restrictions")
config["Restrictions"].should.have.key("GeoRestriction")
restriction = config["Restrictions"]["GeoRestriction"] restriction = config["Restrictions"]["GeoRestriction"]
restriction.should.have.key("RestrictionType").equals("whitelist") assert restriction["RestrictionType"] == "whitelist"
restriction.should.have.key("Quantity").equals(2) assert restriction["Quantity"] == 2
restriction["Items"].should.contain("US") assert "US" in restriction["Items"]
restriction["Items"].should.contain("GB") assert "GB" in restriction["Items"]
@mock_cloudfront @mock_cloudfront
@ -246,19 +205,16 @@ def test_create_distribution_with_allowed_methods():
dist = client.create_distribution(DistributionConfig=config)["Distribution"] dist = client.create_distribution(DistributionConfig=config)["Distribution"]
dist.should.have.key("DistributionConfig")
cache = dist["DistributionConfig"]["DefaultCacheBehavior"] cache = dist["DistributionConfig"]["DefaultCacheBehavior"]
cache.should.have.key("AllowedMethods").equals( assert cache["AllowedMethods"] == {
{ "CachedMethods": {
"CachedMethods": { "Items": ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
"Items": ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], "Quantity": 7,
"Quantity": 7, },
}, "Items": ["GET", "HEAD", "PUT"],
"Items": ["GET", "HEAD", "PUT"], "Quantity": 3,
"Quantity": 3, }
}
)
@mock_cloudfront @mock_cloudfront
@ -275,11 +231,9 @@ def test_create_distribution_with_origins():
dist = client.create_distribution(DistributionConfig=config)["Distribution"] dist = client.create_distribution(DistributionConfig=config)["Distribution"]
origin = dist["DistributionConfig"]["Origins"]["Items"][0] origin = dist["DistributionConfig"]["Origins"]["Items"][0]
origin.should.have.key("ConnectionAttempts").equals(1) assert origin["ConnectionAttempts"] == 1
origin.should.have.key("ConnectionTimeout").equals(2) assert origin["ConnectionTimeout"] == 2
origin.should.have.key("OriginShield").equals( assert origin["OriginShield"] == {"Enabled": True, "OriginShieldRegion": "east"}
{"Enabled": True, "OriginShieldRegion": "east"}
)
@mock_cloudfront @mock_cloudfront
@ -305,26 +259,23 @@ def test_create_distribution_with_additional_fields(
config["DefaultCacheBehavior"]["MinTTL"] = 10 config["DefaultCacheBehavior"]["MinTTL"] = 10
config["DefaultCacheBehavior"]["SmoothStreaming"] = smooth config["DefaultCacheBehavior"]["SmoothStreaming"] = smooth
config["PriceClass"] = "PriceClass_100" config["PriceClass"] = "PriceClass_100"
resp = client.create_distribution(DistributionConfig=config) resp = client.create_distribution(DistributionConfig=config)
distribution = resp["Distribution"] config = resp["Distribution"]["DistributionConfig"]
distribution.should.have.key("DistributionConfig")
config = distribution["DistributionConfig"]
assert config["Aliases"] == {"Items": aliases, "Quantity": len(aliases)} assert config["Aliases"] == {"Items": aliases, "Quantity": len(aliases)}
config.should.have.key("PriceClass").equals("PriceClass_100") assert config["PriceClass"] == "PriceClass_100"
config.should.have.key("IsIPV6Enabled").equals(ipv6) assert config["IsIPV6Enabled"] == ipv6
config["DefaultCacheBehavior"].should.have.key("Compress").equals(compress) assert config["DefaultCacheBehavior"]["Compress"] == compress
config["DefaultCacheBehavior"].should.have.key("MinTTL").equals(10) assert config["DefaultCacheBehavior"]["MinTTL"] == 10
config["DefaultCacheBehavior"].should.have.key("SmoothStreaming").equals(smooth) assert config["DefaultCacheBehavior"]["SmoothStreaming"] == smooth
forwarded = config["DefaultCacheBehavior"]["ForwardedValues"] forwarded = config["DefaultCacheBehavior"]["ForwardedValues"]
forwarded.should.have.key("QueryString").equals(qs) assert forwarded["QueryString"] == qs
forwarded["Cookies"].should.have.key("Forward").equals("whitelist") assert forwarded["Cookies"]["Forward"] == "whitelist"
forwarded["Cookies"].should.have.key("WhitelistedNames") assert forwarded["Cookies"]["WhitelistedNames"]["Items"] == ["x-amz-header"]
forwarded["Cookies"]["WhitelistedNames"].should.have.key("Items").equals(
["x-amz-header"]
)
@mock_cloudfront @mock_cloudfront
@ -336,9 +287,10 @@ def test_create_distribution_returns_etag():
dist_id = resp["Distribution"]["Id"] dist_id = resp["Distribution"]["Id"]
headers = resp["ResponseMetadata"]["HTTPHeaders"] headers = resp["ResponseMetadata"]["HTTPHeaders"]
headers.should.have.key("etag").length_of(13) assert len(headers["etag"]) == 13
headers.should.have.key("location").equals( assert (
f"https://cloudfront.amazonaws.com/2020-05-31/distribution/{dist_id}" headers["location"]
== f"https://cloudfront.amazonaws.com/2020-05-31/distribution/{dist_id}"
) )
@ -355,19 +307,20 @@ def test_create_distribution_needs_unique_caller_reference():
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
client.create_distribution(DistributionConfig=config) client.create_distribution(DistributionConfig=config)
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("DistributionAlreadyExists") assert err["Code"] == "DistributionAlreadyExists"
err["Message"].should.equal( assert (
f"The caller reference that you are using to create a distribution is associated with another distribution. Already exists: {dist1_id}" err["Message"]
== f"The caller reference that you are using to create a distribution is associated with another distribution. Already exists: {dist1_id}"
) )
# Creating another distribution with a different reference # Creating another distribution with a different reference
config = scaffold.example_distribution_config(ref="ref2") config = scaffold.example_distribution_config(ref="ref2")
dist2 = client.create_distribution(DistributionConfig=config) dist2 = client.create_distribution(DistributionConfig=config)
dist1_id.shouldnt.equal(dist2["Distribution"]["Id"]) assert dist1_id != dist2["Distribution"]["Id"]
resp = client.list_distributions()["DistributionList"] resp = client.list_distributions()["DistributionList"]
resp.should.have.key("Quantity").equals(2) assert resp["Quantity"] == 2
resp.should.have.key("Items").length_of(2) assert len(resp["Items"]) == 2
@mock_cloudfront @mock_cloudfront
@ -378,10 +331,10 @@ def test_get_distribution_config_with_unknown_distribution_id():
client.get_distribution_config(Id="unknown") client.get_distribution_config(Id="unknown")
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(404) assert metadata["HTTPStatusCode"] == 404
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchDistribution") assert err["Code"] == "NoSuchDistribution"
err["Message"].should.equal("The specified distribution does not exist.") assert err["Message"] == "The specified distribution does not exist."
@mock_cloudfront @mock_cloudfront
@ -405,11 +358,11 @@ def test_get_distribution_config_with_mismatched_originid():
} }
) )
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(404) assert metadata["HTTPStatusCode"] == 404
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchOrigin") assert err["Code"] == "NoSuchOrigin"
err["Message"].should.equal( assert (
"One or more of your origins or origin groups do not exist." err["Message"] == "One or more of your origins or origin groups do not exist."
) )
@ -435,11 +388,11 @@ def test_create_origin_without_origin_config():
) )
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(400) assert metadata["HTTPStatusCode"] == 400
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("InvalidOrigin") assert err["Code"] == "InvalidOrigin"
err["Message"].should.equal( assert (
"The specified origin server does not exist or is not valid." err["Message"] == "The specified origin server does not exist or is not valid."
) )
@ -471,11 +424,12 @@ def test_create_distribution_with_invalid_s3_bucket():
) )
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(400) assert metadata["HTTPStatusCode"] == 400
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("InvalidArgument") assert err["Code"] == "InvalidArgument"
err["Message"].should.equal( assert (
"The parameter Origin DomainName does not refer to a valid S3 bucket." err["Message"]
== "The parameter Origin DomainName does not refer to a valid S3 bucket."
) )
@ -487,33 +441,28 @@ def test_create_distribution_custom_config():
dist = client.create_distribution(DistributionConfig=config)["Distribution"][ dist = client.create_distribution(DistributionConfig=config)["Distribution"][
"DistributionConfig" "DistributionConfig"
] ]
dist.should.have.key("Origins") assert len(dist["Origins"]["Items"]) == 1
dist["Origins"].should.have.key("Items").length_of(1) custom_config = dist["Origins"]["Items"][0]["CustomOriginConfig"]
origin = dist["Origins"]["Items"][0]
origin.should.have.key("CustomOriginConfig") assert custom_config["HTTPPort"] == 80
custom_config = origin["CustomOriginConfig"] assert custom_config["HTTPSPort"] == 443
assert custom_config["OriginProtocolPolicy"] == "http-only"
custom_config.should.have.key("HTTPPort").equals(80) assert custom_config["OriginSslProtocols"] == {
custom_config.should.have.key("HTTPSPort").equals(443) "Items": ["TLSv1", "SSLv3"],
custom_config.should.have.key("OriginProtocolPolicy").equals("http-only") "Quantity": 2,
custom_config.should.have.key("OriginSslProtocols").equals( }
{"Items": ["TLSv1", "SSLv3"], "Quantity": 2}
)
@mock_cloudfront @mock_cloudfront
def test_list_distributions_without_any(): def test_list_distributions_without_any():
client = boto3.client("cloudfront", region_name="us-east-1") client = boto3.client("cloudfront", region_name="us-east-1")
resp = client.list_distributions() dlist = client.list_distributions()["DistributionList"]
resp.should.have.key("DistributionList") assert dlist["Marker"] == ""
dlist = resp["DistributionList"] assert dlist["MaxItems"] == 100
dlist.should.have.key("Marker").equals("") assert dlist["IsTruncated"] is False
dlist.should.have.key("MaxItems").equals(100) assert dlist["Quantity"] == 0
dlist.should.have.key("IsTruncated").equals(False) assert "Items" not in dlist
dlist.should.have.key("Quantity").equals(0)
dlist.shouldnt.have.key("Items")
@mock_cloudfront @mock_cloudfront
@ -525,21 +474,19 @@ def test_list_distributions():
config = scaffold.example_distribution_config(ref="ref2") config = scaffold.example_distribution_config(ref="ref2")
dist2 = client.create_distribution(DistributionConfig=config)["Distribution"] dist2 = client.create_distribution(DistributionConfig=config)["Distribution"]
resp = client.list_distributions() dlist = client.list_distributions()["DistributionList"]
resp.should.have.key("DistributionList") assert dlist["Quantity"] == 2
dlist = resp["DistributionList"] assert len(dlist["Items"]) == 2
dlist.should.have.key("Quantity").equals(2)
dlist.should.have.key("Items").length_of(2)
item1 = dlist["Items"][0] item1 = dlist["Items"][0]
item1.should.have.key("Id").equals(dist1["Id"]) assert item1["Id"] == dist1["Id"]
item1.should.have.key("ARN") assert "ARN" in item1
item1.should.have.key("Status").equals("Deployed") assert item1["Status"] == "Deployed"
item2 = dlist["Items"][1] item2 = dlist["Items"][1]
item2.should.have.key("Id").equals(dist2["Id"]) assert item2["Id"] == dist2["Id"]
item2.should.have.key("ARN") assert "ARN" in item2
item2.should.have.key("Status").equals("Deployed") assert item2["Status"] == "Deployed"
@mock_cloudfront @mock_cloudfront
@ -554,15 +501,14 @@ def test_get_distribution():
resp = client.get_distribution(Id=dist_id) resp = client.get_distribution(Id=dist_id)
headers = resp["ResponseMetadata"]["HTTPHeaders"] headers = resp["ResponseMetadata"]["HTTPHeaders"]
headers.should.have.key("etag").length_of(13) assert len(headers["etag"]) == 13
dist = resp["Distribution"] dist = resp["Distribution"]
dist.should.have.key("Id").equals(dist_id) assert dist["Id"] == dist_id
dist.should.have.key("Status").equals("Deployed") assert dist["Status"] == "Deployed"
dist.should.have.key("DomainName").equals(dist["DomainName"]) assert dist["DomainName"] == dist["DomainName"]
dist.should.have.key("DistributionConfig")
config = dist["DistributionConfig"] config = dist["DistributionConfig"]
config.should.have.key("CallerReference").should.equal("ref") assert config["CallerReference"] == "ref"
@mock_cloudfront @mock_cloudfront
@ -574,10 +520,10 @@ def test_get_unknown_distribution():
client.get_distribution(Id="unknown") client.get_distribution(Id="unknown")
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(404) assert metadata["HTTPStatusCode"] == 404
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchDistribution") assert err["Code"] == "NoSuchDistribution"
err["Message"].should.equal("The specified distribution does not exist.") assert err["Message"] == "The specified distribution does not exist."
@mock_cloudfront @mock_cloudfront
@ -588,10 +534,10 @@ def test_delete_unknown_distribution():
client.delete_distribution(Id="unknown", IfMatch="..") client.delete_distribution(Id="unknown", IfMatch="..")
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(404) assert metadata["HTTPStatusCode"] == 404
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchDistribution") assert err["Code"] == "NoSuchDistribution"
err["Message"].should.equal("The specified distribution does not exist.") assert err["Message"] == "The specified distribution does not exist."
@mock_cloudfront @mock_cloudfront
@ -603,11 +549,12 @@ def test_delete_distribution_without_ifmatch():
client.delete_distribution(Id="...") client.delete_distribution(Id="...")
metadata = exc.value.response["ResponseMetadata"] metadata = exc.value.response["ResponseMetadata"]
metadata["HTTPStatusCode"].should.equal(400) assert metadata["HTTPStatusCode"] == 400
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("InvalidIfMatchVersion") assert err["Code"] == "InvalidIfMatchVersion"
err["Message"].should.equal( assert (
"The If-Match version is missing or not valid for the resource." err["Message"]
== "The If-Match version is missing or not valid for the resource."
) )
@ -629,7 +576,7 @@ def test_delete_distribution_random_etag():
with pytest.raises(ClientError) as exc: with pytest.raises(ClientError) as exc:
client.get_distribution(Id=dist_id) client.get_distribution(Id=dist_id)
err = exc.value.response["Error"] err = exc.value.response["Error"]
err["Code"].should.equal("NoSuchDistribution") assert err["Code"] == "NoSuchDistribution"
@mock_cloudfront @mock_cloudfront
@ -641,97 +588,79 @@ def test_get_distribution_config():
dist = client.create_distribution(DistributionConfig=config) dist = client.create_distribution(DistributionConfig=config)
dist_id = dist["Distribution"]["Id"] dist_id = dist["Distribution"]["Id"]
resp = client.get_distribution_config(Id=dist_id) config = client.get_distribution_config(Id=dist_id)["DistributionConfig"]
resp.should.have.key("DistributionConfig") assert config["CallerReference"] == "ref"
config = resp["DistributionConfig"] assert config["Aliases"]["Quantity"] == 0
config.should.have.key("CallerReference").should.equal("ref")
config.should.have.key("Aliases")
config["Aliases"].should.have.key("Quantity").equals(0)
config.should.have.key("Origins")
origins = config["Origins"] origins = config["Origins"]
origins.should.have.key("Quantity").equals(1) assert origins["Quantity"] == 1
origins.should.have.key("Items").length_of(1) assert len(origins["Items"]) == 1
origin = origins["Items"][0] origin = origins["Items"][0]
origin.should.have.key("Id").equals("origin1") assert origin["Id"] == "origin1"
origin.should.have.key("DomainName").equals("asdf.s3.us-east-1.amazonaws.com") assert origin["DomainName"] == "asdf.s3.us-east-1.amazonaws.com"
origin.should.have.key("OriginPath").equals("/example") assert origin["OriginPath"] == "/example"
origin.should.have.key("CustomHeaders") assert origin["CustomHeaders"]["Quantity"] == 0
origin["CustomHeaders"].should.have.key("Quantity").equals(0)
origin.should.have.key("ConnectionAttempts").equals(3) assert origin["ConnectionAttempts"] == 3
origin.should.have.key("ConnectionTimeout").equals(10) assert origin["ConnectionTimeout"] == 10
origin.should.have.key("OriginShield").equals({"Enabled": False}) assert origin["OriginShield"] == {"Enabled": False}
config.should.have.key("OriginGroups").equals({"Quantity": 0}) assert config["OriginGroups"] == {"Quantity": 0}
config.should.have.key("DefaultCacheBehavior")
default_cache = config["DefaultCacheBehavior"] default_cache = config["DefaultCacheBehavior"]
default_cache.should.have.key("TargetOriginId").should.equal("origin1") assert default_cache["TargetOriginId"] == "origin1"
default_cache.should.have.key("TrustedSigners")
signers = default_cache["TrustedSigners"] signers = default_cache["TrustedSigners"]
signers.should.have.key("Enabled").equals(False) assert signers["Enabled"] is False
signers.should.have.key("Quantity").equals(0) assert signers["Quantity"] == 0
default_cache.should.have.key("TrustedKeyGroups")
groups = default_cache["TrustedKeyGroups"] groups = default_cache["TrustedKeyGroups"]
groups.should.have.key("Enabled").equals(False) assert groups["Enabled"] is False
groups.should.have.key("Quantity").equals(0) assert groups["Quantity"] == 0
default_cache.should.have.key("ViewerProtocolPolicy").equals("allow-all") assert default_cache["ViewerProtocolPolicy"] == "allow-all"
default_cache.should.have.key("AllowedMethods")
methods = default_cache["AllowedMethods"] methods = default_cache["AllowedMethods"]
methods.should.have.key("Quantity").equals(2) assert methods["Quantity"] == 2
methods.should.have.key("Items") assert set(methods["Items"]) == {"HEAD", "GET"}
set(methods["Items"]).should.equal({"HEAD", "GET"})
methods.should.have.key("CachedMethods")
cached_methods = methods["CachedMethods"] cached_methods = methods["CachedMethods"]
cached_methods.should.have.key("Quantity").equals(2) assert cached_methods["Quantity"] == 2
set(cached_methods["Items"]).should.equal({"HEAD", "GET"}) assert set(cached_methods["Items"]) == {"HEAD", "GET"}
default_cache.should.have.key("SmoothStreaming").equals(False) assert default_cache["SmoothStreaming"] is False
default_cache.should.have.key("Compress").equals(True) assert default_cache["Compress"] is True
default_cache.should.have.key("LambdaFunctionAssociations").equals({"Quantity": 0}) assert default_cache["LambdaFunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FunctionAssociations").equals({"Quantity": 0}) assert default_cache["FunctionAssociations"] == {"Quantity": 0}
default_cache.should.have.key("FieldLevelEncryptionId").equals("") assert default_cache["FieldLevelEncryptionId"] == ""
default_cache.should.have.key("CachePolicyId") assert "CachePolicyId" in default_cache
config.should.have.key("CacheBehaviors").equals({"Quantity": 0}) assert config["CacheBehaviors"] == {"Quantity": 0}
config.should.have.key("CustomErrorResponses").equals({"Quantity": 0}) assert config["CustomErrorResponses"] == {"Quantity": 0}
config.should.have.key("Comment").equals( assert config["Comment"] == "an optional comment that's not actually optional"
"an optional comment that's not actually optional"
)
config.should.have.key("Logging")
logging = config["Logging"] logging = config["Logging"]
logging.should.have.key("Enabled").equals(False) assert logging["Enabled"] is False
logging.should.have.key("IncludeCookies").equals(False) assert logging["IncludeCookies"] is False
logging.should.have.key("Bucket").equals("") assert logging["Bucket"] == ""
logging.should.have.key("Prefix").equals("") assert logging["Prefix"] == ""
config.should.have.key("PriceClass").equals("PriceClass_All") assert config["PriceClass"] == "PriceClass_All"
config.should.have.key("Enabled").equals(False) assert config["Enabled"] is False
config.should.have.key("WebACLId") assert "WebACLId" in config
config.should.have.key("HttpVersion").equals("http2") assert config["HttpVersion"] == "http2"
config.should.have.key("IsIPV6Enabled").equals(True) assert config["IsIPV6Enabled"] is True
config.should.have.key("ViewerCertificate")
cert = config["ViewerCertificate"] cert = config["ViewerCertificate"]
cert.should.have.key("CloudFrontDefaultCertificate").equals(True) assert cert["CloudFrontDefaultCertificate"] is True
cert.should.have.key("MinimumProtocolVersion").equals("TLSv1") assert cert["MinimumProtocolVersion"] == "TLSv1"
cert.should.have.key("CertificateSource").equals("cloudfront") assert cert["CertificateSource"] == "cloudfront"
config.should.have.key("Restrictions") assert config["Restrictions"]["GeoRestriction"] == {
config["Restrictions"].should.have.key("GeoRestriction") "RestrictionType": "none",
restriction = config["Restrictions"]["GeoRestriction"] "Quantity": 0,
restriction.should.have.key("RestrictionType").equals("none") }
restriction.should.have.key("Quantity").equals(0)
config.should.have.key("WebACLId") assert config["WebACLId"] == ""
config.should.have.key("WebACLId").equals("")

View File

@ -1,7 +1,6 @@
import boto3 import boto3
from moto import mock_cloudfront from moto import mock_cloudfront
from . import cloudfront_test_scaffolding as scaffold from . import cloudfront_test_scaffolding as scaffold
import sure # noqa # pylint: disable=unused-import
@mock_cloudfront @mock_cloudfront
@ -19,18 +18,16 @@ def test_create_invalidation_with_single_path():
}, },
) )
resp.should.have.key("Location") assert "Location" in resp
resp.should.have.key("Invalidation") assert "Invalidation" in resp
resp["Invalidation"].should.have.key("Id") assert "Id" in resp["Invalidation"]
resp["Invalidation"].should.have.key("Status").equals("COMPLETED") assert resp["Invalidation"]["Status"] == "COMPLETED"
resp["Invalidation"].should.have.key("CreateTime") assert "CreateTime" in resp["Invalidation"]
resp["Invalidation"].should.have.key("InvalidationBatch").equals( assert resp["Invalidation"]["InvalidationBatch"] == {
{ "Paths": {"Quantity": 1, "Items": ["/path1"]},
"Paths": {"Quantity": 1, "Items": ["/path1"]}, "CallerReference": "ref2",
"CallerReference": "ref2", }
}
)
@mock_cloudfront @mock_cloudfront
@ -48,18 +45,16 @@ def test_create_invalidation_with_multiple_paths():
}, },
) )
resp.should.have.key("Location") assert "Location" in resp
resp.should.have.key("Invalidation") assert "Invalidation" in resp
resp["Invalidation"].should.have.key("Id") assert "Id" in resp["Invalidation"]
resp["Invalidation"].should.have.key("Status").equals("COMPLETED") assert resp["Invalidation"]["Status"] == "COMPLETED"
resp["Invalidation"].should.have.key("CreateTime") assert "CreateTime" in resp["Invalidation"]
resp["Invalidation"].should.have.key("InvalidationBatch").equals( assert resp["Invalidation"]["InvalidationBatch"] == {
{ "Paths": {"Quantity": 2, "Items": ["/path1", "/path2"]},
"Paths": {"Quantity": 2, "Items": ["/path1", "/path2"]}, "CallerReference": "ref2",
"CallerReference": "ref2", }
}
)
@mock_cloudfront @mock_cloudfront
@ -77,32 +72,26 @@ def test_list_invalidations():
) )
invalidation_id = resp["Invalidation"]["Id"] invalidation_id = resp["Invalidation"]["Id"]
resp = client.list_invalidations( resp = client.list_invalidations(DistributionId=dist_id)
DistributionId=dist_id,
)
resp.should.have.key("InvalidationList") assert "NextMarker" not in resp["InvalidationList"]
resp["InvalidationList"].shouldnt.have.key("NextMarker") assert resp["InvalidationList"]["MaxItems"] == 100
resp["InvalidationList"].should.have.key("MaxItems").equal(100) assert resp["InvalidationList"]["IsTruncated"] is False
resp["InvalidationList"].should.have.key("IsTruncated").equal(False) assert resp["InvalidationList"]["Quantity"] == 1
resp["InvalidationList"].should.have.key("Quantity").equal(1) assert len(resp["InvalidationList"]["Items"]) == 1
resp["InvalidationList"].should.have.key("Items").length_of(1) assert resp["InvalidationList"]["Items"][0]["Id"] == invalidation_id
resp["InvalidationList"]["Items"][0].should.have.key("Id").equal(invalidation_id) assert "CreateTime" in resp["InvalidationList"]["Items"][0]
resp["InvalidationList"]["Items"][0].should.have.key("CreateTime") assert resp["InvalidationList"]["Items"][0]["Status"] == "COMPLETED"
resp["InvalidationList"]["Items"][0].should.have.key("Status").equal("COMPLETED")
@mock_cloudfront @mock_cloudfront
def test_list_invalidations__no_entries(): def test_list_invalidations__no_entries():
client = boto3.client("cloudfront", region_name="us-west-1") client = boto3.client("cloudfront", region_name="us-west-1")
resp = client.list_invalidations( resp = client.list_invalidations(DistributionId="SPAM")
DistributionId="SPAM",
)
resp.should.have.key("InvalidationList") assert "NextMarker" not in resp["InvalidationList"]
resp["InvalidationList"].shouldnt.have.key("NextMarker") assert resp["InvalidationList"]["MaxItems"] == 100
resp["InvalidationList"].should.have.key("MaxItems").equal(100) assert resp["InvalidationList"]["IsTruncated"] is False
resp["InvalidationList"].should.have.key("IsTruncated").equal(False) assert resp["InvalidationList"]["Quantity"] == 0
resp["InvalidationList"].should.have.key("Quantity").equal(0) assert "Items" not in resp["InvalidationList"]
resp["InvalidationList"].shouldnt.have.key("Items")