<commit_before># 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 mock
import six
from webob import exc

from oslo_serialization import jsonutils
from oslo_utils import uuidutils

from senlin.api.middleware import fault
from senlin.api.openstack.v1 import policies
from senlin.common import exception as senlin_exc
from senlin.common.i18n import _
from senlin.common import policy
from senlin.objects.requests import policies as vorp
from senlin.rpc import client as rpc_client
from senlin.tests.unit.api import shared
from senlin.tests.unit.common import base


@mock.patch.object(policy, 'enforce')
class PolicyControllerTest(shared.ControllerTest, base.SenlinTestCase):
    def setUp(self):
        super(PolicyControllerTest, self).setUp()

        class DummyConfig(object):
            bind_port = 8778

        cfgopts = DummyConfig()
        self.controller = policies.PolicyController(options=cfgopts)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_normal(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        req = self._get('/policies')

        engine_resp = [
            {
                u'id': u'aaaa-bbbb-cccc',
                u'name': u'policy-1',
                u'type': u'test_policy_type',
                u'spec': {
                    u'param_1': u'value1',
                    u'param_2': u'value2',
                },
                u'created_time': u'2015-02-24T19:17:22Z',
                u'updated_time': None,
            }
        ]

        mock_call.return_value = engine_resp

        result = self.controller.index(req)

        expected = {u'policies': engine_resp}
        self.assertEqual(expected, result)

        mock_call.assert_called_with(req.context, 'policy_list2',
                                     mock.ANY)

        request = mock_call.call_args[0][2]
        self.assertIsInstance(request, vorp.PolicyListRequest)
        self.assertTrue(request.project_safe)
        self.assertFalse(request.obj_attr_is_set('name'))
        self.assertFalse(request.obj_attr_is_set('type'))
        self.assertFalse(request.obj_attr_is_set('limit'))
        self.assertFalse(request.obj_attr_is_set('marker'))
        self.assertFalse(request.obj_attr_is_set('sort'))

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_whitelists_params(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        fake_id = uuidutils.generate_uuid()
        params = {
            'name': 'FAKE',
            'type': 'TYPE',
            'limit': 20,
            'marker': fake_id,
            'sort': 'name:asc',
            'global_project': True,
        }
        req = self._get('/policies', params=params)

        engine_resp = [{'foo': 'bar'}]
        mock_call.return_value = engine_resp

        result = self.controller.index(req)

        expected = {u'policies': engine_resp}
        self.assertEqual(expected, result)

        mock_call.assert_called_once_with(req.context, 'policy_list2',
                                          mock.ANY)
        request = mock_call.call_args[0][2]
        self.assertIsInstance(request, vorp.PolicyListRequest)
        self.assertFalse(request.project_safe)
        self.assertEqual(['FAKE'], request.name)
        self.assertEqual(['TYPE'], request.type)
        self.assertEqual(20, request.limit)
        self.assertEqual(fake_id, request.marker)
        self.assertEqual('name:asc', request.sort)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_whitelist_bad_params(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        params = {
            'balrog': 'fake_value'
        }
        req = self._get('/policies', params=params)

        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.index,
                               req)

        self.assertEqual("Invalid parameter balrog", six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_gloable_project_invalid(self, mock_call,
                                                  mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        params = {
            'global_project': 'No',
        }
        req = self._get('/policies', params=params)

        ex = self.assertRaises(senlin_exc.InvalidParameter,
                               self.controller.index,
                               req)

        self.assertEqual("Invalid value 'No' specified for 'global_project'",
                         six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_limit_non_int(self, mock_call, mock_enforce):
        mock_call = self.patchobject(rpc_client.EngineClient, 'policy_list',
                                     return_value=[])

        params = {'limit': 'abc'}
        req = self._get('/policies', params=params)
        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.index,
                               req)

        self.assertIn("invalid literal for int() with base 10: 'abc'",
                      six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    def test_policy_index_denied_policy(self, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', False)<commit_msg>fix policy-list2 error<commit_after># 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 mock
import six
from webob import exc

from oslo_serialization import jsonutils
from oslo_utils import uuidutils

from senlin.api.middleware import fault
from senlin.api.openstack.v1 import policies
from senlin.common import exception as senlin_exc
from senlin.common.i18n import _
from senlin.common import policy
from senlin.objects.requests import policies as vorp
from senlin.rpc import client as rpc_client
from senlin.tests.unit.api import shared
from senlin.tests.unit.common import base


@mock.patch.object(policy, 'enforce')
class PolicyControllerTest(shared.ControllerTest, base.SenlinTestCase):
    def setUp(self):
        super(PolicyControllerTest, self).setUp()

        class DummyConfig(object):
            bind_port = 8778

        cfgopts = DummyConfig()
        self.controller = policies.PolicyController(options=cfgopts)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_normal(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        req = self._get('/policies')

        engine_resp = [
            {
                u'id': u'aaaa-bbbb-cccc',
                u'name': u'policy-1',
                u'type': u'test_policy_type',
                u'spec': {
                    u'param_1': u'value1',
                    u'param_2': u'value2',
                },
                u'created_time': u'2015-02-24T19:17:22Z',
                u'updated_time': None,
            }
        ]

        mock_call.return_value = engine_resp

        result = self.controller.index(req)

        expected = {u'policies': engine_resp}
        self.assertEqual(expected, result)

        mock_call.assert_called_with(req.context, 'policy_list2',
                                     mock.ANY)

        request = mock_call.call_args[0][2]
        self.assertIsInstance(request, vorp.PolicyListRequest)
        self.assertTrue(request.project_safe)
        self.assertFalse(request.obj_attr_is_set('name'))
        self.assertFalse(request.obj_attr_is_set('type'))
        self.assertFalse(request.obj_attr_is_set('limit'))
        self.assertFalse(request.obj_attr_is_set('marker'))
        self.assertFalse(request.obj_attr_is_set('sort'))

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_whitelists_params(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        fake_id = uuidutils.generate_uuid()
        params = {
            'name': 'FAKE',
            'type': 'TYPE',
            'limit': 20,
            'marker': fake_id,
            'sort': 'name:asc',
            'global_project': True,
        }
        req = self._get('/policies', params=params)

        engine_resp = [{'foo': 'bar'}]
        mock_call.return_value = engine_resp

        result = self.controller.index(req)

        expected = {u'policies': engine_resp}
        self.assertEqual(expected, result)

        mock_call.assert_called_once_with(req.context, 'policy_list2',
                                          mock.ANY)
        request = mock_call.call_args[0][2]
        self.assertIsInstance(request, vorp.PolicyListRequest)
        self.assertFalse(request.project_safe)
        self.assertEqual(['FAKE'], request.name)
        self.assertEqual(['TYPE'], request.type)
        self.assertEqual(20, request.limit)
        self.assertEqual(fake_id, request.marker)
        self.assertEqual('name:asc', request.sort)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_whitelist_bad_params(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        params = {
            'balrog': 'fake_value'
        }
        req = self._get('/policies', params=params)

        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.index,
                               req)

        self.assertEqual("Invalid parameter balrog", six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_gloable_project_invalid(self, mock_call,
                                                  mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)
        params = {
            'global_project': 'No',
        }
        req = self._get('/policies', params=params)

        ex = self.assertRaises(senlin_exc.InvalidParameter,
                               self.controller.index,
                               req)

        self.assertEqual("Invalid value 'No' specified for 'global_project'",
                         six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    @mock.patch.object(rpc_client.EngineClient, 'call2')
    def test_policy_index_limit_non_int(self, mock_call, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', True)

        params = {'limit': 'abc'}
        req = self._get('/policies', params=params)
        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.controller.index,
                               req)

        self.assertIn("invalid literal for int() with base 10: 'abc'",
                      six.text_type(ex))
        self.assertEqual(0, mock_call.call_count)

    def test_policy_index_denied_policy(self, mock_enforce):
        self._mock_enforce_setup(mock_enforce, 'index', False)
{'fraction_non_alphanumeric': 0.10228957338165047, 'fraction_numerical': 0.008318234228298468, 'mean_word_length': 2.4128724002248454, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2554185', 'n_tokens_mistral': 3539, 'n_tokens_neox': 3448, 'n_words': 698}