Clean up shell submodule unit tests

Since we no longer rely on print_dict/print_list we can remove it and
all of our test scaffolding that supported their usage.

Change-Id: I68dd335bf6cc3a50cdbf081d1a708595f914a949
This commit is contained in:
Ian Cordasco 2017-03-03 11:22:38 -06:00
parent 99fd7c88a3
commit 4bd5bc647e
8 changed files with 26 additions and 171 deletions

View File

@ -12,13 +12,7 @@
# License for the specific language governing permissions and limitations
# under the License.
"""Craton CLI helper classes and functions."""
import json
import os
import prettytable
import six
import textwrap
from oslo_utils import encodeutils
def arg(*args, **kwargs):
@ -72,92 +66,6 @@ def field_labels_from(attributes):
return [field.replace('_', ' ').title() for field in attributes]
def print_list(objs, fields, formatters=None, sortby_index=0,
mixed_case_fields=None, field_labels=None):
"""Print a list or objects as a table, one row per object.
:param objs: iterable of :class:`Resource`
:param fields: attributes that correspond to columns, in order
:param formatters: `dict` of callables for field formatting
:param sortby_index: index of the field for sorting table rows
:param mixed_case_fields: fields corresponding to object attributes that
have mixed case names (e.g., 'serverId')
:param field_labels: Labels to use in the heading of the table, default to
fields.
"""
formatters = formatters or {}
mixed_case_fields = mixed_case_fields or []
field_labels = field_labels or fields
if len(field_labels) != len(fields):
raise ValueError("Field labels list %(labels)s has different number "
"of elements than fields list %(fields)s",
{'labels': field_labels, 'fields': fields})
if sortby_index is None:
kwargs = {}
else:
kwargs = {'sortby': field_labels[sortby_index]}
pt = prettytable.PrettyTable(field_labels)
pt.align = 'l'
for o in objs:
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](o))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
data = getattr(o, field_name, '')
row.append(data)
pt.add_row(row)
if six.PY3:
print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
else:
print(encodeutils.safe_encode(pt.get_string(**kwargs)))
def print_dict(dct, dict_property="Property", wrap=0, dict_value='Value',
json_flag=False):
"""Print a `dict` as a table of two columns.
:param dct: `dict` to print
:param dict_property: name of the first column
:param wrap: wrapping for the second column
:param dict_value: header label for the value (second) column
:param json_flag: print `dict` as JSON instead of table
"""
if json_flag:
print(json.dumps(dct, indent=4, separators=(',', ': ')))
return
pt = prettytable.PrettyTable([dict_property, dict_value])
pt.align = 'l'
for k, v in sorted(dct.items()):
# convert dict to str to check length
if isinstance(v, dict):
v = six.text_type(v)
if wrap > 0:
v = textwrap.fill(six.text_type(v), wrap)
# if value has a newline, add in multiple rows
# e.g. fault with stacktrace
if v and isinstance(v, six.string_types) and r'\n' in v:
lines = v.strip().split(r'\n')
col1 = k
for line in lines:
pt.add_row([col1, line])
col1 = ''
else:
pt.add_row([k, v])
if six.PY3:
print(encodeutils.safe_encode(pt.get_string()).decode())
else:
print(encodeutils.safe_encode(pt.get_string()))
def env(*args, **kwargs):
"""Return the first environment variable set.

View File

@ -44,61 +44,11 @@ class TestShellCommand(base.TestCase):
kwargs.setdefault('formatter', self.formatter)
return argparse.Namespace(**kwargs)
class TestShellCommandUsingPrintDict(TestShellCommand):
"""Base class for shell commands using print_dict."""
def setUp(self):
"""Initialize test fixtures."""
super(TestShellCommandUsingPrintDict, self).setUp()
self.print_dict_patch = mock.patch(
'cratonclient.common.cliutils.print_dict'
)
self.print_dict = self.print_dict_patch.start()
def tearDown(self):
"""Clean-up test fixtures."""
super(TestShellCommandUsingPrintDict, self).tearDown()
self.print_dict_patch.stop()
def assertNothingWasCalled(self):
"""Assert inventory, list, and print_dict were not called."""
self.assertFalse(self.craton_client.inventory.called)
self.assertFalse(self.print_dict.called)
class TestShellCommandUsingPrintList(TestShellCommand):
"""Base class for shell commands using print_list."""
def setUp(self):
"""Initialize test fixtures."""
super(TestShellCommandUsingPrintList, self).setUp()
self.print_list_patch = mock.patch(
'cratonclient.common.cliutils.print_list'
)
self.print_list = self.print_list_patch.start()
def tearDown(self):
"""Clean-up test fixtures."""
super(TestShellCommandUsingPrintList, self).tearDown()
self.print_list_patch.stop()
def assertNothingWasCalled(self):
"""Assert inventory, list, and print_dict were not called."""
self.assertFalse(self.craton_client.inventory.called)
self.assertFalse(self.print_list.called)
def assertSortedPrintListFieldsEqualTo(self, expected_fields):
"""Assert the sorted fields parameter is equal expected_fields."""
kwargs = self.formatter.configure.call_args[1]
self.assertListEqual(expected_fields,
sorted(kwargs['fields']))
def assertSortedFieldsEqualTo(self, expected_fields):
"""Assert the sorted fields parameter is equal expected_fields."""
kwargs = self.formatter.configure.call_args[1]
self.assertListEqual(expected_fields,
sorted(kwargs['fields']))
"""Assert nothing was called on the formatter."""
self.assertListEqual([], self.craton_client.mock_calls)
self.assertFalse(self.formatter.configure.called)
self.assertFalse(self.formatter.handle.called)
def assertFieldsEqualTo(self, expected_fields):
"""Assert the sorted fields parameter is equal expected_fields."""

View File

@ -19,7 +19,7 @@ from cratonclient.shell.v1 import cells_shell
from cratonclient.tests.unit.shell import base
class TestDoShellShow(base.TestShellCommandUsingPrintDict):
class TestDoShellShow(base.TestShellCommand):
"""Unit tests for the cell show command."""
def test_simple_usage(self):
@ -36,7 +36,7 @@ class TestDoShellShow(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoCellList(base.TestShellCommandUsingPrintList):
class TestDoCellList(base.TestShellCommand):
"""Unit tests for the cell list command."""
def assertNothingWasCalled(self):
@ -206,7 +206,7 @@ class TestDoCellList(base.TestShellCommandUsingPrintList):
)
class TestDoCellCreate(base.TestShellCommandUsingPrintDict):
class TestDoCellCreate(base.TestShellCommand):
"""Unit tests for the cell create command."""
def args_for(self, **kwargs):
@ -244,7 +244,7 @@ class TestDoCellCreate(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoCellUpdate(base.TestShellCommandUsingPrintDict):
class TestDoCellUpdate(base.TestShellCommand):
"""Unit tests for the cell update command."""
def args_for(self, **kwargs):

View File

@ -19,7 +19,7 @@ from cratonclient.shell.v1 import clouds_shell
from cratonclient.tests.unit.shell import base
class TestDoCloudShow(base.TestShellCommandUsingPrintDict):
class TestDoCloudShow(base.TestShellCommand):
"""Unit tests for the cloud-show command."""
def test_prints_cloud_data(self):
@ -33,7 +33,7 @@ class TestDoCloudShow(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoCloudCreate(base.TestShellCommandUsingPrintDict):
class TestDoCloudCreate(base.TestShellCommand):
"""Unit tests for the cloud-create command."""
def args_for(self, **kwargs):
@ -68,7 +68,7 @@ class TestDoCloudCreate(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoCloudUpdate(base.TestShellCommandUsingPrintDict):
class TestDoCloudUpdate(base.TestShellCommand):
"""Unit tests for cloud-update command."""
def args_for(self, **kwargs):
@ -86,8 +86,7 @@ class TestDoCloudUpdate(base.TestShellCommandUsingPrintDict):
clouds_shell.do_cloud_update,
args,
)
self.assertFalse(self.craton_client.clouds.update.called)
self.assertFalse(self.print_dict.called)
self.assertNothingWasCalled()
def test_name_is_updated(self):
"""Verify the name attribute update is sent."""
@ -189,7 +188,7 @@ class TestDoCloudDelete(base.TestShellCommand):
self.assertFalse(self.print_func.called)
class TestDoCloudList(base.TestShellCommandUsingPrintList):
class TestDoCloudList(base.TestShellCommand):
"""Test cloud-list command."""
def args_for(self, **kwargs):

View File

@ -16,7 +16,7 @@ from cratonclient.shell.v1 import devices_shell
from cratonclient.tests.unit.shell import base
class TestDoDeviceList(base.TestShellCommandUsingPrintList):
class TestDoDeviceList(base.TestShellCommand):
"""Unit tests for the device list command."""
def args_for(self, **kwargs):

View File

@ -19,7 +19,7 @@ from cratonclient.shell.v1 import hosts_shell
from cratonclient.tests.unit.shell import base
class TestDoHostShow(base.TestShellCommandUsingPrintDict):
class TestDoHostShow(base.TestShellCommand):
"""Unit tests for the host show command."""
def test_print_host_data(self):
@ -34,7 +34,7 @@ class TestDoHostShow(base.TestShellCommandUsingPrintDict):
self.craton_client.hosts.get.assert_called_once_with(246)
class TestDoHostList(base.TestShellCommandUsingPrintList):
class TestDoHostList(base.TestShellCommand):
"""Unit tests for the host list command."""
def args_for(self, **kwargs):
@ -208,9 +208,7 @@ class TestDoHostList(base.TestShellCommandUsingPrintList):
autopaginate=False,
marker=None,
)
self.assertSortedPrintListFieldsEqualTo([
'cell_id', 'id', 'name',
])
self.assertFieldsEqualTo(['id', 'name', 'cell_id'])
def test_invalid_sort_key(self):
"""Verify that we disallow invalid sort keys."""
@ -295,7 +293,7 @@ class TestDoHostList(base.TestShellCommandUsingPrintList):
)
class TestDoHostCreate(base.TestShellCommandUsingPrintDict):
class TestDoHostCreate(base.TestShellCommand):
"""Tests for the do_host_create shell command."""
def args_for(self, **kwargs):
@ -371,7 +369,7 @@ class TestDoHostCreate(base.TestShellCommandUsingPrintDict):
)
class TestDoHostUpdate(base.TestShellCommandUsingPrintDict):
class TestDoHostUpdate(base.TestShellCommand):
"""Tests host-update shell command."""
def setUp(self):

View File

@ -21,7 +21,7 @@ from cratonclient.shell.v1 import projects_shell
from cratonclient.tests.unit.shell import base
class TestDoShellShow(base.TestShellCommandUsingPrintDict):
class TestDoShellShow(base.TestShellCommand):
"""Unit tests for the project show command."""
def test_simple_usage(self):
@ -38,7 +38,7 @@ class TestDoShellShow(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoProjectList(base.TestShellCommandUsingPrintList):
class TestDoProjectList(base.TestShellCommand):
"""Unit tests for the project list command."""
def assertNothingWasCalled(self):
@ -181,7 +181,7 @@ class TestDoProjectList(base.TestShellCommandUsingPrintList):
)
class TestDoProjectCreate(base.TestShellCommandUsingPrintDict):
class TestDoProjectCreate(base.TestShellCommand):
"""Unit tests for the project create command."""
def args_for(self, **kwargs):

View File

@ -19,7 +19,7 @@ from cratonclient.shell.v1 import regions_shell
from cratonclient.tests.unit.shell import base
class TestDoRegionShow(base.TestShellCommandUsingPrintDict):
class TestDoRegionShow(base.TestShellCommand):
"""Unit tests for the region-show command."""
def test_prints_region_data(self):
@ -33,7 +33,7 @@ class TestDoRegionShow(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoRegionCreate(base.TestShellCommandUsingPrintDict):
class TestDoRegionCreate(base.TestShellCommand):
"""Unit tests for the region-create command."""
def args_for(self, **kwargs):
@ -71,7 +71,7 @@ class TestDoRegionCreate(base.TestShellCommandUsingPrintDict):
self.assertEqual(1, self.formatter.handle.call_count)
class TestDoRegionUpdate(base.TestShellCommandUsingPrintDict):
class TestDoRegionUpdate(base.TestShellCommand):
"""Unit tests for region-update command."""
def args_for(self, **kwargs):
@ -196,7 +196,7 @@ class TestDoRegionDelete(base.TestShellCommand):
self.assertFalse(self.print_func.called)
class TestDoRegionList(base.TestShellCommandUsingPrintList):
class TestDoRegionList(base.TestShellCommand):
"""Test region-list command."""
def args_for(self, **kwargs):