# 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
from libcloud.utils.iso8601 import UTC

try:
    import simplejson as json
except ImportError:
    import json

from mock import Mock, patch

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.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 OpenStack_1_0_Tests(unittest.TestCase, TestCaseMixin):
    should_list_locations = False
    should_list_volumes = False

    driver_klass = OpenStack_1_0_NodeDriver
    driver_args = OPENSTACK_PARAMS
    driver_kwargs = {}
    # driver_kwargs = {'ex_force_auth_version': '1.0'}

    @classmethod
    def create_driver(self):
        if self is not OpenStack_1_0_FactoryMethodTests:
            self.driver_type = self.driver_klass
        return self.driver_type(*self.driver_args, **self.driver_kwargs)

    def setUp(self):
        # monkeypatch get_endpoint because the base openstack driver doesn't actually
        # work with old devstack but this class/tests are still used by the rackspace
        # driver
        def get_endpoint(*args, **kwargs):
            return "https://servers.api.rackspacecloud.com/v1.0/slug"
        self.driver_klass.connectionCls.get_endpoint = get_endpoint

        self.driver_klass.connectionCls.conn_classes = (OpenStackMockHttp,
                                                        OpenStackMockHttp)
        self.driver_klass.connectionCls.auth_url = "https://auth.api.example.com"

        OpenStackMockHttp.type = None

        self.driver = self.create_driver()
        # normally authentication happens lazily, but we force it here
        self.driver.connection._populate_hosts_and_request_paths()
        clear_pricing_data()

    @patch('libcloud.common.openstack.OpenStackServiceCatalog')
    def test_populate_hosts_and_requests_path(self, _):
        tomorrow = datetime.datetime.today() + datetime.timedelta(1)
        cls = self.driver_klass.connectionCls

        count = 5

        # Test authentication and token re-use
        con = cls('username', 'key')
        osa = con.get_auth_class()

        mocked_auth_method = Mock()
        osa.authenticate = mocked_auth_method

        # Valid token returned on first call, should be reused.
        for i in range(0, count):
            con._populate_hosts_and_request_paths()

            if i == 0:
                osa.auth_token = '1234'
                osa.auth_token_expires = tomorrow

        self.assertEqual(mocked_auth_method.call_count, 1)

        osa.auth_token = None
        osa.auth_token_expires = None

        # ex_force_auth_token provided, authenticate should never be called
        con = cls('username', 'key', ex_force_base_url='http://ponies',
                  ex_force_auth_token='1234')
        osa = con.get_auth_class()

        mocked_auth_method = Mock()
        osa.authenticate = mocked_auth_method

        for i in range(0, count):
            con._populate_hosts_and_request_paths()

        self.assertEqual(mocked_auth_method.call_count, 0)

    def test_auth_token_is_set(self):
        self.driver.connection._populate_hosts_and_request_paths()
        self.assertEqual(
            self.driver.connection.auth_token, "aaaaaaaaaaaa-bbb-cccccccccccccc")

    def test_auth_token_expires_is_set(self):
        self.driver.connection._populate_hosts_and_request_paths()

        expires = self.driver.connection.auth_token_expires
        self.assertEqual(expires.isoformat(), "2031-11-23T21:00:14-06:00")

    def test_auth(self):
        if self.driver.connection._auth_version == '2.0':
            return

        OpenStackMockHttp.type = 'UNAUTHORIZED'
        try:
            self.driver = self.create_driver()
            self.driver.list_nodes()
        except InvalidCredsError:
            e = sys.exc_info()[1]
            self.assertEqual(True, isinstance(e, InvalidCredsError))
        else:
            self.fail('test should have thrown')

    def test_auth_missing_key(self):
        if self.driver.connection._auth_version == '2.0':
            return

        OpenStackMockHttp.type = 'UNAUTHORIZED_MISSING_KEY'
        try:
            self.driver = self.create_driver()
            self.driver.list_nodes()
        except MalformedResponseError:
            e = sys.exc_info()[1]
            self.assertEqual(True, isinstance(e, MalformedResponseError))
        else:
            self.fail('test should have thrown')

    def test_auth_server_error(self):
        if self.driver.connection._auth_version == '2.0':
            return

        OpenStackMockHttp.type = 'INTERNAL_SERVER_ERROR'
        try:
            self.driver = self.create_driver()
            self.driver.list_nodes()
        except MalformedResponseError:
            e = sys.exc_info()[1]
            self.assertEqual(True, isinstance(e, MalformedResponseError))
        else:
            self.fail('test should have thrown')

    def test_error_parsing_when_body_is_missing_message(self):
        OpenStackMockHttp.type = 'NO_MESSAGE_IN_ERROR_BODY'
        try:
            self.driver.list_images()
        except Exception:
            e = sys.exc_info()[1]
            self.assertEqual(True, isinstance(e, Exception))
        else:
            self.fail('test should have thrown')

    def test_list_locations(self):
        locations = self.driver.list_locations()
        self.assertEqual(len(locations), 1)

    def test_list_nodes(self):
        OpenStackMockHttp.type = 'EMPTY'
        ret = self.driver.list_nodes()
        self.assertEqual(len(ret), 0)
        OpenStackMockHttp.type = None
        ret = self.driver.list_nodes()
        self.assertEqual(len(ret), 1)
        node = ret[0]
        self.assertEqual('67.23.21.33', node.public_ips[0])
        self.assertTrue('10.176.168.218' in node.private_ips)
        self.assertEqual(node.extra.get('flavorId'), '1')
        self.assertEqual(node.extra.get('imageId'), '11')
        self.assertEqual(type(node.extra.get('metadata')), type(dict()))
        OpenStackMockHttp.type = 'METADATA'
        ret = self.driver.list_nodes()
        self.assertEqual(len(ret), 1)
        node = ret[0]
        self.assertEqual(type(node.extra.get('metadata')), type(dict()))
        self.assertEqual(node.extra.get('metadata').get('somekey'),
                         'somevalue')
        OpenStackMockHttp.type = None

    def test_list_images(self):
        ret = self.driver.list_images()
        expected = {10: {'serverId': None,
                         'status': 'ACTIVE',
                         'created': '2009-07-20T09:14:37-05:00',
                         'updated': '2009-07-20T09:14:37-05:00',
                         'progress': None,
                         'minDisk': None,
                         'minRam': None},
                    11: {'serverId': '91221',
                         'status': 'ACTIVE',
                         'created': '2009-11-29T20:22:09-06:00',
                         'updated': '2009-11-29T20:24:08-06:00',
                         'progress': '100',
                         'minDisk': '5',
                         'minRam': '256'}}
        for ret_idx, extra in list(expected.items()):
            for key, value in list(extra.items()):
                self.assertEqual(ret[ret_idx].extra[key], value)

    def test_create_node(self):
        image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)',
                          driver=self.driver)
        size = NodeSize(1, '256 slice', None, None, None, None,
                        driver=self.driver)
        node = self.driver.create_node(name='racktest', image=image, size=size)
        self.assertEqual(node.name, 'racktest')
        self.assertEqual(node.extra.get('password'), 'racktestvJq7d3')

    def test_create_node_without_adminPass(self):
        OpenStackMockHttp.type = 'NO_ADMIN_PASS'
        image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)',
                          driver=self.driver)
        size = NodeSize(1, '256 slice', None, None, None, None,
                        driver=self.driver)
        node = self.driver.create_node(name='racktest', image=image, size=size)
        self.assertEqual(node.name, 'racktest')
        self.assertEqual(node.extra.get('password'), None)

    def test_create_node_ex_shared_ip_group(self):
        OpenStackMockHttp.type = 'EX_SHARED_IP_GROUP'
        image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)',
                          driver=self.driver)
        size = NodeSize(1, '256 slice', None, None, None, None,
                        driver=self.driver)
        node = self.driver.create_node(name='racktest', image=image, size=size,
                                       ex_shared_ip_group_id='12345')
        self.assertEqual(node.name, 'racktest')
        self.assertEqual(node.extra.get('password'), 'racktestvJq7d3')

    def test_create_node_with_metadata(self):
        OpenStackMockHttp.type = 'METADATA'
        image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)',
                          driver=self.driver)
        size = NodeSize(1, '256 slice', None, None, None, None,
                        driver=self.driver)
        metadata = {'a': 'b', 'c': 'd'}
        files = {'/file1': 'content1', '/file2': 'content2'}
        node = self.driver.create_node(name='racktest', image=image, size=size,
                                       metadata=metadata, files=files)
        self.assertEqual(node.name, 'racktest')
        self.assertEqual(node.extra.get('password'), 'racktestvJq7d3')
        self.assertEqual(node.extra.get('metadata'), metadata)

    def test_reboot_node(self):
        node = Node(id=72258, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        ret = node.reboot()
        self.assertTrue(ret is True)

    def test_destroy_node(self):
        node = Node(id=72258, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        ret = node.destroy()
        self.assertTrue(ret is True)

    def test_ex_limits(self):
        limits = self.driver.ex_limits()
        self.assertTrue("rate" in limits)
        self.assertTrue("absolute" in limits)

    def test_create_image(self):
        node = Node(id=444222, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        image = self.driver.create_image(node, "imgtest")
        self.assertEqual(image.name, "imgtest")
        self.assertEqual(image.id, "12345")

    def test_delete_image(self):
        image = NodeImage(id=333111, name='Ubuntu 8.10 (intrepid)',
                          driver=self.driver)
        ret = self.driver.delete_image(image)
        self.assertTrue(ret)

    def test_ex_list_ip_addresses(self):
        ret = self.driver.ex_list_ip_addresses(node_id=72258)
        self.assertEqual(2, len(ret.public_addresses))
        self.assertTrue('67.23.10.131' in ret.public_addresses)
        self.assertTrue('67.23.10.132' in ret.public_addresses)
        self.assertEqual(1, len(ret.private_addresses))
        self.assertTrue('10.176.42.16' in ret.private_addresses)

    def test_ex_list_ip_groups(self):
        ret = self.driver.ex_list_ip_groups()
        self.assertEqual(2, len(ret))
        self.assertEqual('1234', ret[0].id)
        self.assertEqual('Shared IP Group 1', ret[0].name)
        self.assertEqual('5678', ret[1].id)
        self.assertEqual('Shared IP Group 2', ret[1].name)
        self.assertTrue(ret[0].servers is None)

    def test_ex_list_ip_groups_detail(self):
        ret = self.driver.ex_list_ip_groups(details=True)

        self.assertEqual(2, len(ret))

        self.assertEqual('1234', ret[0].id)
        self.assertEqual('Shared IP Group 1', ret[0].name)
        self.assertEqual(2, len(ret[0].servers))
        self.assertEqual('422', ret[0].servers[0])
        self.assertEqual('3445', ret[0].servers[1])

        self.assertEqual('5678', ret[1].id)
        self.assertEqual('Shared IP Group 2', ret[1].name)
        self.assertEqual(3, len(ret[1].servers))
        self.assertEqual('23203', ret[1].servers[0])
        self.assertEqual('2456', ret[1].servers[1])
        self.assertEqual('9891', ret[1].servers[2])

    def test_ex_create_ip_group(self):
        ret = self.driver.ex_create_ip_group('Shared IP Group 1', '5467')
        self.assertEqual('1234', ret.id)
        self.assertEqual('Shared IP Group 1', ret.name)
        self.assertEqual(1, len(ret.servers))
        self.assertEqual('422', ret.servers[0])

    def test_ex_delete_ip_group(self):
        ret = self.driver.ex_delete_ip_group('5467')
        self.assertEqual(True, ret)

    def test_ex_share_ip(self):
        ret = self.driver.ex_share_ip('1234', '3445', '67.23.21.133')
        self.assertEqual(True, ret)

    def test_ex_unshare_ip(self):
        ret = self.driver.ex_unshare_ip('3445', '67.23.21.133')
        self.assertEqual(True, ret)

    def test_ex_resize(self):
        node = Node(id=444222, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        size = NodeSize(1, '256 slice', None, None, None, None,
                        driver=self.driver)
        self.assertTrue(self.driver.ex_resize(node=node, size=size))

    def test_ex_confirm_resize(self):
        node = Node(id=444222, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        self.assertTrue(self.driver.ex_confirm_resize(node=node))

    def test_ex_revert_resize(self):
        node = Node(id=444222, name=None, state=None, public_ips=None,
                    private_ips=None, driver=self.driver)
        self.assertTrue(self.driver.ex_revert_resize(node=node))

    def test_list_sizes(self):
        sizes = self.driver.list_sizes()
        self.assertEqual(len(sizes), 7, 'Wrong sizes count')

        for size in sizes:
            self.assertTrue(isinstance(size.price, float),
                            'Wrong size price type')

            if self.driver.api_name == 'openstack':
                self.assertEqual(size.price, 0,
                                 'Size price should be zero by default')

    def test_list_sizes_with_specified_pricing(self):
        if self.driver.api_name != 'openstack':
            return

        pricing = dict((str(i), i) for i in range(1, 8))

        set_pricing(driver_type='compute', driver_name='openstack',
                    pricing=pricing)

        sizes = self.driver.list_sizes()
        self.assertEqual(len(sizes), 7, 'Wrong sizes count')

        for size in sizes:
            self.assertTrue(isinstance(size.price, float),
                            'Wrong size price type')
            self.assertEqual(float(size.price), float(pricing[size.id]))


class OpenStack_1_0_FactoryMethodTests(OpenStack_1_0_Tests):
    should_list_locations = False
    should_list_volumes = False

    driver_klass = OpenStack_1_0_NodeDriver
    driver_type = get_driver(Provider.OPENSTACK)
    driver_args = OPENSTACK_PARAMS + ('1.0',)

    def test_factory_method_invalid_version(self):
        try:
            self.driver_type(*(OPENSTACK_PARAMS + ('15.5',)))
        except NotImplementedError:
            pass
        else:
            self.fail('Exception was not thrown')


class OpenStackMockHttp(MockHttpTestCase):
    fixtures = ComputeFileFixtures('openstack')
    auth_fixtures = OpenStackFixtures()
    json_content_headers = {'content-type': 'application/json; charset=UTF-8'}

    # fake auth token response
    def _v1_0(self, method, url, body, headers):
        headers = {
            'x-server-management-url': 'https://servers.api.rackspacecloud.com/v1.0/slug',
            'x-auth-token': 'FE011C19-CF86-4F87-BE5D-9229145D7A06',
            'x-cdn-management-url': 'https://cdn.clouddrive.com/v1/MossoCloudFS_FE011C19-CF86-4F87-BE5D-9229145D7A06',
            'x-storage-token': 'FE011C19-CF86-4F87-BE5D-9229145D7A06',
            'x-storage-url': 'https://storage4.clouddrive.com/v1/MossoCloudFS_FE011C19-CF86-4F87-BE5D-9229145D7A06'}
        return (httplib.NO_CONTENT, "", headers, httplib.responses[httplib.NO_CONTENT])

    def _v1_0_UNAUTHORIZED(self, method, url, body, headers):
        return (httplib.UNAUTHORIZED, "", {}, httplib.responses[httplib.UNAUTHORIZED])

    def _v1_0_INTERNAL_SERVER_ERROR(self, method, url, body, headers):
        return (httplib.INTERNAL_SERVER_ERROR, "<h1>500: Internal Server Error</h1>", {},
                httplib.responses[httplib.INTERNAL_SERVER_ERROR])

    def _v1_0_slug_images_detail_NO_MESSAGE_IN_ERROR_BODY(self, method, url, body, headers):
        body = self.fixtures.load('300_multiple_choices.json')
        return (httplib.MULTIPLE_CHOICES, body, self.json_content_headers, httplib.responses[httplib.OK])

    def _v1_0_UNAUTHORIZED_MISSING_KEY(self, method, url, body, headers):
        headers = {
            'x-server-management-url': 'https://servers.api.rackspacecloud.com/v1.0/slug',
            'x-auth-tokenx': 'FE011C19-CF86-4F87-BE5D-9229145D7A06',
            'x-cdn-management-url': 'https://cdn.clouddrive.com/v1/MossoCloudFS_FE011C19-CF86-4F87-BE5D-9229145D7A06'}
        return (httplib.NO_CONTENT, "", headers, httplib.responses[httplib.NO_CONTENT])

    def _v2_0_tokens(self, method, url, body, headers):
        body = self.auth_fixtures.load('_v2_0__auth.json')
        return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK])

    def _v1_0_slug_servers_detail_EMPTY(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_detail_empty.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_servers_detail(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_detail.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_servers_detail_METADATA(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_detail_metadata.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_images_333111(self, method, url, body, headers):
        if method != "DELETE":
            raise NotImplementedError()
        # this is currently used for deletion of an image
        # as such it should not accept GET/POST
        return(httplib.NO_CONTENT, "", "", httplib.responses[httplib.NO_CONTENT])

    def _v1_0_slug_images(self, method, url, body, headers):
        if method != "POST":
            raise NotImplementedError()
        # this is currently used for creation of new image with
        # POST request, don't handle GET to avoid possible confusion
        body = self.fixtures.load('v1_slug_images_post.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_images_detail(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_images_detail.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_servers(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_NO_ADMIN_PASS(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_no_admin_pass.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_EX_SHARED_IP_GROUP(self, method, url, body, headers):
        # test_create_node_ex_shared_ip_group
        # Verify that the body contains sharedIpGroupId XML element
        body = u(body)
        self.assertTrue(body.find('sharedIpGroupId="12345"') != -1)
        body = self.fixtures.load('v1_slug_servers.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_METADATA(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_metadata.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_72258_action(self, method, url, body, headers):
        if method != "POST" or body[:8] != "<reboot ":
            raise NotImplementedError()
        # only used by reboot() right now, but we will need to parse body
        # someday !!!!
        return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_limits(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_limits.xml')
        return (httplib.ACCEPTED, body, XML_HEADERS, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_72258(self, method, url, body, headers):
        if method != "DELETE":
            raise NotImplementedError()
        # only used by destroy node()
        return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_72258_ips(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_servers_ips.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_shared_ip_groups_5467(self, method, url, body, headers):
        if method != 'DELETE':
            raise NotImplementedError()
        return (httplib.NO_CONTENT, "", {}, httplib.responses[httplib.NO_CONTENT])

    def _v1_0_slug_shared_ip_groups(self, method, url, body, headers):

        fixture = 'v1_slug_shared_ip_group.xml' if method == 'POST' else 'v1_slug_shared_ip_groups.xml'
        body = self.fixtures.load(fixture)
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_shared_ip_groups_detail(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_shared_ip_groups_detail.xml')
        return (httplib.OK, body, XML_HEADERS, httplib.responses[httplib.OK])

    def _v1_0_slug_servers_3445_ips_public_67_23_21_133(self, method, url, body, headers):
        return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])

    def _v1_0_slug_servers_444222_action(self, method, url, body, headers):
        body = u(body)
        if body.find('resize') != -1:
            # test_ex_resize_server
            return (httplib.ACCEPTED, "", headers, httplib.responses[httplib.NO_CONTENT])
        elif body.find('confirmResize') != -1:
            # test_ex_confirm_resize
            return (httplib.NO_CONTENT, "", headers, httplib.responses[httplib.NO_CONTENT])
        elif body.find('revertResize') != -1:
            # test_ex_revert_resize
            return (httplib.NO_CONTENT, "", headers, httplib.responses[httplib.NO_CONTENT])

    def _v1_0_slug_flavors_detail(self, method, url, body, headers):
        body = self.fixtures.load('v1_slug_flavors_detail.xml')
        headers = {
            'date': 'Tue, 14 Jun 2011 09:43:55 GMT', 'content-length': '529'}
        headers.update(XML_HEADERS)