def test_create_group_with_config_and_list_scaling_group_states(self, mock_sgrp):
        """
        Listing scaling group states returns one :class:`GroupState` per group,
        and adding another scaling group increases the number of scaling groups
        in the collection.  These are tested together since testing list
        involves putting scaling groups in the collection (create), and testing
        creation involves enumerating the collection (list)

        Creation of a scaling group with a 'config' parameter creates a
        scaling group with the specified configuration.
        """
        policies = group_examples.policy()[:2]
        self.assertEqual(self.validate_list_states_return_value(
                         self.mock_log, self.
                         tenant_id), [],
                         "Should start off with zero groups")
        manifest = self.validate_create_return_value(
            self.mock_log, self.tenant_id, self.config, self.launch, policies)

        self.assertEqual(self.mock_uuid.call_count, 3)  # 1 group, 3 policies

        self.assertEqual(manifest, {
            'groupConfiguration': self.config,
            'launchConfiguration': self.launch,
            'scalingPolicies': dict(zip(('2', '3'), policies)),
            'id': '1'
        })

        result = self.validate_list_states_return_value(self.mock_log, self.tenant_id)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].group_id, '1', "Group not added to collection")

        mock_sgrp.assert_called_once_with(
            mock.ANY, self.tenant_id, '1', self.collection,
            {'config': self.config, 'launch': self.launch, 'policies': policies})
Esempio n. 2
0
    def setUp(self):
        """
        Create a mock group
        """
        self.tenant_id = '11111'
        self.group_id = '1'
        self.mock_log = mock.MagicMock()
        self.collection = mock.MagicMock(spec=[], data={self.tenant_id: {}})

        self.config = {'name': 'aname', 'cooldown': 0, 'minEntities': 0}
        # this is the config with all the default vals
        self.output_config = {
            'name': 'aname',
            'cooldown': 0,
            'minEntities': 0,
            'maxEntities': None,
            'metadata': {}
        }
        self.launch_config = {
            "type": "launch_server",
            "args": {
                "server": {
                    "these are": "some args"
                }
            }
        }
        self.policies = group_examples.policy()[:1]
        self.group = MockScalingGroup(
            self.mock_log, self.tenant_id, self.group_id, self.collection, {
                'config': self.config,
                'launch': self.launch_config,
                'policies': self.policies
            })

        self.collection.data[self.tenant_id]['1'] = self.group
Esempio n. 3
0
class CreateScalingPoliciesTestCase(TestCase):
    """
    Verification that the JSON schema for creating scaling policies is correct
    """
    one_policy = group_examples.policy()[0]

    def test_schema_valid(self):
        """
        The schema itself is a valid Draft 3 schema
        """
        Draft3Validator.check_schema(rest_schemas.create_policies_request)

    def test_empty_array_valid(self):
        """
        Seems pointless to disallow empty arrays, so empty arrays validate.
        """
        validate([], rest_schemas.create_policies_request)

    def test_duplicate_policies_valid(self):
        """
        Duplicate policies are valid
        """
        validate([self.one_policy] * 5, rest_schemas.create_policies_request)

    def test_non_array_policy_fails(self):
        """
        A single policy, not in an array, fails to validate.
        """
        self.assertRaises(ValidationError, validate, self.one_policy,
                          rest_schemas.create_policies_request)
    def update_and_view_scaling_policy(self, path):
        """
        Updating a scaling policy returns with a 204 no content.  When viewing
        the policy again, it should contain the updated version.
        """
        request_body = policy()[-1]  # the one that was not created
        wrapper = self.successResultOf(
            request(root, 'PUT', path, body=json.dumps(request_body)))
        self.assertEqual(wrapper.response.code, 204,
                         "Update failed: {0}".format(wrapper.content))
        self.assertEqual(wrapper.content, "")

        # now try to view
        wrapper = self.successResultOf(request(root, 'GET', path))
        self.assertEqual(wrapper.response.code, 200)

        response = json.loads(wrapper.content)
        updated = response['policy']

        self.assertIn('id', updated)
        self.assertIn('links', updated)
        self.assertIn(
            path, [_strip_base_url(link["href"]) for link in updated["links"]])

        del updated['id']
        del updated['links']

        self.assertEqual(updated, request_body)
Esempio n. 5
0
    def update_and_view_scaling_policy(self, path):
        """
        Updating a scaling policy returns with a 204 no content.  When viewing
        the policy again, it should contain the updated version.
        """
        request_body = policy()[-1]  # the one that was not created
        wrapper = self.successResultOf(
            request(root, 'PUT', path, body=json.dumps(request_body)))
        self.assertEqual(wrapper.response.code, 204,
                         "Update failed: {0}".format(wrapper.content))
        self.assertEqual(wrapper.content, "")

        # now try to view
        wrapper = self.successResultOf(request(root, 'GET', path))
        self.assertEqual(wrapper.response.code, 200)

        response = json.loads(wrapper.content)
        updated = response['policy']

        self.assertIn('id', updated)
        self.assertIn('links', updated)
        self.assertIn(
            path, [_strip_base_url(link["href"]) for link in updated["links"]])

        del updated['id']
        del updated['links']

        self.assertEqual(updated, request_body)
    def setUp(self):
        """
        Create a mock group
        """
        self.tenant_id = '11111'
        self.group_id = '1'
        self.mock_log = mock.MagicMock()
        self.collection = mock.MagicMock(spec=[], data={self.tenant_id: {}})

        self.config = {
            'name': 'aname',
            'cooldown': 0,
            'minEntities': 0
        }
        # this is the config with all the default vals
        self.output_config = {
            'name': 'aname',
            'cooldown': 0,
            'minEntities': 0,
            'maxEntities': None,
            'metadata': {}
        }
        self.launch_config = {
            "type": "launch_server",
            "args": {"server": {"these are": "some args"}}
        }
        self.policies = group_examples.policy()[:1]
        self.group = MockScalingGroup(
            self.mock_log, self.tenant_id, self.group_id, self.collection,
            {'config': self.config, 'launch': self.launch_config,
             'policies': self.policies})

        self.collection.data[self.tenant_id]['1'] = self.group
Esempio n. 7
0
    def update_and_view_scaling_policy(self, path):
        """
        Updating a scaling policy returns with a 204 no content.  When viewing
        the policy again, it should contain the updated version.
        """
        request_body = policy()[-1]  # the one that was not created
        wrapper = yield request(root, 'PUT', path,
                                body=json.dumps(request_body))
        self.assert_response(wrapper, 204, "Update policy failed.")
        self.assertEqual(wrapper.content, "")

        # now try to view
        wrapper = yield request(root, 'GET', path)
        self.assert_response(wrapper, 200)

        response = json.loads(wrapper.content)
        updated = response['policy']

        self.assertIn('id', updated)
        self.assertIn('links', updated)
        self.assertIn(
            path, [path_only(link["href"]) for link in updated["links"]])

        del updated['id']
        del updated['links']

        self.assertEqual(updated, request_body)
Esempio n. 8
0
 def setUp(self):
     """
     Set up a reference to a standard, valid policy, config, and launch
     configs.
     """
     self.policy = group_examples.policy()[0]
     self.config = group_examples.config()[0]
     self.launch = group_examples.launch_server_config()[0]
Esempio n. 9
0
 def setUp(self):
     """
     Set up a reference to a standard, valid policy, config, and launch
     configs.
     """
     self.policy = group_examples.policy()[0]
     self.config = group_examples.config()[0]
     self.launch = group_examples.launch_server_config()[0]
Esempio n. 10
0
 def test_creation_with_scaling_policies_valid(self):
     """
     Creation with an array of many scaling policies
     """
     validate({
         'groupConfiguration': self.config,
         'launchConfiguration': self.launch,
         'scalingPolicies': group_examples.policy()
     }, rest_schemas.create_group_request)
Esempio n. 11
0
    def test_list_policies_offsets_by_marker(self):
        """
        Listing all policies will offset the list by the last seen parameter
        """
        self.policies = group_examples.policy()[:3]
        self.group = MockScalingGroup(
            self.mock_log, self.tenant_id, self.group_id, self.collection,
            {'config': self.config, 'launch': self.launch_config,
             'policies': self.policies})

        policies = self.validate_list_policies_return_value(limit=2, marker='1')
        self.assertEqual([p['id'] for p in policies], ['2', '3'])
Esempio n. 12
0
    def test_list_policies_limits_number_of_policies(self):
        """
        Listing all policies limits the number of policies by the limit
        specified
        """
        self.policies = group_examples.policy()[:3]
        self.group = MockScalingGroup(
            self.mock_log, self.tenant_id, self.group_id, self.collection,
            {'config': self.config, 'launch': self.launch_config,
             'policies': self.policies})

        policies = self.validate_list_policies_return_value(limit=2)
        self.assertEqual([p['id'] for p in policies], ['1', '2'])
Esempio n. 13
0
    def create_and_view_scaling_policies(self):
        """
        Creating valid scaling policies returns with a 200 OK, a Location
        header pointing to the list of all scaling policies, and a response
        containing a list of the newly created scaling policy resources only.

        :return: a list self links to the new scaling policies (not guaranteed
            to be in any consistent order)
        """
        request_body = policy()[:
                                -1]  # however many of them there are minus one
        wrapper = self.successResultOf(
            request(root,
                    'POST',
                    self.policies_url,
                    body=json.dumps(request_body)))

        self.assertEqual(wrapper.response.code, 201,
                         "Create failed: {0}".format(wrapper.content))
        response = json.loads(wrapper.content)

        self.assertEqual(len(request_body), len(response["policies"]))

        # this iterates over the response policies, checks to see that each have
        # 'id' and 'links' keys, and then checks to see that the rest of the
        # response policy is in the original set of policies to be created
        for pol in response["policies"]:
            original_pol = pol.copy()
            for key in ('id', 'links'):
                self.assertIn(key, pol)
                del original_pol[key]
            self.assertIn(original_pol, request_body)

        headers = wrapper.response.headers.getRawHeaders('Location')
        self.assertTrue(headers is not None)
        self.assertEqual(1, len(headers))

        # now make sure the Location header points to the list policies header
        self.assertEqual(_strip_base_url(headers[0]), self.policies_url)

        links = [
            _strip_base_url(link["href"]) for link in pol["links"]
            if link["rel"] == "self" for pol in response["policies"]
        ]
        return links
Esempio n. 14
0
    def test_create_group_with_config_and_list_scaling_group_states(
            self, mock_sgrp):
        """
        Listing scaling group states returns one :class:`GroupState` per group,
        and adding another scaling group increases the number of scaling groups
        in the collection.  These are tested together since testing list
        involves putting scaling groups in the collection (create), and testing
        creation involves enumerating the collection (list)

        Creation of a scaling group with a 'config' parameter creates a
        scaling group with the specified configuration.
        """
        policies = group_examples.policy()[:2]
        self.assertEqual(
            self.validate_list_states_return_value(self.mock_log,
                                                   self.tenant_id), [],
            "Should start off with zero groups")
        manifest = self.validate_create_return_value(self.mock_log,
                                                     self.tenant_id,
                                                     self.config, self.launch,
                                                     policies)

        self.assertEqual(self.mock_uuid.call_count, 3)  # 1 group, 3 policies

        self.assertEqual(
            manifest, {
                'groupConfiguration': self.config,
                'launchConfiguration': self.launch,
                'scalingPolicies': dict(zip(('2', '3'), policies)),
                'id': '1'
            })

        result = self.validate_list_states_return_value(
            self.mock_log, self.tenant_id)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].group_id, '1',
                         "Group not added to collection")

        mock_sgrp.assert_called_once_with(mock.ANY, self.tenant_id, '1',
                                          self.collection, {
                                              'config': self.config,
                                              'launch': self.launch,
                                              'policies': policies
                                          })
Esempio n. 15
0
    def setUp(self):
        """
        Create a mock group
        """
        set_config_data({'limits': {'absolute': {'maxWebhooksPerPolicy': 10,
                                                 'maxPoliciesPerGroup': 10}}})
        self.addCleanup(set_config_data, {})

        self.tenant_id = '11111'
        self.group_id = '1'
        self.mock_log = mock.MagicMock()
        self.collection = mock.MagicMock(spec=[], data={self.tenant_id: {}})

        self.config = {
            'name': 'aname',
            'cooldown': 0,
            'minEntities': 0
        }
        # this is the config with all the default vals
        self.output_config = {
            'name': 'aname',
            'cooldown': 0,
            'minEntities': 0,
            'maxEntities': None,
            'metadata': {}
        }
        self.launch_config = group_examples.launch_server_config()[0]
        self.policies = group_examples.policy()[:1]
        self.group = MockScalingGroup(
            self.mock_log, self.tenant_id, self.group_id, self.collection,
            {'config': self.config, 'launch': self.launch_config,
             'policies': self.policies})

        self.collection.data[self.tenant_id]['1'] = self.group

        self.counter = 0

        def generate_uuid():
            self.counter += 1
            return self.counter

        self.mock_uuid = patch(self, 'otter.models.mock.uuid4',
                               side_effect=generate_uuid)
Esempio n. 16
0
    def create_and_view_scaling_policies(self):
        """
        Creating valid scaling policies returns with a 200 OK, a Location
        header pointing to the list of all scaling policies, and a response
        containing a list of the newly created scaling policy resources only.

        :return: a list self links to the new scaling policies (not guaranteed
            to be in any consistent order)
        """
        request_body = policy()[:-1]  # however many of them there are minus one

        def _verify_create_response(wrapper):
            self.assert_response(wrapper, 201, "Create policies failed.")
            response = json.loads(wrapper.content)

            self.assertEqual(len(request_body), len(response["policies"]))

            # this iterates over the response policies, checks to see that each
            # have 'id' and 'links' keys, and then checks to see that the rest
            # of the response policy is in the original set of policies to be
            #created
            for pol in response["policies"]:
                original_pol = pol.copy()
                for key in ('id', 'links'):
                    self.assertIn(key, pol)
                    del original_pol[key]
                self.assertIn(original_pol, request_body)

            # now make sure the Location header points to the list policies
            #header
            location = path_only(self.get_location_header(wrapper))
            self.assertEqual(location, self.policies_url)

            links = [path_only(link["href"])
                     for link in pol["links"] if link["rel"] == "self"
                     for pol in response["policies"]]
            return links

        d = request(root, 'POST', self.policies_url,
                    body=json.dumps(request_body))
        return d.addCallback(_verify_create_response)
    def create_and_view_scaling_policies(self):
        """
        Creating valid scaling policies returns with a 200 OK, a Location
        header pointing to the list of all scaling policies, and a response
        containing a list of the newly created scaling policy resources only.

        :return: a list self links to the new scaling policies (not guaranteed
            to be in any consistent order)
        """
        request_body = policy()[:-1]  # however many of them there are minus one
        wrapper = self.successResultOf(request(
            root, 'POST', self.policies_url, body=json.dumps(request_body)))

        self.assertEqual(wrapper.response.code, 201,
                         "Create failed: {0}".format(wrapper.content))
        response = json.loads(wrapper.content)

        self.assertEqual(len(request_body), len(response["policies"]))

        # this iterates over the response policies, checks to see that each have
        # 'id' and 'links' keys, and then checks to see that the rest of the
        # response policy is in the original set of policies to be created
        for pol in response["policies"]:
            original_pol = pol.copy()
            for key in ('id', 'links'):
                self.assertIn(key, pol)
                del original_pol[key]
            self.assertIn(original_pol, request_body)

        headers = wrapper.response.headers.getRawHeaders('Location')
        self.assertTrue(headers is not None)
        self.assertEqual(1, len(headers))

        # now make sure the Location header points to the list policies header
        self.assertEqual(_strip_base_url(headers[0]), self.policies_url)

        links = [_strip_base_url(link["href"])
                 for link in pol["links"] if link["rel"] == "self"
                 for pol in response["policies"]]
        return links
Esempio n. 18
0
 def test_valid_examples_validate(self):
     """
     The scaling policy examples all validate.
     """
     for example in group_examples.policy():
         validate(example, group_schemas.policy)
Esempio n. 19
0
 def setUp(self):
     """
     Store copies of schedule type policies
     """
     self.at_policy = deepcopy(group_examples.policy()[3])
     self.cron_policy = deepcopy(group_examples.policy()[4])
Esempio n. 20
0
 def test_valid_examples_validate(self):
     """
     The scaling policy examples all validate.
     """
     for example in group_examples.policy():
         validate(example, group_schemas.policy)
Esempio n. 21
0
 def setUp(self):
     """
     Store copies of schedule type policies
     """
     self.at_policy = deepcopy(group_examples.policy()[3])
     self.cron_policy = deepcopy(group_examples.policy()[4])