Skip to content

Commit

Permalink
Add tests for utils.friendly_join
Browse files Browse the repository at this point in the history
  • Loading branch information
rhgrant10 committed Mar 29, 2020
1 parent 86b5541 commit 8995e7a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
20 changes: 20 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -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
12 changes: 8 additions & 4 deletions tsplib95/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}'

0 comments on commit 8995e7a

Please sign in to comment.