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 IsDictContaining(BaseMatcher): |
11
|
|
|
|
12
|
|
|
def __init__(self, key_matcher, value_matcher): |
13
|
|
|
self.key_matcher = key_matcher |
14
|
|
|
self.value_matcher = value_matcher |
15
|
|
|
|
16
|
|
|
def _matches(self, dictionary): |
17
|
|
|
if hasmethod(dictionary, 'items'): |
18
|
|
|
for key, value in dictionary.items(): |
19
|
|
|
if self.key_matcher.matches(key) and self.value_matcher.matches(value): |
20
|
|
|
return True |
21
|
|
|
return False |
22
|
|
|
|
23
|
|
|
def describe_to(self, description): |
24
|
|
|
description.append_text('a dictionary containing [') \ |
25
|
|
|
.append_description_of(self.key_matcher) \ |
26
|
|
|
.append_text(': ') \ |
27
|
|
|
.append_description_of(self.value_matcher) \ |
28
|
|
|
.append_text(']') |
29
|
|
|
|
30
|
|
|
|
31
|
|
|
def has_entry(key_match, value_match): |
32
|
|
|
"""Matches if dictionary contains key-value entry satisfying a given pair |
33
|
|
|
of matchers. |
34
|
|
|
|
35
|
|
|
:param key_match: The matcher to satisfy for the key, or an expected value |
36
|
|
|
for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. |
37
|
|
|
:param value_match: The matcher to satisfy for the value, or an expected |
38
|
|
|
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. |
39
|
|
|
|
40
|
|
|
This matcher iterates the evaluated dictionary, searching for any key-value |
41
|
|
|
entry that satisfies ``key_match`` and ``value_match``. If a matching entry |
42
|
|
|
is found, ``has_entry`` is satisfied. |
43
|
|
|
|
44
|
|
|
Any argument that is not a matcher is implicitly wrapped in an |
45
|
|
|
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for |
46
|
|
|
equality. |
47
|
|
|
|
48
|
|
|
Examples:: |
49
|
|
|
|
50
|
|
|
has_entry(equal_to('foo'), equal_to(1)) |
51
|
|
|
has_entry('foo', 1) |
52
|
|
|
|
53
|
|
|
""" |
54
|
|
|
return IsDictContaining(wrap_matcher(key_match), wrap_matcher(value_match)) |
55
|
|
|
|