<commit_before># Copyright 2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
import mock

from touchdown.core import errors, serializers

from touchdown.aws.cloudfront import Distribution

from . import aws
from touchdown.aws.session import session


class TestMetadata(unittest.TestCase):

    def test_waiter_waity_enough(self):
        waiter = session.get_waiter_model("cloudfront")
        self.assertEqual(waiter.get_waiter("DistributionDeployed").max_attempts, 50)


class TestCloudFrontDistributionSerializing(unittest.TestCase):

    def setUp(self):
        uuid = mock.Mock()
        uuid.return_value = "e64daba4-dddf-478e-a39b-b15a74325330"

        self.uuid = mock.patch('uuid.uuid4', uuid)
        self.uuid.start()

    def tearDown(self):
        self.uuid.stop()

    def test_simple_distribution(self):
        distribution = Distribution(
            None,
            name="example.com",
        )
        result = serializers.Resource().render(mock.Mock(), distribution)
        del result['CallerReference']
        self.assertEqual(result, {
            'Origins': {'Items': [], 'Quantity': 0},
            'Restrictions': {'GeoRestriction': {'RestrictionType': 'none', 'Quantity': 0}},
            'DefaultRootObject': '/',
            'PriceClass': 'PriceClass_100',
            'Enabled': True,
            'CustomErrorResponses': {'Items': [], 'Quantity': 0},
            'CacheBehaviors': {'Items': [], 'Quantity': 0},
            'Aliases': {'Items': ['example.com'], 'Quantity': 1},
            'Logging': {'Enabled': False, 'Prefix': '', 'Bucket': '', 'IncludeCookies': False},
            'Comment': 'example.com',
            'ViewerCertificate': {
                'CloudFrontDefaultCertificate': True,
                'MinimumProtocolVersion': 'TLSv1',
                'SSLSupportMethod': 'sni-only'
            },
        })

    def test_simple_distribution_with_aliases(self):
        distribution = Distribution(
            None,
            name="example.com",
            aliases=['www.example.com'],
        )
        result = serializers.Resource().render(mock.Mock(), distribution)
        del result['CallerReference']
        self.assertEqual(result, {
            'Origins': {'Items': [], 'Quantity': 0},
            'Restrictions': {'GeoRestriction': {'RestrictionType': 'none', 'Quantity': 0}},
            'DefaultRootObject': '/',
            'PriceClass': 'PriceClass_100',
            'Enabled': True,
            'CustomErrorResponses': {'Items': [], 'Quantity': 0},
            'CacheBehaviors': {'Items': [], 'Quantity': 0},
            'Aliases': {'Items': ['example.com', 'www.example.com'], 'Quantity': 2},
            'Logging': {'Enabled': False, 'Prefix': '', 'Bucket': '', 'IncludeCookies': False},
            'Comment': 'example.com',
            'ViewerCertificate': {
                'CloudFrontDefaultCertificate': True,
                'MinimumProtocolVersion': 'TLSv1',
                'SSLSupportMethod': 'sni-only'
            },
        })


class TestCloudFront(aws.TestBasicUsage):

    def setUpResource(self):
        self.expected_resource_id = 'EDFDVBD6EXAMPLE'
        self.resource = self.aws.add_distribution(
            name='www.example.com',
            origins=[{
                "name": "fred",
                "domain_name": "backend.example.com",
            }],
            default_cache_behavior={
                "target_origin": "fred",
            },
        )

    # FIXME: Refactor tests so matching can be done in a generic way
    def test_no_change(self):
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2014-11-06/distribution", self.fixture_found, expires=1)
        self.responses.add_fixture(
            "GET",
            "https://cloudfront.amazonaws.com/2014-11-06/distribution/EDFDVBD6EXAMPLE",
            "aws_distribution_get",
            expires=1
        )
        self.assertRaises(errors.NothingChanged, self.goal.execute)
        self.assertEqual(self.plan.resource_id, self.expected_resource_id)

    # FIXME: Refactor tests so matching can be done in a generic way
    def test_create(self):
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2014-11-06/distribution", self.fixture_404, expires=1)
        self.responses.add_fixture("POST", self.base_url, self.fixture_create, expires=1)
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2014-11-06/distribution", self.fixture_found)
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2014-11-06/distribution/EDFDVBD6EXAMPLE", "aws_distribution_get")
        self.goal.execute()
        self.assertEqual(self.plan.resource_id, self.expected_resource_id)<commit_msg>Update CloudFront tests<commit_after># Copyright 2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
import mock

from touchdown.core import errors, serializers

from touchdown.aws.cloudfront import Distribution

from . import aws
from touchdown.aws.session import session


class TestMetadata(unittest.TestCase):

    def test_waiter_waity_enough(self):
        waiter = session.get_waiter_model("cloudfront")
        self.assertEqual(waiter.get_waiter("DistributionDeployed").max_attempts, 50)


class TestCloudFrontDistributionSerializing(unittest.TestCase):

    def setUp(self):
        uuid = mock.Mock()
        uuid.return_value = "e64daba4-dddf-478e-a39b-b15a74325330"

        self.uuid = mock.patch('uuid.uuid4', uuid)
        self.uuid.start()

    def tearDown(self):
        self.uuid.stop()

    def test_simple_distribution(self):
        distribution = Distribution(
            None,
            name="example.com",
        )
        result = serializers.Resource().render(mock.Mock(), distribution)
        del result['CallerReference']
        self.assertEqual(result, {
            'Origins': {'Items': [], 'Quantity': 0},
            'Restrictions': {'GeoRestriction': {'RestrictionType': 'none', 'Quantity': 0}},
            'DefaultRootObject': '/',
            'PriceClass': 'PriceClass_100',
            'Enabled': True,
            'CustomErrorResponses': {'Items': [], 'Quantity': 0},
            'CacheBehaviors': {'Items': [], 'Quantity': 0},
            'Aliases': {'Items': ['example.com'], 'Quantity': 1},
            'Logging': {'Enabled': False, 'Prefix': '', 'Bucket': '', 'IncludeCookies': False},
            'Comment': 'example.com',
            'ViewerCertificate': {
                'CloudFrontDefaultCertificate': True,
                'MinimumProtocolVersion': 'TLSv1',
                'SSLSupportMethod': 'sni-only'
            },
        })

    def test_simple_distribution_with_aliases(self):
        distribution = Distribution(
            None,
            name="example.com",
            aliases=['www.example.com'],
        )
        result = serializers.Resource().render(mock.Mock(), distribution)
        del result['CallerReference']
        self.assertEqual(result, {
            'Origins': {'Items': [], 'Quantity': 0},
            'Restrictions': {'GeoRestriction': {'RestrictionType': 'none', 'Quantity': 0}},
            'DefaultRootObject': '/',
            'PriceClass': 'PriceClass_100',
            'Enabled': True,
            'CustomErrorResponses': {'Items': [], 'Quantity': 0},
            'CacheBehaviors': {'Items': [], 'Quantity': 0},
            'Aliases': {'Items': ['example.com', 'www.example.com'], 'Quantity': 2},
            'Logging': {'Enabled': False, 'Prefix': '', 'Bucket': '', 'IncludeCookies': False},
            'Comment': 'example.com',
            'ViewerCertificate': {
                'CloudFrontDefaultCertificate': True,
                'MinimumProtocolVersion': 'TLSv1',
                'SSLSupportMethod': 'sni-only'
            },
        })


class TestCloudFront(aws.TestBasicUsage):

    def setUpResource(self):
        self.expected_resource_id = 'EDFDVBD6EXAMPLE'
        self.resource = self.aws.add_distribution(
            name='www.example.com',
            origins=[{
                "name": "fred",
                "domain_name": "backend.example.com",
            }],
            default_cache_behavior={
                "target_origin": "fred",
            },
        )

    # FIXME: Refactor tests so matching can be done in a generic way
    def test_no_change(self):
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2015-07-27/distribution", self.fixture_found, expires=1)
        self.responses.add_fixture(
            "GET",
            "https://cloudfront.amazonaws.com/2015-07-27/distribution/EDFDVBD6EXAMPLE",
            "aws_distribution_get",
            expires=1
        )
        self.assertRaises(errors.NothingChanged, self.goal.execute)
        self.assertEqual(self.plan.resource_id, self.expected_resource_id)

    # FIXME: Refactor tests so matching can be done in a generic way
    def test_create(self):
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2015-07-27/distribution", self.fixture_404, expires=1)
        self.responses.add_fixture("POST", self.base_url, self.fixture_create, expires=1)
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2015-07-27/distribution", self.fixture_found)
        self.responses.add_fixture("GET", "https://cloudfront.amazonaws.com/2015-07-27/distribution/EDFDVBD6EXAMPLE", "aws_distribution_get")
        self.goal.execute()
        self.assertEqual(self.plan.resource_id, self.expected_resource_id)
{'fraction_non_alphanumeric': 0.13376278893520274, 'fraction_numerical': 0.018378173550587344, 'mean_word_length': 2.6848167539267016, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 10, 'lorem ipsum': 0, 'www.': 8, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '671244', 'n_tokens_mistral': 3148, 'n_tokens_neox': 2926, 'n_words': 631}