Beispiel #1
0
class ClientTest(testtools.TestCase):
    @mock.patch('zunclient.api_versions.discover_version',
                return_value=api_versions.APIVersion('1.1'))
    @mock.patch('zunclient.v1.client.Client')
    def test_no_version_argument(self, mock_zun_client_v1,
                                 mock_discover_version):
        client.Client(auth_url='http://example/identity', username='******')
        mock_zun_client_v1.assert_called_with(
            api_version=api_versions.APIVersion('1.1'),
            auth_url='http://example/identity',
            username='******')

    @mock.patch('zunclient.api_versions.discover_version',
                return_value=api_versions.APIVersion('1.1'))
    @mock.patch('zunclient.v1.client.Client')
    def test_valid_version_argument(self, mock_zun_client_v1,
                                    mock_discover_version):
        client.Client(version='1',
                      auth_url='http://example/identity',
                      username='******')
        mock_zun_client_v1.assert_called_with(
            api_version=api_versions.APIVersion('1.1'),
            auth_url='http://example/identity',
            username='******')

    def test_invalid_version_argument(self):
        self.assertRaises(exceptions.UnsupportedVersion,
                          client.Client,
                          version='2')
Beispiel #2
0
    def test_get_string(self):
        v1_string = "3.23"
        v1 = api_versions.APIVersion(v1_string)
        self.assertEqual(v1_string, v1.get_string())

        self.assertRaises(ValueError,
                          api_versions.APIVersion().get_string)
    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                subs = api_versions.get_substitutions(callback)
                if do_help:
                    desc += msg % {'start': subs[0].start_version.get_string(),
                                   'end': subs[-1].end_version.get_string()}
                else:
                    for versioned_method in subs:
                        if version.matches(versioned_method.start_version,
                                           versioned_method.end_version):
                            callback = versioned_method.func
                            break
                    else:
                        continue

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = (
                subparsers.add_parser(command,
                                      help=action_help,
                                      description=desc,
                                      add_help=False,
                                      formatter_class=OpenStackHelpFormatter)
            )
            subparser.add_argument('-h', '--help',
                                   action='help',
                                   help=argparse.SUPPRESS,)
            self.subcommands[command] = subparser

            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get("help", "") + (msg % {
                            "start": start_version.get_string(),
                            "end": end_version.get_string()})
                    else:
                        if not version.matches(start_version, end_version):
                            continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=callback)
Beispiel #4
0
    def test_make_client(self, p_client, mock_get_api_version):

        instance = mock.Mock()
        instance._api_version = {"container": '1'}
        instance._region_name = 'zun_region'
        instance.session = 'zun_session'
        mock_get_api_version.return_value = api_versions.APIVersion('1.2')

        plugin.make_client(instance)
        p_client.assert_called_with(region_name='zun_region',
                                    session='zun_session',
                                    service_type='container',
                                    api_version=api_versions.APIVersion('1.2'))
Beispiel #5
0
    def test_end_version_is_none(self, mock_versioned_method, mock_name):
        func_name = "foo"
        mock_name.return_value = func_name
        mock_versioned_method.side_effect = self._side_effect_of_vers_method

        @api_versions.wraps("2.2")
        def foo(*args, **kwargs):
            pass

        foo(self._get_obj_with_vers("2.4"))

        mock_versioned_method.assert_called_once_with(
            func_name, api_versions.APIVersion("2.2"),
            api_versions.APIVersion("2.latest"), mock.ANY)
Beispiel #6
0
    def test_version_comparisons(self):
        v1 = api_versions.APIVersion("2.0")
        v2 = api_versions.APIVersion("2.5")
        v3 = api_versions.APIVersion("5.23")
        v4 = api_versions.APIVersion("2.0")
        v_null = api_versions.APIVersion()

        self.assertTrue(v1 < v2)
        self.assertTrue(v3 > v2)
        self.assertTrue(v1 != v2)
        self.assertTrue(v1 == v4)
        self.assertTrue(v1 != v_null)
        self.assertTrue(v_null == v_null)
        self.assertRaises(TypeError, v1.__le__, "2.1")
Beispiel #7
0
    def test_api_version_doesnt_match(self, mock_versioned_method, mock_name):
        func_name = "foo"
        mock_name.return_value = func_name
        mock_versioned_method.side_effect = self._side_effect_of_vers_method

        @api_versions.wraps("2.2", "2.6")
        def foo(*args, **kwargs):
            pass

        self.assertRaises(exceptions.VersionNotFoundForAPIMethod, foo,
                          self._get_obj_with_vers("2.1"))

        mock_versioned_method.assert_called_once_with(
            func_name, api_versions.APIVersion("2.2"),
            api_versions.APIVersion("2.6"), mock.ANY)
Beispiel #8
0
 def test_no_version_argument(self, mock_zun_client_v1,
                              mock_discover_version):
     client.Client(auth_url='http://example/identity', username='******')
     mock_zun_client_v1.assert_called_with(
         api_version=api_versions.APIVersion('1.1'),
         auth_url='http://example/identity',
         username='******')
Beispiel #9
0
def zunclient(request):
    (username, token_id, project_id,
     endpoint_override) = get_auth_params_from_request(request)

    insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
    cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
    LOG.debug('zunclient connection created using the token "%s" and url'
              ' "%s"' % (token_id, endpoint_override))
    api_version = API_VERSION
    if API_VERSION.is_latest():
        c = zun_client.Client(
            username=username,
            project_id=project_id,
            auth_token=token_id,
            endpoint_override=endpoint_override,
            insecure=insecure,
            cacert=cacert,
            api_version=api_versions.APIVersion("1.1"),
        )
        api_version = api_versions.discover_version(c, api_version)
    c = zun_client.Client(username=username,
                          project_id=project_id,
                          auth_token=token_id,
                          endpoint_override=endpoint_override,
                          insecure=insecure,
                          cacert=cacert,
                          api_version=api_version)
    return c
Beispiel #10
0
def make_client(instance):
    """Returns a zun service client"""
    requested_api_version = instance._api_version[API_NAME]

    zun_client = utils.get_client_class(
        API_NAME,
        requested_api_version,
        API_VERSIONS)
    LOG.debug("Instantiating zun client: {0}".format(
              zun_client))

    api_version = api_versions.get_api_version(requested_api_version)
    if api_version.is_latest():
        client = zun_client(
            region_name=instance._region_name,
            session=instance.session,
            service_type='container',
            api_version=api_versions.APIVersion("1.1"),
        )
        api_version = api_versions.discover_version(client, api_version)

    client = zun_client(
        region_name=instance._region_name,
        session=instance.session,
        service_type='container',
        api_version=api_version,
    )
    return client
Beispiel #11
0
def zunclient(request):
    (
        username,
        token_id,
        project_id,
        endpoint_override
    ) = get_auth_params_from_request(request)

    LOG.debug('zunclient connection created using the token "%s" and url'
              ' "%s"' % (token_id, endpoint_override))
    api_version = API_VERSION
    if API_VERSION.is_latest():
        c = zun_client.Client(
            username=username,
            project_id=project_id,
            auth_token=token_id,
            endpoint_override=endpoint_override,
            api_version=api_versions.APIVersion("1.1"),
        )
        api_version = api_versions.discover_version(c, api_version)
    c = zun_client.Client(username=username,
                          project_id=project_id,
                          auth_token=token_id,
                          endpoint_override=endpoint_override,
                          api_version=api_version)
    return c
Beispiel #12
0
    def test_server_exception_msg_and_traceback(self):
        error_msg = 'another test error'
        error_trace = ("\"Traceback (most recent call last):\\n\\n  "
                       "File \\\"/usr/local/lib/python2.7/...")
        error_body = _get_error_body(error_msg, error_trace)
        fake_resp = utils.FakeResponse({'content-type': 'application/json'},
                                       six.StringIO(error_body),
                                       version=1,
                                       status=500)
        client = http.HTTPClient(
            'http://localhost/',
            api_version=api_versions.APIVersion('1.latest'))
        client.get_connection = (
            lambda *a, **kw: utils.FakeConnection(fake_resp))

        error = self.assertRaises(exc.InternalServerError, client.json_request,
                                  'GET', '/v1/resources')

        self.assertEqual(
            '%(error)s (HTTP 500)\n%(trace)s' % {
                'error': error_msg,
                'trace': error_trace
            }, "%(error)s\n%(details)s" % {
                'error': str(error),
                'details': str(error.details)
            })
Beispiel #13
0
 def test_api_version_is_not_null(self):
     api_version = api_versions.APIVersion("2.3")
     headers = {}
     api_versions.update_headers(headers, api_version)
     self.assertEqual(
         {"OpenStack-API-Version":
          "container %s" % api_version.get_string()},
         headers)
 def setUp(self):
     super(ShellTest, self).setUp()
     self.nc_util = mock.patch(
         'zunclient.common.cliutils.isunauthenticated').start()
     self.nc_util.return_value = False
     self.discover_version = mock.patch(
         'zunclient.api_versions.discover_version').start()
     self.discover_version.return_value = api_versions.APIVersion('1.1')
 def put_archive(self, id, path, data):
     # API version 1.25 or later will expect Base64-encoded data
     if self.api_version >= api_versions.APIVersion("1.25"):
         data = utils.encode_file_data(data)
     return self._action(id,
                         '/put_archive',
                         qparams={'path': path},
                         body={'data': data})
Beispiel #16
0
 def __init__(self,
              user_agent=USER_AGENT,
              logger=LOG,
              api_version=DEFAULT_API_VERSION,
              *args,
              **kwargs):
     self.user_agent = USER_AGENT
     self.api_version = api_version or api_versions.APIVersion()
     super(SessionClient, self).__init__(*args, **kwargs)
Beispiel #17
0
 def test_server_is_too_new(self):
     fake_client = mock.MagicMock()
     fake_client.versions.get_current.return_value = mock.MagicMock(
         max_version="1.7", min_version="1.4")
     api_versions.MAX_API_VERSION = "1.3"
     api_versions.MIN_API_VERSION = "1.1"
     self.assertRaises(exceptions.UnsupportedVersion,
                       api_versions.discover_version, fake_client,
                       api_versions.APIVersion('1.latest'))
 def get_archive(self, id, path):
     res = self._action(id,
                        '/get_archive',
                        method='GET',
                        qparams={'path': path})[1]
     # API version 1.25 or later will return Base64-encoded data
     if self.api_version >= api_versions.APIVersion("1.25"):
         res['data'] = utils.decode_file_data(res['data'])
     else:
         res['data'] = res['data'].encode()
     return res
Beispiel #19
0
    def test_server_without_microversion_and_no_version_field(self):
        fake_client = mock.MagicMock()
        fake_client.versions.get_current.return_value = versions.Version(
            None, {})
        api_versions.MAX_API_VERSION = "1.11"
        api_versions.MIN_API_VERSION = "1.1"

        self.assertEqual(
            "1.1",
            api_versions.discover_version(
                fake_client, api_versions.APIVersion('1.latest')).get_string())
Beispiel #20
0
    def test_client_end_version_is_the_latest_one(self):
        fake_client = mock.MagicMock()
        fake_client.versions.get_current.return_value = mock.MagicMock(
            max_version="1.16", min_version="1.4")
        api_versions.MAX_API_VERSION = "1.11"
        api_versions.MIN_API_VERSION = "1.1"

        self.assertEqual(
            "1.11",
            api_versions.discover_version(
                fake_client, api_versions.APIVersion('1.latest')).get_string())
 def test_exception(self):
     fake_response = utils.FakeSessionResponse(
         {}, content="", status_code=504)
     fake_session = mock.MagicMock()
     fake_session.request.side_effect = [fake_response]
     client = http.SessionClient(
         api_version=api_versions.APIVersion('1.latest'),
         session=fake_session, endpoint_override='http://zun')
     self.assertRaises(exceptions.GatewayTimeout,
                       client.json_request,
                       'GET', '/v1/resources')
Beispiel #22
0
 def _test_main_region(self, command, expected_region_name, mock_client):
     self.shell(command)
     mock_client.assert_called_once_with(
         username='******', password='******',
         interface='publicURL', project_id=None,
         project_name='project_name', auth_url=self.AUTH_URL,
         service_type='container', region_name=expected_region_name,
         project_domain_id='', project_domain_name='',
         user_domain_id='', user_domain_name='', profile=None,
         endpoint_override=None, insecure=False, cacert=None,
         cert=None, key=None,
         version=api_versions.APIVersion('1.29'))
Beispiel #23
0
 def _add_subparser_args(self, subparser, arguments, version, do_help, msg):
     for (args, kwargs) in arguments:
         start_version = kwargs.get("start_version", None)
         if start_version:
             start_version = api_versions.APIVersion(start_version)
             end_version = kwargs.get("end_version", None)
             if end_version:
                 end_version = api_versions.APIVersion(end_version)
             else:
                 end_version = api_versions.APIVersion(
                     "%s.latest" % start_version.ver_major)
             if do_help:
                 kwargs["help"] = kwargs.get("help", "") + (msg % {
                     "start": start_version.get_string(),
                     "end": end_version.get_string()})
             else:
                 if not version.matches(start_version, end_version):
                     continue
         kw = kwargs.copy()
         kw.pop("start_version", None)
         kw.pop("end_version", None)
         subparser.add_argument(*args, **kwargs)
Beispiel #24
0
    def test_server_exception_empty_body(self):
        error_body = _get_error_body()

        fake_session = utils.FakeSession({'Content-Type': 'application/json'},
                                         error_body, 500)

        client = http.SessionClient(
            api_version=api_versions.APIVersion('1.latest'),
            session=fake_session)

        error = self.assertRaises(exc.InternalServerError, client.json_request,
                                  'GET', '/v1/resources')

        self.assertEqual('Internal Server Error (HTTP 500)', str(error))
Beispiel #25
0
    def test_server_exception_empty_body(self):
        error_body = _get_error_body()
        fake_resp = utils.FakeResponse({'content-type': 'application/json'},
                                       six.StringIO(error_body),
                                       version=1,
                                       status=500)
        client = http.HTTPClient(
            'http://localhost/',
            api_version=api_versions.APIVersion('1.latest'))
        client.get_connection = (
            lambda *a, **kw: utils.FakeConnection(fake_resp))

        error = self.assertRaises(exc.InternalServerError, client.json_request,
                                  'GET', '/v1/resources')
        self.assertEqual('Internal Server Error (HTTP 500)', str(error))
Beispiel #26
0
    def test_401_unauthorized_exception(self):
        error_body = _get_error_body()
        fake_resp = utils.FakeResponse({'content-type': 'text/plain'},
                                       six.StringIO(error_body),
                                       version=1,
                                       status=401)
        client = http.HTTPClient(
            'http://localhost/',
            api_version=api_versions.APIVersion('1.latest'))

        client.get_connection = (
            lambda *a, **kw: utils.FakeConnection(fake_resp))

        self.assertRaises(exc.Unauthorized, client.json_request, 'GET',
                          '/v1/resources')
Beispiel #27
0
 def test_main_endpoint_public(self, mock_client):
     self.make_env(fake_env=FAKE_ENV4)
     self.shell(
         '--zun-api-version 1.29 '
         '--endpoint-type publicURL service-list')
     mock_client.assert_called_once_with(
         username='******', password='******',
         interface='publicURL', project_id='project_id',
         project_name=None, auth_url=self.AUTH_URL,
         service_type='container', region_name=None,
         project_domain_id='', project_domain_name='Default',
         user_domain_id='', user_domain_name='Default',
         endpoint_override=None, insecure=False, profile=None,
         cacert=None, cert=None, key=None,
         version=api_versions.APIVersion('1.29'))
    def test_bypass_url(self):
        fake_response = utils.FakeSessionResponse(
            {}, content="", status_code=201)
        fake_session = mock.MagicMock()
        fake_session.request.side_effect = [fake_response]

        client = http.SessionClient(
            api_version=api_versions.APIVersion('1.latest'),
            session=fake_session, endpoint_override='http://zun')

        client.json_request('GET', '/v1/services')
        self.assertEqual(
            fake_session.request.call_args[1]['endpoint_override'],
            'http://zun'
        )
Beispiel #29
0
    def test_version_matches(self):
        v1 = api_versions.APIVersion("2.0")
        v2 = api_versions.APIVersion("2.5")
        v3 = api_versions.APIVersion("2.45")
        v4 = api_versions.APIVersion("3.3")
        v5 = api_versions.APIVersion("3.23")
        v6 = api_versions.APIVersion("2.0")
        v7 = api_versions.APIVersion("3.3")
        v8 = api_versions.APIVersion("4.0")
        v_null = api_versions.APIVersion()

        self.assertTrue(v2.matches(v1, v3))
        self.assertTrue(v2.matches(v1, v_null))
        self.assertTrue(v1.matches(v6, v2))
        self.assertTrue(v4.matches(v2, v7))
        self.assertTrue(v4.matches(v_null, v7))
        self.assertTrue(v4.matches(v_null, v8))
        self.assertFalse(v1.matches(v2, v3))
        self.assertFalse(v5.matches(v2, v4))
        self.assertFalse(v2.matches(v3, v1))

        self.assertRaises(ValueError, v_null.matches, v1, v3)
Beispiel #30
0
    def setUp(self):
        super(TestCommandLineArgument, self).setUp()
        self.make_env(fake_env=FAKE_ENV)
        session_client = mock.patch(
            'zunclient.common.httpclient.SessionClient')
        session_client.start()
        loader = mock.patch('keystoneauth1.loading.get_plugin_loader')
        loader.start()
        session = mock.patch('keystoneauth1.session.Session')
        session.start()
        discover = mock.patch('zunclient.api_versions.discover_version',
                              return_value=api_versions.APIVersion('1.1'))
        discover.start()

        self.addCleanup(session_client.stop)
        self.addCleanup(loader.stop)
        self.addCleanup(session.stop)
        self.addCleanup(discover.stop)