Ejemplo n.º 1
0
    def _cs_request(self, url, method, **kwargs):
        # Check that certain things are called correctly
        if method in ['GET', 'DELETE']:
            assert 'body' not in kwargs
        elif method == 'PUT':
            assert 'body' in kwargs

        # Call the method
        args = urlparse.parse_qsl(urlparse.urlparse(url)[4])
        kwargs.update(args)
        munged_url = url.rsplit('?', 1)[0]
        munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_')
        munged_url = munged_url.replace('-', '_')

        callback = "%s_%s" % (method.lower(), munged_url)

        if not hasattr(self, callback):
            raise AssertionError('Called unknown API method: %s %s, '
                                 'expected fakes method name: %s' %
                                 (method, url, callback))

        # Note the call
        self.callstack.append((method, url, kwargs.get('body', None)))
        status, headers, body = getattr(self, callback)(**kwargs)
        r = utils.TestResponse({
            "status_code": status,
            "text": body,
            "headers": headers,
        })
        return r, body

        if hasattr(status, 'items'):
            return utils.TestResponse(status), body
        else:
            return utils.TestResponse({"status": status}), body
Ejemplo n.º 2
0
    def test_sessionclient_request_method_raises_badrequest(
            self, mock_request):
        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        resp = {
            "badRequest": {
                "message": "Invalid image identifier or unable to access "
                "requested image.",
                "code": 400
            }
        }

        mock_response = utils.TestResponse({
            "status_code": 400,
            "text": six.b(json.dumps(resp)),
        })

        # 'request' method of Adaptor will return 400 response
        mock_request.return_value = mock_response
        session_client = cinderclient.client.SessionClient(session=mock.Mock())

        # 'from_response' method will raise BadRequest because
        # resp.status_code is 400
        self.assertRaises(exceptions.BadRequest, session_client.request,
                          mock.sentinel.url, 'POST', **kwargs)
        self.assertIsNotNone(session_client._logger)
Ejemplo n.º 3
0
    def test_authenticate_success(self):
        cs = client.Client("username", "password", "project_id", "auth_url")
        management_url = 'https://localhost/v1.1/443470'
        auth_response = utils.TestResponse({
            'status_code': 204,
            'headers': {
                'x-server-management-url': management_url,
                'x-auth-token': '1b751d74-de0c-46ae-84f0-915744b582d1',
            },
        })
        mock_request = mock.Mock(return_value=(auth_response))

        @mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'Accept': 'application/json',
                'X-Auth-User': '******',
                'X-Auth-Key': 'password',
                'X-Auth-Project-Id': 'project_id',
                'User-Agent': cs.client.USER_AGENT
            }
            mock_request.assert_called_with("GET",
                                            cs.client.auth_url,
                                            headers=headers,
                                            **self.TEST_REQUEST_BASE)

            self.assertEqual(auth_response.headers['x-server-management-url'],
                             cs.client.management_url)
            self.assertEqual(auth_response.headers['x-auth-token'],
                             cs.client.auth_token)

        test_auth_call()
Ejemplo n.º 4
0
def mock_http_request(resp=None):
    """Mock an HTTP Request."""
    if not resp:
        resp = {
            "access": {
                "token": {
                    "expires": "12345",
                    "id": "FAKE_ID",
                    "tenant": {
                        "id": "FAKE_TENANT_ID",
                    }
                },
                "serviceCatalog": [
                    {
                        "type": "volume",
                        "endpoints": [
                            {
                                "region": "RegionOne",
                                "adminURL": "http://localhost:8774/v1",
                                "internalURL": "http://localhost:8774/v1",
                                "publicURL": "http://localhost:8774/v1/",
                            },
                        ],
                    },
                ],
            },
        }

    auth_response = utils.TestResponse({
        "status_code": 200,
        "text": json.dumps(resp),
    })
    return mock.Mock(return_value=(auth_response))
Ejemplo n.º 5
0
    def test_authenticate_failure(self):
        cs = client.Client("username", "password", "project_id", "auth_url")
        auth_response = utils.TestResponse({"status_code": 401})
        mock_request = mock.Mock(return_value=(auth_response))

        @mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)

        test_auth_call()
Ejemplo n.º 6
0
    def test_get_server_version(self, url, mock_request):
        mock_response = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(fakes.fake_request_get())
        })

        mock_request.return_value = mock_response

        min_version, max_version = cinderclient.client.get_server_version(url)
        self.assertEqual(min_version, api_versions.APIVersion('3.0'))
        self.assertEqual(max_version, api_versions.APIVersion('3.16'))
Ejemplo n.º 7
0
    def test_get_server_version_v2(self, mock_request):

        mock_response = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(fakes.fake_request_get_no_v3())
        })

        mock_request.return_value = mock_response

        url = "http://192.168.122.127:8776/v2/e5526285ebd741b1819393f772f11fc3"

        min_version, max_version = cinderclient.client.get_server_version(url)
        self.assertEqual(api_versions.APIVersion('2.0'), min_version)
        self.assertEqual(api_versions.APIVersion('2.0'), max_version)
Ejemplo n.º 8
0
    def test_get_server_version_insecure(self, mock_request):
        mock_response = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(fakes.fake_request_get_no_v3())
        })

        mock_request.return_value = mock_response

        url = (
            "https://192.168.122.127:8776/v3/e5526285ebd741b1819393f772f11fc3")
        expected_url = "https://192.168.122.127:8776/"

        cinderclient.client.get_server_version(url, True)

        mock_request.assert_called_once_with(expected_url, verify=False)
Ejemplo n.º 9
0
    def test_authenticate_failure(self):
        cs = client.Client("username", "password", "project_id",
                           "http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)

        test_auth_call()
Ejemplo n.º 10
0
    def test_get_highest_client_server_version(self, version, mock_request):

        mock_response = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(fakes.fake_request_get())
        })

        mock_request.return_value = mock_response

        url = "http://192.168.122.127:8776/v3/e5526285ebd741b1819393f772f11fc3"

        with mock.patch.object(api_versions, 'MAX_VERSION', version):
            highest = (
                cinderclient.client.get_highest_client_server_version(url))
        expected = version if version == '3.12' else '3.16'
        self.assertEqual(expected, highest)
Ejemplo n.º 11
0
    def test_sessionclient_request_method(self, mock_from_resp, mock_request):
        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        resp = {
            "text": {
                "volume": {
                    "status": "creating",
                    "id": "431253c0-e203-4da2-88df-60c756942aaf",
                    "size": 1
                }
            },
            "code": 202
        }

        request_id = "req-f551871a-4950-4225-9b2c-29a14c8f075e"
        mock_response = utils.TestResponse({
            "status_code": 202,
            "text": six.b(json.dumps(resp)),
            "headers": {
                "x-openstack-request-id": request_id
            },
        })

        # 'request' method of Adaptor will return 202 response
        mock_request.return_value = mock_response
        session_client = cinderclient.client.SessionClient(session=mock.Mock())
        response, body = session_client.request(mock.sentinel.url, 'POST',
                                                **kwargs)
        self.assertIsNotNone(session_client._logger)

        # In this case, from_response method will not get called
        # because response status_code is < 400
        self.assertEqual(202, response.status_code)
        self.assertFalse(mock_from_resp.called)
Ejemplo n.º 12
0
    def _cs_request(self, url, method, **kwargs):
        # Check that certain things are called correctly
        if method in ['GET', 'DELETE']:
            assert 'body' not in kwargs
        elif method == 'PUT':
            assert 'body' in kwargs

        # Call the method
        args = urlparse.parse_qsl(urlparse.urlparse(url)[4])
        kwargs.update(args)
        url_split = url.rsplit('?', 1)
        munged_url = url_split[0]
        if len(url_split) > 1:
            parameters = url_split[1]
            if 'marker' in parameters:
                self.marker = int(parameters.rsplit('marker=', 1)[1])
            else:
                self.marker = None
        else:
            self.marker = None
        munged_url = munged_url.strip('/').replace('/', '_').replace('.', '_')
        munged_url = munged_url.replace('-', '_')

        callback = "%s_%s" % (method.lower(), munged_url)

        if not hasattr(self, callback):
            raise AssertionError('Called unknown API method: %s %s, '
                                 'expected fakes method name: %s' %
                                 (method, url, callback))

        # Note the call
        self.callstack.append((method, url, kwargs.get('body', None)))
        status, headers, body = getattr(self, callback)(**kwargs)
        # add fake request-id header
        headers['x-openstack-request-id'] = REQUEST_ID
        if self.version_header:
            headers['OpenStack-API-version'] = self.version_header
        r = utils.TestResponse({
            "status_code": status,
            "text": body,
            "headers": headers,
        })
        return r, body
Ejemplo n.º 13
0
    def test_sessionclient_request_method_raises_overlimit(self, mock_request):
        resp = {
            "overLimitFault": {
                "message": "This request was rate-limited.",
                "code": 413
            }
        }

        mock_response = utils.TestResponse({
            "status_code": 413,
            "text": six.b(json.dumps(resp)),
        })

        # 'request' method of Adaptor will return 413 response
        mock_request.return_value = mock_response
        session_client = cinderclient.client.SessionClient(session=mock.Mock())

        self.assertRaises(exceptions.OverLimit, session_client.request,
                          mock.sentinel.url, 'GET')
        self.assertIsNotNone(session_client._logger)
Ejemplo n.º 14
0
    def test_sessionclient_request_method(self, mock_from_resp, mock_request):
        kwargs = {
            "body": {
                "volume": {
                    "status": "creating",
                    "imageRef": "username",
                    "attach_status": "detached"
                },
                "authenticated": "True"
            }
        }

        resp = {
            "text": {
                "volume": {
                    "status": "creating",
                    "id": "431253c0-e203-4da2-88df-60c756942aaf",
                    "size": 1
                }
            },
            "code": 202
        }

        mock_response = utils.TestResponse({
            "status_code": 202,
            "text": json.dumps(resp),
        })

        # 'request' method of Adaptor will return 202 response
        mock_request.return_value = mock_response
        mock_session = mock.Mock()
        mock_session.get_endpoint.return_value = fixture_base.VOLUME_V1_URL
        session_client = cinderclient.client.SessionClient(
            session=mock_session)
        response, body = session_client.request(fixture_base.VOLUME_V1_URL,
                                                'POST', **kwargs)

        # In this case, from_response method will not get called
        # because response status_code is < 400
        self.assertEqual(202, response.status_code)
        self.assertFalse(mock_from_resp.called)
Ejemplo n.º 15
0
    def test_authenticate_tenant_id(self):
        cs = client.Client("username",
                           "password",
                           auth_url="http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'User-Agent': cs.client.USER_AGENT,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
            body = {
                'auth': {
                    'passwordCredentials': {
                        'username': cs.client.user,
                        'password': cs.client.password,
                    },
                    'tenantId': cs.client.tenant_id,
                },
            }

            token_url = cs.client.auth_url + "/tokens"
            mock_request.assert_called_with("POST",
                                            token_url,
                                            headers=headers,
                                            data=json.dumps(body),
                                            allow_redirects=True,
                                            **self.TEST_REQUEST_BASE)

            endpoints = resp["access"]["serviceCatalog"][0]['endpoints']
            public_url = endpoints[0]["publicURL"].rstrip('/')
            self.assertEqual(public_url, cs.client.management_url)
            token_id = resp["access"]["token"]["id"]
            self.assertEqual(token_id, cs.client.auth_token)
            tenant_id = resp["access"]["token"]["tenant"]["id"]
            self.assertEqual(tenant_id, cs.client.tenant_id)

        test_auth_call()
# 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 json
import mock
import requests
import uuid

from cinderclient import client
from cinderclient import exceptions
from cinderclient.tests.unit import utils

fake_response = utils.TestResponse({
    "status_code": 200,
    "text": '{"hi": "there"}',
})
mock_request = mock.Mock(return_value=(fake_response))

fake_201_response = utils.TestResponse({
    "status_code": 201,
    "text": '{"hi": "there"}',
})
mock_201_request = mock.Mock(return_value=(fake_201_response))

refused_response = utils.TestResponse({
    "status_code": 400,
    "text": '[Errno 111] Connection refused',
})
refused_mock_request = mock.Mock(return_value=(refused_response))
Ejemplo n.º 17
0
    def test_auth_redirect(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           "http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'User-Agent': cs.client.USER_AGENT,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
            body = {
                'auth': {
                    'passwordCredentials': {
                        'username': cs.client.user,
                        'password': cs.client.password,
                    },
                    'tenantName': cs.client.projectid,
                },
            }

            token_url = cs.client.auth_url + "/tokens"
            mock_request.assert_called_with("POST",
                                            token_url,
                                            headers=headers,
                                            data=json.dumps(body),
                                            allow_redirects=True,
                                            **self.TEST_REQUEST_BASE)

            resp = dict_correct_response
            endpoints = resp["access"]["serviceCatalog"][0]['endpoints']
            public_url = endpoints[0]["publicURL"].rstrip('/')
            self.assertEqual(public_url, cs.client.management_url)
            token_id = resp["access"]["token"]["id"]
            self.assertEqual(token_id, cs.client.auth_token)

        test_auth_call()
Ejemplo n.º 18
0
# 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 requests

from cinderclient import client
from cinderclient import exceptions
from cinderclient.tests.unit import utils

fake_response = utils.TestResponse({
    "status_code": 200,
    "text": '{"hi": "there"}',
})

fake_response_empty = utils.TestResponse({
    "status_code": 200,
    "text": '{"access": {}}'
})

mock_request = mock.Mock(return_value=(fake_response))
mock_request_empty = mock.Mock(return_value=(fake_response_empty))

bad_400_response = utils.TestResponse({
    "status_code":
    400,
    "text":
    '{"error": {"message": "n/a", "details": "Terrible!"}}',