rename neutron to tacker

Change-Id: I1d7c0729d387827e8d4355db9f4dccb265c2ec32
This commit is contained in:
Isaku Yamahata 2014-06-27 18:06:02 +09:00
parent 066bddc79f
commit 14eeda8a0b
39 changed files with 319 additions and 284 deletions

View File

@ -24,13 +24,13 @@ import os
from keystoneclient import access from keystoneclient import access
import requests import requests
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import utils from tackerclient.common import utils
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
if os.environ.get('NEUTRONCLIENT_DEBUG'): if os.environ.get('TACKERCLIENT_DEBUG'):
ch = logging.StreamHandler() ch = logging.StreamHandler()
_logger.setLevel(logging.DEBUG) _logger.setLevel(logging.DEBUG)
_logger.addHandler(ch) _logger.addHandler(ch)
@ -44,7 +44,7 @@ logging.getLogger("requests").setLevel(_requests_log_level)
class HTTPClient(object): class HTTPClient(object):
"""Handles the REST calls and responses, include authn.""" """Handles the REST calls and responses, include authn."""
USER_AGENT = 'python-neutronclient' USER_AGENT = 'python-tackerclient'
def __init__(self, username=None, user_id=None, def __init__(self, username=None, user_id=None,
tenant_name=None, tenant_id=None, tenant_name=None, tenant_id=None,
@ -242,7 +242,7 @@ class HTTPClient(object):
try: try:
resp, body = self._cs_request(url, "GET") resp, body = self._cs_request(url, "GET")
except exceptions.Unauthorized: except exceptions.Unauthorized:
# rollback to authenticate() to handle case when neutron client # rollback to authenticate() to handle case when tacker client
# is initialized just before the token is expired # is initialized just before the token is expired
self.authenticate() self.authenticate()
return self.endpoint_url return self.endpoint_url

View File

@ -15,7 +15,7 @@
import gettext import gettext
t = gettext.translation('neutronclient', fallback=True) t = gettext.translation('tackerclient', fallback=True)
try: try:
ugettext = t.ugettext # Python 2 ugettext = t.ugettext # Python 2
except AttributeError: except AttributeError:

View File

@ -19,8 +19,8 @@
import logging import logging
from neutronclient import client from tackerclient import client
from neutronclient.neutron import client as neutron_client from tackerclient.tacker import client as tacker_client
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -44,10 +44,7 @@ class ClientCache(object):
class ClientManager(object): class ClientManager(object):
"""Manages access to API clients, including authentication. """Manages access to API clients, including authentication.
""" """
neutron = ClientCache(neutron_client.make_client) tacker = ClientCache(tacker_client.make_client)
# Provide support for old quantum commands (for example
# in stable versions)
quantum = neutron
def __init__(self, token=None, url=None, def __init__(self, token=None, url=None,
auth_url=None, auth_url=None,

View File

@ -15,12 +15,12 @@
EXT_NS = '_extension_ns' EXT_NS = '_extension_ns'
XML_NS_V20 = 'http://openstack.org/quantum/api/v2.0' XML_NS_V10 = 'http://openstack.org/tacker/api/v1.0'
XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance" XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"
XSI_ATTR = "xsi:nil" XSI_ATTR = "xsi:nil"
XSI_NIL_ATTR = "xmlns:xsi" XSI_NIL_ATTR = "xmlns:xsi"
TYPE_XMLNS = "xmlns:quantum" TYPE_XMLNS = "xmlns:tacker"
TYPE_ATTR = "quantum:type" TYPE_ATTR = "tacker:type"
VIRTUAL_ROOT_KEY = "_v_root" VIRTUAL_ROOT_KEY = "_v_root"
ATOM_NAMESPACE = "http://www.w3.org/2005/Atom" ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"
ATOM_XMLNS = "xmlns:atom" ATOM_XMLNS = "xmlns:atom"
@ -33,11 +33,6 @@ TYPE_FLOAT = "float"
TYPE_LIST = "list" TYPE_LIST = "list"
TYPE_DICT = "dict" TYPE_DICT = "dict"
PLURALS = {'networks': 'network', PLURALS = {'templates': 'template',
'ports': 'port', 'devices': 'device',
'subnets': 'subnet', 'services': 'service'}
'dns_nameservers': 'dns_nameserver',
'host_routes': 'host_route',
'allocation_pools': 'allocation_pool',
'fixed_ips': 'fixed_ip',
'extensions': 'extension'}

View File

@ -13,24 +13,24 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from neutronclient.common import _ from tackerclient.common import _
""" """
Neutron base exception handling. Tacker base exception handling.
Exceptions are classified into three categories: Exceptions are classified into three categories:
* Exceptions corresponding to exceptions from neutron server: * Exceptions corresponding to exceptions from tacker server:
This type of exceptions should inherit one of exceptions This type of exceptions should inherit one of exceptions
in HTTP_EXCEPTION_MAP. in HTTP_EXCEPTION_MAP.
* Exceptions from client library: * Exceptions from client library:
This type of exceptions should inherit NeutronClientException. This type of exceptions should inherit TackerClientException.
* Exceptions from CLI code: * Exceptions from CLI code:
This type of exceptions should inherit NeutronCLIError. This type of exceptions should inherit TackerCLIError.
""" """
class NeutronException(Exception): class TackerException(Exception):
"""Base Neutron Exception """Base Tacker Exception
To correctly use this class, inherit from it and define To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd a 'message' property. That message will get printf'd
@ -52,8 +52,8 @@ class NeutronException(Exception):
return self._error_string return self._error_string
class NeutronClientException(NeutronException): class TackerClientException(TackerException):
"""Base exception which exceptions from Neutron are mapped into. """Base exception which exceptions from Tacker are mapped into.
NOTE: on the client side, we use different exception types in order NOTE: on the client side, we use different exception types in order
to allow client library users to handle server exceptions in try...except to allow client library users to handle server exceptions in try...except
@ -63,39 +63,39 @@ class NeutronClientException(NeutronException):
def __init__(self, message=None, **kwargs): def __init__(self, message=None, **kwargs):
if 'status_code' in kwargs: if 'status_code' in kwargs:
self.status_code = kwargs['status_code'] self.status_code = kwargs['status_code']
super(NeutronClientException, self).__init__(message, **kwargs) super(TackerClientException, self).__init__(message, **kwargs)
# Base exceptions from Neutron # Base exceptions from Tacker
class BadRequest(NeutronClientException): class BadRequest(TackerClientException):
status_code = 400 status_code = 400
class Unauthorized(NeutronClientException): class Unauthorized(TackerClientException):
status_code = 401 status_code = 401
message = _("Unauthorized: bad credentials.") message = _("Unauthorized: bad credentials.")
class Forbidden(NeutronClientException): class Forbidden(TackerClientException):
status_code = 403 status_code = 403
message = _("Forbidden: your credentials don't give you access to this " message = _("Forbidden: your credentials don't give you access to this "
"resource.") "resource.")
class NotFound(NeutronClientException): class NotFound(TackerClientException):
status_code = 404 status_code = 404
class Conflict(NeutronClientException): class Conflict(TackerClientException):
status_code = 409 status_code = 409
class InternalServerError(NeutronClientException): class InternalServerError(TackerClientException):
status_code = 500 status_code = 500
class ServiceUnavailable(NeutronClientException): class ServiceUnavailable(TackerClientException):
status_code = 503 status_code = 503
@ -110,9 +110,9 @@ HTTP_EXCEPTION_MAP = {
} }
# Exceptions mapped to Neutron server exceptions # Exceptions mapped to Tacker server exceptions
# These are defined if a user of client library needs specific exception. # These are defined if a user of client library needs specific exception.
# Exception name should be <Neutron Exception Name> + 'Client' # Exception name should be <Tacker Exception Name> + 'Client'
# e.g., NetworkNotFound -> NetworkNotFoundClient # e.g., NetworkNotFound -> NetworkNotFoundClient
class NetworkNotFoundClient(NotFound): class NetworkNotFoundClient(NotFound):
@ -143,7 +143,7 @@ class OverQuotaClient(Conflict):
pass pass
# TODO(amotoki): It is unused in Neutron, but it is referred to # TODO(amotoki): It is unused in Tacker, but it is referred to
# in Horizon code. After Horizon code is updated, remove it. # in Horizon code. After Horizon code is updated, remove it.
class AlreadyAttachedClient(Conflict): class AlreadyAttachedClient(Conflict):
pass pass
@ -160,23 +160,23 @@ class ExternalIpAddressExhaustedClient(BadRequest):
# Exceptions from client library # Exceptions from client library
class NoAuthURLProvided(Unauthorized): class NoAuthURLProvided(Unauthorized):
message = _("auth_url was not provided to the Neutron client") message = _("auth_url was not provided to the Tacker client")
class EndpointNotFound(NeutronClientException): class EndpointNotFound(TackerClientException):
message = _("Could not find Service or Region in Service Catalog.") message = _("Could not find Service or Region in Service Catalog.")
class EndpointTypeNotFound(NeutronClientException): class EndpointTypeNotFound(TackerClientException):
message = _("Could not find endpoint type %(type_)s in Service Catalog.") message = _("Could not find endpoint type %(type_)s in Service Catalog.")
class AmbiguousEndpoints(NeutronClientException): class AmbiguousEndpoints(TackerClientException):
message = _("Found more than one matching endpoint in Service Catalog: " message = _("Found more than one matching endpoint in Service Catalog: "
"%(matching_endpoints)") "%(matching_endpoints)")
class RequestURITooLong(NeutronClientException): class RequestURITooLong(TackerClientException):
"""Raised when a request fails with HTTP error 414.""" """Raised when a request fails with HTTP error 414."""
def __init__(self, **kwargs): def __init__(self, **kwargs):
@ -184,40 +184,40 @@ class RequestURITooLong(NeutronClientException):
super(RequestURITooLong, self).__init__(**kwargs) super(RequestURITooLong, self).__init__(**kwargs)
class ConnectionFailed(NeutronClientException): class ConnectionFailed(TackerClientException):
message = _("Connection to neutron failed: %(reason)s") message = _("Connection to tacker failed: %(reason)s")
class SslCertificateValidationError(NeutronClientException): class SslCertificateValidationError(TackerClientException):
message = _("SSL certificate validation has failed: %(reason)s") message = _("SSL certificate validation has failed: %(reason)s")
class MalformedResponseBody(NeutronClientException): class MalformedResponseBody(TackerClientException):
message = _("Malformed response body: %(reason)s") message = _("Malformed response body: %(reason)s")
class InvalidContentType(NeutronClientException): class InvalidContentType(TackerClientException):
message = _("Invalid content type %(content_type)s.") message = _("Invalid content type %(content_type)s.")
# Command line exceptions # Command line exceptions
class NeutronCLIError(NeutronException): class TackerCLIError(TackerException):
"""Exception raised when command line parsing fails.""" """Exception raised when command line parsing fails."""
pass pass
class CommandError(NeutronCLIError): class CommandError(TackerCLIError):
pass pass
class UnsupportedVersion(NeutronCLIError): class UnsupportedVersion(TackerCLIError):
"""Indicates that the user is trying to use an unsupported """Indicates that the user is trying to use an unsupported
version of the API version of the API
""" """
pass pass
class NeutronClientNoUniqueMatch(NeutronCLIError): class TackerClientNoUniqueMatch(TackerCLIError):
message = _("Multiple %(resource)s matches found for name '%(name)s'," message = _("Multiple %(resource)s matches found for name '%(name)s',"
" use an ID to be more specific.") " use an ID to be more specific.")

View File

@ -14,7 +14,7 @@
# under the License. # under the License.
# #
### ###
### Codes from neutron wsgi ### Codes from tacker wsgi
### ###
import logging import logging
@ -22,10 +22,10 @@ import logging
from xml.etree import ElementTree as etree from xml.etree import ElementTree as etree
from xml.parsers import expat from xml.parsers import expat
from neutronclient.common import constants from tackerclient.common import constants
from neutronclient.common import exceptions as exception from tackerclient.common import exceptions as exception
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
from neutronclient.openstack.common import jsonutils from tackerclient.openstack.common import jsonutils
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -76,7 +76,7 @@ class XMLDictSerializer(DictSerializer):
if not xmlns: if not xmlns:
xmlns = self.metadata.get('xmlns') xmlns = self.metadata.get('xmlns')
if not xmlns: if not xmlns:
xmlns = constants.XML_NS_V20 xmlns = constants.XML_NS_V10
self.xmlns = xmlns self.xmlns = xmlns
def default(self, data): def default(self, data):
@ -242,7 +242,7 @@ class XMLDeserializer(TextDeserializer):
self.metadata = metadata or {} self.metadata = metadata or {}
xmlns = self.metadata.get('xmlns') xmlns = self.metadata.get('xmlns')
if not xmlns: if not xmlns:
xmlns = constants.XML_NS_V20 xmlns = constants.XML_NS_V10
self.xmlns = xmlns self.xmlns = xmlns
def _get_key(self, tag): def _get_key(self, tag):
@ -359,7 +359,7 @@ class XMLDeserializer(TextDeserializer):
return self.default(datastring) return self.default(datastring)
# NOTE(maru): this class is duplicated from neutron.wsgi # NOTE(maru): this class is duplicated from tacker.wsgi
class Serializer(object): class Serializer(object):
"""Serializes and deserializes dictionaries to certain MIME types.""" """Serializes and deserializes dictionaries to certain MIME types."""

View File

@ -23,9 +23,9 @@ import logging
import os import os
import sys import sys
from neutronclient.common import _ from tackerclient.common import _
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.openstack.common import strutils from tackerclient.openstack.common import strutils
def env(*vars, **kwargs): def env(*vars, **kwargs):

View File

@ -15,8 +15,8 @@
import netaddr import netaddr
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
def validate_int_range(parsed_args, attr_name, min_value=None, max_value=None): def validate_int_range(parsed_args, attr_name, min_value=None, max_value=None):

View File

@ -19,7 +19,7 @@ gettext for openstack-common modules.
Usual usage in an openstack.common module: Usual usage in an openstack.common module:
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
""" """
import copy import copy
@ -32,8 +32,8 @@ import UserString
from babel import localedata from babel import localedata
import six import six
_localedir = os.environ.get('neutronclient'.upper() + '_LOCALEDIR') _localedir = os.environ.get('tackerclient'.upper() + '_LOCALEDIR')
_t = gettext.translation('neutronclient', localedir=_localedir, fallback=True) _t = gettext.translation('tackerclient', localedir=_localedir, fallback=True)
_AVAILABLE_LANGUAGES = {} _AVAILABLE_LANGUAGES = {}
USE_LAZY = False USE_LAZY = False
@ -53,7 +53,7 @@ def enable_lazy():
def _(msg): def _(msg):
if USE_LAZY: if USE_LAZY:
return Message(msg, 'neutronclient') return Message(msg, 'tackerclient')
else: else:
return _t.ugettext(msg) return _t.ugettext(msg)

View File

@ -19,7 +19,7 @@ Import related utilities and helper functions.
import sys import sys
import traceback import traceback
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
def import_class(import_str): def import_class(import_str):

View File

@ -51,10 +51,10 @@ else:
import six import six
import six.moves.xmlrpc_client as xmlrpclib import six.moves.xmlrpc_client as xmlrpclib
from neutronclient.openstack.common import gettextutils from tackerclient.openstack.common import gettextutils
from neutronclient.openstack.common import importutils from tackerclient.openstack.common import importutils
from neutronclient.openstack.common import strutils from tackerclient.openstack.common import strutils
from neutronclient.openstack.common import timeutils from tackerclient.openstack.common import timeutils
netaddr = importutils.try_import("netaddr") netaddr = importutils.try_import("netaddr")

View File

@ -23,7 +23,7 @@ import unicodedata
import six import six
from neutronclient.openstack.common.gettextutils import _ # noqa from tackerclient.openstack.common.gettextutils import _ # noqa
# Used for looking up extensions of text # Used for looking up extensions of text

View File

@ -14,21 +14,21 @@
# under the License. # under the License.
# #
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import utils from tackerclient.common import utils
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
API_NAME = 'network' API_NAME = 'network'
API_VERSIONS = { API_VERSIONS = {
'2.0': 'neutronclient.v2_0.client.Client', '1.0': 'tackerclient.v1_0.client.Client',
} }
def make_client(instance): def make_client(instance):
"""Returns an neutron client. """Returns an tacker client.
""" """
neutron_client = utils.get_client_class( tacker_client = utils.get_client_class(
API_NAME, API_NAME,
instance._api_version[API_NAME], instance._api_version[API_NAME],
API_VERSIONS, API_VERSIONS,
@ -36,17 +36,17 @@ def make_client(instance):
instance.initialize() instance.initialize()
url = instance._url url = instance._url
url = url.rstrip("/") url = url.rstrip("/")
if '2.0' == instance._api_version[API_NAME]: if '1.0' == instance._api_version[API_NAME]:
client = neutron_client(username=instance._username, client = tacker_client(username=instance._username,
tenant_name=instance._tenant_name, tenant_name=instance._tenant_name,
password=instance._password, password=instance._password,
region_name=instance._region_name, region_name=instance._region_name,
auth_url=instance._auth_url, auth_url=instance._auth_url,
endpoint_url=url, endpoint_url=url,
token=instance._token, token=instance._token,
auth_strategy=instance._auth_strategy, auth_strategy=instance._auth_strategy,
insecure=instance._insecure, insecure=instance._insecure,
ca_cert=instance._ca_cert) ca_cert=instance._ca_cert)
return client return client
else: else:
raise exceptions.UnsupportedVersion(_("API version %s is not " raise exceptions.UnsupportedVersion(_("API version %s is not "
@ -55,12 +55,12 @@ def make_client(instance):
def Client(api_version, *args, **kwargs): def Client(api_version, *args, **kwargs):
"""Return an neutron client. """Return an tacker client.
@param api_version: only 2.0 is supported now @param api_version: only 1.0 is supported now
""" """
neutron_client = utils.get_client_class( tacker_client = utils.get_client_class(
API_NAME, API_NAME,
api_version, api_version,
API_VERSIONS, API_VERSIONS,
) )
return neutron_client(*args, **kwargs) return tacker_client(*args, **kwargs)

View File

@ -26,10 +26,10 @@ from cliff import lister
from cliff import show from cliff import show
import six import six
from neutronclient.common import command from tackerclient.common import command
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import utils from tackerclient.common import utils
from neutronclient.openstack.common.gettextutils import _ from tackerclient.openstack.common.gettextutils import _
HEX_ELEM = '[0-9A-Fa-f]' HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}', UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
@ -59,7 +59,7 @@ def find_resourceid_by_id(client, resource, resource_id):
"'%(id)s'") % "'%(id)s'") %
{'resource': resource, 'id': resource_id}) {'resource': resource, 'id': resource_id})
# 404 is used to simulate server side behavior # 404 is used to simulate server side behavior
raise exceptions.NeutronClientException( raise exceptions.TackerClientException(
message=not_found_message, status_code=404) message=not_found_message, status_code=404)
@ -70,14 +70,14 @@ def _find_resourceid_by_name(client, resource, name):
collection = resource_plural collection = resource_plural
info = data[collection] info = data[collection]
if len(info) > 1: if len(info) > 1:
raise exceptions.NeutronClientNoUniqueMatch(resource=resource, raise exceptions.TackerClientNoUniqueMatch(resource=resource,
name=name) name=name)
elif len(info) == 0: elif len(info) == 0:
not_found_message = (_("Unable to find %(resource)s with name " not_found_message = (_("Unable to find %(resource)s with name "
"'%(name)s'") % "'%(name)s'") %
{'resource': resource, 'name': name}) {'resource': resource, 'name': name})
# 404 is used to simulate server side behavior # 404 is used to simulate server side behavior
raise exceptions.NeutronClientException( raise exceptions.TackerClientException(
message=not_found_message, status_code=404) message=not_found_message, status_code=404)
else: else:
return info[0]['id'] return info[0]['id']
@ -86,7 +86,7 @@ def _find_resourceid_by_name(client, resource, name):
def find_resourceid_by_name_or_id(client, resource, name_or_id): def find_resourceid_by_name_or_id(client, resource, name_or_id):
try: try:
return find_resourceid_by_id(client, resource, name_or_id) return find_resourceid_by_id(client, resource, name_or_id)
except exceptions.NeutronClientException: except exceptions.TackerClientException:
return _find_resourceid_by_name(client, resource, name_or_id) return _find_resourceid_by_name(client, resource, name_or_id)
@ -182,7 +182,7 @@ def parse_args_to_dict(values_specs):
Besides known options and arguments, our commands also support user to Besides known options and arguments, our commands also support user to
put more options to the end of command line. For example, put more options to the end of command line. For example,
list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1' list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1'
is extra options to our list_nets. This feature can support V2.0 API's is extra options to our list_nets. This feature can support V1.0 API's
fields selection and filters. For example, to list networks which has name fields selection and filters. For example, to list networks which has name
'test4', we can have list_nets -- --name=test4. 'test4', we can have list_nets -- --name=test4.
@ -327,7 +327,7 @@ def update_dict(obj, dict, attributes):
class TableFormater(table.TableFormatter): class TableFormater(table.TableFormatter):
"""This class is used to keep consistency with prettytable 0.6. """This class is used to keep consistency with prettytable 0.6.
https://bugs.launchpad.net/python-neutronclient/+bug/1165962 https://bugs.launchpad.net/python-tackerclient/+bug/1165962
""" """
def emit_list(self, column_names, data, stdout, parsed_args): def emit_list(self, column_names, data, stdout, parsed_args):
if column_names: if column_names:
@ -340,35 +340,35 @@ class TableFormater(table.TableFormatter):
# command.OpenStackCommand is abstract class so that metaclass of # command.OpenStackCommand is abstract class so that metaclass of
# subclass must be subclass of metaclass of all its base. # subclass must be subclass of metaclass of all its base.
# otherwise metaclass conflict exception is raised. # otherwise metaclass conflict exception is raised.
class NeutronCommandMeta(abc.ABCMeta): class TackerCommandMeta(abc.ABCMeta):
def __new__(cls, name, bases, cls_dict): def __new__(cls, name, bases, cls_dict):
if 'log' not in cls_dict: if 'log' not in cls_dict:
cls_dict['log'] = logging.getLogger( cls_dict['log'] = logging.getLogger(
cls_dict['__module__'] + '.' + name) cls_dict['__module__'] + '.' + name)
return super(NeutronCommandMeta, cls).__new__(cls, return super(TackerCommandMeta, cls).__new__(cls,
name, bases, cls_dict) name, bases, cls_dict)
@six.add_metaclass(NeutronCommandMeta) @six.add_metaclass(TackerCommandMeta)
class NeutronCommand(command.OpenStackCommand): class TackerCommand(command.OpenStackCommand):
api = 'network' api = 'network'
values_specs = [] values_specs = []
json_indent = None json_indent = None
def __init__(self, app, app_args): def __init__(self, app, app_args):
super(NeutronCommand, self).__init__(app, app_args) super(TackerCommand, self).__init__(app, app_args)
# NOTE(markmcclain): This is no longer supported in cliff version 1.5.2 # NOTE(markmcclain): This is no longer supported in cliff version 1.5.2
# see https://bugs.launchpad.net/python-neutronclient/+bug/1265926 # see https://bugs.launchpad.net/python-tackerclient/+bug/1265926
#if hasattr(self, 'formatters'): #if hasattr(self, 'formatters'):
#self.formatters['table'] = TableFormater() #self.formatters['table'] = TableFormater()
def get_client(self): def get_client(self):
return self.app.client_manager.neutron return self.app.client_manager.tacker
def get_parser(self, prog_name): def get_parser(self, prog_name):
parser = super(NeutronCommand, self).get_parser(prog_name) parser = super(TackerCommand, self).get_parser(prog_name)
parser.add_argument( parser.add_argument(
'--request-format', '--request-format',
help=_('The xml or json request format'), help=_('The xml or json request format'),
@ -403,7 +403,7 @@ class NeutronCommand(command.OpenStackCommand):
return {} return {}
class CreateCommand(NeutronCommand, show.ShowOne): class CreateCommand(TackerCommand, show.ShowOne):
"""Create a resource for a given tenant """Create a resource for a given tenant
""" """
@ -425,14 +425,14 @@ class CreateCommand(NeutronCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)' % parsed_args) self.log.debug('get_data(%s)' % parsed_args)
neutron_client = self.get_client() tacker_client = self.get_client()
neutron_client.format = parsed_args.request_format tacker_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
body = self.args2body(parsed_args) body = self.args2body(parsed_args)
body[self.resource].update(_extra_values) body[self.resource].update(_extra_values)
obj_creator = getattr(neutron_client, obj_creator = getattr(tacker_client,
"create_%s" % self.resource) "create_%s" % self.resource)
data = obj_creator(body) data = obj_creator(body)
self.format_output_data(data) self.format_output_data(data)
@ -446,7 +446,7 @@ class CreateCommand(NeutronCommand, show.ShowOne):
return zip(*sorted(info.iteritems())) return zip(*sorted(info.iteritems()))
class UpdateCommand(NeutronCommand): class UpdateCommand(TackerCommand):
"""Update resource's information """Update resource's information
""" """
@ -465,8 +465,8 @@ class UpdateCommand(NeutronCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)', parsed_args) self.log.debug('run(%s)', parsed_args)
neutron_client = self.get_client() tacker_client = self.get_client()
neutron_client.format = parsed_args.request_format tacker_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
@ -480,11 +480,11 @@ class UpdateCommand(NeutronCommand):
_("Must specify new values to update %s") % self.resource) _("Must specify new values to update %s") % self.resource)
if self.allow_names: if self.allow_names:
_id = find_resourceid_by_name_or_id( _id = find_resourceid_by_name_or_id(
neutron_client, self.resource, parsed_args.id) tacker_client, self.resource, parsed_args.id)
else: else:
_id = find_resourceid_by_id( _id = find_resourceid_by_id(
neutron_client, self.resource, parsed_args.id) tacker_client, self.resource, parsed_args.id)
obj_updator = getattr(neutron_client, obj_updator = getattr(tacker_client,
"update_%s" % self.resource) "update_%s" % self.resource)
obj_updator(_id, body) obj_updator(_id, body)
print((_('Updated %(resource)s: %(id)s') % print((_('Updated %(resource)s: %(id)s') %
@ -493,7 +493,7 @@ class UpdateCommand(NeutronCommand):
return return
class DeleteCommand(NeutronCommand): class DeleteCommand(TackerCommand):
"""Delete a given resource """Delete a given resource
""" """
@ -516,12 +516,12 @@ class DeleteCommand(NeutronCommand):
def run(self, parsed_args): def run(self, parsed_args):
self.log.debug('run(%s)', parsed_args) self.log.debug('run(%s)', parsed_args)
neutron_client = self.get_client() tacker_client = self.get_client()
neutron_client.format = parsed_args.request_format tacker_client.format = parsed_args.request_format
obj_deleter = getattr(neutron_client, obj_deleter = getattr(tacker_client,
"delete_%s" % self.resource) "delete_%s" % self.resource)
if self.allow_names: if self.allow_names:
_id = find_resourceid_by_name_or_id(neutron_client, self.resource, _id = find_resourceid_by_name_or_id(tacker_client, self.resource,
parsed_args.id) parsed_args.id)
else: else:
_id = parsed_args.id _id = parsed_args.id
@ -533,7 +533,7 @@ class DeleteCommand(NeutronCommand):
return return
class ListCommand(NeutronCommand, lister.Lister): class ListCommand(TackerCommand, lister.Lister):
"""List resources that belong to a given tenant """List resources that belong to a given tenant
""" """
@ -565,16 +565,16 @@ class ListCommand(NeutronCommand, lister.Lister):
search_opts.update({'verbose': 'True'}) search_opts.update({'verbose': 'True'})
return search_opts return search_opts
def call_server(self, neutron_client, search_opts, parsed_args): def call_server(self, tacker_client, search_opts, parsed_args):
resource_plural = _get_resource_plural(self.resource, neutron_client) resource_plural = _get_resource_plural(self.resource, tacker_client)
obj_lister = getattr(neutron_client, "list_%s" % resource_plural) obj_lister = getattr(tacker_client, "list_%s" % resource_plural)
data = obj_lister(**search_opts) data = obj_lister(**search_opts)
return data return data
def retrieve_list(self, parsed_args): def retrieve_list(self, parsed_args):
"""Retrieve a list of resources from Neutron server""" """Retrieve a list of resources from Tacker server"""
neutron_client = self.get_client() tacker_client = self.get_client()
neutron_client.format = parsed_args.request_format tacker_client.format = parsed_args.request_format
_extra_values = parse_args_to_dict(self.values_specs) _extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values, _merge_args(self, parsed_args, _extra_values,
self.values_specs) self.values_specs)
@ -596,15 +596,15 @@ class ListCommand(NeutronCommand, lister.Lister):
dirs = dirs[:len(keys)] dirs = dirs[:len(keys)]
if dirs: if dirs:
search_opts.update({'sort_dir': dirs}) search_opts.update({'sort_dir': dirs})
data = self.call_server(neutron_client, search_opts, parsed_args) data = self.call_server(tacker_client, search_opts, parsed_args)
collection = _get_resource_plural(self.resource, neutron_client) collection = _get_resource_plural(self.resource, tacker_client)
return data.get(collection, []) return data.get(collection, [])
def extend_list(self, data, parsed_args): def extend_list(self, data, parsed_args):
"""Update a retrieved list. """Update a retrieved list.
This method provides a way to modify a original list returned from This method provides a way to modify a original list returned from
the neutron server. For example, you can add subnet cidr information the tacker server. For example, you can add subnet cidr information
to a list network. to a list network.
""" """
pass pass
@ -632,7 +632,7 @@ class ListCommand(NeutronCommand, lister.Lister):
return self.setup_columns(data, parsed_args) return self.setup_columns(data, parsed_args)
class ShowCommand(NeutronCommand, show.ShowOne): class ShowCommand(TackerCommand, show.ShowOne):
"""Show information of a given resource """Show information of a given resource
""" """
@ -656,8 +656,8 @@ class ShowCommand(NeutronCommand, show.ShowOne):
def get_data(self, parsed_args): def get_data(self, parsed_args):
self.log.debug('get_data(%s)', parsed_args) self.log.debug('get_data(%s)', parsed_args)
neutron_client = self.get_client() tacker_client = self.get_client()
neutron_client.format = parsed_args.request_format tacker_client.format = parsed_args.request_format
params = {} params = {}
if parsed_args.show_details: if parsed_args.show_details:
@ -665,12 +665,12 @@ class ShowCommand(NeutronCommand, show.ShowOne):
if parsed_args.fields: if parsed_args.fields:
params = {'fields': parsed_args.fields} params = {'fields': parsed_args.fields}
if self.allow_names: if self.allow_names:
_id = find_resourceid_by_name_or_id(neutron_client, self.resource, _id = find_resourceid_by_name_or_id(tacker_client, self.resource,
parsed_args.id) parsed_args.id)
else: else:
_id = parsed_args.id _id = parsed_args.id
obj_shower = getattr(neutron_client, "show_%s" % self.resource) obj_shower = getattr(tacker_client, "show_%s" % self.resource)
data = obj_shower(_id, **params) data = obj_shower(_id, **params)
self.format_output_data(data) self.format_output_data(data)
resource = data[self.resource] resource = data[self.resource]

View File

@ -0,0 +1,40 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# Licensed 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 tackerclient.openstack.common.gettextutils import _
from tackerclient.tacker import v1_0 as cmd_base
class ListExt(cmd_base.ListCommand):
"""List all extensions."""
resource = 'extension'
list_columns = ['alias', 'name']
class ShowExt(cmd_base.ShowCommand):
"""Show information of a given resource."""
resource = "extension"
allow_names = False
def get_parser(self, prog_name):
parser = super(cmd_base.ShowCommand, self).get_parser(prog_name)
cmd_base.add_show_list_common_argument(parser)
parser.add_argument(
'id', metavar='EXT-ALIAS',
help=_('The extension alias'))
return parser

View File

@ -23,9 +23,9 @@ import mox
import requests import requests
import testtools import testtools
from neutronclient import client from tackerclient import client
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import utils from tackerclient.common import utils
USERNAME = 'testuser' USERNAME = 'testuser'
@ -53,7 +53,7 @@ KS_TOKEN_RESULT = {
'publicURL': ENDPOINT_URL, 'publicURL': ENDPOINT_URL,
'region': REGION}], 'region': REGION}],
'type': 'network', 'type': 'network',
'name': 'Neutron Service'} 'name': 'Tacker Service'}
] ]
} }
} }
@ -61,7 +61,7 @@ KS_TOKEN_RESULT = {
ENDPOINTS_RESULT = { ENDPOINTS_RESULT = {
'endpoints': [{ 'endpoints': [{
'type': 'network', 'type': 'network',
'name': 'Neutron Service', 'name': 'Tacker Service',
'region': REGION, 'region': REGION,
'adminURL': ENDPOINT_URL, 'adminURL': ENDPOINT_URL,
'internalURL': ENDPOINT_URL, 'internalURL': ENDPOINT_URL,
@ -170,7 +170,7 @@ class CLITestAuthKeystone(testtools.TestCase):
res200 = get_response(200) res200 = get_response(200)
res401 = get_response(401) res401 = get_response(401)
# If a token is expired, neutron server retruns 401 # If a token is expired, tacker server retruns 401
self.client.request( self.client.request(
mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', mox.StrContains(ENDPOINT_URL + '/resource'), 'GET',
headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)
@ -195,7 +195,7 @@ class CLITestAuthKeystone(testtools.TestCase):
res401 = get_response(401) res401 = get_response(401)
# If a token is expired, neutron server returns 401 # If a token is expired, tacker server returns 401
self.client.request( self.client.request(
mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', mox.StrContains(ENDPOINT_URL + '/resource'), 'GET',
headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN)

View File

@ -16,104 +16,104 @@
import testtools import testtools
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.neutron import v2_0 as neutronV20 from tackerclient.tacker import v1_0 as tackerV10
class CLITestArgs(testtools.TestCase): class CLITestArgs(testtools.TestCase):
def test_empty(self): def test_empty(self):
_mydict = neutronV20.parse_args_to_dict([]) _mydict = tackerV10.parse_args_to_dict([])
self.assertEqual({}, _mydict) self.assertEqual({}, _mydict)
def test_default_bool(self): def test_default_bool(self):
_specs = ['--my_bool', '--arg1', 'value1'] _specs = ['--my_bool', '--arg1', 'value1']
_mydict = neutronV20.parse_args_to_dict(_specs) _mydict = tackerV10.parse_args_to_dict(_specs)
self.assertTrue(_mydict['my_bool']) self.assertTrue(_mydict['my_bool'])
def test_bool_true(self): def test_bool_true(self):
_specs = ['--my-bool', 'type=bool', 'true', '--arg1', 'value1'] _specs = ['--my-bool', 'type=bool', 'true', '--arg1', 'value1']
_mydict = neutronV20.parse_args_to_dict(_specs) _mydict = tackerV10.parse_args_to_dict(_specs)
self.assertTrue(_mydict['my_bool']) self.assertTrue(_mydict['my_bool'])
def test_bool_false(self): def test_bool_false(self):
_specs = ['--my_bool', 'type=bool', 'false', '--arg1', 'value1'] _specs = ['--my_bool', 'type=bool', 'false', '--arg1', 'value1']
_mydict = neutronV20.parse_args_to_dict(_specs) _mydict = tackerV10.parse_args_to_dict(_specs)
self.assertFalse(_mydict['my_bool']) self.assertFalse(_mydict['my_bool'])
def test_nargs(self): def test_nargs(self):
_specs = ['--tag', 'x', 'y', '--arg1', 'value1'] _specs = ['--tag', 'x', 'y', '--arg1', 'value1']
_mydict = neutronV20.parse_args_to_dict(_specs) _mydict = tackerV10.parse_args_to_dict(_specs)
self.assertIn('x', _mydict['tag']) self.assertIn('x', _mydict['tag'])
self.assertIn('y', _mydict['tag']) self.assertIn('y', _mydict['tag'])
def test_badarg(self): def test_badarg(self):
_specs = ['--tag=t', 'x', 'y', '--arg1', 'value1'] _specs = ['--tag=t', 'x', 'y', '--arg1', 'value1']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
def test_badarg_with_minus(self): def test_badarg_with_minus(self):
_specs = ['--arg1', 'value1', '-D'] _specs = ['--arg1', 'value1', '-D']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
def test_goodarg_with_minus_number(self): def test_goodarg_with_minus_number(self):
_specs = ['--arg1', 'value1', '-1', '-1.0'] _specs = ['--arg1', 'value1', '-1', '-1.0']
_mydict = neutronV20.parse_args_to_dict(_specs) _mydict = tackerV10.parse_args_to_dict(_specs)
self.assertEqual(['value1', '-1', '-1.0'], self.assertEqual(['value1', '-1', '-1.0'],
_mydict['arg1']) _mydict['arg1'])
def test_badarg_duplicate(self): def test_badarg_duplicate(self):
_specs = ['--tag=t', '--arg1', 'value1', '--arg1', 'value1'] _specs = ['--tag=t', '--arg1', 'value1', '--arg1', 'value1']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
def test_badarg_early_type_specification(self): def test_badarg_early_type_specification(self):
_specs = ['type=dict', 'key=value'] _specs = ['type=dict', 'key=value']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
def test_arg(self): def test_arg(self):
_specs = ['--tag=t', '--arg1', 'value1'] _specs = ['--tag=t', '--arg1', 'value1']
self.assertEqual('value1', self.assertEqual('value1',
neutronV20.parse_args_to_dict(_specs)['arg1']) tackerV10.parse_args_to_dict(_specs)['arg1'])
def test_dict_arg(self): def test_dict_arg(self):
_specs = ['--tag=t', '--arg1', 'type=dict', 'key1=value1,key2=value2'] _specs = ['--tag=t', '--arg1', 'type=dict', 'key1=value1,key2=value2']
arg1 = neutronV20.parse_args_to_dict(_specs)['arg1'] arg1 = tackerV10.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1['key1']) self.assertEqual('value1', arg1['key1'])
self.assertEqual('value2', arg1['key2']) self.assertEqual('value2', arg1['key2'])
def test_dict_arg_with_attribute_named_type(self): def test_dict_arg_with_attribute_named_type(self):
_specs = ['--tag=t', '--arg1', 'type=dict', 'type=value1,key2=value2'] _specs = ['--tag=t', '--arg1', 'type=dict', 'type=value1,key2=value2']
arg1 = neutronV20.parse_args_to_dict(_specs)['arg1'] arg1 = tackerV10.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1['type']) self.assertEqual('value1', arg1['type'])
self.assertEqual('value2', arg1['key2']) self.assertEqual('value2', arg1['key2'])
def test_list_of_dict_arg(self): def test_list_of_dict_arg(self):
_specs = ['--tag=t', '--arg1', 'type=dict', _specs = ['--tag=t', '--arg1', 'type=dict',
'list=true', 'key1=value1,key2=value2'] 'list=true', 'key1=value1,key2=value2']
arg1 = neutronV20.parse_args_to_dict(_specs)['arg1'] arg1 = tackerV10.parse_args_to_dict(_specs)['arg1']
self.assertEqual('value1', arg1[0]['key1']) self.assertEqual('value1', arg1[0]['key1'])
self.assertEqual('value2', arg1[0]['key2']) self.assertEqual('value2', arg1[0]['key2'])
def test_clear_action(self): def test_clear_action(self):
_specs = ['--anyarg', 'action=clear'] _specs = ['--anyarg', 'action=clear']
args = neutronV20.parse_args_to_dict(_specs) args = tackerV10.parse_args_to_dict(_specs)
self.assertIsNone(args['anyarg']) self.assertIsNone(args['anyarg'])
def test_bad_values_str(self): def test_bad_values_str(self):
_specs = ['--strarg', 'type=str'] _specs = ['--strarg', 'type=str']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
def test_bad_values_list(self): def test_bad_values_list(self):
_specs = ['--listarg', 'list=true', 'type=str'] _specs = ['--listarg', 'list=true', 'type=str']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
_specs = ['--listarg', 'type=list'] _specs = ['--listarg', 'type=list']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)
_specs = ['--listarg', 'type=list', 'action=clear'] _specs = ['--listarg', 'type=list', 'action=clear']
self.assertRaises(exceptions.CommandError, self.assertRaises(exceptions.CommandError,
neutronV20.parse_args_to_dict, _specs) tackerV10.parse_args_to_dict, _specs)

View File

@ -23,13 +23,13 @@ import mox
import sys import sys
import testtools import testtools
from neutronclient.common import constants from tackerclient.common import constants
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.neutron import v2_0 as neutronV2_0 from tackerclient import shell
from neutronclient import shell from tackerclient.tacker import v1_0 as tackerV1_0
from neutronclient.v2_0 import client from tackerclient.v1_0 import client
API_VERSION = "2.0" API_VERSION = "1.0"
FORMAT = 'json' FORMAT = 'json'
TOKEN = 'testtoken' TOKEN = 'testtoken'
ENDURL = 'localurl' ENDURL = 'localurl'
@ -155,7 +155,7 @@ class MyComparator(mox.Comparator):
return str(self.lhs) return str(self.lhs)
class CLITestV20Base(testtools.TestCase): class CLITestV10Base(testtools.TestCase):
format = 'json' format = 'json'
test_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' test_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
@ -169,16 +169,16 @@ class CLITestV20Base(testtools.TestCase):
client.Client.EXTED_PLURALS.update(constants.PLURALS) client.Client.EXTED_PLURALS.update(constants.PLURALS)
client.Client.EXTED_PLURALS.update({'tags': 'tag'}) client.Client.EXTED_PLURALS.update({'tags': 'tag'})
return {'plurals': client.Client.EXTED_PLURALS, return {'plurals': client.Client.EXTED_PLURALS,
'xmlns': constants.XML_NS_V20, 'xmlns': constants.XML_NS_V10,
constants.EXT_NS: {'prefix': 'http://xxxx.yy.com'}} constants.EXT_NS: {'prefix': 'http://xxxx.yy.com'}}
def setUp(self, plurals={}): def setUp(self, plurals={}):
"""Prepare the test environment.""" """Prepare the test environment."""
super(CLITestV20Base, self).setUp() super(CLITestV10Base, self).setUp()
client.Client.EXTED_PLURALS.update(constants.PLURALS) client.Client.EXTED_PLURALS.update(constants.PLURALS)
client.Client.EXTED_PLURALS.update(plurals) client.Client.EXTED_PLURALS.update(plurals)
self.metadata = {'plurals': client.Client.EXTED_PLURALS, self.metadata = {'plurals': client.Client.EXTED_PLURALS,
'xmlns': constants.XML_NS_V20, 'xmlns': constants.XML_NS_V10,
constants.EXT_NS: {'prefix': constants.EXT_NS: {'prefix':
'http://xxxx.yy.com'}} 'http://xxxx.yy.com'}}
self.mox = mox.Mox() self.mox = mox.Mox()
@ -186,13 +186,13 @@ class CLITestV20Base(testtools.TestCase):
self.fake_stdout = FakeStdout() self.fake_stdout = FakeStdout()
self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.fake_stdout)) self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.fake_stdout))
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'neutronclient.neutron.v2_0.find_resourceid_by_name_or_id', 'tackerclient.tacker.v1_0.find_resourceid_by_name_or_id',
self._find_resourceid)) self._find_resourceid))
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'neutronclient.neutron.v2_0.find_resourceid_by_id', 'tackerclient.tacker.v1_0.find_resourceid_by_id',
self._find_resourceid)) self._find_resourceid))
self.useFixture(fixtures.MonkeyPatch( self.useFixture(fixtures.MonkeyPatch(
'neutronclient.v2_0.client.Client.get_attr_metadata', 'tackerclient.v1_0.client.Client.get_attr_metadata',
self._get_attr_metadata)) self._get_attr_metadata))
self.client = client.Client(token=TOKEN, endpoint_url=self.endurl) self.client = client.Client(token=TOKEN, endpoint_url=self.endurl)
@ -210,7 +210,9 @@ class CLITestV20Base(testtools.TestCase):
'credential', 'network_profile', 'credential', 'network_profile',
'policy_profile', 'ikepolicy', 'policy_profile', 'ikepolicy',
'ipsecpolicy', 'metering_label', 'ipsecpolicy', 'metering_label',
'metering_label_rule', 'net_partition'] 'metering_label_rule', 'net_partition',
'device_template', 'device',
'service_instance']
if (resource in non_admin_status_resources): if (resource in non_admin_status_resources):
body = {resource: {}, } body = {resource: {}, }
else: else:
@ -232,8 +234,8 @@ class CLITestV20Base(testtools.TestCase):
self.client.format = self.format self.client.format = self.format
resstr = self.client.serialize(ress) resstr = self.client.serialize(ress)
# url method body # url method body
resource_plural = neutronV2_0._get_resource_plural(resource, resource_plural = tackerV1_0._get_resource_plural(resource,
self.client) self.client)
path = getattr(self.client, resource_plural + "_path") path = getattr(self.client, resource_plural + "_path")
# Work around for LP #1217791. XML deserializer called from # Work around for LP #1217791. XML deserializer called from
# MyComparator does not decodes XML string correctly. # MyComparator does not decodes XML string correctly.
@ -502,7 +504,7 @@ class CLITestV20Base(testtools.TestCase):
self.assertIn(myid, _str) self.assertIn(myid, _str)
class ClientV2TestJson(CLITestV20Base): class ClientV1TestJson(CLITestV10Base):
def test_do_request_unicode(self): def test_do_request_unicode(self):
self.client.format = self.format self.client.format = self.format
self.mox.StubOutWithMock(self.client.httpclient, "request") self.mox.StubOutWithMock(self.client.httpclient, "request")
@ -551,7 +553,7 @@ class ClientV2TestJson(CLITestV20Base):
).AndReturn((MyResp(400, reason='An error'), '')) ).AndReturn((MyResp(400, reason='An error'), ''))
self.mox.ReplayAll() self.mox.ReplayAll()
error = self.assertRaises(exceptions.NeutronClientException, error = self.assertRaises(exceptions.TackerClientException,
self.client.do_request, 'PUT', '/test', self.client.do_request, 'PUT', '/test',
body='', params=params) body='', params=params)
self.assertEqual("An error", str(error)) self.assertEqual("An error", str(error))
@ -559,23 +561,23 @@ class ClientV2TestJson(CLITestV20Base):
self.mox.UnsetStubs() self.mox.UnsetStubs()
class ClientV2UnicodeTestXML(ClientV2TestJson): class ClientV1UnicodeTestXML(ClientV1TestJson):
format = 'xml' format = 'xml'
class CLITestV20ExceptionHandler(CLITestV20Base): class CLITestV10ExceptionHandler(CLITestV10Base):
def _test_exception_handler_v20( def _test_exception_handler_v10(
self, expected_exception, status_code, expected_msg, self, expected_exception, status_code, expected_msg,
error_type=None, error_msg=None, error_detail=None, error_type=None, error_msg=None, error_detail=None,
error_content=None): error_content=None):
if error_content is None: if error_content is None:
error_content = {'NeutronError': {'type': error_type, error_content = {'TackerError': {'type': error_type,
'message': error_msg, 'message': error_msg,
'detail': error_detail}} 'detail': error_detail}}
e = self.assertRaises(expected_exception, e = self.assertRaises(expected_exception,
client.exception_handler_v20, client.exception_handler_v10,
status_code, error_content) status_code, error_content)
self.assertEqual(status_code, e.status_code) self.assertEqual(status_code, e.status_code)
@ -586,14 +588,14 @@ class CLITestV20ExceptionHandler(CLITestV20Base):
expected_msg = error_msg expected_msg = error_msg
self.assertEqual(expected_msg, e.message) self.assertEqual(expected_msg, e.message)
def test_exception_handler_v20_ip_address_in_use(self): def test_exception_handler_v10_ip_address_in_use(self):
err_msg = ('Unable to complete operation for network ' err_msg = ('Unable to complete operation for network '
'fake-network-uuid. The IP address fake-ip is in use.') 'fake-network-uuid. The IP address fake-ip is in use.')
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.IpAddressInUseClient, 409, err_msg, exceptions.IpAddressInUseClient, 409, err_msg,
'IpAddressInUse', err_msg, '') 'IpAddressInUse', err_msg, '')
def test_exception_handler_v20_neutron_known_error(self): def test_exception_handler_v10_tacker_known_error(self):
known_error_map = [ known_error_map = [
('NetworkNotFound', exceptions.NetworkNotFoundClient, 404), ('NetworkNotFound', exceptions.NetworkNotFoundClient, 404),
('PortNotFound', exceptions.PortNotFoundClient, 404), ('PortNotFound', exceptions.PortNotFoundClient, 404),
@ -611,62 +613,62 @@ class CLITestV20ExceptionHandler(CLITestV20Base):
error_msg = 'dummy exception message' error_msg = 'dummy exception message'
error_detail = 'sample detail' error_detail = 'sample detail'
for server_exc, client_exc, status_code in known_error_map: for server_exc, client_exc, status_code in known_error_map:
self._test_exception_handler_v20( self._test_exception_handler_v10(
client_exc, status_code, client_exc, status_code,
error_msg + '\n' + error_detail, error_msg + '\n' + error_detail,
server_exc, error_msg, error_detail) server_exc, error_msg, error_detail)
def test_exception_handler_v20_neutron_known_error_without_detail(self): def test_exception_handler_v10_tacker_known_error_without_detail(self):
error_msg = 'Network not found' error_msg = 'Network not found'
error_detail = '' error_detail = ''
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NetworkNotFoundClient, 404, exceptions.NetworkNotFoundClient, 404,
error_msg, error_msg,
'NetworkNotFound', error_msg, error_detail) 'NetworkNotFound', error_msg, error_detail)
def test_exception_handler_v20_unknown_error_to_per_code_exception(self): def test_exception_handler_v10_unknown_error_to_per_code_exception(self):
for status_code, client_exc in exceptions.HTTP_EXCEPTION_MAP.items(): for status_code, client_exc in exceptions.HTTP_EXCEPTION_MAP.items():
error_msg = 'Unknown error' error_msg = 'Unknown error'
error_detail = 'This is detail' error_detail = 'This is detail'
self._test_exception_handler_v20( self._test_exception_handler_v10(
client_exc, status_code, client_exc, status_code,
error_msg + '\n' + error_detail, error_msg + '\n' + error_detail,
'UnknownError', error_msg, error_detail) 'UnknownError', error_msg, error_detail)
def test_exception_handler_v20_neutron_unknown_status_code(self): def test_exception_handler_v10_tacker_unknown_status_code(self):
error_msg = 'Unknown error' error_msg = 'Unknown error'
error_detail = 'This is detail' error_detail = 'This is detail'
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NeutronClientException, 501, exceptions.TackerClientException, 501,
error_msg + '\n' + error_detail, error_msg + '\n' + error_detail,
'UnknownError', error_msg, error_detail) 'UnknownError', error_msg, error_detail)
def test_exception_handler_v20_bad_neutron_error(self): def test_exception_handler_v10_bad_tacker_error(self):
error_content = {'NeutronError': {'unknown_key': 'UNKNOWN'}} error_content = {'TackerError': {'unknown_key': 'UNKNOWN'}}
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NeutronClientException, 500, exceptions.TackerClientException, 500,
expected_msg={'unknown_key': 'UNKNOWN'}, expected_msg={'unknown_key': 'UNKNOWN'},
error_content=error_content) error_content=error_content)
def test_exception_handler_v20_error_dict_contains_message(self): def test_exception_handler_v10_error_dict_contains_message(self):
error_content = {'message': 'This is an error message'} error_content = {'message': 'This is an error message'}
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NeutronClientException, 500, exceptions.TackerClientException, 500,
expected_msg='This is an error message', expected_msg='This is an error message',
error_content=error_content) error_content=error_content)
def test_exception_handler_v20_error_dict_not_contain_message(self): def test_exception_handler_v10_error_dict_not_contain_message(self):
error_content = {'error': 'This is an error message'} error_content = {'error': 'This is an error message'}
expected_msg = '%s-%s' % (500, error_content) expected_msg = '%s-%s' % (500, error_content)
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NeutronClientException, 500, exceptions.TackerClientException, 500,
expected_msg=expected_msg, expected_msg=expected_msg,
error_content=error_content) error_content=error_content)
def test_exception_handler_v20_default_fallback(self): def test_exception_handler_v10_default_fallback(self):
error_content = 'This is an error message' error_content = 'This is an error message'
expected_msg = '%s-%s' % (500, error_content) expected_msg = '%s-%s' % (500, error_content)
self._test_exception_handler_v20( self._test_exception_handler_v10(
exceptions.NeutronClientException, 500, exceptions.TackerClientException, 500,
expected_msg=expected_msg, expected_msg=expected_msg,
error_content=error_content) error_content=error_content)

View File

@ -15,13 +15,13 @@
import sys import sys
from neutronclient.neutron.v2_0.extension import ListExt from tackerclient.tacker.v1_0.extension import ListExt
from neutronclient.neutron.v2_0.extension import ShowExt from tackerclient.tacker.v1_0.extension import ShowExt
from neutronclient.tests.unit.test_cli20 import CLITestV20Base from tackerclient.tests.unit.test_cli10 import CLITestV10Base
from neutronclient.tests.unit.test_cli20 import MyApp from tackerclient.tests.unit.test_cli10 import MyApp
class CLITestV20Extension(CLITestV20Base): class CLITestV10Extension(CLITestV10Base):
id_field = 'alias' id_field = 'alias'
def test_list_extensions(self): def test_list_extensions(self):

View File

@ -23,20 +23,20 @@ import logging
import testtools import testtools
from testtools import helpers from testtools import helpers
from neutronclient.neutron import v2_0 as neutronV20 from tackerclient.tacker import v1_0 as tackerV10
class TestCommandMeta(testtools.TestCase): class TestCommandMeta(testtools.TestCase):
def test_neutron_command_meta_defines_log(self): def test_tacker_command_meta_defines_log(self):
class FakeCommand(neutronV20.NeutronCommand): class FakeCommand(tackerV10.TackerCommand):
pass pass
self.assertTrue(helpers.safe_hasattr(FakeCommand, 'log')) self.assertTrue(helpers.safe_hasattr(FakeCommand, 'log'))
self.assertIsInstance(FakeCommand.log, logging.getLoggerClass()) self.assertIsInstance(FakeCommand.log, logging.getLoggerClass())
self.assertEqual(FakeCommand.log.name, __name__ + ".FakeCommand") self.assertEqual(FakeCommand.log.name, __name__ + ".FakeCommand")
def test_neutron_command_log_defined_explicitly(self): def test_tacker_command_log_defined_explicitly(self):
class FakeCommand(neutronV20.NeutronCommand): class FakeCommand(tackerV10.TackerCommand):
log = None log = None
self.assertTrue(helpers.safe_hasattr(FakeCommand, 'log')) self.assertTrue(helpers.safe_hasattr(FakeCommand, 'log'))

View File

@ -16,15 +16,15 @@
import mox import mox
import testtools import testtools
from neutronclient.client import HTTPClient from tackerclient.client import HTTPClient
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.tests.unit.test_cli20 import MyResp from tackerclient.tests.unit.test_cli10 import MyResp
AUTH_TOKEN = 'test_token' AUTH_TOKEN = 'test_token'
END_URL = 'test_url' END_URL = 'test_url'
METHOD = 'GET' METHOD = 'GET'
URL = 'http://test.test:1234/v2.0/test' URL = 'http://test.test:1234/v1.0/test'
class TestHTTPClient(testtools.TestCase): class TestHTTPClient(testtools.TestCase):

View File

@ -25,17 +25,17 @@ import mox
import testtools import testtools
from testtools import matchers from testtools import matchers
from neutronclient.common import clientmanager from tackerclient.common import clientmanager
from neutronclient import shell as openstack_shell from tackerclient import shell as openstack_shell
DEFAULT_USERNAME = 'username' DEFAULT_USERNAME = 'username'
DEFAULT_PASSWORD = 'password' DEFAULT_PASSWORD = 'password'
DEFAULT_TENANT_ID = 'tenant_id' DEFAULT_TENANT_ID = 'tenant_id'
DEFAULT_TENANT_NAME = 'tenant_name' DEFAULT_TENANT_NAME = 'tenant_name'
DEFAULT_AUTH_URL = 'http://127.0.0.1:5000/v2.0/' DEFAULT_AUTH_URL = 'http://127.0.0.1:5000/v1.0/'
DEFAULT_TOKEN = '3bcc3d3a03f44e3d8377f9247b0ad155' DEFAULT_TOKEN = '3bcc3d3a03f44e3d8377f9247b0ad155'
DEFAULT_URL = 'http://quantum.example.org:9696/' DEFAULT_URL = 'http://tacker.example.org:8888/'
class ShellTest(testtools.TestCase): class ShellTest(testtools.TestCase):
@ -63,7 +63,7 @@ class ShellTest(testtools.TestCase):
try: try:
sys.stdout = cStringIO.StringIO() sys.stdout = cStringIO.StringIO()
sys.stderr = cStringIO.StringIO() sys.stderr = cStringIO.StringIO()
_shell = openstack_shell.NeutronShell('2.0') _shell = openstack_shell.TackerShell('1.0')
_shell.run(argstr.split()) _shell.run(argstr.split())
except SystemExit: except SystemExit:
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()
@ -93,8 +93,8 @@ class ShellTest(testtools.TestCase):
def test_help_on_subcommand(self): def test_help_on_subcommand(self):
required = [ required = [
'.*?^usage: .* quota-list'] '.*?^usage: .* device-template-list']
stdout, stderr = self.shell('help quota-list') stdout, stderr = self.shell('help device-template-list')
for r in required: for r in required:
self.assertThat( self.assertThat(
stdout, stdout,
@ -111,43 +111,44 @@ class ShellTest(testtools.TestCase):
def test_unknown_auth_strategy(self): def test_unknown_auth_strategy(self):
self.useFixture(fixtures.FakeLogger(level=logging.DEBUG)) self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
stdout, stderr = self.shell('--os-auth-strategy fake quota-list') stdout, stderr = self.shell('--os-auth-strategy fake '
'device-template-list')
self.assertFalse(stdout) self.assertFalse(stdout)
self.assertEqual('You must provide a service URL via ' self.assertEqual('You must provide a service URL via '
'either --os-url or env[OS_URL]', stderr.strip()) 'either --os-url or env[OS_URL]', stderr.strip())
def test_auth(self): def test_auth(self):
#import pdb; pdb.set_trace() #import pdb; pdb.set_trace()
neutron_shell = openstack_shell.NeutronShell('2.0') tacker_shell = openstack_shell.TackerShell('1.0')
self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.mox.UnsetStubs)
self.mox.StubOutWithMock(clientmanager.ClientManager, '__init__') self.mox.StubOutWithMock(clientmanager.ClientManager, '__init__')
self.mox.StubOutWithMock(neutron_shell, 'run_subcommand') self.mox.StubOutWithMock(tacker_shell, 'run_subcommand')
clientmanager.ClientManager.__init__( clientmanager.ClientManager.__init__(
token='', url='', auth_url='http://127.0.0.1:5000/', token='', url='', auth_url='http://127.0.0.1:5000/',
tenant_name='test', tenant_id='tenant_id', tenant_name='test', tenant_id='tenant_id',
username='test', user_id='', username='test', user_id='',
password='test', region_name='', api_version={'network': '2.0'}, password='test', region_name='', api_version={'network': '1.0'},
auth_strategy='keystone', service_type='network', auth_strategy='keystone', service_type='network',
endpoint_type='publicURL', insecure=False, ca_cert=None, endpoint_type='publicURL', insecure=False, ca_cert=None,
log_credentials=True) log_credentials=True)
neutron_shell.run_subcommand(['quota-list']) tacker_shell.run_subcommand(['device-template-list'])
self.mox.ReplayAll() self.mox.ReplayAll()
cmdline = ('--os-username test ' cmdline = ('--os-username test '
'--os-password test ' '--os-password test '
'--os-tenant-name test ' '--os-tenant-name test '
'--os-auth-url http://127.0.0.1:5000/ ' '--os-auth-url http://127.0.0.1:5000/ '
'--os-auth-strategy keystone quota-list') '--os-auth-strategy keystone device-template-list')
neutron_shell.run(cmdline.split()) tacker_shell.run(cmdline.split())
self.mox.VerifyAll() self.mox.VerifyAll()
def test_build_option_parser(self): def test_build_option_parser(self):
neutron_shell = openstack_shell.NeutronShell('2.0') tacker_shell = openstack_shell.TackerShell('1.0')
result = neutron_shell.build_option_parser('descr', '2.0') result = tacker_shell.build_option_parser('descr', '1.0')
self.assertEqual(True, isinstance(result, argparse.ArgumentParser)) self.assertEqual(True, isinstance(result, argparse.ArgumentParser))
def test_main_with_unicode(self): def test_main_with_unicode(self):
self.mox.StubOutClassWithMocks(openstack_shell, 'NeutronShell') self.mox.StubOutClassWithMocks(openstack_shell, 'TackerShell')
qshell_mock = openstack_shell.NeutronShell('2.0') qshell_mock = openstack_shell.TackerShell('1.0')
unicode_text = u'\u7f51\u7edc' unicode_text = u'\u7f51\u7edc'
argv = ['net-list', unicode_text, unicode_text.encode('utf-8')] argv = ['net-list', unicode_text, unicode_text.encode('utf-8')]
qshell_mock.run([u'net-list', unicode_text, qshell_mock.run([u'net-list', unicode_text,
@ -159,8 +160,8 @@ class ShellTest(testtools.TestCase):
self.assertEqual(ret, 0) self.assertEqual(ret, 0)
def test_endpoint_option(self): def test_endpoint_option(self):
shell = openstack_shell.NeutronShell('2.0') shell = openstack_shell.TackerShell('1.0')
parser = shell.build_option_parser('descr', '2.0') parser = shell.build_option_parser('descr', '1.0')
# Neither $OS_ENDPOINT_TYPE nor --endpoint-type # Neither $OS_ENDPOINT_TYPE nor --endpoint-type
namespace = parser.parse_args([]) namespace = parser.parse_args([])
@ -175,8 +176,8 @@ class ShellTest(testtools.TestCase):
"public") "public")
self.useFixture(fixture) self.useFixture(fixture)
shell = openstack_shell.NeutronShell('2.0') shell = openstack_shell.TackerShell('1.0')
parser = shell.build_option_parser('descr', '2.0') parser = shell.build_option_parser('descr', '1.0')
# $OS_ENDPOINT_TYPE but not --endpoint-type # $OS_ENDPOINT_TYPE but not --endpoint-type
namespace = parser.parse_args([]) namespace = parser.parse_args([])

View File

@ -18,16 +18,16 @@ import mox
import requests import requests
import testtools import testtools
from neutronclient.client import HTTPClient from tackerclient.client import HTTPClient
from neutronclient.common.clientmanager import ClientManager from tackerclient.common.clientmanager import ClientManager
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient import shell as openstack_shell from tackerclient import shell as openstack_shell
AUTH_TOKEN = 'test_token' AUTH_TOKEN = 'test_token'
END_URL = 'test_url' END_URL = 'test_url'
METHOD = 'GET' METHOD = 'GET'
URL = 'http://test.test:1234/v2.0/' URL = 'http://test.test:1234/v1.0/'
CA_CERT = '/tmp/test/path' CA_CERT = '/tmp/test/path'
@ -43,7 +43,7 @@ class TestSSL(testtools.TestCase):
def test_ca_cert_passed(self): def test_ca_cert_passed(self):
self.mox.StubOutWithMock(ClientManager, '__init__') self.mox.StubOutWithMock(ClientManager, '__init__')
self.mox.StubOutWithMock(openstack_shell.NeutronShell, 'interact') self.mox.StubOutWithMock(openstack_shell.TackerShell, 'interact')
ClientManager.__init__( ClientManager.__init__(
ca_cert=CA_CERT, ca_cert=CA_CERT,
@ -64,17 +64,17 @@ class TestSSL(testtools.TestCase):
user_id=mox.IgnoreArg(), user_id=mox.IgnoreArg(),
log_credentials=mox.IgnoreArg(), log_credentials=mox.IgnoreArg(),
) )
openstack_shell.NeutronShell.interact().AndReturn(0) openstack_shell.TackerShell.interact().AndReturn(0)
self.mox.ReplayAll() self.mox.ReplayAll()
openstack_shell.NeutronShell('2.0').run(['--os-cacert', CA_CERT]) openstack_shell.TackerShell('1.0').run(['--os-cacert', CA_CERT])
self.mox.VerifyAll() self.mox.VerifyAll()
def test_ca_cert_passed_as_env_var(self): def test_ca_cert_passed_as_env_var(self):
self.useFixture(fixtures.EnvironmentVariable('OS_CACERT', CA_CERT)) self.useFixture(fixtures.EnvironmentVariable('OS_CACERT', CA_CERT))
self.mox.StubOutWithMock(ClientManager, '__init__') self.mox.StubOutWithMock(ClientManager, '__init__')
self.mox.StubOutWithMock(openstack_shell.NeutronShell, 'interact') self.mox.StubOutWithMock(openstack_shell.TackerShell, 'interact')
ClientManager.__init__( ClientManager.__init__(
ca_cert=CA_CERT, ca_cert=CA_CERT,
@ -95,10 +95,10 @@ class TestSSL(testtools.TestCase):
user_id=mox.IgnoreArg(), user_id=mox.IgnoreArg(),
log_credentials=mox.IgnoreArg(), log_credentials=mox.IgnoreArg(),
) )
openstack_shell.NeutronShell.interact().AndReturn(0) openstack_shell.TackerShell.interact().AndReturn(0)
self.mox.ReplayAll() self.mox.ReplayAll()
openstack_shell.NeutronShell('2.0').run([]) openstack_shell.TackerShell('1.0').run([])
self.mox.VerifyAll() self.mox.VerifyAll()
def test_client_manager_properly_creates_httpclient_instance(self): def test_client_manager_properly_creates_httpclient_instance(self):
@ -118,11 +118,11 @@ class TestSSL(testtools.TestCase):
) )
self.mox.ReplayAll() self.mox.ReplayAll()
version = {'network': '2.0'} version = {'network': '1.0'}
ClientManager(ca_cert=CA_CERT, ClientManager(ca_cert=CA_CERT,
api_version=version, api_version=version,
url=END_URL, url=END_URL,
token=AUTH_TOKEN).neutron token=AUTH_TOKEN).tacker
self.mox.VerifyAll() self.mox.VerifyAll()
def test_proper_exception_is_raised_when_cert_validation_fails(self): def test_proper_exception_is_raised_when_cert_validation_fails(self):

View File

@ -18,8 +18,8 @@ import sys
import testtools import testtools
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import utils from tackerclient.common import utils
class TestUtils(testtools.TestCase): class TestUtils(testtools.TestCase):

View File

@ -15,8 +15,8 @@
import testtools import testtools
from neutronclient.common import exceptions from tackerclient.common import exceptions
from neutronclient.common import validators from tackerclient.common import validators
class FakeParsedArgs(): class FakeParsedArgs():

View File

@ -19,4 +19,4 @@
import pbr.version import pbr.version
__version__ = pbr.version.VersionInfo('python-neutronclient').version_string() __version__ = pbr.version.VersionInfo('python-tackerclient').version_string()