src.hamcrest.library.object.HasLength   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 19
Duplicated Lines 0 %
Metric Value
dl 0
loc 19
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A describe_mismatch() 0 5 2
A describe_to() 0 3 1
A _matches() 0 4 2
A __init__() 0 2 1
1
from hamcrest.core.base_matcher import BaseMatcher
2
from hamcrest.core.helpers.hasmethod import hasmethod
3
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
4
5
__author__ = "Jon Reid"
6
__copyright__ = "Copyright 2011 hamcrest.org"
7
__license__ = "BSD, see License.txt"
8
9
10
class HasLength(BaseMatcher):
11
12
    def __init__(self, len_matcher):
13
        self.len_matcher = len_matcher
14
15
    def _matches(self, item):
16
        if not hasmethod(item, '__len__'):
17
            return False
18
        return self.len_matcher.matches(len(item))
19
20
    def describe_mismatch(self, item, mismatch_description):
21
        super(HasLength, self).describe_mismatch(item, mismatch_description)
22
        if hasmethod(item, '__len__'):
23
            mismatch_description.append_text(' with length of ')    \
24
                                .append_description_of(len(item))
25
26
    def describe_to(self, description):
27
        description.append_text('an object with length of ')    \
28
                    .append_description_of(self.len_matcher)
29
30
31
def has_length(match):
32
    """Matches if ``len(item)`` satisfies a given matcher.
33
34
    :param match: The matcher to satisfy, or an expected value for
35
        :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
36
37
    This matcher invokes the :py:func:`len` function on the evaluated object to
38
    get its length, passing the result to a given matcher for evaluation.
39
40
    If the ``match`` argument is not a matcher, it is implicitly wrapped in an
41
    :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
42
    :equality.
43
44
    Examples::
45
46
        has_length(greater_than(6))
47
        has_length(5)
48
49
    """
50
    return HasLength(wrap_matcher(match))
51