<commit_before># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

from __future__ import with_statement

import os
import sys
import unittest
import datetime

try:
    import simplejson as json
except ImportError:
    import json

from mock import Mock

from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import method_type
from libcloud.utils.py3 import u

from libcloud.common.types import InvalidCredsError, MalformedResponseError, \
    LibcloudError
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.common.openstack import OpenStackAuthConnection
from libcloud.common.openstack import AUTH_TOKEN_EXPIRES_GRACE_SECONDS
from libcloud.compute.types import Provider, KeyPairDoesNotExistError
from libcloud.compute.providers import get_driver
from libcloud.compute.drivers.openstack import (
    OpenStack_1_0_NodeDriver, OpenStack_1_0_Response,
    OpenStack_1_1_NodeDriver, OpenStackSecurityGroup,
    OpenStackSecurityGroupRule, OpenStack_1_1_FloatingIpPool,
    OpenStack_1_1_FloatingIpAddress, OpenStackKeyPair
)
from libcloud.compute.base import Node, NodeImage, NodeSize
from libcloud.pricing import set_pricing, clear_pricing_data

from libcloud.test import MockResponse, MockHttpTestCase, XML_HEADERS
from libcloud.test.file_fixtures import ComputeFileFixtures, OpenStackFixtures
from libcloud.test.compute import TestCaseMixin

from libcloud.test.secrets import OPENSTACK_PARAMS

BASE_DIR = os.path.abspath(os.path.split(__file__)[0])


class OpenStack_1_0_ResponseTestCase(unittest.TestCase):
    XML = """<?xml version="1.0" encoding="UTF-8"?><root/>"""

    def test_simple_xml_content_type_handling(self):
        http_response = MockResponse(
            200, OpenStack_1_0_ResponseTestCase.XML, headers={'content-type': 'application/xml'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML")

    def test_extended_xml_content_type_handling(self):
        http_response = MockResponse(200,
                                     OpenStack_1_0_ResponseTestCase.XML,
                                     headers={'content-type': 'application/xml; charset=UTF-8'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML")

    def test_non_xml_content_type_handling(self):
        RESPONSE_BODY = "Accepted"

        http_response = MockResponse(
            202, RESPONSE_BODY, headers={'content-type': 'text/html'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertEqual(
            body, RESPONSE_BODY, "Non-XML body should be returned as is")


class OpenStackServiceCatalogTests(unittest.TestCase):
    # TODO refactor and move into libcloud/test/common

    def setUp(self):
        OpenStackBaseConnection.conn_classes = (OpenStackMockHttp,
                                                OpenStackMockHttp)

        connection = OpenStackBaseConnection(*OPENSTACK_PARAMS)
        connection.auth_url = "https://auth.api.example.com"
        connection._ex_force_base_url = "https://www.foo.com"
        connection.driver = OpenStack_1_0_NodeDriver(*OPENSTACK_PARAMS)

        self.service_catalog = connection.get_service_catalog()
        self.catalog = self.service_catalog.get_catalog()

    def test_connection_get_service_catalog(self):
        endpoints = self.service_catalog.get_endpoints('cloudFilesCDN', 'cloudFilesCDN')
        public_urls = self.service_catalog.get_public_urls('cloudFilesCDN', 'cloudFilesCDN')

        expected_urls = [
            'https://cdn2.clouddrive.com/v1/MossoCloudFS',
            'https://cdn2.clouddrive.com/v1/MossoCloudFS'
        ]

        self.assertTrue('cloudFilesCDN' in self.catalog)
        self.assertEqual(len(endpoints), 2)
        self.assertEqual(public_urls, expected_urls)

    def test_get_regions(self):
        regions = self.service_catalog.get_regions()
        self.assertEqual(regions, ['ORD', 'LON'])

    def test_get_service_names(self):
        OpenStackBaseConnection.conn_classes = (OpenStack_2_0_MockHttp,
                                                OpenStack_2_0_MockHttp)
        OpenStackBaseConnection._auth_version = '2.0'

        connection = OpenStackBaseConnection(*OPENSTACK_PARAMS)
        connection.auth_url = "https://auth.api.example.com"
        connection._ex_force_base_url = "https://www.foo.com"
        connection.driver = OpenStack_1_0_NodeDriver(*OPENSTACK_PARAMS)
<commit_msg>Sort the regions for a consistent result.<commit_after># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

from __future__ import with_statement

import os
import sys
import unittest
import datetime

try:
    import simplejson as json
except ImportError:
    import json

from mock import Mock

from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import method_type
from libcloud.utils.py3 import u

from libcloud.common.types import InvalidCredsError, MalformedResponseError, \
    LibcloudError
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.common.openstack import OpenStackAuthConnection
from libcloud.common.openstack import AUTH_TOKEN_EXPIRES_GRACE_SECONDS
from libcloud.compute.types import Provider, KeyPairDoesNotExistError
from libcloud.compute.providers import get_driver
from libcloud.compute.drivers.openstack import (
    OpenStack_1_0_NodeDriver, OpenStack_1_0_Response,
    OpenStack_1_1_NodeDriver, OpenStackSecurityGroup,
    OpenStackSecurityGroupRule, OpenStack_1_1_FloatingIpPool,
    OpenStack_1_1_FloatingIpAddress, OpenStackKeyPair
)
from libcloud.compute.base import Node, NodeImage, NodeSize
from libcloud.pricing import set_pricing, clear_pricing_data

from libcloud.test import MockResponse, MockHttpTestCase, XML_HEADERS
from libcloud.test.file_fixtures import ComputeFileFixtures, OpenStackFixtures
from libcloud.test.compute import TestCaseMixin

from libcloud.test.secrets import OPENSTACK_PARAMS

BASE_DIR = os.path.abspath(os.path.split(__file__)[0])


class OpenStack_1_0_ResponseTestCase(unittest.TestCase):
    XML = """<?xml version="1.0" encoding="UTF-8"?><root/>"""

    def test_simple_xml_content_type_handling(self):
        http_response = MockResponse(
            200, OpenStack_1_0_ResponseTestCase.XML, headers={'content-type': 'application/xml'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML")

    def test_extended_xml_content_type_handling(self):
        http_response = MockResponse(200,
                                     OpenStack_1_0_ResponseTestCase.XML,
                                     headers={'content-type': 'application/xml; charset=UTF-8'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertTrue(hasattr(body, 'tag'), "Body should be parsed as XML")

    def test_non_xml_content_type_handling(self):
        RESPONSE_BODY = "Accepted"

        http_response = MockResponse(
            202, RESPONSE_BODY, headers={'content-type': 'text/html'})
        body = OpenStack_1_0_Response(http_response, None).parse_body()

        self.assertEqual(
            body, RESPONSE_BODY, "Non-XML body should be returned as is")


class OpenStackServiceCatalogTests(unittest.TestCase):
    # TODO refactor and move into libcloud/test/common

    def setUp(self):
        OpenStackBaseConnection.conn_classes = (OpenStackMockHttp,
                                                OpenStackMockHttp)

        connection = OpenStackBaseConnection(*OPENSTACK_PARAMS)
        connection.auth_url = "https://auth.api.example.com"
        connection._ex_force_base_url = "https://www.foo.com"
        connection.driver = OpenStack_1_0_NodeDriver(*OPENSTACK_PARAMS)

        self.service_catalog = connection.get_service_catalog()
        self.catalog = self.service_catalog.get_catalog()

    def test_connection_get_service_catalog(self):
        endpoints = self.service_catalog.get_endpoints('cloudFilesCDN', 'cloudFilesCDN')
        public_urls = self.service_catalog.get_public_urls('cloudFilesCDN', 'cloudFilesCDN')

        expected_urls = [
            'https://cdn2.clouddrive.com/v1/MossoCloudFS',
            'https://cdn2.clouddrive.com/v1/MossoCloudFS'
        ]

        self.assertTrue('cloudFilesCDN' in self.catalog)
        self.assertEqual(len(endpoints), 2)
        self.assertEqual(public_urls, expected_urls)

    def test_get_regions(self):
        regions = self.service_catalog.get_regions()
        self.assertEqual(sorted(regions), ['LON', 'ORD'])

    def test_get_service_names(self):
        OpenStackBaseConnection.conn_classes = (OpenStack_2_0_MockHttp,
                                                OpenStack_2_0_MockHttp)
        OpenStackBaseConnection._auth_version = '2.0'

        connection = OpenStackBaseConnection(*OPENSTACK_PARAMS)
        connection.auth_url = "https://auth.api.example.com"
        connection._ex_force_base_url = "https://www.foo.com"
        connection.driver = OpenStack_1_0_NodeDriver(*OPENSTACK_PARAMS)

{'fraction_non_alphanumeric': 0.07957534761367907, 'fraction_numerical': 0.010898158586997369, 'mean_word_length': 3.773542600896861, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 2, '>': 7, 'https://': 12, 'lorem ipsum': 0, 'www.': 6, 'xml': 12}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1871872', 'n_tokens_mistral': 3092, 'n_tokens_neox': 3025, 'n_words': 710}