Esempio n. 1
0
    def test_log_resp(self):
        self.logger = self.useFixture(
            fixtures.FakeLogger(format="%(message)s",
                                level=logging.DEBUG,
                                nuke_handlers=True))

        cs = novaclient.client.HTTPClient("user",
                                          None,
                                          "",
                                          connection_pool=True)
        cs.http_log_debug = True
        text = ('{"access": {"token": {"id": "zhaoqin"}}}')
        resp = utils.TestResponse({
            'status_code': 200,
            'headers': {},
            'text': text
        })

        cs.http_log_resp(resp)
        output = self.logger.output.split('\n')

        self.assertIn('RESP: [200] {}', output)
        self.assertIn(
            'RESP BODY: {"access": {"token": {"id":'
            ' "{SHA1}4fc49c6a671ce889078ff6b250f7066cf6d2ada2"}}}', output)
Esempio n. 2
0
    def test_ambiguous_endpoints(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           utils.AUTH_URL_V2,
                           service_type='compute')
        resp = self.get_token()

        # duplicate existing service
        s = resp.add_service('compute')
        s.add_endpoint('http://*****:*****@mock.patch.object(requests.Session, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.AmbiguousEndpoints,
                              cs.client.authenticate)

        test_auth_call()
Esempio n. 3
0
    def test_authenticate_success(self):
        cs = client.Client("username", "password", "project_id",
                           utils.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(cs.client.management_url,
                             auth_response.headers['x-server-management-url'])
            self.assertEqual(cs.client.auth_token,
                             auth_response.headers['x-auth-token'])

        test_auth_call()
Esempio n. 4
0
    def test_authenticate_failure(self):
        cs = client.Client("username", "password", "project_id",
                           utils.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()
Esempio n. 5
0
    def test_authenticate_with_token_failure(self):
        cs = client.Client("username", None, "project_id", utils.AUTH_URL_V2)
        cs.client.auth_token = "FAKE_ID"
        resp = {"unauthorized": {"message": "Unauthorized", "code": "401"}}
        auth_response = utils.TestResponse({
            "status_code": 401,
            "text": json.dumps(resp),
        })

        mock_request = mock.Mock(return_value=(auth_response))

        with mock.patch.object(requests.Session, "request", mock_request):
            self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)
Esempio n. 6
0
def mock_http_request(resp=None):
    """Mock an HTTP Request."""
    if not resp:
        resp = fixture.V2Token()
        resp.set_scope()
        s = resp.add_service('compute')
        s.add_endpoint("http://localhost:8774/v1.1", region='RegionOne')

    auth_response = utils.TestResponse({
        "status_code": 200,
        "text": json.dumps(resp),
    })
    return mock.Mock(return_value=(auth_response))
Esempio n. 7
0
 def _test_from_response(self, body, expected_message):
     data = {
         'status_code': 404,
         'headers': {
             'content-type': 'application/json',
             'x-openstack-request-id': (
                 'req-d9df03b0-4150-4b53-8157-7560ccf39f75'),
         }
     }
     response = test_utils.TestResponse(data)
     fake_url = 'http://localhost:8774/v2.1/fake/flavors/test'
     error = exceptions.from_response(response, body, fake_url, 'GET')
     self.assertIsInstance(error, exceptions.NotFound)
     self.assertEqual(expected_message, error.message)
Esempio n. 8
0
    def test_authenticate_success(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           utils.AUTH_URL_V2,
                           service_type='compute',
                           direct_use=False)
        resp = self.get_token()

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

        mock_request = mock.Mock(return_value=(auth_response))

        @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)

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

        test_auth_call()
Esempio n. 9
0
    def test_authenticate_failure(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           utils.AUTH_URL_V2,
                           direct_use=False)
        resp = {"unauthorized": {"message": "Unauthorized", "code": "401"}}
        auth_response = utils.TestResponse({
            "status_code": 401,
            "text": json.dumps(resp),
        })

        mock_request = mock.Mock(return_value=(auth_response))

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

        test_auth_call()
Esempio n. 10
0
    def test_get_current_with_http_client(self, mock_list,
                                          mock_is_session_client):
        headers = {'x-openstack-request-id': fakes.FAKE_REQUEST_ID}
        resp = utils.TestResponse({"headers": headers})
        current_version = versions.Version(
            None, {"links": [{"href": "http://nova-api:8774/v2.1"}]},
            loaded=True)

        all_versions = [
            versions.Version(
                None, {"links": [{"href": "http://url/v1"}]}, loaded=True),
            versions.Version(
                None, {"links": [{"href": "http://url/v2"}]}, loaded=True),
            versions.Version(
                None, {"links": [{"href": "http://url/v3"}]}, loaded=True),
            current_version,
            versions.Version(
                None, {"links": [{"href": "http://url/v21"}]}, loaded=True)]
        mock_list.return_value = base.ListWithMeta(all_versions, resp)
        v = self.cs.versions.get_current()
        self.assert_request_id(v, fakes.FAKE_REQUEST_ID_LIST)
        self.assertEqual(current_version, v)
Esempio n. 11
0
    def test_v2_auth_redirect(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           utils.AUTH_URL_V2,
                           service_type='compute')
        dict_correct_response = self.get_token()
        correct_response = json.dumps(dict_correct_response)
        dict_responses = [
            {
                "headers": {
                    'location': 'http://127.0.0.1:5001'
                },
                "status_code": 305,
                "text": "Use proxy"
            },
            # Configured on admin port, nova redirects to v2.0 port.
            # When trying to connect on it, keystone auth succeed by v1.0
            # protocol (through headers) but tokens are being returned in
            # body (looks like keystone bug). Leaved for compatibility.
            {
                "headers": {},
                "status_code": 200,
                "text": correct_response
            },
            {
                "headers": {},
                "status_code": 200,
                "text": correct_response
            }
        ]

        responses = [(utils.TestResponse(resp)) for resp in dict_responses]

        def side_effect(*args, **kwargs):
            return responses.pop(0)

        mock_request = mock.Mock(side_effect=side_effect)

        @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"
            kwargs = copy.copy(self.TEST_REQUEST_BASE)
            kwargs['headers'] = headers
            kwargs['data'] = json.dumps(body)
            mock_request.assert_called_with("POST",
                                            token_url,
                                            allow_redirects=True,
                                            **kwargs)

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

        test_auth_call()
Esempio n. 12
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 requests
import six

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

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

refused_response = utils.TestResponse({
    "status_code": 400,
    "text": '[Errno 111] Connection refused',
})
refused_mock_request = mock.Mock(return_value=(refused_response))

bad_req_response = utils.TestResponse({
    "status_code": 400,
    "text": '',
})
bad_req_mock_request = mock.Mock(return_value=(bad_req_response))