<commit_before># Copyright 2012 OpenStack Foundation
#
# 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 gettext
import socket
import uuid

from babel import localedata
import mock
from oslotest import mockpatch
from testtools import matchers
import webob

from keystone.common import environment
from keystone.common import wsgi
from keystone import exception
from keystone.openstack.common import gettextutils
from keystone.openstack.common.gettextutils import _
from keystone.openstack.common import jsonutils
from keystone import tests


class FakeApp(wsgi.Application):
    def index(self, context):
        return {'a': 'b'}


class FakeAttributeCheckerApp(wsgi.Application):
    def index(self, context):
        return context['query_string']

    def has_attribute(self, body, attr):
        body_dict = jsonutils.loads(body)
        try:
            self._require_attribute(body_dict, attr)
            return True
        except exception.ValidationError as ex:
            return (False, ex.message)

    def has_attributes(self, body, attr):
        body_dict = jsonutils.loads(body)
        try:
            self._require_attributes(body_dict, attr)
            return True
        except exception.ValidationError as ex:
            return (False, ex.message)


class BaseWSGITest(tests.TestCase):
    def setUp(self):
        self.app = FakeApp()
        super(BaseWSGITest, self).setUp()

    def _make_request(self, url='/'):
        req = webob.Request.blank(url)
        args = {'action': 'index', 'controller': None}
        req.environ['wsgiorg.routing_args'] = [None, args]
        return req


class ApplicationTest(BaseWSGITest):
    def test_response_content_type(self):
        req = self._make_request()
        resp = req.get_response(self.app)
        self.assertEqual(resp.content_type, 'application/json')

    def test_query_string_available(self):
        class FakeApp(wsgi.Application):
            def index(self, context):
                return context['query_string']
        req = self._make_request(url='/?1=2')
        resp = req.get_response(FakeApp())
        self.assertEqual(jsonutils.loads(resp.body), {'1': '2'})

    def test_headers_available(self):
        class FakeApp(wsgi.Application):
            def index(self, context):
                return context['headers']

        app = FakeApp()
        req = self._make_request(url='/?1=2')
        req.headers['X-Foo'] = "bar"
        resp = req.get_response(app)
        self.assertIn('X-Foo', eval(resp.body))

    def test_render_response(self):
        data = {'attribute': 'value'}
        body = '{"attribute": "value"}'

        resp = wsgi.render_response(body=data)
        self.assertEqual(resp.status, '200 OK')
        self.assertEqual(resp.status_int, 200)
        self.assertEqual(resp.body, body)
        self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')
        self.assertEqual(resp.headers.get('Content-Length'), str(len(body)))

    def test_render_response_custom_status(self):
        resp = wsgi.render_response(status=(501, 'Not Implemented'))
        self.assertEqual(resp.status, '501 Not Implemented')
        self.assertEqual(resp.status_int, 501)

    def test_successful_require_attribute(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?1=2')
        resp = req.get_response(app)
        self.assertTrue(app.has_attribute(resp.body, '1'))

    def test_require_attribute(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?1=2')
        resp = req.get_response(app)
        self.assertFalse(app.has_attribute(resp.body, 'a')[0])

    def test_successful_require_multiple_attributes(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?a=1&b=2')
        resp = req.get_response(app)
        self.assertTrue(app.has_attributes(resp.body, ['a', 'b']))

    def test_attribute_missing_from_request(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?a=1&b=2')
        resp = req.get_response(app)
        validation = app.has_attributes(resp.body, ['a',
                                        'missing_attribute'])
        self.assertFalse(validation[0])
        self.assertIn('missing_attribute', validation[1])

    def test_no_required_attributes_present(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/')
        resp = req.get_response(app)
        validation = app.has_attributes(resp.body, ['missing_attribute1',
                                        'missing_attribute2'])
        self.assertFalse(validation[0])
        self.assertIn('missing_attribute1', validation[1])
        self.assertIn('missing_attribute2', validation[1])

    def test_render_response_custom_headers(self):
        resp = wsgi.render_response(headers=[('Custom-Header', 'Some-Value')])
        self.assertEqual(resp.headers.get('Custom-Header'), 'Some-Value')
        self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')

    def test_render_response_no_body(self):
        resp = wsgi.render_response()
        self.assertEqual(resp.status, '204 No Content')
        self.assertEqual(resp.status_int, 204)
        self.assertEqual(resp.body, '')
        self.assertEqual(resp.headers.get('Content-Length'), '0')
        self.assertIsNone(resp.headers.get('Content-Type'))

    def test_application_local_config(self):<commit_msg>Refactor tests regarding required attributes<commit_after># Copyright 2012 OpenStack Foundation
#
# 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 gettext
import socket
import uuid

from babel import localedata
import mock
from oslotest import mockpatch
from testtools import matchers
import webob

from keystone.common import environment
from keystone.common import wsgi
from keystone import exception
from keystone.openstack.common import gettextutils
from keystone.openstack.common.gettextutils import _
from keystone.openstack.common import jsonutils
from keystone import tests


class FakeApp(wsgi.Application):
    def index(self, context):
        return {'a': 'b'}


class FakeAttributeCheckerApp(wsgi.Application):
    def index(self, context):
        return context['query_string']

    def assert_attribute(self, body, attr):
        """Asserts that the given request has a certain attribute."""
        ref = jsonutils.loads(body)
        self._require_attribute(ref, attr)

    def assert_attributes(self, body, attr):
        """Asserts that the given request has a certain set attributes."""
        ref = jsonutils.loads(body)
        self._require_attributes(ref, attr)


class BaseWSGITest(tests.TestCase):
    def setUp(self):
        self.app = FakeApp()
        super(BaseWSGITest, self).setUp()

    def _make_request(self, url='/'):
        req = webob.Request.blank(url)
        args = {'action': 'index', 'controller': None}
        req.environ['wsgiorg.routing_args'] = [None, args]
        return req


class ApplicationTest(BaseWSGITest):
    def test_response_content_type(self):
        req = self._make_request()
        resp = req.get_response(self.app)
        self.assertEqual(resp.content_type, 'application/json')

    def test_query_string_available(self):
        class FakeApp(wsgi.Application):
            def index(self, context):
                return context['query_string']
        req = self._make_request(url='/?1=2')
        resp = req.get_response(FakeApp())
        self.assertEqual(jsonutils.loads(resp.body), {'1': '2'})

    def test_headers_available(self):
        class FakeApp(wsgi.Application):
            def index(self, context):
                return context['headers']

        app = FakeApp()
        req = self._make_request(url='/?1=2')
        req.headers['X-Foo'] = "bar"
        resp = req.get_response(app)
        self.assertIn('X-Foo', eval(resp.body))

    def test_render_response(self):
        data = {'attribute': 'value'}
        body = '{"attribute": "value"}'

        resp = wsgi.render_response(body=data)
        self.assertEqual(resp.status, '200 OK')
        self.assertEqual(resp.status_int, 200)
        self.assertEqual(resp.body, body)
        self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')
        self.assertEqual(resp.headers.get('Content-Length'), str(len(body)))

    def test_render_response_custom_status(self):
        resp = wsgi.render_response(status=(501, 'Not Implemented'))
        self.assertEqual(resp.status, '501 Not Implemented')
        self.assertEqual(resp.status_int, 501)

    def test_successful_require_attribute(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?1=2')
        resp = req.get_response(app)
        app.assert_attribute(resp.body, '1')

    def test_require_attribute_fail_if_attribute_not_present(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?1=2')
        resp = req.get_response(app)
        self.assertRaises(exception.ValidationError,
                          app.assert_attribute, resp.body, 'a')

    def test_successful_require_multiple_attributes(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?a=1&b=2')
        resp = req.get_response(app)
        app.assert_attributes(resp.body, ['a', 'b'])

    def test_attribute_missing_from_request(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/?a=1&b=2')
        resp = req.get_response(app)
        ex = self.assertRaises(exception.ValidationError,
                               app.assert_attributes,
                               resp.body, ['a', 'missing_attribute'])
        self.assertThat(ex.message, matchers.Contains('missing_attribute'))

    def test_no_required_attributes_present(self):
        app = FakeAttributeCheckerApp()
        req = self._make_request(url='/')
        resp = req.get_response(app)

        ex = self.assertRaises(exception.ValidationError,
                               app.assert_attributes, resp.body,
                               ['missing_attribute1', 'missing_attribute2'])
        self.assertThat(ex.message, matchers.Contains('missing_attribute1'))
        self.assertThat(ex.message, matchers.Contains('missing_attribute2'))

    def test_render_response_custom_headers(self):
        resp = wsgi.render_response(headers=[('Custom-Header', 'Some-Value')])
        self.assertEqual(resp.headers.get('Custom-Header'), 'Some-Value')
        self.assertEqual(resp.headers.get('Vary'), 'X-Auth-Token')

    def test_render_response_no_body(self):
        resp = wsgi.render_response()
        self.assertEqual(resp.status, '204 No Content')
        self.assertEqual(resp.status_int, 204)
        self.assertEqual(resp.body, '')
        self.assertEqual(resp.headers.get('Content-Length'), '0')
        self.assertIsNone(resp.headers.get('Content-Type'))

    def test_application_local_config(self):
{'fraction_non_alphanumeric': 0.11408721854858961, 'fraction_numerical': 0.008705114254624592, 'mean_word_length': 3.103021978021978, 'pattern_counts': {'":': 2, '<': 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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6583555', 'n_tokens_mistral': 3509, 'n_tokens_neox': 3399, 'n_words': 750}