Completed
Pull Request — master (#81)
by
unknown
01:06
created

SequenceMapsMatcher.describe_to()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
1
from hamcrest.core.base_matcher import BaseMatcher
2
from hamcrest.core.string_description import StringDescription
3
4
5
class SequenceMapsMatcher(BaseMatcher):
6
    def __init__(self, matcher_callable, expected_items):
7
        self.matcher = matcher_callable
8
        self.expected = expected_items
9
        self.description = StringDescription()
10
11
12
    def _matches(self, actual_items):
13
        result = True
14
        for i, (exp, act) in enumerate(zip(self.expected, actual_items)):
15
            matcher = self.matcher(exp)
16
            if not matcher.matches(act):
17
                self.description.append_text("\n          [{0}] ".format(i))
18
                matcher.describe_mismatch(act, self.description)
19
                result = False
20
        return result
21
22
23
    def describe_to(self, description):
24
        description.append("A collection of items, containing:")
25
        for i, item in enumerate(self.expected):
26
            description.append_text(
27
                "\n          [{0}] ".format(i)
28
            ).append_description_of(
29
                self.matcher(item)
30
            )
31
32
33
    def describe_mismatch(self, item, mismatch_description):
34
        mismatch_description.append(self.description)
35
36
37
def maps(matcher_callable, items):
38
    """
39
    Matches if each item of the expected collection matches each corresponding
40
    item in the actual collection using the provided matcher_callable and
41
    in the same order.
42
43
    That is, if you provide :py:func:`~hamcrest.core.core.isequal.equal_to`
44
    as the matcher callable, the 0th item of your actual collection must be equal
45
    to the 0th item of you expected collection, 1st == 1st, and so on.
46
47
    Please note, that unlike in most other cases, you shouldn't call the matcher
48
    function/callable yourself.
49
50
    `assert_that([1, 2, 3], maps(equal_to, [1, 2, 3])`
51
52
    :param matcher_callable: The matcher callable that must be applied to the items.
53
    :type matcher_callable: :py:class:`~hamcrest.core.base_matcher.BaseMatcher`
54
    :param items: Expected collection of items
55
    :type items:
56
    :return: matcher
57
    :rtype: :py:class:`~hamcrest.core.base_matcher.BaseMatcher`
58
    """
59
    return SequenceMapsMatcher(matcher_callable, items)
60