Minor changes to Cluster create and list functions

-Added unit test for Cluster Create and List
 -Added docs folder
Change-Id: Ica21e5331b77a0252370a9d5527b62907a2963c2
This commit is contained in:
Abitha Palaniappan 2015-02-10 15:41:18 -08:00
parent 4a81f0d0d6
commit 828756a0ee
18 changed files with 635 additions and 24 deletions

2
.gitignore vendored
View File

@ -21,3 +21,5 @@ doc/build/*
dist
cueclient/versioninfo
.testrepository
.idea/
*.DS_Store

View File

@ -1,4 +1,4 @@
[DEFAULT]
test_command=OS_STDOUT_CAPTURE=1 OS_STDERR_CAPTURE=1 ${PYTHON:-python} -m subunit.run discover -t ./ ./designateclient/tests $LISTOPT $IDOPTION
test_command=OS_STDOUT_CAPTURE=1 OS_STDERR_CAPTURE=1 ${PYTHON:-python} -m subunit.run discover -t ./ ${TESTS_DIR:-./cueclient/tests/} $LISTOPT $IDOPTION
test_id_option=--load-list $IDFILE
test_list_option=--list
test_list_option=--list

View File

26
cueclient/tests/base.py Normal file
View File

@ -0,0 +1,26 @@
# 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.
#
import argparse
import mock
from cueclient.tests import utils
class TestCueBase(utils.TestCommand):
def setUp(self):
super(TestCueBase, self).setUp()
self.app = mock.Mock(name='app')
self.app.client_manager = mock.Mock(name='client_manager')
self.namespace = argparse.Namespace()

81
cueclient/tests/fakes.py Normal file
View File

@ -0,0 +1,81 @@
# Copyright 2013 Nebula Inc.
#
# 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.
#
import sys
import six
AUTH_TOKEN = "foobar"
AUTH_URL = "http://0.0.0.0"
class FakeStdout:
def __init__(self):
self.content = []
def write(self, text):
self.content.append(text)
def make_string(self):
result = ''
for line in self.content:
result = result + line
return result
class FakeApp(object):
def __init__(self, _stdout):
self.stdout = _stdout
self.client_manager = None
self.stdin = sys.stdin
self.stdout = _stdout or sys.stdout
self.stderr = sys.stderr
self.restapi = None
class FakeClientManager(object):
def __init__(self):
self.compute = None
self.identity = None
self.image = None
self.object = None
self.volume = None
self.network = None
self.auth_ref = None
class FakeModule(object):
def __init__(self, name, version):
self.name = name
self.__version__ = version
class FakeResource(object):
def __init__(self, manager, info, loaded=False):
self.manager = manager
self._info = info
self._add_details(info)
self._loaded = loaded
def _add_details(self, info):
for (k, v) in six.iteritems(info):
setattr(self, k, v)
def __repr__(self):
reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and
k != 'manager')
info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
return "<%s %s>" % (self.__class__.__name__, info)

94
cueclient/tests/utils.py Normal file
View File

@ -0,0 +1,94 @@
# Copyright 2012-2013 OpenStack Foundation
# Copyright 2013 Nebula Inc.
#
# 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.
#
import os
import sys
import fixtures
import testtools
from cueclient.tests import fakes
class TestCase(testtools.TestCase):
def setUp(self):
testtools.TestCase.setUp(self)
if (os.environ.get("OS_STDOUT_CAPTURE") == "True" or
os.environ.get("OS_STDOUT_CAPTURE") == "1"):
stdout = self.useFixture(fixtures.StringStream("stdout")).stream
self.useFixture(fixtures.MonkeyPatch("sys.stdout", stdout))
if (os.environ.get("OS_STDERR_CAPTURE") == "True" or
os.environ.get("OS_STDERR_CAPTURE") == "1"):
stderr = self.useFixture(fixtures.StringStream("stderr")).stream
self.useFixture(fixtures.MonkeyPatch("sys.stderr", stderr))
def assertNotCalled(self, m, msg=None):
"""Assert a function was not called."""
if m.called:
if not msg:
msg = 'method %s should not have been called' % m
self.fail(msg)
# 2.6 doesn't have the assert dict equals so make sure that it exists
if tuple(sys.version_info)[0:2] < (2, 7):
def assertIsInstance(self, obj, cls, msg=None):
"""self.assertTrue(isinstance(obj, cls)), with a nicer message."""
if not isinstance(obj, cls):
standardMsg = '%s is not an instance of %r' % (obj, cls)
self.fail(self._formatMessage(msg, standardMsg))
def assertDictEqual(self, d1, d2, msg=None):
# Simple version taken from 2.7
self.assertIsInstance(d1, dict,
'First argument is not a dictionary')
self.assertIsInstance(d2, dict,
'Second argument is not a dictionary')
if d1 != d2:
if msg:
self.fail(msg)
else:
standardMsg = '%r != %r' % (d1, d2)
self.fail(standardMsg)
class TestCommand(TestCase):
"""Test cliff command classes."""
def setUp(self):
super(TestCommand, self).setUp()
# Build up a fake app
self.fake_stdout = fakes.FakeStdout()
self.app = fakes.FakeApp(self.fake_stdout)
self.app.client_manager = fakes.FakeClientManager()
def check_parser(self, cmd, args, verify_args):
"""Test for parsing arguments"""
cmd_parser = cmd.get_parser('check_parser')
try:
parsed_args = cmd_parser.parse_args(args)
except SystemExit:
raise Exception("Argument parse failed")
for av in verify_args:
attr, value = av
if attr:
self.assertIn(attr, parsed_args)
self.assertEqual(getattr(parsed_args, attr), value)
return parsed_args

View File

View File

@ -0,0 +1,81 @@
# 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.
#
import mock
from cueclient.tests import base
from cueclient.v1.cli import clusters
class TestListClusters(base.TestCueBase):
def test_list_clusters(self):
"""test cluster list."""
arglist = [
]
verifylist = [
]
response = {
"results": [{"id": "111",
"name": "cluster_01", }]
}
lister = mock.Mock(return_value=response)
self.app.client_manager.mq.clusters.list = lister
cmd = clusters.ListClustersCommand(self.app, self.namespace)
parsed_args = self.check_parser(cmd, arglist, verifylist)
result = cmd.take_action(parsed_args)
lister.assert_called_with()
self.assertEqual(['id', 'name'], result[0])
class TestCreateCluster(base.TestCueBase):
def test_create_cluster(self):
"""test to create a new cluster with all input arguments"""
cluster_name = "test_Cluster"
cluster_network_id = "111222333445"
cluster_flavor = "1"
cluster_size = "2"
response = {"id": "222",
"project_id": "test",
"network_id": cluster_network_id,
"name": cluster_name,
"status": "BUILDING",
"flavor": cluster_flavor,
"size": cluster_size,
"volume_size": "1024",
"deleted": "0",
"created_at": "2015-02-04 00:35:02",
"updated_at": "2015-02-04 00:35:02",
"deleted_at": ""
}
arglist = ["--name", cluster_name, "--nic", cluster_network_id,
"--flavor", cluster_flavor, "--size", cluster_size]
verifylist = [
]
mocker = mock.Mock(return_value=response)
self.app.client_manager.mq.clusters.create = mocker
cmd = clusters.CreateClusterCommand(self.app, self.namespace)
parsed_args = self.check_parser(cmd, arglist, verifylist)
result = list(cmd.take_action(parsed_args))
filtered = [('created_at', 'deleted', 'deleted_at', 'flavor', 'id',
'name', 'network_id', 'project_id', 'size', 'status',
'updated_at', 'volume_size'),
('2015-02-04 00:35:02', '0', '', '1',
'222', 'test_Cluster',
'111222333445', 'test', '2', 'BUILDING',
'2015-02-04 00:35:02', '1024')]
self.assertEqual(filtered, result)

View File

@ -1,3 +1,17 @@
# Copyright 2012-2013 OpenStack Foundation
#
# 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.
#
import os
@ -13,3 +27,26 @@ def env(*vars, **kwargs):
if value:
return value
return kwargs.get('default', '')
def get_item_properties(item, fields, mixed_case_fields=[], formatters={}):
"""Return a tuple containing the item properties.
:param item: a single dict resource
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values
"""
row = []
for field in fields:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = item[field_name] if field_name in item else ''
if field in formatters:
row.append(formatters[field](data))
else:
row.append(data)
return tuple(row)

View File

@ -56,7 +56,7 @@ class ShowClusterCommand(show.ShowOne):
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.dns
client = self.app.client_manager.mq
data = client.clusters.get(parsed_args.id)
@ -70,22 +70,22 @@ class CreateClusterCommand(show.ShowOne):
parser = super(CreateClusterCommand, self).get_parser(prog_name)
parser.add_argument('--name', help="Cluster Name", required=True)
parser.add_argument('--description', help="Description")
parser.add_argument('--nic', help="Network to place nodes on",
required=True)
parser.add_argument('--flavor', help="Flavor to use.")
parser.add_argument('--volume_size', help="Volume size", default=1024)
parser.add_argument('--flavor', help="Flavor to use.", required=True)
parser.add_argument('--size', help="Number of nodes", required=True)
parser.add_argument('--volume_size', help="Volume size")
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.dns
client = self.app.client_manager.mq
data = client.clusters.create(
parsed_args.name,
description=parsed_args.description,
name=parsed_args.name,
nic=parsed_args.nic,
flavor=parsed_args.flavor,
size=parsed_args.size,
volume_size=parsed_args.volume_size)
return zip(*sorted(six.iteritems(data)))
@ -109,7 +109,7 @@ class SetClusterCommand(command.Command):
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.dns
client = self.app.client_manager.mq
data = {}
@ -146,6 +146,6 @@ class DeleteClusterCommand(command.Command):
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.dns
client = self.app.client_manager.mq
client.clusters.delete(parsed_args.id)
LOG.info('Cluster %s was deleted', parsed_args.id)

View File

@ -13,24 +13,27 @@
# 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 cueclient import client
from cueclient import controller
class ClusterController(client.Controller):
def create(self, name, nic, description=None, flavor='m1.medium',
volume_size=1024):
class ClusterController(controller.Controller):
def create(self, name, nic, flavor, size, volume_size):
data = {
"network_id": nic,
"name": name,
"flavor": flavor,
"size": size,
"volume_size": volume_size
}
url = self.build_url("/clusters")
return self._post(url, data=data)
return self._post(url, json=data)
def list(self, marker=None, limit=None, params=None):
url = self.build_url("/clusters", marker, limit, params)
return self._get(url)
return self._get(url, "clusters")
def get(self, cluster_id):
url = self.build_url("/clusters/%s" % cluster_id)

260
doc/source/conf.py Normal file
View File

@ -0,0 +1,260 @@
# -*- coding: utf-8 -*-
#
# python-cueclient documentation build configuration file, created by
# sphinx-quickstart on Wed Feb 11 14:55:41 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'python-cueclient'
copyright = u'2015, Openstack Cue Team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'python-cueclientdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'python-cueclient.tex', u'python-cueclient Documentation',
u'Openstack Cue Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'python-cueclient', u'python-cueclient Documentation',
[u'Openstack Cue Team'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'python-cueclient', u'python-cueclient Documentation',
u'Openstack Cue Team', 'python-cueclient', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

22
doc/source/index.rst Normal file
View File

@ -0,0 +1,22 @@
.. python-cueclient documentation master file, created by
sphinx-quickstart on Wed Feb 11 14:55:41 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to python-cueclient's documentation!
============================================
Contents:
.. toctree::
:maxdepth: 2
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -4,6 +4,7 @@
cliff>=1.7.0 # Apache-2.0
pbr>=0.6,!=0.7,<1.0
python-keystoneclient>=0.11.1
python-openstackclient>=0.3.0
requests>=2.2.0,!=2.4.0
six>=1.7.0
stevedore>=1.1.0 # Apache-2.0

View File

@ -29,11 +29,11 @@ packages =
[entry_points]
openstack.mq.v1 =
cluster_create = cueclient.v1.cli.clusters:CreateClusterCommand
cluster_list = cueclient.v1.cli.clusters:ListClustersCommand
cluster_show = cueclient.v1.cli.clusters:ShowClusterCommand
cluster_set = cueclient.v1.cli.clusters:SetClusterCommand
cluster_delete = cueclient.v1.cli.clusters:DeleteClusterCommand
mq_cluster_create = cueclient.v1.cli.clusters:CreateClusterCommand
mq_cluster_list = cueclient.v1.cli.clusters:ListClustersCommand
mq_cluster_show = cueclient.v1.cli.clusters:ShowClusterCommand
mq_cluster_set = cueclient.v1.cli.clusters:SetClusterCommand
mq_cluster_delete = cueclient.v1.cli.clusters:DeleteClusterCommand
openstack.cli.extension =
mq = cueclient.osc.plugin

View File

@ -5,6 +5,10 @@
hacking>=0.9.2,<0.10
coverage>=3.6
discover
fixtures>=0.3.14
mock>=1.0
python-subunit>=0.0.18
sphinx>=1.1.2,!=1.2.0,!=1.3b1,<1.3
testrepository>=0.0.18
# Doc requirements
sphinx>=1.1.2,!=1.2.0,!=1.3b1,<1.3

View File

@ -1,5 +1,5 @@
[tox]
envlist = py26,py27,flake8
envlist = py27,flake8
minversion = 1.6
[testenv]