Skip to content

Commit

Permalink
utils: fixes CLI filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
Rokas Maciulaitis committed Jan 16, 2020
1 parent f558c06 commit dba7b6a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
12 changes: 9 additions & 3 deletions reana_commons/utils.py
Expand Up @@ -26,22 +26,28 @@
def click_table_printer(headers, _filter, data):
"""Generate space separated output for click commands."""
_filter = [h.lower() for h in _filter] + [h.upper() for h in _filter]
header_indexes = [i for i, item in enumerate(headers)]
if _filter:
header_indexes = \
[i for i, item in enumerate(headers) if item.upper() in _filter]
headers = [h for h in headers if not _filter or h in _filter]
# Maximum header width
header_widths = [len(h) for h in headers]

for row in data:
for idx in range(len(headers)):
for i, idx in enumerate(header_indexes):
# If a row contains an element which is wider update maximum width
if header_widths[idx] < len(str(row[idx])):
header_widths[idx] = len(str(row[idx]))
if header_widths[i] < len(str(row[idx])):
header_widths[i] = len(str(row[idx]))
# Prepare the format string with the maximum widths
formatted_output_parts = ['{{:<{0}}}'.format(hw)
for hw in header_widths]
formatted_output = ' '.join(formatted_output_parts)
# Print the table with the headers capitalized
click.echo(formatted_output.format(*[h.upper() for h in headers]))
for row in data:
if header_indexes:
row = [row[i] for i in header_indexes]
click.echo(formatted_output.format(*row))


Expand Down
20 changes: 20 additions & 0 deletions tests/test_utils.py
Expand Up @@ -32,6 +32,26 @@ def test_click_table_printer(capsys):
'\nvery_very_long_row_two\n'


def test_click_table_printer_filter(capsys):
"""Test click_table_printer with filter."""
headers = ['header_one', 'header_two']
sample_data = [['very_very_long_row_one', 'second_column'],
['very_very_long_row_two', 'second_column']]
click_table_printer(headers, [headers[1]], sample_data)
out, err = capsys.readouterr()
assert out == 'HEADER_TWO \nsecond_column\nsecond_column\n'


def test_click_table_printer_filter_wrong_header(capsys):
"""Test click_table_printer with filter when header is non existing."""
headers = ['header_one', 'header_two']
sample_data = [['very_very_long_row_one', 'second_column'],
['very_very_long_row_two', 'second_column']]
click_table_printer(headers, ['badheader'], sample_data)
out, err = capsys.readouterr()
assert out == '\n\n\n'


def test_calculate_hash_of_dir(sample_workflow_workspace):
"""Test calculate_hash_of_dir."""
non_existing_dir_hash = calculate_hash_of_dir('a/b/c')
Expand Down

0 comments on commit dba7b6a

Please sign in to comment.