Пример #1
0
    def test_policy_create(self):
        """
        Tries to create a set of policies.
        """
        self.mock_group.create_policies.return_value = defer.succeed([
            dict(id="5", **policy_examples()[0])])
        response_body = self.assert_status_code(
            201, None, 'POST', json.dumps(policy_examples()[:1]),
            # location header points to the policy list
            '/v1.0/11111/groups/1/policies/')

        self.mock_group.create_policies.assert_called_once_with(
            policy_examples()[:1])

        resp = json.loads(response_body)
        validate(resp, rest_schemas.create_policies_response)

        expected_policy = policy_examples()[0]
        expected_policy['id'] = '5'
        expected_policy['links'] = [
            {
                'rel': 'self',
                'href': '/v1.0/11111/groups/1/policies/5/'
            }
        ]
        self.assertEqual(resp, {"policies": [expected_policy]})
Пример #2
0
    def test_policy_create_bobby_null(self, create_policy, mock_url):
        """
        Tries to create a regular policy with bobby active
        """
        self.mock_group.create_policies.return_value = defer.succeed(
            [dict(id="5", **policy_examples()[0])])
        response_body = self.assert_status_code(
            201,
            None,
            'POST',
            json.dumps(policy_examples()[:1]),
            # location header points to the policy list
            '/v1.0/11111/groups/1/policies/')

        self.assertFalse(create_policy.called)

        self.mock_group.create_policies.assert_called_once_with(
            policy_examples()[:1])

        resp = json.loads(response_body)
        validate(resp, rest_schemas.create_policies_response)

        expected_policy = policy_examples()[0]
        expected_policy['id'] = '5'
        expected_policy['links'] = [{
            'rel': 'self',
            'href': '/v1.0/11111/groups/1/policies/5/'
        }]
        self.assertEqual(resp, {"policies": [expected_policy]})
Пример #3
0
    def test_policy_create_audit_logged(self, logger):
        """
        Policy creation is audit-logged
        """
        self.root = Otter(self.mock_store, 'region').app.resource()
        self.assertFalse(logger.msg.called)
        resp = policy_examples()[0]
        resp['id'] = '5'

        self.mock_group.create_policies.return_value = defer.succeed([resp])
        self.assert_status_code(
            201,
            None,
            'POST',
            json.dumps(policy_examples()[:1]),
            # location header points to the policy list
            '/v1.0/11111/groups/1/policies/')
        logger.msg.assert_any_call('Created policies.',
                                   request_ip='ip',
                                   event_type='request.policy.create',
                                   audit_log=True,
                                   tenant_id='11111',
                                   scaling_group_id='1',
                                   transaction_id='transaction-id',
                                   data={'policies': [resp]},
                                   system=mock.ANY)
Пример #4
0
    def test_policy_dictionary_gets_linkified(self):
        """
        When policies are returned, a properly formed JSON blob containing ids
        and links are returned with a 200 (OK) status
        """
        self.mock_group.list_policies.return_value = defer.succeed(
            [dict(id='5', **policy_examples()[0])])
        response_body = self.assert_status_code(200)
        self.mock_group.list_policies.assert_called_once()

        resp = json.loads(response_body)
        validate(resp, rest_schemas.list_policies_response)
        expected = dict(
            id='5',
            links=[{
                'rel': 'self',
                'href': '/v1.0/11111/groups/1/policies/5/'
            }],
            **policy_examples()[0]
        )

        self.assertEqual(resp, {
            "policies": [expected],
            "policies_links": []
        })
Пример #5
0
    def test_policy_dictionary_gets_translated(self, url_root):
        """
        When there are policies returned as a dict, a properly formed JSON blob
        containing ids and links are returned with a 200 (OK) status
        """
        self.mock_group.list_policies.return_value = defer.succeed({
            '5': policy_examples()[0]
        })
        response_body = self.assert_status_code(200)
        self.mock_group.list_policies.assert_called_once()

        resp = json.loads(response_body)
        validate(resp, rest_schemas.list_policies_response)
        expected = policy_examples()[0]
        expected['id'] = '5'
        expected['links'] = [
            {
                'rel': 'self',
                'href': '/v1.0/11111/groups/1/policies/5/'
            }
        ]
        self.assertEqual(resp, {
            "policies": [expected],
            "policies_links": []
        })
Пример #6
0
    def test_update_policy_success(self):
        """
        Replace existing details of a policy with new details.
        """
        (self.mock_group.
            update_policy.
            return_value) = defer.succeed(None)

        response_body = self.assert_status_code(
            204, method="PUT", body=json.dumps(policy_examples()[1]))
        self.assertEqual(response_body, "")
        self.mock_store.get_scaling_group.assert_called_once_with(mock.ANY, '11111', '1')
        self.mock_group.update_policy.assert_called_once_with(
            self.policy_id, policy_examples()[1])
Пример #7
0
    def test_view_manifest(self, url_root):
        """
        Viewing the manifest of an existant group returns whatever the
        implementation's `view_manifest()` method returns, in string format
        """
        manifest = {
            'groupConfiguration': config_examples()[0],
            'launchConfiguration': launch_examples()[0],
            'scalingPolicies': {
                "5": policy_examples()[0]
            },
            'id': 'one'
        }
        self.mock_group.view_manifest.return_value = defer.succeed(manifest)

        response_body = self.assert_status_code(200, method="GET")
        resp = json.loads(response_body)
        validate(resp, rest_schemas.create_and_manifest_response)

        expected_policy = policy_examples()[0]
        expected_policy.update({
            "id":
            "5",
            "links": [
                {
                    "href": "/v1.0/11111/groups/one/policies/5/",
                    "rel": "self"
                },
            ]
        })

        expected = {
            'group': {
                'groupConfiguration': config_examples()[0],
                'launchConfiguration': launch_examples()[0],
                'scalingPolicies': [expected_policy],
                "id": "one",
                "links": [{
                    "href": "/v1.0/11111/groups/one/",
                    "rel": "self"
                }]
            }
        }
        self.assertEqual(resp, expected)

        self.mock_store.get_scaling_group.assert_called_once_with(
            mock.ANY, '11111', 'one')
        self.mock_group.view_manifest.assert_called_once_with()
Пример #8
0
    def test_update_policy_failure_404(self):
        """
        If you try to update a non existant policy, fails with a 404.
        """
        (self.mock_group.
            update_policy.
            return_value) = defer.fail(NoSuchPolicyError('11111', '1', '2'))

        response_body = self.assert_status_code(
            404, method="PUT", body=json.dumps(policy_examples()[0]))
        resp = json.loads(response_body)

        self.mock_group.update_policy.assert_called_once_with(
            self.policy_id, policy_examples()[0])
        self.assertEqual(resp['type'], 'NoSuchPolicyError')
        self.flushLoggedErrors(NoSuchPolicyError)
Пример #9
0
    def test_update_policy_success(self):
        """
        Replace existing details of a policy with new details.
        """
        (self.mock_group.update_policy.return_value) = defer.succeed(None)

        response_body = self.assert_status_code(204,
                                                method="PUT",
                                                body=json.dumps(
                                                    policy_examples()[1]))
        self.assertEqual(response_body, "")
        self.mock_store.get_scaling_group.assert_called_once_with(
            mock.ANY, '11111', '1')
        self.mock_group.update_policy.assert_called_once_with(
            self.policy_id,
            policy_examples()[1])
Пример #10
0
    def test_view_manifest(self):
        """
        Viewing the manifest of an existant group returns whatever the
        implementation's `view_manifest()` method returns, in string format
        """
        manifest = {
            'groupConfiguration': config_examples()[0],
            'launchConfiguration': launch_examples()[0],
            'id': 'one',
            'state': GroupState('11111', '1', '', {}, {}, None, {}, False),
            'scalingPolicies': [dict(id="5", **policy_examples()[0])]
        }
        self.mock_group.view_manifest.return_value = defer.succeed(manifest)

        response_body = self.assert_status_code(200, method="GET")
        resp = json.loads(response_body)
        validate(resp, rest_schemas.create_and_manifest_response)

        expected_policy = policy_examples()[0]
        expected_policy.update({
            "id": "5",
            "links": [
                {"href": "/v1.0/11111/groups/one/policies/5/", "rel": "self"},
            ]
        })

        expected = {
            'group': {
                'groupConfiguration': config_examples()[0],
                'launchConfiguration': launch_examples()[0],
                'scalingPolicies': [expected_policy],
                "id": "one",
                "links": [
                    {"href": "/v1.0/11111/groups/one/", "rel": "self"}
                ],
                'scalingPolicies_links': [
                    {"href": "/v1.0/11111/groups/one/policies/", "rel": "policies"}
                ],
                'state': manifest['state']
            }
        }
        self.assertEqual(resp, expected)

        self.mock_store.get_scaling_group.assert_called_once_with(
            mock.ANY, '11111', 'one')
        self.mock_group.view_manifest.assert_called_once_with(False)
Пример #11
0
 def test_group_create_many_policies(self):
     """
     Tries to create a scaling group
     """
     self._test_successful_create({
         'groupConfiguration': config_examples()[0],
         'launchConfiguration': launch_examples()[0],
         'scalingPolicies': policy_examples()
     })
Пример #12
0
 def test_update_policy_unknown_error_is_500(self):
     """
     If an unexpected exception is raised, endpoint returns a 500.
     """
     error = DummyException('what')
     self.mock_group.update_policy.return_value = defer.fail(error)
     self.assert_status_code(500, method="PUT",
                             body=json.dumps(policy_examples()[1]))
     self.flushLoggedErrors()
Пример #13
0
    def test_update_policy_failure_404(self):
        """
        If you try to update a non existant policy, fails with a 404.
        """
        (self.mock_group.update_policy.return_value) = defer.fail(
            NoSuchPolicyError('11111', '1', '2'))

        response_body = self.assert_status_code(404,
                                                method="PUT",
                                                body=json.dumps(
                                                    policy_examples()[0]))
        resp = json.loads(response_body)

        self.mock_group.update_policy.assert_called_once_with(
            self.policy_id,
            policy_examples()[0])
        self.assertEqual(resp['error']['type'], 'NoSuchPolicyError')
        self.flushLoggedErrors(NoSuchPolicyError)
Пример #14
0
 def test_update_policy_unknown_error_is_500(self):
     """
     If an unexpected exception is raised, endpoint returns a 500.
     """
     error = DummyException('what')
     self.mock_group.update_policy.return_value = defer.fail(error)
     self.assert_status_code(500,
                             method="PUT",
                             body=json.dumps(policy_examples()[1]))
     self.flushLoggedErrors()
Пример #15
0
    def test_policy_create_audit_logged(self, logger):
        """
        Policy creation is audit-logged
        """
        self.root = Otter(self.mock_store, 'region').app.resource()
        self.assertFalse(logger.msg.called)
        resp = policy_examples()[0]
        resp['id'] = '5'

        self.mock_group.create_policies.return_value = defer.succeed([resp])
        self.assert_status_code(
            201, None, 'POST', json.dumps(policy_examples()[:1]),
            # location header points to the policy list
            '/v1.0/11111/groups/1/policies/')
        logger.msg.assert_any_call(
            'Created policies.', request_ip='ip',
            event_type='request.policy.create',
            audit_log=True, tenant_id='11111', scaling_group_id='1',
            transaction_id='transaction-id', data={'policies': [resp]},
            system=mock.ANY)
Пример #16
0
    def test_policy_dictionary_gets_linkified(self):
        """
        When policies are returned, a properly formed JSON blob containing ids
        and links are returned with a 200 (OK) status
        """
        self.mock_group.list_policies.return_value = defer.succeed(
            [dict(id='5', **policy_examples()[0])])
        response_body = self.assert_status_code(200)
        self.mock_group.list_policies.assert_called_once_with(limit=100)

        resp = json.loads(response_body)
        validate(resp, rest_schemas.list_policies_response)
        expected = dict(id='5',
                        links=[{
                            'rel': 'self',
                            'href': '/v1.0/11111/groups/1/policies/5/'
                        }],
                        **policy_examples()[0])

        self.assertEqual(resp, {"policies": [expected], "policies_links": []})
Пример #17
0
 def test_group_create_one_policy(self):
     """
     Tries to create a scaling group
     """
     self._test_successful_create({
         'groupConfiguration':
         config_examples()[0],
         'launchConfiguration':
         launch_examples()[0],
         'scalingPolicies': [policy_examples()[0]]
     })
Пример #18
0
    def test_get_policy(self):
        """
        Get details of a specific policy.  The response should conform with
        the json schema.
        """
        self.mock_group.get_policy.return_value = defer.succeed(
            policy_examples()[0])

        response_body = self.assert_status_code(200, method="GET")
        resp = json.loads(response_body)

        validate(resp, rest_schemas.get_policy_response)

        expected = policy_examples()[0]
        expected['id'] = self.policy_id
        expected['links'] = [
            {
                'rel': 'self',
                'href': '/v1.0/11111/groups/1/policies/{0}/'.format(self.policy_id)
            }
        ]
        self.assertEqual(resp, {'policy': expected})
Пример #19
0
    def test_get_policy(self):
        """
        Get details of a specific policy.  The response should conform with
        the json schema.
        """
        self.mock_group.get_policy.return_value = defer.succeed(
            policy_examples()[0])

        response_body = self.assert_status_code(200, method="GET")
        resp = json.loads(response_body)

        validate(resp, rest_schemas.get_policy_response)

        expected = policy_examples()[0]
        expected['id'] = self.policy_id
        expected['links'] = [{
            'rel':
            'self',
            'href':
            '/v1.0/11111/groups/1/policies/{0}/'.format(self.policy_id)
        }]
        self.assertEqual(resp, {'policy': expected})
Пример #20
0
 def test_get_policies_links_called(self, mock_get_policies_links):
     """
     'scalingPolicies_links' is added in response by calling `get_policies_links`
     """
     policies = [dict(id="5", **policy_examples()[0])]
     manifest = {
         'id': 'one',
         'state': GroupState('11111', '1', '', {}, {}, None, {}, False),
         'scalingPolicies': policies
     }
     self.mock_group.view_manifest.return_value = defer.succeed(manifest)
     response_body = self.assert_status_code(200, method="GET")
     resp = json.loads(response_body)
     self.assertEqual(resp['group']['scalingPolicies_links'], 'pol links')
     mock_get_policies_links.assert_called_once_with(
         policies, '11111', 'one', rel='policies')
Пример #21
0
    def test_policies_links_next(self):
        """
        When more than limit policies are returned, a properly formed JSON blob with
        policies_links containing next link is returned with a 200 (OK) status
        """
        self.mock_group.list_policies.return_value = defer.succeed(
            [dict(id='{}'.format(i), **policy_examples()[0])
             for i in range(1, 102)])
        response_body = self.assert_status_code(200)
        self.mock_group.list_policies.assert_called_once()

        resp = json.loads(response_body)
        validate(resp, rest_schemas.list_policies_response)
        expected_links = [
            {'href': '/v1.0/11111/groups/1/policies/?marker=100&limit=100',
             'rel': 'next'}
        ]
        self.assertEqual(resp['policies_links'], expected_links)
Пример #22
0
    def test_policies_links_next(self):
        """
        When more than limit policies are returned, a properly formed JSON blob with
        policies_links containing next link is returned with a 200 (OK) status
        """
        self.mock_group.list_policies.return_value = defer.succeed([
            dict(id='{}'.format(i), **policy_examples()[0])
            for i in range(1, 102)
        ])
        response_body = self.assert_status_code(200)
        self.mock_group.list_policies.assert_called_once_with(limit=100)

        resp = json.loads(response_body)
        validate(resp, rest_schemas.list_policies_response)
        expected_links = [{
            'href': '/v1.0/11111/groups/1/policies/?limit=100&marker=100',
            'rel': 'next'
        }]
        self.assertEqual(resp['policies_links'], expected_links)
Пример #23
0
        "groupConfiguration": config,
        "launchConfiguration": launch_config,
        "scalingPolicies": create_policies_request
    },
    "additionalProperties": False
}

create_group_request_examples = [
    {
        "groupConfiguration": config_examples()[0],
        "launchConfiguration": launch_server_config_examples()[0]
    },
    {
        "groupConfiguration": config_examples()[0],
        "launchConfiguration": launch_server_config_examples()[0],
        "scalingPolicies": [policy_examples()[0]]
    },
    {
        "groupConfiguration": config_examples()[1],
        "launchConfiguration": launch_server_config_examples()[1],
        "scalingPolicies": policy_examples()[1:3]
    }
]

# the response from creating a group and the response for viewing the manifest
# is exactly the same.
create_and_manifest_response = _openstackify_schema("group", {
    "type": "object",
    "description": ("Schema of the JSON used to display the scaling group's "
                    "manifested view, which is also returned by create group."),
    "properties": {
Пример #24
0
    def test_view_manifest_with_webhooks(self):
        """
        `view_manifest` gives webhooks information in policies if query args contains
        ?webhooks=true
        """
        manifest = {
            'groupConfiguration': config_examples()[0],
            'launchConfiguration': launch_examples()[0],
            'id': 'one',
            'state': GroupState('11111', '1', '', {}, {}, None, {}, False),
            'scalingPolicies': [dict(id="5", **policy_examples()[0]),
                                dict(id="6", **policy_examples()[1])]
        }
        webhooks = [
            [
                {
                    'id': '3',
                    'name': 'three',
                    'metadata': {},
                    'capability': {"version": "1", 'hash': 'xxx'}
                },
                {
                    'id': '4',
                    'name': 'four',
                    'metadata': {},
                    'capability': {"version": "1", 'hash': 'yyy'}
                }
            ],
            [
                {
                    'id': '5',
                    'name': 'five',
                    'metadata': {},
                    'capability': {"version": "1", 'hash': 'xxx'}
                },
                {
                    'id': '6',
                    'name': 'six',
                    'metadata': {},
                    'capability': {"version": "1", 'hash': 'yyy'}
                }
            ]
        ]
        webhooks_internal_links = [
            [[{"href": '/v1.0/11111/groups/one/policies/5/webhooks/3/', "rel": "self"},
              {"href": '/v1.0/execute/1/xxx/', "rel": "capability"}],
             [{"href": '/v1.0/11111/groups/one/policies/5/webhooks/4/', "rel": "self"},
              {"href": '/v1.0/execute/1/yyy/', "rel": "capability"}]],
            [[{"href": '/v1.0/11111/groups/one/policies/6/webhooks/5/', "rel": "self"},
              {"href": '/v1.0/execute/1/xxx/', "rel": "capability"}],
             [{"href": '/v1.0/11111/groups/one/policies/6/webhooks/6/', "rel": "self"},
              {"href": '/v1.0/execute/1/yyy/', "rel": "capability"}]]
        ]
        webhooks_links = [
            [{'href': '/v1.0/11111/groups/one/policies/5/webhooks/', 'rel': 'webhooks'}],
            [{'href': '/v1.0/11111/groups/one/policies/6/webhooks/', 'rel': 'webhooks'}]
        ]
        manifest['scalingPolicies'][0]['webhooks'] = webhooks[0]
        manifest['scalingPolicies'][1]['webhooks'] = webhooks[1]
        self.mock_group.view_manifest.return_value = defer.succeed(manifest)

        response_body = self.assert_status_code(
            200, endpoint="{0}?webhooks=true".format(self.endpoint), method="GET")
        resp = json.loads(response_body)
        validate(resp, rest_schemas.create_and_manifest_response)

        exp_policies = deepcopy(manifest['scalingPolicies'])
        for i in [0, 1]:
            exp_policies[i]['webhooks'] = deepcopy(webhooks[i])
            for j, webhook in enumerate(exp_policies[i]['webhooks']):
                exp_policies[i]['webhooks'][j]['links'] = webhooks_internal_links[i][j]
            exp_policies[i]['webhooks_links'] = webhooks_links[i]

        self.assertEqual(resp['group']['scalingPolicies'], exp_policies)