Skip to content

Commit

Permalink
Nicer errors in assert_ordered.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jan 6, 2019
1 parent c5868e0 commit aa89f23
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
8 changes: 8 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
4.3
===

Nicer error message in ``assert_ordered`` when the assertion
fails. Now reports the full supplied items and not just the keys
in the errors. When ``<`` or ``>`` are used, the error message
renders more directly.

4.2
===

Expand Down
11 changes: 8 additions & 3 deletions jaraco/itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,15 +1034,20 @@ def assert_ordered(iterable, key=lambda x: x, comp=operator.le):
>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.gt))
>>> list(assert_ordered(range(5), comp=operator.ge))
Traceback (most recent call last):
...
AssertionError: not <built-in function gt> (0, 1)
AssertionError: 0 < 1
>>> list(assert_ordered(range(5, 0, -1), key=operator.neg))
[5, 4, 3, 2, 1]
"""
err_tmpl = (
"{pair[0]} > {pair[1]}" if comp is operator.le else
"{pair[0]} < {pair[1]}" if comp is operator.ge else
"not {comp} {pair}"
)
for pair in more_itertools.pairwise(iterable):
keyed = tuple(map(key, pair))
assert comp(*keyed), "not {comp} {keyed}".format(**locals())
assert comp(*keyed), err_tmpl.format(**locals())
yield pair[0]
yield pair[1]

0 comments on commit aa89f23

Please sign in to comment.