From 8995e7a69c397b53cf17ccfec68eac85b141d272 Mon Sep 17 00:00:00 2001 From: Robert Grant Date: Sat, 28 Mar 2020 21:43:22 -0700 Subject: [PATCH] Add tests for utils.friendly_join --- tests/test_utils.py | 20 ++++++++++++++++++++ tsplib95/utils.py | 12 ++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 tests/test_utils.py diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..1b2d00a --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,20 @@ +import pytest + +from tsplib95 import utils + + +@pytest.mark.parametrize('items,kw,result,exc', [ + ([], {}, '', None), + (list('abc'), {}, 'a, b, and c', None), + (list('abc'), {'limit': 3}, 'a, b, and c', None), + (list('a'), {'limit': 3}, 'a', None), + (list('ab'), {'limit': 3}, 'a and b', None), + (list('abcd'), {'limit': 3}, 'a, b, c, and 1 more', None), + (list('abcde'), {'limit': 3}, 'a, b, c, and 2 more', None), +]) +def test_friendly_join(items, kw, result, exc): + if exc is not None: + with pytest.raises(exc): + utils.friendly_join(items, **kw) + else: + assert utils.friendly_join(items, **kw) == result diff --git a/tsplib95/utils.py b/tsplib95/utils.py index 850de4b..6109e89 100644 --- a/tsplib95/utils.py +++ b/tsplib95/utils.py @@ -117,10 +117,14 @@ def friendly_join(items, limit=None): if limit is not None: truncated = len(items) - limit items = items[:limit] - items.append(f'{truncated} more') + if truncated > 0: + items.append(f'{truncated} more') - *items, last = items + *items, last_item = items if not items: - return str(last) + return str(last_item) - return f'{", ".join(items)} and {last}' + # oxford commas are important + if len(items) == 1: + return f'{items[0]} and {last_item}' + return f'{", ".join(items)}, and {last_item}'