Completed
Pull Request — master (#78)
by
unknown
37s
created

IsSequenceOnlyContaining._matches()   A

Complexity

Conditions 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 9
rs 9.2
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
            for item in sequence:
20
                if not self.matcher.matches(item):
21
                    return False
22
            return True
23
        except TypeError:
24
            return False
25
26
    def describe_to(self, description):
27
        description.append_text('a sequence containing items matching ')    \
28
                    .append_description_of(self.matcher)
29
30
31
def only_contains(*items):
32
    """Matches if each element of sequence satisfies any of the given matchers.
33
34
    :param match1,...: A comma-separated list of matchers.
35
36
    This matcher iterates the evaluated sequence, confirming whether each
37
    element satisfies any of the given matchers.
38
39
    Example::
40
41
        only_contains(less_than(4))
42
43
    will match ``[3,1,2]``.
44
45
    Any argument that is not a matcher is implicitly wrapped in an
46
    :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
47
    equality.
48
49
    """
50
    matchers = []
51
    for item in items:
52
        matchers.append(wrap_matcher(item))
53
    return IsSequenceOnlyContaining(any_of(*matchers))
54