From fa43d08dcb30183b7b0c3a70dbd833893d0e60ce Mon Sep 17 00:00:00 2001 From: Maru Newby Date: Fri, 13 Apr 2012 17:03:05 -0700 Subject: [PATCH] Clean up codebase in accordance with HACKING/PEP8. * Adds HACKING.rst * Addresses 981208 Change-Id: I3d701ca9a748a0c4ceada7d76a31dc6bb2d5969b --- HACKING.rst | 187 +++++++++++++++++ quantumclient/__init__.py | 40 ++-- quantumclient/cli.py | 211 +++++++++++-------- quantumclient/cli_lib.py | 233 +++++++++++++-------- quantumclient/common/serializer.py | 2 +- quantumclient/tests/unit/test_cli.py | 29 ++- quantumclient/tests/unit/test_clientlib.py | 88 ++++---- 7 files changed, 539 insertions(+), 251 deletions(-) create mode 100644 HACKING.rst diff --git a/HACKING.rst b/HACKING.rst new file mode 100644 index 000000000..d99a07f9a --- /dev/null +++ b/HACKING.rst @@ -0,0 +1,187 @@ +QuantumClient Style Commandments +================================ + +- Step 1: Read http://www.python.org/dev/peps/pep-0008/ +- Step 2: Read http://www.python.org/dev/peps/pep-0008/ again +- Step 3: Read on + + +General +------- +- Put two newlines between top-level code (funcs, classes, etc) +- Put one newline between methods in classes and anywhere else +- Do not write "except:", use "except Exception:" at the very least +- Include your name with TODOs as in "#TODO(termie)" +- Do not shadow a built-in or reserved word. Example:: + + def list(): + return [1, 2, 3] + + mylist = list() # BAD, shadows `list` built-in + + class Foo(object): + def list(self): + return [1, 2, 3] + + mylist = Foo().list() # OKAY, does not shadow built-in + + +Imports +------- +- Do not make relative imports +- Order your imports by the full module path +- Organize your imports according to the following template + +Example:: + + # vim: tabstop=4 shiftwidth=4 softtabstop=4 + {{stdlib imports in human alphabetical order}} + \n + {{third-party lib imports in human alphabetical order}} + \n + {{quantum imports in human alphabetical order}} + \n + \n + {{begin your code}} + + +Human Alphabetical Order Examples +--------------------------------- +Example:: + + import httplib + import logging + import random + import StringIO + import time + import unittest + + import eventlet + import webob.exc + + import quantum.api.networks + from quantum.api import ports + from quantum.db import models + from quantum.extensions import multiport + import quantum.manager + from quantum import service + + +Docstrings +---------- +Example:: + + """A one line docstring looks like this and ends in a period.""" + + + """A multiline docstring has a one-line summary, less than 80 characters. + + Then a new paragraph after a newline that explains in more detail any + general information about the function, class or method. Example usages + are also great to have here if it is a complex class for function. + + When writing the docstring for a class, an extra line should be placed + after the closing quotations. For more in-depth explanations for these + decisions see http://www.python.org/dev/peps/pep-0257/ + + If you are going to describe parameters and return values, use Sphinx, the + appropriate syntax is as follows. + + :param foo: the foo parameter + :param bar: the bar parameter + :returns: return_type -- description of the return value + :returns: description of the return value + :raises: AttributeError, KeyError + """ + + +Dictionaries/Lists +------------------ +If a dictionary (dict) or list object is longer than 80 characters, its items +should be split with newlines. Embedded iterables should have their items +indented. Additionally, the last item in the dictionary should have a trailing +comma. This increases readability and simplifies future diffs. + +Example:: + + my_dictionary = { + "image": { + "name": "Just a Snapshot", + "size": 2749573, + "properties": { + "user_id": 12, + "arch": "x86_64", + }, + "things": [ + "thing_one", + "thing_two", + ], + "status": "ACTIVE", + }, + } + + +Calling Methods +--------------- +Calls to methods 80 characters or longer should format each argument with +newlines. This is not a requirement, but a guideline:: + + unnecessarily_long_function_name('string one', + 'string two', + kwarg1=constants.ACTIVE, + kwarg2=['a', 'b', 'c']) + + +Rather than constructing parameters inline, it is better to break things up:: + + list_of_strings = [ + 'what_a_long_string', + 'not as long', + ] + + dict_of_numbers = { + 'one': 1, + 'two': 2, + 'twenty four': 24, + } + + object_one.call_a_method('string three', + 'string four', + kwarg1=list_of_strings, + kwarg2=dict_of_numbers) + + +Internationalization (i18n) Strings +----------------------------------- +In order to support multiple languages, we have a mechanism to support +automatic translations of exception and log strings. + +Example:: + + msg = _("An error occurred") + raise HTTPBadRequest(explanation=msg) + +If you have a variable to place within the string, first internationalize the +template string then do the replacement. + +Example:: + + msg = _("Missing parameter: %s") % ("flavor",) + LOG.error(msg) + +If you have multiple variables to place in the string, use keyword parameters. +This helps our translators reorder parameters when needed. + +Example:: + + msg = _("The server with id %(s_id)s has no key %(m_key)s") + LOG.error(msg % {"s_id": "1234", "m_key": "imageId"}) + + +Creating Unit Tests +------------------- +For every new feature, unit tests should be created that both test and +(implicitly) document the usage of said feature. If submitting a patch for a +bug that had no unit test, a new passing unit test should be added. If a +submitted bug fix does have a unit test, be sure to add a new one that fails +without the patch and passes with the patch. diff --git a/quantumclient/__init__.py b/quantumclient/__init__.py index b7e0f504c..056e0dccc 100644 --- a/quantumclient/__init__.py +++ b/quantumclient/__init__.py @@ -16,9 +16,9 @@ # under the License. # @author: Tyler Smith, Cisco Systems -import logging import gettext import httplib +import logging import socket import time import urllib @@ -33,6 +33,8 @@ from quantumclient.common.serializer import Serializer LOG = logging.getLogger('quantumclient') + + AUTH_TOKEN_HEADER = "X-Auth-Token" @@ -53,7 +55,7 @@ def exception_handler_v10(status_code, error_content): 430: 'portNotFound', 431: 'requestedStateInvalid', 432: 'portInUse', - 440: 'alreadyAttached' + 440: 'alreadyAttached', } quantum_errors = { @@ -66,7 +68,7 @@ def exception_handler_v10(status_code, error_content): 431: exceptions.StateInvalidClient, 432: exceptions.PortInUseClient, 440: exceptions.AlreadyAttachedClient, - 501: NotImplementedError + 501: NotImplementedError, } # Find real error type @@ -75,8 +77,7 @@ def exception_handler_v10(status_code, error_content): error_type = quantum_error_types.get(status_code) if error_type: error_dict = error_content[error_type] - error_message = error_dict['message'] + "\n" +\ - error_dict['detail'] + error_message = error_dict['message'] + "\n" + error_dict['detail'] else: error_message = error_content # raise the appropriate error! @@ -128,7 +129,7 @@ def exception_handler_v11(status_code, error_content): EXCEPTION_HANDLERS = { '1.0': exception_handler_v10, - '1.1': exception_handler_v11 + '1.1': exception_handler_v11, } @@ -166,9 +167,12 @@ class Client(object): "network": ["id", "name"], "port": ["id", "state"], "attachment": ["id"]}, - "plurals": {"networks": "network", - "ports": "port"}}, - } + "plurals": { + "networks": "network", + "ports": "port", + }, + }, + } # Action query strings networks_path = "/networks" @@ -249,8 +253,8 @@ class Client(object): # Salvatore: Isolating this piece of code in its own method to # facilitate stubout for testing if self.logger: - self.logger.debug("Quantum Client Request:\n" \ - + method + " " + action + "\n") + self.logger.debug("Quantum Client Request:\n" + + method + " " + action + "\n") if body: self.logger.debug(body) conn.request(method, action, body, headers) @@ -286,7 +290,7 @@ class Client(object): try: connection_type = self.get_connection_type() headers = headers or {"Content-Type": - "application/%s" % self.format} + "application/%s" % self.format} # if available, add authentication token if self.auth_token: headers[AUTH_TOKEN_HEADER] = self.auth_token @@ -301,8 +305,8 @@ class Client(object): status_code = self.get_status_code(res) data = res.read() if self.logger: - self.logger.debug("Quantum Client Reply (code = %s) :\n %s" \ - % (str(status_code), data)) + self.logger.debug("Quantum Client Reply (code = %s) :\n %s" % + (str(status_code), data)) if status_code in (httplib.OK, httplib.CREATED, httplib.ACCEPTED, @@ -335,8 +339,8 @@ class Client(object): elif type(data) is dict: return Serializer().serialize(data, self.content_type()) else: - raise Exception("unable to serialize object of type = '%s'" \ - % type(data)) + raise Exception("unable to serialize object of type = '%s'" % + type(data)) def deserialize(self, data, status_code): """ @@ -344,8 +348,8 @@ class Client(object): """ if status_code == 204: return data - return Serializer(self._serialization_metadata).\ - deserialize(data, self.content_type()) + return Serializer(self._serialization_metadata).deserialize( + data, self.content_type()) def content_type(self, format=None): """ diff --git a/quantumclient/cli.py b/quantumclient/cli.py index 99ce0f102..a1a5b1da5 100755 --- a/quantumclient/cli.py +++ b/quantumclient/cli.py @@ -34,90 +34,114 @@ from quantumclient.common import utils #Configure logger for client - cli logger is a child of it #NOTE(salvatore-orlando): logger name does not map to package #this is deliberate. Simplifies logger configuration -LOG = logging.getLogger('quantum') +LOG = logging.getLogger('quantumclient') + + DEFAULT_QUANTUM_VERSION = '1.1' FORMAT = 'json' commands_v10 = { - "list_nets": { - "func": cli_lib.list_nets, - "args": ["tenant-id"]}, - "list_nets_detail": { - "func": cli_lib.list_nets_detail, - "args": ["tenant-id"]}, - "create_net": { - "func": cli_lib.create_net, - "args": ["tenant-id", "net-name"]}, - "delete_net": { - "func": cli_lib.delete_net, - "args": ["tenant-id", "net-id"]}, - "show_net": { - "func": cli_lib.show_net, - "args": ["tenant-id", "net-id"]}, - "show_net_detail": { - "func": cli_lib.show_net_detail, - "args": ["tenant-id", "net-id"]}, - "update_net": { - "func": cli_lib.update_net, - "args": ["tenant-id", "net-id", "new-name"]}, - "list_ports": { - "func": cli_lib.list_ports, - "args": ["tenant-id", "net-id"]}, - "list_ports_detail": { - "func": cli_lib.list_ports_detail, - "args": ["tenant-id", "net-id"]}, - "create_port": { - "func": cli_lib.create_port, - "args": ["tenant-id", "net-id"]}, - "delete_port": { - "func": cli_lib.delete_port, - "args": ["tenant-id", "net-id", "port-id"]}, - "update_port": { - "func": cli_lib.update_port, - "args": ["tenant-id", "net-id", "port-id", "params"]}, - "show_port": { - "func": cli_lib.show_port, - "args": ["tenant-id", "net-id", "port-id"]}, - "show_port_detail": { - "func": cli_lib.show_port_detail, - "args": ["tenant-id", "net-id", "port-id"]}, - "plug_iface": { - "func": cli_lib.plug_iface, - "args": ["tenant-id", "net-id", "port-id", "iface-id"]}, - "unplug_iface": { - "func": cli_lib.unplug_iface, - "args": ["tenant-id", "net-id", "port-id"]}, - "show_iface": { - "func": cli_lib.show_iface, - "args": ["tenant-id", "net-id", "port-id"]}, } + "list_nets": { + "func": cli_lib.list_nets, + "args": ["tenant-id"], + }, + "list_nets_detail": { + "func": cli_lib.list_nets_detail, + "args": ["tenant-id"], + }, + "create_net": { + "func": cli_lib.create_net, + "args": ["tenant-id", "net-name"], + }, + "delete_net": { + "func": cli_lib.delete_net, + "args": ["tenant-id", "net-id"], + }, + "show_net": { + "func": cli_lib.show_net, + "args": ["tenant-id", "net-id"], + }, + "show_net_detail": { + "func": cli_lib.show_net_detail, + "args": ["tenant-id", "net-id"], + }, + "update_net": { + "func": cli_lib.update_net, + "args": ["tenant-id", "net-id", "new-name"], + }, + "list_ports": { + "func": cli_lib.list_ports, + "args": ["tenant-id", "net-id"], + }, + "list_ports_detail": { + "func": cli_lib.list_ports_detail, + "args": ["tenant-id", "net-id"], + }, + "create_port": { + "func": cli_lib.create_port, + "args": ["tenant-id", "net-id"], + }, + "delete_port": { + "func": cli_lib.delete_port, + "args": ["tenant-id", "net-id", "port-id"], + }, + "update_port": { + "func": cli_lib.update_port, + "args": ["tenant-id", "net-id", "port-id", "params"], + }, + "show_port": { + "func": cli_lib.show_port, + "args": ["tenant-id", "net-id", "port-id"], + }, + "show_port_detail": { + "func": cli_lib.show_port_detail, + "args": ["tenant-id", "net-id", "port-id"], + }, + "plug_iface": { + "func": cli_lib.plug_iface, + "args": ["tenant-id", "net-id", "port-id", "iface-id"], + }, + "unplug_iface": { + "func": cli_lib.unplug_iface, + "args": ["tenant-id", "net-id", "port-id"], + }, + "show_iface": { + "func": cli_lib.show_iface, + "args": ["tenant-id", "net-id", "port-id"], + }, + } commands_v11 = commands_v10.copy() commands_v11.update({ - "list_nets": { - "func": cli_lib.list_nets_v11, - "args": ["tenant-id"], - "filters": ["name", "op-status", "port-op-status", "port-state", - "has-attachment", "attachment", "port"]}, - "list_nets_detail": { - "func": cli_lib.list_nets_detail_v11, - "args": ["tenant-id"], - "filters": ["name", "op-status", "port-op-status", "port-state", - "has-attachment", "attachment", "port"]}, - "list_ports": { - "func": cli_lib.list_ports_v11, - "args": ["tenant-id", "net-id"], - "filters": ["name", "op-status", "has-attachment", "attachment"]}, - "list_ports_detail": { - "func": cli_lib.list_ports_detail_v11, - "args": ["tenant-id", "net-id"], - "filters": ["name", "op-status", "has-attachment", "attachment"]}, - }) + "list_nets": { + "func": cli_lib.list_nets_v11, + "args": ["tenant-id"], + "filters": ["name", "op-status", "port-op-status", "port-state", + "has-attachment", "attachment", "port"], + }, + "list_nets_detail": { + "func": cli_lib.list_nets_detail_v11, + "args": ["tenant-id"], + "filters": ["name", "op-status", "port-op-status", "port-state", + "has-attachment", "attachment", "port"], + }, + "list_ports": { + "func": cli_lib.list_ports_v11, + "args": ["tenant-id", "net-id"], + "filters": ["name", "op-status", "has-attachment", "attachment"], + }, + "list_ports_detail": { + "func": cli_lib.list_ports_detail_v11, + "args": ["tenant-id", "net-id"], + "filters": ["name", "op-status", "has-attachment", "attachment"], + }, + }) commands = { '1.0': commands_v10, - '1.1': commands_v11 + '1.1': commands_v11, } clients = { '1.0': Client, - '1.1': ClientV11 + '1.1': ClientV11, } @@ -125,23 +149,24 @@ def help(version): print "\nCommands:" cmds = commands[version] for k in cmds.keys(): - print " %s %s %s" % (k, - " ".join(["<%s>" % y for y in cmds[k]["args"]]), - 'filters' in cmds[k] and "[filterspec ...]" or "") + print " %s %s %s" % ( + k, + " ".join(["<%s>" % y for y in cmds[k]["args"]]), + 'filters' in cmds[k] and "[filterspec ...]" or "") def print_usage(cmd, version): cmds = commands[version] - print "Usage:\n %s %s" % (cmd, - " ".join(["<%s>" % y for y in cmds[cmd]["args"]])) + print "Usage:\n %s %s" % ( + cmd, " ".join(["<%s>" % y for y in cmds[cmd]["args"]])) def build_args(cmd, cmdargs, arglist): arglist_len = len(arglist) cmdargs_len = len(cmdargs) if arglist_len < cmdargs_len: - message = "Not enough arguments for \"%s\" (expected: %d, got: %d)"\ - % (cmd, len(cmdargs), arglist_len) + message = ("Not enough arguments for \"%s\" (expected: %d, got: %d)" % + (cmd, len(cmdargs), arglist_len)) raise exceptions.QuantumCLIError(message=message) args = arglist[:cmdargs_len] return args @@ -192,12 +217,13 @@ def build_cmd(cmd, cmd_args, cmd_filters, arglist, version): return None, None filter_len = (filters is not None) and len(filters) or 0 if len(arglist) - len(args) - filter_len > 0: - message = "Too many arguments for \"%s\" (expected: %d, got: %d)"\ - % (cmd, len(cmd_args), arglist_len) + message = ("Too many arguments for \"%s\" (expected: %d, got: %d)" % + (cmd, len(cmd_args), arglist_len)) LOG.error(message) print "Error in command line: %s " % message - print "Usage:\n %s %s" % (cmd, - " ".join(["<%s>" % y for y in commands[version][cmd]["args"]])) + print "Usage:\n %s %s" % ( + cmd, + " ".join(["<%s>" % y for y in commands[version][cmd]["args"]])) return None, None # Append version to arguments for cli functions args.append(version) @@ -219,18 +245,21 @@ def main(): usagestr = "Usage: %prog [OPTIONS] [args]" parser = OptionParser(usage=usagestr) parser.add_option("-H", "--host", dest="host", - type="string", default="127.0.0.1", help="ip address of api host") + type="string", default="127.0.0.1", + help="ip address of api host") parser.add_option("-p", "--port", dest="port", - type="int", default=9696, help="api poort") + type="int", default=9696, help="api poort") parser.add_option("-s", "--ssl", dest="ssl", - action="store_true", default=False, help="use ssl") + action="store_true", default=False, help="use ssl") parser.add_option("-v", "--verbose", dest="verbose", - action="store_true", default=False, help="turn on verbose logging") + action="store_true", default=False, + help="turn on verbose logging") parser.add_option("-f", "--logfile", dest="logfile", - type="string", default="syslog", help="log file path") + type="string", default="syslog", help="log file path") parser.add_option("-t", "--token", dest="token", - type="string", default=None, help="authentication token") - parser.add_option('--version', + type="string", default=None, help="authentication token") + parser.add_option( + '--version', default=utils.env('QUANTUM_VERSION', default=DEFAULT_QUANTUM_VERSION), help='Accepts 1.1 and 1.0, defaults to env[QUANTUM_VERSION].') options, args = parser.parse_args() diff --git a/quantumclient/cli_lib.py b/quantumclient/cli_lib.py index 6ff8a1f79..6111bcb3d 100755 --- a/quantumclient/cli_lib.py +++ b/quantumclient/cli_lib.py @@ -23,10 +23,13 @@ import logging import traceback -FORMAT = "json" + LOG = logging.getLogger('quantumclient.cli_lib') +FORMAT = "json" + + class OutputTemplate(object): """ A class for generating simple templated output. Based on Python templating mechanism. @@ -95,90 +98,146 @@ class CmdOutputTemplate(OutputTemplate): Extends OutputTemplate loading a different template for each command. """ - _templates_v10 = { - "list_nets": "Virtual Networks for Tenant %(tenant_id)s\n" + - "%(networks|\tNetwork ID: %(id)s)s", - "list_nets_detail": "Virtual Networks for Tenant %(tenant_id)s\n" + - "%(networks|\tNetwork %(name)s with ID: %(id)s)s", - "show_net": "Network ID: %(network.id)s\n" + - "Network Name: %(network.name)s", - "show_net_detail": "Network ID: %(network.id)s\n" + - "Network Name: %(network.name)s\n" + - "Ports: %(network.ports|\tID: %(id)s\n" + - "\t\tadministrative state: %(state)s\n" + - "\t\tinterface: %(attachment.id)s)s", - "create_net": "Created a new Virtual Network with ID: " + - "%(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "update_net": "Updated Virtual Network with ID: " + - "%(network.id)s\n" + - "for Tenant: %(tenant_id)s\n", - "delete_net": "Deleted Virtual Network with ID: " + - "%(network_id)s\n" + - "for Tenant %(tenant_id)s", - "list_ports": "Ports on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s\n" + - "%(ports|\tLogical Port: %(id)s)s", - "list_ports_detail": "Ports on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s\n" + - "%(ports|\tLogical Port: %(id)s\n" + - "\t\tadministrative State: %(state)s)s", - "create_port": "Created new Logical Port with ID: " + - "%(port_id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "show_port": "Logical Port ID: %(port.id)s\n" + - "administrative State: %(port.state)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "show_port_detail": "Logical Port ID: %(port.id)s\n" + - "administrative State: %(port.state)s\n" + - "interface: %(port.attachment.id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "update_port": "Updated Logical Port " + - "with ID: %(port.id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for tenant: %(tenant_id)s", - "delete_port": "Deleted Logical Port with ID: %(port_id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "plug_iface": "Plugged interface %(attachment)s\n" + - "into Logical Port: %(port_id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "unplug_iface": "Unplugged interface from Logical Port:" + - "%(port_id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "show_iface": "interface: %(iface.id)s\n" + - "plugged in Logical Port ID: %(port_id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s"} + _templates_v10 = dict( + list_nets=""" +Virtual Networks for Tenant %(tenant_id)s +%(networks|\tNetwork ID: %(id)s)s +""".strip(), + + list_nets_detail=""" +Virtual Networks for Tenant %(tenant_id)s +%(networks|\tNetwork %(name)s with ID: %(id)s)s +""".strip(), + + show_net=""" +Network ID: %(network.id)s +Network Name: %(network.name)s +""".strip(), + + show_net_detail=""" +Network ID: %(network.id)s +Network Name: %(network.name)s +Ports: %(network.ports|\tID: %(id)s +\t\tadministrative state: %(state)s +\t\tinterface: %(attachment.id)s)s +""".strip(), + + create_net=""" +Created a new Virtual Network with ID: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + update_net=""" +Updated Virtual Network with ID: %(network.id)s +for Tenant: %(tenant_id)s +""".strip(), + + delete_net=""" +Deleted Virtual Network with ID: %(network_id)s +for Tenant %(tenant_id)s +""".strip(), + + list_ports=""" +Ports on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +%(ports|\tLogical Port: %(id)s)s +""".strip(), + + list_ports_detail=""" +Ports on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +%(ports|\tLogical Port: %(id)s +\t\tadministrative State: %(state)s)s +""".strip(), + + create_port=""" +Created new Logical Port with ID: %(port_id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + show_port=""" +Logical Port ID: %(port.id)s +administrative State: %(port.state)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + show_port_detail=""" +Logical Port ID: %(port.id)s +administrative State: %(port.state)s +interface: %(port.attachment.id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + update_port=""" +Updated Logical Port with ID: %(port.id)s +on Virtual Network: %(network_id)s +for tenant: %(tenant_id)s +""".strip(), + + delete_port=""" +Deleted Logical Port with ID: %(port_id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + plug_iface=""" +Plugged interface %(attachment)s +into Logical Port: %(port_id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + unplug_iface=""" +Unplugged interface from Logical Port: %(port_id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + show_iface=""" +interface: %(iface.id)s +plugged in Logical Port ID: %(port_id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + ) _templates_v11 = _templates_v10.copy() - _templates_v11.update({ - "show_net": "Network ID: %(network.id)s\n" + - "network Name: %(network.name)s\n" + - "operational Status: %(network.op-status)s", - "show_net_detail": "Network ID: %(network.id)s\n" + - "Network Name: %(network.name)s\n" + - "operational Status: %(network.op-status)s\n" + - "Ports: %(network.ports|\tID: %(id)s\n" + - "\t\tadministrative state: %(state)s\n" + - "\t\tinterface: %(attachment.id)s)s", - "show_port": "Logical Port ID: %(port.id)s\n" + - "administrative state: %(port.state)s\n" + - "operational status: %(port.op-status)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - "show_port_detail": "Logical Port ID: %(port.id)s\n" + - "administrative State: %(port.state)s\n" + - "operational status: %(port.op-status)s\n" + - "interface: %(port.attachment.id)s\n" + - "on Virtual Network: %(network_id)s\n" + - "for Tenant: %(tenant_id)s", - }) + _templates_v11.update(dict( + show_net=""" +Network ID: %(network.id)s +network Name: %(network.name)s +operational Status: %(network.op-status)s +""".strip(), + + show_net_detail=""" +Network ID: %(network.id)s +Network Name: %(network.name)s +operational Status: %(network.op-status)s +Ports: %(network.ports|\tID: %(id)s +\t\tadministrative state: %(state)s +\t\tinterface: %(attachment.id)s)s +""".strip(), + + show_port=""" +Logical Port ID: %(port.id)s +administrative state: %(port.state)s +operational status: %(port.op-status)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + + show_port_detail=""" +Logical Port ID: %(port.id)s +administrative State: %(port.state)s +operational status: %(port.op-status)s +interface: %(port.attachment.id)s +on Virtual Network: %(network_id)s +for Tenant: %(tenant_id)s +""".strip(), + )) _templates = { '1.0': _templates_v10, @@ -197,8 +256,8 @@ def _handle_exception(ex): if ex.args and isinstance(ex.args[-1][0], dict): status_code = ex.args[-1][0].get('status_code', None) message = ex.args[-1][0].get('message', None) - msg_1 = "Command failed with error code: %s" \ - % (status_code or '') + msg_1 = ("Command failed with error code: %s" % + (status_code or '')) msg_2 = "Error message:%s" % (message or '') print msg_1 print msg_2 @@ -207,8 +266,8 @@ def _handle_exception(ex): def prepare_output(cmd, tenant_id, response, version): - LOG.debug("Preparing output for response:%s, version:%s" - % (response, version)) + LOG.debug("Preparing output for response:%s, version:%s" % + (response, version)) response['tenant_id'] = tenant_id output = str(CmdOutputTemplate(cmd, response, version)) LOG.debug("Finished preparing output for command:%s", cmd) diff --git a/quantumclient/common/serializer.py b/quantumclient/common/serializer.py index 7fefd2dc1..6e914673a 100644 --- a/quantumclient/common/serializer.py +++ b/quantumclient/common/serializer.py @@ -43,7 +43,7 @@ class Serializer(object): return self.get_deserialize_handler(content_type)(datastring) except Exception: raise exception.MalformedResponseBody( - reason="Unable to deserialize response body") + reason="Unable to deserialize response body") def get_deserialize_handler(self, content_type): handlers = { diff --git a/quantumclient/tests/unit/test_cli.py b/quantumclient/tests/unit/test_cli.py index c68eb6a54..6cf618c47 100644 --- a/quantumclient/tests/unit/test_cli.py +++ b/quantumclient/tests/unit/test_cli.py @@ -21,7 +21,6 @@ """ - import logging import sys import unittest @@ -43,8 +42,8 @@ class CLITest(unittest.TestCase): def setUp(self): """Prepare the test environment""" options = {} - options['plugin_provider'] = \ - 'quantum.plugins.sample.SamplePlugin.FakePlugin' + options['plugin_provider'] = ( + 'quantum.plugins.sample.SamplePlugin.FakePlugin') #TODO: make the version of the API router configurable self.api = server.APIRouterV11(options) @@ -160,17 +159,25 @@ class CLITest(unittest.TestCase): 'op-status': nw.op_status} port_list = db.port_list(nw.uuid) if not port_list: - network['ports'] = [{'id': '', - 'state': '', - 'attachment': {'id': ''}}] + network['ports'] = [ + { + 'id': '', + 'state': '', + 'attachment': { + 'id': '', + }, + }, + ] else: network['ports'] = [] for port in port_list: - network['ports'].append({'id': port.uuid, - 'state': port.state, - 'attachment': {'id': - port.interface_id - or ''}}) + network['ports'].append({ + 'id': port.uuid, + 'state': port.state, + 'attachment': { + 'id': port.interface_id or '', + }, + }) # Fill CLI template output = cli.prepare_output('show_net_detail', diff --git a/quantumclient/tests/unit/test_clientlib.py b/quantumclient/tests/unit/test_clientlib.py index 94df09242..3b88f1521 100644 --- a/quantumclient/tests/unit/test_clientlib.py +++ b/quantumclient/tests/unit/test_clientlib.py @@ -17,15 +17,17 @@ # @author: Tyler Smith, Cisco Systems import logging -import unittest import re +import unittest from quantumclient.common import exceptions from quantumclient.common.serializer import Serializer from quantumclient import Client + LOG = logging.getLogger('quantumclient.tests.test_api') + # Set a couple tenants to use for testing TENANT_1 = 'totore' TENANT_2 = 'totore2' @@ -119,7 +121,7 @@ class APITest(unittest.TestCase): return data def _test_list_networks(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_list_networks - tenant:%s "\ + LOG.debug("_test_list_networks - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.list_networks, @@ -129,13 +131,13 @@ class APITest(unittest.TestCase): data=[], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_list_networks - tenant:%s "\ - "- format:%s - END", format, tenant) + LOG.debug("_test_list_networks - tenant:%s - format:%s - END", + format, tenant) def _test_list_networks_details(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_list_networks_details - tenant:%s "\ + LOG.debug("_test_list_networks_details - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.list_networks_details, @@ -145,12 +147,12 @@ class APITest(unittest.TestCase): data=[], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_list_networks_details - tenant:%s "\ + LOG.debug("_test_list_networks_details - tenant:%s " "- format:%s - END", format, tenant) def _test_show_network(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_show_network - tenant:%s "\ + LOG.debug("_test_show_network - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.show_network, @@ -160,12 +162,12 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_show_network - tenant:%s "\ + LOG.debug("_test_show_network - tenant:%s " "- format:%s - END", format, tenant) def _test_show_network_details(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_show_network_details - tenant:%s "\ + LOG.debug("_test_show_network_details - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.show_network_details, @@ -175,11 +177,11 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_show_network_details - tenant:%s "\ + LOG.debug("_test_show_network_details - tenant:%s " "- format:%s - END", format, tenant) def _test_create_network(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_create_network - tenant:%s "\ + LOG.debug("_test_create_network - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.create_network, @@ -189,11 +191,11 @@ class APITest(unittest.TestCase): data=[{'network': {'net-name': 'testNetwork'}}], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_create_network - tenant:%s "\ + LOG.debug("_test_create_network - tenant:%s " "- format:%s - END", format, tenant) def _test_update_network(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_update_network - tenant:%s "\ + LOG.debug("_test_update_network - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.update_network, @@ -204,11 +206,11 @@ class APITest(unittest.TestCase): {'network': {'net-name': 'newName'}}], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_update_network - tenant:%s "\ + LOG.debug("_test_update_network - tenant:%s " "- format:%s - END", format, tenant) def _test_delete_network(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_delete_network - tenant:%s "\ + LOG.debug("_test_delete_network - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.delete_network, @@ -218,11 +220,11 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_delete_network - tenant:%s "\ + LOG.debug("_test_delete_network - tenant:%s " "- format:%s - END", format, tenant) def _test_list_ports(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_list_ports - tenant:%s "\ + LOG.debug("_test_list_ports - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.list_ports, @@ -232,12 +234,12 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_list_ports - tenant:%s "\ + LOG.debug("_test_list_ports - tenant:%s " "- format:%s - END", format, tenant) def _test_list_ports_details(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_list_ports_details - tenant:%s "\ + LOG.debug("_test_list_ports_details - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.list_ports_details, @@ -247,11 +249,11 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_list_ports_details - tenant:%s "\ + LOG.debug("_test_list_ports_details - tenant:%s " "- format:%s - END", format, tenant) def _test_show_port(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_show_port - tenant:%s "\ + LOG.debug("_test_show_port - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.show_port, @@ -261,12 +263,12 @@ class APITest(unittest.TestCase): data=["001", "001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_show_port - tenant:%s "\ + LOG.debug("_test_show_port - tenant:%s " "- format:%s - END", format, tenant) def _test_show_port_details(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_show_port_details - tenant:%s "\ + LOG.debug("_test_show_port_details - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.show_port_details, @@ -276,11 +278,11 @@ class APITest(unittest.TestCase): data=["001", "001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_show_port_details - tenant:%s "\ + LOG.debug("_test_show_port_details - tenant:%s " "- format:%s - END", format, tenant) def _test_create_port(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_create_port - tenant:%s "\ + LOG.debug("_test_create_port - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.create_port, @@ -290,11 +292,11 @@ class APITest(unittest.TestCase): data=["001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_create_port - tenant:%s "\ + LOG.debug("_test_create_port - tenant:%s " "- format:%s - END", format, tenant) def _test_delete_port(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_delete_port - tenant:%s "\ + LOG.debug("_test_delete_port - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.delete_port, @@ -304,11 +306,11 @@ class APITest(unittest.TestCase): data=["001", "001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_delete_port - tenant:%s "\ + LOG.debug("_test_delete_port - tenant:%s " "- format:%s - END", format, tenant) def _test_update_port(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_update_port - tenant:%s "\ + LOG.debug("_test_update_port - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.update_port, @@ -319,12 +321,12 @@ class APITest(unittest.TestCase): {'port': {'state': 'ACTIVE'}}], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_update_port - tenant:%s "\ + LOG.debug("_test_update_port - tenant:%s " "- format:%s - END", format, tenant) def _test_show_port_attachment(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_show_port_attachment - tenant:%s "\ + LOG.debug("_test_show_port_attachment - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.show_port_attachment, @@ -334,12 +336,12 @@ class APITest(unittest.TestCase): data=["001", "001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_show_port_attachment - tenant:%s "\ + LOG.debug("_test_show_port_attachment - tenant:%s " "- format:%s - END", format, tenant) def _test_attach_resource(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_attach_resource - tenant:%s "\ + LOG.debug("_test_attach_resource - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.attach_resource, @@ -350,12 +352,12 @@ class APITest(unittest.TestCase): {'resource': {'id': '1234'}}], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_attach_resource - tenant:%s "\ + LOG.debug("_test_attach_resource - tenant:%s " "- format:%s - END", format, tenant) def _test_detach_resource(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_detach_resource - tenant:%s "\ + LOG.debug("_test_detach_resource - tenant:%s " "- format:%s - START", format, tenant) self._assert_sanity(self.client.detach_resource, @@ -365,12 +367,12 @@ class APITest(unittest.TestCase): data=["001", "001"], params={'tenant': tenant, 'format': format}) - LOG.debug("_test_detach_resource - tenant:%s "\ + LOG.debug("_test_detach_resource - tenant:%s " "- format:%s - END", format, tenant) def _test_ssl_certificates(self, tenant=TENANT_1, format='json', status=200): - LOG.debug("_test_ssl_certificates - tenant:%s "\ + LOG.debug("_test_ssl_certificates - tenant:%s " "- format:%s - START", format, tenant) # Set SSL, and our cert file @@ -379,16 +381,16 @@ class APITest(unittest.TestCase): self.client.key_file = self.client.cert_file = cert_file data = self._assert_sanity(self.client.list_networks, - status, - "GET", - "networks", - data=[], - params={'tenant': tenant, 'format': format}) + status, + "GET", + "networks", + data=[], + params={'tenant': tenant, 'format': format}) self.assertEquals(data["key_file"], cert_file) self.assertEquals(data["cert_file"], cert_file) - LOG.debug("_test_ssl_certificates - tenant:%s "\ + LOG.debug("_test_ssl_certificates - tenant:%s " "- format:%s - END", format, tenant) def test_list_networks_json(self):