From dba7b6a3bbe702dfe0f66857ba01caadd9bb6832 Mon Sep 17 00:00:00 2001 From: Rokas Maciulaitis Date: Wed, 15 Jan 2020 13:41:15 +0100 Subject: [PATCH] utils: fixes CLI filtering * Addresses reanahub/reana-client/issues/349 --- reana_commons/utils.py | 12 +++++++++--- tests/test_utils.py | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/reana_commons/utils.py b/reana_commons/utils.py index b8bcc124..96854b19 100644 --- a/reana_commons/utils.py +++ b/reana_commons/utils.py @@ -26,15 +26,19 @@ 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] @@ -42,6 +46,8 @@ def click_table_printer(headers, _filter, data): # 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)) diff --git a/tests/test_utils.py b/tests/test_utils.py index 6a6baa27..ab8cba64 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -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')