Skip to content

Commit

Permalink
fix output printing on dict with no printable keys (google#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
jtratner authored and dbieber committed Mar 28, 2017
1 parent 51fc990 commit ea80933
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 8 deletions.
15 changes: 7 additions & 8 deletions fire/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,21 +214,20 @@ def _DictAsString(result, verbose=False):
Returns:
A string representing the dict
"""
result = {key: value for key, value in result.items()
if _ComponentVisible(key, verbose)}

if not result:
return '{}'

longest_key = max(
len(str(key)) for key in result.keys()
if _ComponentVisible(key, verbose)
)
longest_key = max(len(str(key)) for key in result.keys())
format_string = '{{key:{padding}s}} {{value}}'.format(padding=longest_key + 1)

lines = []
for key, value in result.items():
if _ComponentVisible(key, verbose):
line = format_string.format(
key=str(key) + ':', value=_OneLineResult(value))
lines.append(line)
line = format_string.format(key=str(key) + ':',
value=_OneLineResult(value))
lines.append(line)
return '\n'.join(lines)


Expand Down
7 changes: 7 additions & 0 deletions fire/core_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,12 @@ def testFireErrorMultipleValues(self):
error = core.FireError('Example error', 'value')
self.assertIsNotNone(error)

def testPrintEmptyDict(self):
with self.assertStdoutMatches('{}'):
core.Fire(tc.EmptyDictOutput, 'totally_empty')
with self.assertStdoutMatches('{}'):
core.Fire(tc.EmptyDictOutput, 'nothing_printable')


if __name__ == '__main__':
testutils.main()
8 changes: 8 additions & 0 deletions fire/test_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,11 @@ def __eq__(self, other):

def __ne__(self, other):
raise ValueError('Instances of this class cannot be compared.')


class EmptyDictOutput(object):
def totally_empty(self):
return {}

def nothing_printable(self):
return {'__do_not_print_me': 1}
9 changes: 9 additions & 0 deletions fire/testutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@

class BaseTestCase(unittest.TestCase):
"""Shared test case for Python Fire tests."""
@contextlib.contextmanager
def assertStdoutMatches(self, regexp):
"""Asserts the context generates stdout matching regexp"""
stdout = six.StringIO()
with mock.patch.object(sys, 'stdout', stdout):
yield
value = stdout.getvalue()
if not re.search(regexp, value, re.DOTALL | re.MULTILINE):
raise AssertionError('Expected %r to match %r' % (value, regexp))

@contextlib.contextmanager
def assertRaisesFireExit(self, code, regexp=None):
Expand Down

0 comments on commit ea80933

Please sign in to comment.