Completed
Pull Request — master (#75)
by Cézar
01:32
created

lection.IsSequenceOnlyContaining._matches()   B

Complexity

Conditions 5

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 5
dl 0
loc 11
rs 8.5454
1
from hamcrest.core.base_matcher import BaseMatcher
2
from hamcrest.core.core.anyof import any_of
3
from hamcrest.core.helpers.hasmethod import hasmethod
4
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
5
6
__author__ = "Jon Reid"
7
__copyright__ = "Copyright 2011 hamcrest.org"
8
__license__ = "BSD, see License.txt"
9
10
11
class IsSequenceOnlyContaining(BaseMatcher):
12
13
    def __init__(self, matcher):
14
        self.matcher = matcher
15
16
    def _matches(self, sequence):
17
        try:
18
            sequence = list(sequence)
19
            if len(sequence) == 0:
20
                return False
21
            for item in sequence:
22
                if not self.matcher.matches(item):
23
                    return False
24
            return True
25
        except TypeError:
26
            return False
27
28
    def describe_to(self, description):
29
        description.append_text('a sequence containing items matching ')    \
30
                    .append_description_of(self.matcher)
31
32
33
def only_contains(*items):
34
    """Matches if each element of sequence satisfies any of the given matchers.
35
36
    :param match1,...: A comma-separated list of matchers.
37
38
    This matcher iterates the evaluated sequence, confirming whether each
39
    element satisfies any of the given matchers.
40
41
    Example::
42
43
        only_contains(less_than(4))
44
45
    will match ``[3,1,2]``.
46
47
    Any argument that is not a matcher is implicitly wrapped in an
48
    :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
49
    equality.
50
51
    """
52
    matchers = []
53
    for item in items:
54
        matchers.append(wrap_matcher(item))
55
    return IsSequenceOnlyContaining(any_of(*matchers))
56