src.hamcrest.library.collection.IsDictContainingKey   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A describe_to() 0 3 1
A _matches() 0 6 4
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 IsDictContainingKey(BaseMatcher):
11
12
    def __init__(self, key_matcher):
13
        self.key_matcher = key_matcher
14
15
    def _matches(self, dictionary):
16
        if hasmethod(dictionary, 'keys'):
17
            for key in dictionary.keys():
18
                if self.key_matcher.matches(key):
19
                    return True
20
        return False
21
22
    def describe_to(self, description):
23
        description.append_text('a dictionary containing key ')     \
24
                    .append_description_of(self.key_matcher)
25
26
27
def has_key(key_match):
28
    """Matches if dictionary contains an entry whose key satisfies a given
29
    matcher.
30
31
    :param key_match: The matcher to satisfy for the key, or an expected value
32
        for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
33
34
    This matcher iterates the evaluated dictionary, searching for any key-value
35
    entry whose key satisfies the given matcher. If a matching entry is found,
36
    ``has_key`` is satisfied.
37
38
    Any argument that is not a matcher is implicitly wrapped in an
39
    :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
40
    equality.
41
42
    Examples::
43
44
        has_key(equal_to('foo'))
45
        has_key('foo')
46
47
    """
48
    return IsDictContainingKey(wrap_matcher(key_match))
49