Skip to content

Commit

Permalink
Ordered comparison matchers should fail for incomparable types. Fix for
Browse files Browse the repository at this point in the history
  • Loading branch information
brunns authored and offbyone committed Mar 3, 2022
1 parent cbc5095 commit 78e99b0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/hamcrest/library/number/ordering_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ def __init__(
self.comparison_description = comparison_description

def _matches(self, item: Any) -> bool:
return self.comparison_function(item, self.value)
try:
return self.comparison_function(item, self.value)
except TypeError:
return False

def describe_to(self, description: Description) -> None:
description.append_text("a value ").append_text(self.comparison_description).append_text(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest

from hamcrest import greater_than
from hamcrest.core.core.isequal import equal_to
from hamcrest.library.collection.issequence_containinginanyorder import contains_inanyorder
from hamcrest_unit_test.matcher_test import MatcherTest
Expand Down Expand Up @@ -84,6 +85,16 @@ def testDescribeMismatchAfterMatch(self):
"no item matches: <2> in [<3>, <1>]", matcher, self._sequence(3, 1)
)

def testIncomparableTypes(self):
self.assert_matches("Incomparable types", contains_inanyorder(*[4, "a"]), ["a", 4])

def testIncomparableTypesInNestedMatcher(self):
self.assert_matches(
"Incomparable types in nested matcher",
contains_inanyorder(*[greater_than(0), "a"]),
["a", 4],
)


class IsConcreteSequenceContainingInAnyOrderTest(
MatcherTest, IsSequenceContainingInAnyOrderBase, SequenceForm
Expand Down
3 changes: 3 additions & 0 deletions tests/hamcrest_unit_test/number/ordering_comparison_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ def testDescribeMismatch(self):
self.assert_describe_mismatch("was <0>", greater_than_or_equal_to(1), 0)
self.assert_describe_mismatch("was <2>", less_than_or_equal_to(1), 2)

def testIncomparableTypes(self):
self.assert_does_not_match("incomparable types", greater_than(1), "a")


if __name__ == "__main__":
unittest.main()

0 comments on commit 78e99b0

Please sign in to comment.