From 78e99b0eb25d5bd81d8f183f50bc91bed2d1fcf5 Mon Sep 17 00:00:00 2001 From: Simon Brunning Date: Thu, 3 Mar 2022 13:31:21 +0000 Subject: [PATCH] Ordered comparison matchers should fail for incomparable types. Fix for #185 --- src/hamcrest/library/number/ordering_comparison.py | 5 ++++- .../issequence_containinginanyorder_test.py | 11 +++++++++++ .../number/ordering_comparison_test.py | 3 +++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/hamcrest/library/number/ordering_comparison.py b/src/hamcrest/library/number/ordering_comparison.py index 6c6275d..f121caf 100644 --- a/src/hamcrest/library/number/ordering_comparison.py +++ b/src/hamcrest/library/number/ordering_comparison.py @@ -22,7 +22,10 @@ class OrderingComparison(BaseMatcher[Any]): 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( diff --git a/tests/hamcrest_unit_test/collection/issequence_containinginanyorder_test.py b/tests/hamcrest_unit_test/collection/issequence_containinginanyorder_test.py index 5c21fbb..b36d192 100644 --- a/tests/hamcrest_unit_test/collection/issequence_containinginanyorder_test.py +++ b/tests/hamcrest_unit_test/collection/issequence_containinginanyorder_test.py @@ -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 @@ -84,6 +85,16 @@ class IsSequenceContainingInAnyOrderBase(object): "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 diff --git a/tests/hamcrest_unit_test/number/ordering_comparison_test.py b/tests/hamcrest_unit_test/number/ordering_comparison_test.py index 76143df..d944519 100644 --- a/tests/hamcrest_unit_test/number/ordering_comparison_test.py +++ b/tests/hamcrest_unit_test/number/ordering_comparison_test.py @@ -67,6 +67,9 @@ class OrderingComparisonTest(MatcherTest): 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() -- 2.27.0