New matcher, AnyMatch.

This commit is contained in:
Jonathan Lange
2012-12-15 13:35:59 +00:00
3 changed files with 60 additions and 0 deletions

7
NEWS
View File

@@ -6,6 +6,13 @@ Changes and improvements to testtools_, grouped by release.
NEXT
~~~~
Improvements
------------
* ``AnyMatch`` added, a new matcher that matches when any item in a collection
matches the given matcher. (Jonathan Lange)
0.9.22
~~~~~~

View File

@@ -236,6 +236,26 @@ class AllMatch(object):
return MismatchesAll(mismatches)
class AnyMatch(object):
"""Matches if any of the provided values match the given matcher."""
def __init__(self, matcher):
self.matcher = matcher
def __str__(self):
return 'AnyMatch(%s)' % (self.matcher,)
def match(self, values):
mismatches = []
for value in values:
mismatch = self.matcher.match(value)
if mismatch:
mismatches.append(mismatch)
else:
return None
return MismatchesAll(mismatches)
class MatchesPredicate(Matcher):
"""Match if a given function returns True.

View File

@@ -14,6 +14,7 @@ from testtools.matchers._higherorder import (
AllMatch,
Annotate,
AnnotatedMismatch,
AnyMatch,
MatchesAny,
MatchesAll,
MatchesPredicate,
@@ -50,6 +51,38 @@ class TestAllMatch(TestCase, TestMatchersInterface):
]
class TestAnyMatch(TestCase, TestMatchersInterface):
matches_matcher = AnyMatch(Equals('elephant'))
matches_matches = [
['grass', 'cow', 'steak', 'milk', 'elephant'],
(13, 'elephant'),
['elephant', 'elephant', 'elephant'],
set(['hippo', 'rhino', 'elephant']),
]
matches_mismatches = [
[],
['grass', 'cow', 'steak', 'milk'],
(13, 12, 10),
['element', 'hephalump', 'pachyderm'],
set(['hippo', 'rhino', 'diplodocus']),
]
str_examples = [
("AnyMatch(Equals('elephant'))", AnyMatch(Equals('elephant'))),
]
describe_examples = [
('Differences: [\n'
'7 != 11\n'
'7 != 9\n'
'7 != 10\n'
']',
[11, 9, 10],
AnyMatch(Equals(7))),
]
class TestAfterPreprocessing(TestCase, TestMatchersInterface):
def parity(x):