Commit 0f383dcc authored by Stavros Sachtouris's avatar Stavros Sachtouris
Browse files

Unittest print_dict + print_list

Refs: #4058
parent b3cb58c2
...@@ -39,8 +39,8 @@ from kamaki.cli import command ...@@ -39,8 +39,8 @@ from kamaki.cli import command
from kamaki.cli.command_tree import CommandTree from kamaki.cli.command_tree import CommandTree
from kamaki.cli.errors import raiseCLIError, CLISyntaxError, CLIBaseUrlError from kamaki.cli.errors import raiseCLIError, CLISyntaxError, CLIBaseUrlError
from kamaki.cli.utils import ( from kamaki.cli.utils import (
format_size, to_bytes, print_dict, print_items, pretty_keys, pretty_dict, format_size, to_bytes, print_dict, print_items, page_hold, bold, ask_user,
page_hold, bold, ask_user, get_path_size, print_json, guess_mime_type) get_path_size, print_json, guess_mime_type)
from kamaki.cli.argument import FlagArgument, ValueArgument, IntArgument from kamaki.cli.argument import FlagArgument, ValueArgument, IntArgument
from kamaki.cli.argument import KeyValueArgument, DateArgument from kamaki.cli.argument import KeyValueArgument, DateArgument
from kamaki.cli.argument import ProgressBarArgument from kamaki.cli.argument import ProgressBarArgument
...@@ -388,7 +388,7 @@ class file_list(_file_container_command, _optional_json): ...@@ -388,7 +388,7 @@ class file_list(_file_container_command, _optional_json):
prfx = ('%s%s. ' % (empty_space, index)) if self['enum'] else '' prfx = ('%s%s. ' % (empty_space, index)) if self['enum'] else ''
if self['detail']: if self['detail']:
print('%s%s' % (prfx, oname)) print('%s%s' % (prfx, oname))
print_dict(pretty_keys(pretty_obj), exclude=('name')) print_dict(pretty_obj, exclude=('name'))
print print
else: else:
oname = '%s%9s %s' % (prfx, size, oname) oname = '%s%9s %s' % (prfx, size, oname)
...@@ -413,7 +413,7 @@ class file_list(_file_container_command, _optional_json): ...@@ -413,7 +413,7 @@ class file_list(_file_container_command, _optional_json):
pretty_c = container.copy() pretty_c = container.copy()
if 'bytes' in container: if 'bytes' in container:
pretty_c['bytes'] = '%s (%s)' % (container['bytes'], size) pretty_c['bytes'] = '%s (%s)' % (container['bytes'], size)
print_dict(pretty_keys(pretty_c), exclude=('name')) print_dict(pretty_c, exclude=('name'))
print print
else: else:
if 'count' in container and 'bytes' in container: if 'count' in container and 'bytes' in container:
...@@ -1761,11 +1761,7 @@ class file_metadata_get(_file_container_command, _optional_json): ...@@ -1761,11 +1761,7 @@ class file_metadata_get(_file_container_command, _optional_json):
until = self['until'] until = self['until']
r = None r = None
if self.container is None: if self.container is None:
if self['detail']: r = self.client.get_account_info(until=until)
r = self.client.get_account_info(until=until)
else:
r = self.client.get_account_meta(until=until)
r = pretty_keys(r, '-')
elif self.path is None: elif self.path is None:
if self['detail']: if self['detail']:
r = self.client.get_container_info(until=until) r = self.client.get_container_info(until=until)
...@@ -1774,9 +1770,9 @@ class file_metadata_get(_file_container_command, _optional_json): ...@@ -1774,9 +1770,9 @@ class file_metadata_get(_file_container_command, _optional_json):
ometa = self.client.get_container_object_meta(until=until) ometa = self.client.get_container_object_meta(until=until)
r = {} r = {}
if cmeta: if cmeta:
r['container-meta'] = pretty_keys(cmeta, '-') r['container-meta'] = cmeta
if ometa: if ometa:
r['object-meta'] = pretty_keys(ometa, '-') r['object-meta'] = ometa
else: else:
if self['detail']: if self['detail']:
r = self.client.get_object_info( r = self.client.get_object_info(
...@@ -1786,7 +1782,6 @@ class file_metadata_get(_file_container_command, _optional_json): ...@@ -1786,7 +1782,6 @@ class file_metadata_get(_file_container_command, _optional_json):
r = self.client.get_object_meta( r = self.client.get_object_meta(
self.path, self.path,
version=self['object_version']) version=self['object_version'])
r = pretty_keys(pretty_keys(r, '-'))
if r: if r:
self._print(r, print_dict) self._print(r, print_dict)
...@@ -1859,7 +1854,7 @@ class file_quota(_file_account_command, _optional_json): ...@@ -1859,7 +1854,7 @@ class file_quota(_file_account_command, _optional_json):
if not self['in_bytes']: if not self['in_bytes']:
for k in output: for k in output:
output[k] = format_size(output[k]) output[k] = format_size(output[k])
pretty_dict(output, '-') print_dict(output, '-')
self._print(self.client.get_account_quota(), pretty_print) self._print(self.client.get_account_quota(), pretty_print)
...@@ -1889,7 +1884,7 @@ class file_containerlimit_get(_file_container_command, _optional_json): ...@@ -1889,7 +1884,7 @@ class file_containerlimit_get(_file_container_command, _optional_json):
if not self['in_bytes']: if not self['in_bytes']:
for k, v in output.items(): for k, v in output.items():
output[k] = 'unlimited' if '0' == v else format_size(v) output[k] = 'unlimited' if '0' == v else format_size(v)
pretty_dict(output, '-') print_dict(output, '-')
self._print( self._print(
self.client.get_container_limit(self.container), pretty_print) self.client.get_container_limit(self.container), pretty_print)
...@@ -2006,7 +2001,7 @@ class file_group_list(_file_account_command, _optional_json): ...@@ -2006,7 +2001,7 @@ class file_group_list(_file_account_command, _optional_json):
@errors.generic.all @errors.generic.all
@errors.pithos.connection @errors.pithos.connection
def _run(self): def _run(self):
self._print(self.client.get_account_group(), pretty_dict, delim='-') self._print(self.client.get_account_group(), print_dict, delim='-')
def main(self): def main(self):
super(self.__class__, self)._run() super(self.__class__, self)._run()
......
...@@ -57,6 +57,11 @@ except ImportError: ...@@ -57,6 +57,11 @@ except ImportError:
suggest['ansicolors']['active'] = True suggest['ansicolors']['active'] = True
def _print(w):
"""Print wrapper is used to help unittests check what is printed"""
print w
def suggest_missing(miss=None, exclude=[]): def suggest_missing(miss=None, exclude=[]):
global suggest global suggest
sgs = dict(suggest) sgs = dict(suggest)
...@@ -116,7 +121,7 @@ def print_json(data): ...@@ -116,7 +121,7 @@ def print_json(data):
:param data: json-dumpable data :param data: json-dumpable data
""" """
print(dumps(data, indent=INDENT_TAB)) _print(dumps(data, indent=INDENT_TAB))
def pretty_dict(d, *args, **kwargs): def pretty_dict(d, *args, **kwargs):
...@@ -156,17 +161,17 @@ def print_dict( ...@@ -156,17 +161,17 @@ def print_dict(
print_str += '%s.' % (i + 1) if with_enumeration else '' print_str += '%s.' % (i + 1) if with_enumeration else ''
print_str += '%s:' % k print_str += '%s:' % k
if isinstance(v, dict): if isinstance(v, dict):
print print_str _print(print_str)
print_dict( print_dict(
v, exclude, indent + INDENT_TAB, v, exclude, indent + INDENT_TAB,
recursive_enumeration, recursive_enumeration) recursive_enumeration, recursive_enumeration)
elif isinstance(v, list) or isinstance(v, tuple): elif isinstance(v, list) or isinstance(v, tuple):
print print_str _print(print_str)
print_list( print_list(
v, exclude, indent + INDENT_TAB, v, exclude, indent + INDENT_TAB,
recursive_enumeration, recursive_enumeration) recursive_enumeration, recursive_enumeration)
else: else:
print '%s %s' % (print_str, v) _print('%s %s' % (print_str, v))
def print_list( def print_list(
...@@ -195,24 +200,23 @@ def print_list( ...@@ -195,24 +200,23 @@ def print_list(
'print_list prinbts a list or tuple') 'print_list prinbts a list or tuple')
assert indent >= 0, 'print_list indent must be >= 0' assert indent >= 0, 'print_list indent must be >= 0'
counter = 0
for i, item in enumerate(l): for i, item in enumerate(l):
print_str = ' ' * indent print_str = ' ' * indent
print_str += '%s.' % (i + 1) if with_enumeration else '' print_str += '%s.' % (i + 1) if with_enumeration else ''
if isinstance(item, dict): if isinstance(item, dict):
if with_enumeration: if with_enumeration:
print print_str _print(print_str)
elif counter and counter < len(l): elif i and i < len(l):
print _print('')
print_dict( print_dict(
item, exclude, item, exclude,
indent + (INDENT_TAB if with_enumeration else 0), indent + (INDENT_TAB if with_enumeration else 0),
recursive_enumeration, recursive_enumeration) recursive_enumeration, recursive_enumeration)
elif isinstance(item, list) or isinstance(item, tuple): elif isinstance(item, list) or isinstance(item, tuple):
if with_enumeration: if with_enumeration:
print print_str _print(print_str)
elif counter and counter < len(l): elif i and i < len(l):
print _print()
print_list( print_list(
item, exclude, indent + INDENT_TAB, item, exclude, indent + INDENT_TAB,
recursive_enumeration, recursive_enumeration) recursive_enumeration, recursive_enumeration)
...@@ -220,8 +224,7 @@ def print_list( ...@@ -220,8 +224,7 @@ def print_list(
item = ('%s' % item).strip() item = ('%s' % item).strip()
if item in exclude: if item in exclude:
continue continue
print '%s%s' % (print_str, item) _print('%s%s' % (print_str, item))
counter += 1
def page_hold(index, limit, maxlen): def page_hold(index, limit, maxlen):
......
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
from unittest import TestCase from unittest import TestCase
#from tempfile import NamedTemporaryFile #from tempfile import NamedTemporaryFile
#from mock import patch, call from mock import patch, call
from itertools import product from itertools import product
...@@ -63,48 +63,143 @@ class UtilsMethods(TestCase): ...@@ -63,48 +63,143 @@ class UtilsMethods(TestCase):
else: else:
self.assertRaises(AssertionError, guess_mime_type, *args) self.assertRaises(AssertionError, guess_mime_type, *args)
def test_pretty_keys(self): @patch('kamaki.cli.utils.dumps', return_value='(dumps output)')
from kamaki.cli.utils import pretty_keys @patch('kamaki.cli.utils._print')
for args, exp in ( def test_print_json(self, PR, JD):
( from kamaki.cli.utils import print_json, INDENT_TAB
({'k1': 'v1', 'k1_k2': 'v2'}, ), print_json('some data')
{'k1': 'v1', 'k1 k2': 'v2'}), JD.assert_called_once_with('some data', indent=INDENT_TAB)
( PR.assert_called_once_with('(dumps output)')
({'k1': 'v1', 'k1_k2': 'v2'}, '1'),
{'k': 'v1', 'k _k2': 'v2'}), @patch('kamaki.cli.utils._print')
( def test_print_dict(self, PR):
({'k1_k2': 'v1', 'k1': {'k2': 'v2', 'k2_k3': 'v3'}}, ), from kamaki.cli.utils import print_dict, INDENT_TAB
{'k1 k2': 'v1', 'k1': {'k2': 'v2', 'k2_k3': 'v3'}}), call_counter = 0
( self.assertRaises(AssertionError, print_dict, 'non-dict think')
( self.assertRaises(AssertionError, print_dict, {}, indent=-10)
{'k1_k2': 'v1', 'k1': {'k2': 'v2', 'k2_k3': 'v3'}}, for args in product(
'_',
True),
{'k1 k2': 'v1', 'k1': {'k2': 'v2', 'k2 k3': 'v3'}}),
( (
( {'k1': 'v1'},
{ {'k1': 'v1', 'k2': 'v2'},
'k1_k2': {'k_1': 'v_1', 'k_2': {'k_3': 'v_3'}}, {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'},
'k1': {'k2': 'v2', 'k2_k3': 'v3'}}, {'k1': 'v1', 'k2': {'k1': 'v1', 'k2': 'v2'}, 'k3': 'v3'},
'_',
True),
{ {
'k1 k2': {'k 1': 'v_1', 'k 2': {'k 3': 'v_3'}}, 'k1': {'k1': 'v1', 'k2': 'v2'},
'k1': {'k2': 'v2', 'k2 k3': 'v3'}}), 'k2': [1, 2, 3],
( 'k3': 'v3'},
( {
{ 'k1': {'k1': 'v1', 'k2': 'v2'},
'k1_k2': {'k_1': 'v_1', 'k_2': {'k_3': 'v_3'}}, 'k2': 42,
'k1': {'k2': 'v2', 'k2_k3': 'v3'}}, 'k3': {'k1': 1, 'k2': [1, 2, 3]}},
'1',
True),
{ {
'k _k2': {'k_': 'v_1', 'k_2': {'k_3': 'v_3'}}, 'k1': {
'k': {'k2': 'v2', 'k2_k3': 'v3'}}) 'k1': 'v1',
): 'k2': [1, 2, 3],
initial = dict(args[0]) 'k3': {'k1': [(1, 2)]}},
self.assert_dicts_are_equal(pretty_keys(*args), exp) 'k2': (3, 4, 5),
self.assert_dicts_are_equal(initial, args[0]) 'k3': {'k1': 1, 'k2': [1, 2, 3]}}),
(tuple(), ('k1', ), ('k1', 'k2')),
(0, 1, 2, 9), (False, True), (False, True)):
d, exclude, indent, with_enumeration, recursive_enumeration = args
with patch('kamaki.cli.utils.print_dict') as PD:
with patch('kamaki.cli.utils.print_list') as PL:
pd_calls, pl_calls = 0, 0
print_dict(*args)
exp_calls = []
for i, (k, v) in enumerate(d.items()):
if k in exclude:
continue
str_k = ' ' * indent
str_k += '%s.' % (i + 1) if with_enumeration else ''
str_k += '%s:' % k
if isinstance(v, dict):
self.assertEqual(
PD.mock_calls[pd_calls],
call(
v,
exclude,
indent + INDENT_TAB,
recursive_enumeration,
recursive_enumeration))
pd_calls += 1
exp_calls.append(call(str_k))
elif isinstance(v, list) or isinstance(v, tuple):
self.assertEqual(
PL.mock_calls[pl_calls],
call(
v,
exclude,
indent + INDENT_TAB,
recursive_enumeration,
recursive_enumeration))
pl_calls += 1
exp_calls.append(call(str_k))
else:
exp_calls.append(call('%s %s' % (str_k, v)))
real_calls = PR.mock_calls[call_counter:]
call_counter = len(PR.mock_calls)
self.assertEqual(sorted(real_calls), sorted(exp_calls))
@patch('kamaki.cli.utils._print')
def test_print_list(self, PR):
from kamaki.cli.utils import print_list, INDENT_TAB
call_counter = 0
self.assertRaises(AssertionError, print_list, 'non-list non-tuple')
self.assertRaises(AssertionError, print_list, {}, indent=-10)
for args in product(
(
['v1', ],
('v2', 'v3'),
[1, '2', 'v3'],
({'k1': 'v1'}, 2, 'v3'),
[(1, 2), 'v2', [(3, 4), {'k3': [5, 6], 'k4': 7}]]),
(tuple(), ('v1', ), ('v1', 1), ('v1', 'k3')),
(0, 1, 2, 9), (False, True), (False, True)):
l, exclude, indent, with_enumeration, recursive_enumeration = args
with patch('kamaki.cli.utils.print_dict') as PD:
with patch('kamaki.cli.utils.print_list') as PL:
pd_calls, pl_calls = 0, 0
print_list(*args)
exp_calls = []
for i, v in enumerate(l):
str_v = ' ' * indent
str_v += '%s.' % (i + 1) if with_enumeration else ''
if isinstance(v, dict):
if with_enumeration:
exp_calls.append(call(str_v))
elif i and i < len(l):
exp_calls.append(call())
self.assertEqual(
PD.mock_calls[pd_calls],
call(
v,
exclude,
indent + (
INDENT_TAB if with_enumeration else 0),
recursive_enumeration,
recursive_enumeration))
pd_calls += 1
elif isinstance(v, list) or isinstance(v, tuple):
if with_enumeration:
exp_calls.append(call(str_v))
elif i and i < len(l):
exp_calls.append(call())
self.assertEqual(
PL.mock_calls[pl_calls],
call(
v,
exclude,
indent + INDENT_TAB,
recursive_enumeration,
recursive_enumeration))
pl_calls += 1
elif ('%s' % v) in exclude:
continue
else:
exp_calls.append(call('%s%s' % (str_v, v)))
real_calls = PR.mock_calls[call_counter:]
call_counter = len(PR.mock_calls)
self.assertEqual(sorted(real_calls), sorted(exp_calls))
if __name__ == '__main__': if __name__ == '__main__':
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment