Ausgabe der neuen DB Einträge
This commit is contained in:
parent
bad48e1627
commit
cfbbb9ee3d
2399 changed files with 843193 additions and 43 deletions
|
|
@ -0,0 +1,44 @@
|
|||
"""Library of Matcher implementations."""
|
||||
|
||||
from hamcrest.core import *
|
||||
from hamcrest.library.collection import *
|
||||
from hamcrest.library.integration import *
|
||||
from hamcrest.library.number import *
|
||||
from hamcrest.library.object import *
|
||||
from hamcrest.library.text import *
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
__all__ = [
|
||||
"has_entry",
|
||||
"has_entries",
|
||||
"has_key",
|
||||
"has_value",
|
||||
"is_in",
|
||||
"empty",
|
||||
"has_item",
|
||||
"has_items",
|
||||
"contains_inanyorder",
|
||||
"contains",
|
||||
"contains_exactly",
|
||||
"only_contains",
|
||||
"match_equality",
|
||||
"matches_regexp",
|
||||
"close_to",
|
||||
"greater_than",
|
||||
"greater_than_or_equal_to",
|
||||
"less_than",
|
||||
"less_than_or_equal_to",
|
||||
"has_length",
|
||||
"has_property",
|
||||
"has_properties",
|
||||
"has_string",
|
||||
"equal_to_ignoring_case",
|
||||
"equal_to_ignoring_whitespace",
|
||||
"contains_string",
|
||||
"ends_with",
|
||||
"starts_with",
|
||||
"string_contains_in_order",
|
||||
]
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
"""Matchers of collections."""
|
||||
from .is_empty import empty
|
||||
from .isdict_containing import has_entry
|
||||
from .isdict_containingentries import has_entries
|
||||
from .isdict_containingkey import has_key
|
||||
from .isdict_containingvalue import has_value
|
||||
from .isin import is_in
|
||||
from .issequence_containing import has_item, has_items
|
||||
from .issequence_containinginanyorder import contains_inanyorder
|
||||
from .issequence_containinginorder import contains, contains_exactly
|
||||
from .issequence_onlycontaining import only_contains
|
||||
|
||||
__author__ = "Chris Rose"
|
||||
__copyright__ = "Copyright 2013 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
from typing import Optional, Sized
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Chris Rose"
|
||||
__copyright__ = "Copyright 2012 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class IsEmpty(BaseMatcher[Sized]):
|
||||
def matches(self, item: Sized, mismatch_description: Optional[Description] = None) -> bool:
|
||||
try:
|
||||
if len(item) == 0:
|
||||
return True
|
||||
|
||||
if mismatch_description:
|
||||
mismatch_description.append_text("has %d item(s)" % len(item))
|
||||
|
||||
except TypeError:
|
||||
if mismatch_description:
|
||||
mismatch_description.append_text("does not support length")
|
||||
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("an empty collection")
|
||||
|
||||
|
||||
def empty() -> Matcher[Sized]:
|
||||
"""
|
||||
This matcher matches any collection-like object that responds to the
|
||||
__len__ method, and has a length of 0.
|
||||
"""
|
||||
return IsEmpty()
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
from typing import Hashable, Mapping, TypeVar, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
K = TypeVar("K", bound=Hashable) # TODO - covariant?
|
||||
V = TypeVar("V")
|
||||
|
||||
|
||||
class IsDictContaining(BaseMatcher[Mapping[K, V]]):
|
||||
def __init__(self, key_matcher: Matcher[K], value_matcher: Matcher[V]) -> None:
|
||||
self.key_matcher = key_matcher
|
||||
self.value_matcher = value_matcher
|
||||
|
||||
def _matches(self, item: Mapping[K, V]) -> bool:
|
||||
if hasmethod(item, "items"):
|
||||
for key, value in item.items():
|
||||
if self.key_matcher.matches(key) and self.value_matcher.matches(value):
|
||||
return True
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a dictionary containing [").append_description_of(
|
||||
self.key_matcher
|
||||
).append_text(": ").append_description_of(self.value_matcher).append_text("]")
|
||||
|
||||
|
||||
def has_entry(
|
||||
key_match: Union[K, Matcher[K]], value_match: Union[V, Matcher[V]]
|
||||
) -> Matcher[Mapping[K, V]]:
|
||||
"""Matches if dictionary contains key-value entry satisfying a given pair
|
||||
of matchers.
|
||||
|
||||
:param key_match: The matcher to satisfy for the key, or an expected value
|
||||
for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
:param value_match: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher iterates the evaluated dictionary, searching for any key-value
|
||||
entry that satisfies ``key_match`` and ``value_match``. If a matching entry
|
||||
is found, ``has_entry`` is satisfied.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_entry(equal_to('foo'), equal_to(1))
|
||||
has_entry('foo', 1)
|
||||
|
||||
"""
|
||||
return IsDictContaining(wrap_matcher(key_match), wrap_matcher(value_match))
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
from typing import Any, Hashable, Mapping, Optional, TypeVar, Union, overload
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
K = TypeVar("K", bound=Hashable)
|
||||
V = TypeVar("V")
|
||||
|
||||
|
||||
class IsDictContainingEntries(BaseMatcher[Mapping[K, V]]):
|
||||
def __init__(self, value_matchers) -> None:
|
||||
self.value_matchers = sorted(value_matchers.items())
|
||||
|
||||
def _not_a_dictionary(
|
||||
self, item: Mapping[K, V], mismatch_description: Optional[Description]
|
||||
) -> bool:
|
||||
if mismatch_description:
|
||||
mismatch_description.append_description_of(item).append_text(" is not a mapping object")
|
||||
return False
|
||||
|
||||
def matches(
|
||||
self, item: Mapping[K, V], mismatch_description: Optional[Description] = None
|
||||
) -> bool:
|
||||
for key, value_matcher in self.value_matchers:
|
||||
|
||||
try:
|
||||
if not key in item:
|
||||
if mismatch_description:
|
||||
mismatch_description.append_text("no ").append_description_of(
|
||||
key
|
||||
).append_text(" key in ").append_description_of(item)
|
||||
return False
|
||||
except TypeError:
|
||||
return self._not_a_dictionary(item, mismatch_description)
|
||||
|
||||
try:
|
||||
actual_value = item[key]
|
||||
except TypeError:
|
||||
return self._not_a_dictionary(item, mismatch_description)
|
||||
|
||||
if not value_matcher.matches(actual_value):
|
||||
if mismatch_description:
|
||||
mismatch_description.append_text("value for ").append_description_of(
|
||||
key
|
||||
).append_text(" ")
|
||||
value_matcher.describe_mismatch(actual_value, mismatch_description)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def describe_mismatch(self, item: Mapping[K, V], mismatch_description: Description) -> None:
|
||||
self.matches(item, mismatch_description)
|
||||
|
||||
def describe_keyvalue(self, index: int, value: V, description: Description) -> None:
|
||||
"""Describes key-value pair at given index."""
|
||||
description.append_description_of(index).append_text(": ").append_description_of(value)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a dictionary containing {")
|
||||
first = True
|
||||
for key, value in self.value_matchers:
|
||||
if not first:
|
||||
description.append_text(", ")
|
||||
self.describe_keyvalue(key, value, description)
|
||||
first = False
|
||||
description.append_text("}")
|
||||
|
||||
|
||||
# Keyword argument form
|
||||
@overload
|
||||
def has_entries(**keys_valuematchers: Union[Matcher[V], V]) -> Matcher[Mapping[str, V]]:
|
||||
...
|
||||
|
||||
|
||||
# Key to matcher dict form
|
||||
@overload
|
||||
def has_entries(keys_valuematchers: Mapping[K, Union[Matcher[V], V]]) -> Matcher[Mapping[K, V]]:
|
||||
...
|
||||
|
||||
|
||||
# Alternating key/matcher form
|
||||
@overload
|
||||
def has_entries(*keys_valuematchers: Any) -> Matcher[Mapping[Any, Any]]:
|
||||
...
|
||||
|
||||
|
||||
def has_entries(*keys_valuematchers, **kv_args):
|
||||
"""Matches if dictionary contains entries satisfying a dictionary of keys
|
||||
and corresponding value matchers.
|
||||
|
||||
:param matcher_dict: A dictionary mapping keys to associated value matchers,
|
||||
or to expected values for
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Note that the keys must be actual keys, not matchers. Any value argument
|
||||
that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_entries({'foo':equal_to(1), 'bar':equal_to(2)})
|
||||
has_entries({'foo':1, 'bar':2})
|
||||
|
||||
``has_entries`` also accepts a list of keyword arguments:
|
||||
|
||||
.. function:: has_entries(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]])
|
||||
|
||||
:param keyword1: A keyword to look up.
|
||||
:param valueMatcher1: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Examples::
|
||||
|
||||
has_entries(foo=equal_to(1), bar=equal_to(2))
|
||||
has_entries(foo=1, bar=2)
|
||||
|
||||
Finally, ``has_entries`` also accepts a list of alternating keys and their
|
||||
value matchers:
|
||||
|
||||
.. function:: has_entries(key1, value_matcher1[, ...])
|
||||
|
||||
:param key1: A key (not a matcher) to look up.
|
||||
:param valueMatcher1: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Examples::
|
||||
|
||||
has_entries('foo', equal_to(1), 'bar', equal_to(2))
|
||||
has_entries('foo', 1, 'bar', 2)
|
||||
|
||||
"""
|
||||
if len(keys_valuematchers) == 1:
|
||||
try:
|
||||
base_dict = keys_valuematchers[0].copy()
|
||||
for key in base_dict:
|
||||
base_dict[key] = wrap_matcher(base_dict[key])
|
||||
except AttributeError:
|
||||
raise ValueError(
|
||||
"single-argument calls to has_entries must pass a dict as the argument"
|
||||
)
|
||||
else:
|
||||
if len(keys_valuematchers) % 2:
|
||||
raise ValueError("has_entries requires key-value pairs")
|
||||
base_dict = {}
|
||||
for index in range(int(len(keys_valuematchers) / 2)):
|
||||
base_dict[keys_valuematchers[2 * index]] = wrap_matcher(
|
||||
keys_valuematchers[2 * index + 1]
|
||||
)
|
||||
|
||||
for key, value in kv_args.items():
|
||||
base_dict[key] = wrap_matcher(value)
|
||||
|
||||
return IsDictContainingEntries(base_dict)
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
from typing import Any, Hashable, Mapping, TypeVar, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
K = TypeVar("K", bound=Hashable)
|
||||
|
||||
|
||||
class IsDictContainingKey(BaseMatcher[Mapping[K, Any]]):
|
||||
def __init__(self, key_matcher: Matcher[K]) -> None:
|
||||
self.key_matcher = key_matcher
|
||||
|
||||
def _matches(self, item: Mapping[K, Any]) -> bool:
|
||||
if hasmethod(item, "keys"):
|
||||
for key in item.keys():
|
||||
if self.key_matcher.matches(key):
|
||||
return True
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a dictionary containing key ").append_description_of(
|
||||
self.key_matcher
|
||||
)
|
||||
|
||||
|
||||
def has_key(key_match: Union[K, Matcher[K]]) -> Matcher[Mapping[K, Any]]:
|
||||
"""Matches if dictionary contains an entry whose key satisfies a given
|
||||
matcher.
|
||||
|
||||
:param key_match: The matcher to satisfy for the key, or an expected value
|
||||
for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher iterates the evaluated dictionary, searching for any key-value
|
||||
entry whose key satisfies the given matcher. If a matching entry is found,
|
||||
``has_key`` is satisfied.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_key(equal_to('foo'))
|
||||
has_key('foo')
|
||||
|
||||
"""
|
||||
return IsDictContainingKey(wrap_matcher(key_match))
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
from typing import Any, Mapping, TypeVar, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
V = TypeVar("V")
|
||||
|
||||
|
||||
class IsDictContainingValue(BaseMatcher[Mapping[Any, V]]):
|
||||
def __init__(self, value_matcher: Matcher[V]) -> None:
|
||||
self.value_matcher = value_matcher
|
||||
|
||||
def _matches(self, item: Mapping[Any, V]) -> bool:
|
||||
if hasmethod(item, "values"):
|
||||
for value in item.values():
|
||||
if self.value_matcher.matches(value):
|
||||
return True
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a dictionary containing value ").append_description_of(
|
||||
self.value_matcher
|
||||
)
|
||||
|
||||
|
||||
def has_value(value: Union[V, Matcher[V]]) -> Matcher[Mapping[Any, V]]:
|
||||
"""Matches if dictionary contains an entry whose value satisfies a given
|
||||
matcher.
|
||||
|
||||
:param value_match: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher iterates the evaluated dictionary, searching for any key-value
|
||||
entry whose value satisfies the given matcher. If a matching entry is
|
||||
found, ``has_value`` is satisfied.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_value(equal_to('bar'))
|
||||
has_value('bar')
|
||||
|
||||
"""
|
||||
return IsDictContainingValue(wrap_matcher(value))
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
from typing import Sequence, TypeVar
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class IsIn(BaseMatcher[T]):
|
||||
def __init__(self, sequence: Sequence[T]) -> None:
|
||||
self.sequence = sequence
|
||||
|
||||
def _matches(self, item: T) -> bool:
|
||||
return item in self.sequence
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("one of ").append_list("(", ", ", ")", self.sequence)
|
||||
|
||||
|
||||
def is_in(sequence: Sequence[T]) -> Matcher[T]:
|
||||
"""Matches if evaluated object is present in a given sequence.
|
||||
|
||||
:param sequence: The sequence to search.
|
||||
|
||||
This matcher invokes the ``in`` membership operator to determine if the
|
||||
evaluated object is a member of the sequence.
|
||||
|
||||
"""
|
||||
return IsIn(sequence)
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
from typing import Sequence, TypeVar, Union, cast
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.core.allof import all_of
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class IsSequenceContaining(BaseMatcher[Sequence[T]]):
|
||||
def __init__(self, element_matcher: Matcher[T]) -> None:
|
||||
self.element_matcher = element_matcher
|
||||
|
||||
def _matches(self, item: Sequence[T]) -> bool:
|
||||
try:
|
||||
for element in item:
|
||||
if self.element_matcher.matches(element):
|
||||
return True
|
||||
except TypeError: # not a sequence
|
||||
pass
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a sequence containing ").append_description_of(
|
||||
self.element_matcher
|
||||
)
|
||||
|
||||
|
||||
# It'd be great to make use of all_of, but we can't be sure we won't
|
||||
# be seeing a one-time sequence here (like a generator); see issue #20
|
||||
# Instead, we wrap it inside a class that will convert the sequence into
|
||||
# a concrete list and then hand it off to the all_of matcher.
|
||||
class IsSequenceContainingEvery(BaseMatcher[Sequence[T]]):
|
||||
def __init__(self, *element_matchers: Matcher[T]) -> None:
|
||||
delegates = [cast(Matcher[Sequence[T]], has_item(e)) for e in element_matchers]
|
||||
self.matcher = all_of(*delegates) # type: Matcher[Sequence[T]]
|
||||
|
||||
def _matches(self, item: Sequence[T]) -> bool:
|
||||
try:
|
||||
return self.matcher.matches(list(item))
|
||||
except TypeError:
|
||||
return False
|
||||
|
||||
def describe_mismatch(self, item: Sequence[T], mismatch_description: Description) -> None:
|
||||
self.matcher.describe_mismatch(item, mismatch_description)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
self.matcher.describe_to(description)
|
||||
|
||||
|
||||
def has_item(match: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Matches if any element of sequence satisfies a given matcher.
|
||||
|
||||
:param match: The matcher to satisfy, or an expected value for
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher iterates the evaluated sequence, searching for any element
|
||||
that satisfies a given matcher. If a matching element is found,
|
||||
``has_item`` is satisfied.
|
||||
|
||||
If the ``match`` argument is not a matcher, it is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
"""
|
||||
return IsSequenceContaining(wrap_matcher(match))
|
||||
|
||||
|
||||
def has_items(*items: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Matches if all of the given matchers are satisfied by any elements of
|
||||
the sequence.
|
||||
|
||||
:param match1,...: A comma-separated list of matchers.
|
||||
|
||||
This matcher iterates the given matchers, searching for any elements in the
|
||||
evaluated sequence that satisfy them. If each matcher is satisfied, then
|
||||
``has_items`` is satisfied.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
"""
|
||||
matchers = []
|
||||
for item in items:
|
||||
matchers.append(wrap_matcher(item))
|
||||
return IsSequenceContainingEvery(*matchers)
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
from typing import MutableSequence, Optional, Sequence, TypeVar, Union, cast
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class MatchInAnyOrder(object):
|
||||
def __init__(
|
||||
self, matchers: Sequence[Matcher[T]], mismatch_description: Optional[Description]
|
||||
) -> None:
|
||||
self.matchers = cast(MutableSequence[Matcher[T]], matchers[:])
|
||||
self.mismatch_description = mismatch_description
|
||||
|
||||
def matches(self, item: T) -> bool:
|
||||
return self.isnotsurplus(item) and self.ismatched(item)
|
||||
|
||||
def isfinished(self, item: Sequence[T]) -> bool:
|
||||
if not self.matchers:
|
||||
return True
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("no item matches: ").append_list(
|
||||
"", ", ", "", self.matchers
|
||||
).append_text(" in ").append_list("[", ", ", "]", item)
|
||||
return False
|
||||
|
||||
def isnotsurplus(self, item: T) -> bool:
|
||||
if not self.matchers:
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("not matched: ").append_description_of(item)
|
||||
return False
|
||||
return True
|
||||
|
||||
def ismatched(self, item: T) -> bool:
|
||||
for index, matcher in enumerate(self.matchers):
|
||||
if matcher.matches(item):
|
||||
del self.matchers[index]
|
||||
return True
|
||||
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("not matched: ").append_description_of(item)
|
||||
return False
|
||||
|
||||
|
||||
class IsSequenceContainingInAnyOrder(BaseMatcher[Sequence[T]]):
|
||||
def __init__(self, matchers: Sequence[Matcher[T]]) -> None:
|
||||
self.matchers = matchers
|
||||
|
||||
def matches(
|
||||
self, item: Sequence[T], mismatch_description: Optional[Description] = None
|
||||
) -> bool:
|
||||
try:
|
||||
sequence = list(item)
|
||||
matchsequence = MatchInAnyOrder(self.matchers, mismatch_description)
|
||||
for element in sequence:
|
||||
if not matchsequence.matches(element):
|
||||
return False
|
||||
return matchsequence.isfinished(sequence)
|
||||
except TypeError:
|
||||
if mismatch_description:
|
||||
super(IsSequenceContainingInAnyOrder, self).describe_mismatch(
|
||||
item, mismatch_description
|
||||
)
|
||||
return False
|
||||
|
||||
def describe_mismatch(self, item: Sequence[T], mismatch_description: Description) -> None:
|
||||
self.matches(item, mismatch_description)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a sequence over ").append_list(
|
||||
"[", ", ", "]", self.matchers
|
||||
).append_text(" in any order")
|
||||
|
||||
|
||||
def contains_inanyorder(*items: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Matches if sequences's elements, in any order, satisfy a given list of
|
||||
matchers.
|
||||
|
||||
:param match1,...: A comma-separated list of matchers.
|
||||
|
||||
This matcher iterates the evaluated sequence, seeing if each element
|
||||
satisfies any of the given matchers. The matchers are tried from left to
|
||||
right, and when a satisfied matcher is found, it is no longer a candidate
|
||||
for the remaining elements. If a one-to-one correspondence is established
|
||||
between elements and matchers, ``contains_inanyorder`` is satisfied.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
"""
|
||||
|
||||
matchers = []
|
||||
for item in items:
|
||||
matchers.append(wrap_matcher(item))
|
||||
return IsSequenceContainingInAnyOrder(matchers)
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import warnings
|
||||
from typing import Optional, Sequence, TypeVar, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class MatchingInOrder(object):
|
||||
def __init__(
|
||||
self, matchers: Sequence[Matcher[T]], mismatch_description: Optional[Description]
|
||||
) -> None:
|
||||
self.matchers = matchers
|
||||
self.mismatch_description = mismatch_description
|
||||
self.next_match_index = 0
|
||||
|
||||
def matches(self, item: T) -> bool:
|
||||
return self.isnotsurplus(item) and self.ismatched(item)
|
||||
|
||||
def isfinished(self) -> bool:
|
||||
if self.next_match_index < len(self.matchers):
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("No item matched: ").append_description_of(
|
||||
self.matchers[self.next_match_index]
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def ismatched(self, item: T) -> bool:
|
||||
matcher = self.matchers[self.next_match_index]
|
||||
if not matcher.matches(item):
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("item " + str(self.next_match_index) + ": ")
|
||||
matcher.describe_mismatch(item, self.mismatch_description)
|
||||
return False
|
||||
self.next_match_index += 1
|
||||
return True
|
||||
|
||||
def isnotsurplus(self, item: T) -> bool:
|
||||
if len(self.matchers) <= self.next_match_index:
|
||||
if self.mismatch_description:
|
||||
self.mismatch_description.append_text("Not matched: ").append_description_of(item)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class IsSequenceContainingInOrder(BaseMatcher[Sequence[T]]):
|
||||
def __init__(self, matchers: Sequence[Matcher[T]]) -> None:
|
||||
self.matchers = matchers
|
||||
|
||||
def matches(
|
||||
self, item: Sequence[T], mismatch_description: Optional[Description] = None
|
||||
) -> bool:
|
||||
try:
|
||||
matchsequence = MatchingInOrder(self.matchers, mismatch_description)
|
||||
for element in item:
|
||||
if not matchsequence.matches(element):
|
||||
return False
|
||||
return matchsequence.isfinished()
|
||||
except TypeError:
|
||||
if mismatch_description:
|
||||
super(IsSequenceContainingInOrder, self).describe_mismatch(
|
||||
item, mismatch_description
|
||||
)
|
||||
return False
|
||||
|
||||
def describe_mismatch(self, item: Sequence[T], mismatch_description: Description) -> None:
|
||||
self.matches(item, mismatch_description)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a sequence containing ").append_list("[", ", ", "]", self.matchers)
|
||||
|
||||
|
||||
def contains_exactly(*items: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Matches if sequence's elements satisfy a given list of matchers, in order.
|
||||
|
||||
:param match1,...: A comma-separated list of matchers.
|
||||
|
||||
This matcher iterates the evaluated sequence and a given list of matchers,
|
||||
seeing if each element satisfies its corresponding matcher.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
"""
|
||||
matchers = []
|
||||
for item in items:
|
||||
matchers.append(wrap_matcher(item))
|
||||
return IsSequenceContainingInOrder(matchers)
|
||||
|
||||
|
||||
def contains(*items: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Deprecated - use contains_exactly(*items)"""
|
||||
warnings.warn("deprecated - use contains_exactly(*items)", DeprecationWarning)
|
||||
return contains_exactly(*items)
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
from typing import Sequence, TypeVar, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.core.anyof import any_of
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class IsSequenceOnlyContaining(BaseMatcher[Sequence[T]]):
|
||||
def __init__(self, matcher: Matcher[T]) -> None:
|
||||
self.matcher = matcher
|
||||
|
||||
def _matches(self, item: Sequence[T]) -> bool:
|
||||
try:
|
||||
sequence = list(item)
|
||||
if len(sequence) == 0:
|
||||
return False
|
||||
for element in sequence:
|
||||
if not self.matcher.matches(element):
|
||||
return False
|
||||
return True
|
||||
except TypeError:
|
||||
return False
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a sequence containing items matching ").append_description_of(
|
||||
self.matcher
|
||||
)
|
||||
|
||||
|
||||
def only_contains(*items: Union[Matcher[T], T]) -> Matcher[Sequence[T]]:
|
||||
"""Matches if each element of sequence satisfies any of the given matchers.
|
||||
|
||||
:param match1,...: A comma-separated list of matchers.
|
||||
|
||||
This matcher iterates the evaluated sequence, confirming whether each
|
||||
element satisfies any of the given matchers.
|
||||
|
||||
Example::
|
||||
|
||||
only_contains(less_than(4))
|
||||
|
||||
will match ``[3,1,2]``.
|
||||
|
||||
Any argument that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
"""
|
||||
matchers = []
|
||||
for item in items:
|
||||
matchers.append(wrap_matcher(item))
|
||||
return IsSequenceOnlyContaining(any_of(*matchers))
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
"""Utilities for integrating Hamcrest with other libraries."""
|
||||
|
||||
from .match_equality import match_equality
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
from typing import Any
|
||||
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
from hamcrest.core.string_description import tostring
|
||||
|
||||
__author__ = "Chris Rose"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
__unittest = True
|
||||
|
||||
|
||||
class EqualityWrapper(object):
|
||||
def __init__(self, matcher: Matcher) -> None:
|
||||
self.matcher = matcher
|
||||
|
||||
def __eq__(self, obj: Any) -> bool:
|
||||
return self.matcher.matches(obj)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return repr(self)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return tostring(self.matcher)
|
||||
|
||||
|
||||
def match_equality(matcher: Matcher) -> EqualityWrapper:
|
||||
"""Wraps a matcher to define equality in terms of satisfying the matcher.
|
||||
|
||||
``match_equality`` allows Hamcrest matchers to be used in libraries that
|
||||
are not Hamcrest-aware. They might use the equality operator::
|
||||
|
||||
assert match_equality(matcher) == object
|
||||
|
||||
Or they might provide a method that uses equality for its test::
|
||||
|
||||
library.method_that_tests_eq(match_equality(matcher))
|
||||
|
||||
One concrete example is integrating with the ``assert_called_with`` methods
|
||||
in Michael Foord's `mock <http://www.voidspace.org.uk/python/mock/>`_
|
||||
library.
|
||||
|
||||
"""
|
||||
return EqualityWrapper(wrap_matcher(matcher))
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
"""Matchers that perform numeric comparisons."""
|
||||
|
||||
from .iscloseto import close_to
|
||||
from .ordering_comparison import (
|
||||
greater_than,
|
||||
greater_than_or_equal_to,
|
||||
less_than,
|
||||
less_than_or_equal_to,
|
||||
)
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
from decimal import Decimal
|
||||
from math import fabs
|
||||
from typing import Any, Union, overload
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
Number = Union[float, Decimal] # Argh, https://github.com/python/mypy/issues/3186
|
||||
|
||||
|
||||
def isnumeric(value: Any) -> bool:
|
||||
"""Confirm that 'value' can be treated numerically; duck-test accordingly
|
||||
"""
|
||||
if isinstance(value, (float, complex, int)):
|
||||
return True
|
||||
|
||||
try:
|
||||
_ = (fabs(value) + 0 - 0) * 1
|
||||
return True
|
||||
except ArithmeticError:
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
class IsCloseTo(BaseMatcher[Number]):
|
||||
def __init__(self, value: Number, delta: Number) -> None:
|
||||
if not isnumeric(value):
|
||||
raise TypeError("IsCloseTo value must be numeric")
|
||||
if not isnumeric(delta):
|
||||
raise TypeError("IsCloseTo delta must be numeric")
|
||||
|
||||
self.value = value
|
||||
self.delta = delta
|
||||
|
||||
def _matches(self, item: Number) -> bool:
|
||||
if not isnumeric(item):
|
||||
return False
|
||||
return self._diff(item) <= self.delta
|
||||
|
||||
def _diff(self, item: Number) -> float:
|
||||
# TODO - Fails for mixed floats & Decimals
|
||||
return fabs(item - self.value) # type: ignore
|
||||
|
||||
def describe_mismatch(self, item: Number, mismatch_description: Description) -> None:
|
||||
if not isnumeric(item):
|
||||
super(IsCloseTo, self).describe_mismatch(item, mismatch_description)
|
||||
else:
|
||||
actual_delta = self._diff(item)
|
||||
mismatch_description.append_description_of(item).append_text(
|
||||
" differed by "
|
||||
).append_description_of(actual_delta)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a numeric value within ").append_description_of(
|
||||
self.delta
|
||||
).append_text(" of ").append_description_of(self.value)
|
||||
|
||||
|
||||
@overload
|
||||
def close_to(value: float, delta: float) -> Matcher[float]:
|
||||
...
|
||||
|
||||
|
||||
@overload
|
||||
def close_to(value: Decimal, delta: Decimal) -> Matcher[Decimal]:
|
||||
...
|
||||
|
||||
|
||||
def close_to(value, delta):
|
||||
"""Matches if object is a number close to a given value, within a given
|
||||
delta.
|
||||
|
||||
:param value: The value to compare against as the expected value.
|
||||
:param delta: The maximum delta between the values for which the numbers
|
||||
are considered close.
|
||||
|
||||
This matcher compares the evaluated object against ``value`` to see if the
|
||||
difference is within a positive ``delta``.
|
||||
|
||||
Example::
|
||||
|
||||
close_to(3.0, 0.25)
|
||||
|
||||
"""
|
||||
return IsCloseTo(value, delta)
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import operator
|
||||
from typing import Any, Callable
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class OrderingComparison(BaseMatcher[Any]):
|
||||
def __init__(
|
||||
self,
|
||||
value: Any,
|
||||
comparison_function: Callable[[Any, Any], bool],
|
||||
comparison_description: str,
|
||||
) -> None:
|
||||
self.value = value
|
||||
self.comparison_function = comparison_function
|
||||
self.comparison_description = comparison_description
|
||||
|
||||
def _matches(self, item: Any) -> bool:
|
||||
return self.comparison_function(item, self.value)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a value ").append_text(self.comparison_description).append_text(
|
||||
" "
|
||||
).append_description_of(self.value)
|
||||
|
||||
|
||||
def greater_than(value: Any) -> Matcher[Any]:
|
||||
"""Matches if object is greater than a given value.
|
||||
|
||||
:param value: The value to compare against.
|
||||
|
||||
"""
|
||||
return OrderingComparison(value, operator.gt, "greater than")
|
||||
|
||||
|
||||
def greater_than_or_equal_to(value: Any) -> Matcher[Any]:
|
||||
"""Matches if object is greater than or equal to a given value.
|
||||
|
||||
:param value: The value to compare against.
|
||||
|
||||
"""
|
||||
return OrderingComparison(value, operator.ge, "greater than or equal to")
|
||||
|
||||
|
||||
def less_than(value: Any) -> Matcher[Any]:
|
||||
"""Matches if object is less than a given value.
|
||||
|
||||
:param value: The value to compare against.
|
||||
|
||||
"""
|
||||
return OrderingComparison(value, operator.lt, "less than")
|
||||
|
||||
|
||||
def less_than_or_equal_to(value: Any) -> Matcher[Any]:
|
||||
"""Matches if object is less than or equal to a given value.
|
||||
|
||||
:param value: The value to compare against.
|
||||
|
||||
"""
|
||||
return OrderingComparison(value, operator.le, "less than or equal to")
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
"""Matchers that inspect objects and classes."""
|
||||
|
||||
from .haslength import has_length
|
||||
from .hasproperty import has_properties, has_property
|
||||
from .hasstring import has_string
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
from collections.abc import Sized
|
||||
from typing import Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class HasLength(BaseMatcher[Sized]):
|
||||
def __init__(self, len_matcher: Matcher[int]) -> None:
|
||||
self.len_matcher = len_matcher
|
||||
|
||||
def _matches(self, item: Sized) -> bool:
|
||||
if not hasmethod(item, "__len__"):
|
||||
return False
|
||||
return self.len_matcher.matches(len(item))
|
||||
|
||||
def describe_mismatch(self, item: Sized, mismatch_description: Description) -> None:
|
||||
super(HasLength, self).describe_mismatch(item, mismatch_description)
|
||||
if hasmethod(item, "__len__"):
|
||||
mismatch_description.append_text(" with length of ").append_description_of(len(item))
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("an object with length of ").append_description_of(self.len_matcher)
|
||||
|
||||
|
||||
def has_length(match: Union[int, Matcher[int]]) -> Matcher[Sized]:
|
||||
"""Matches if ``len(item)`` satisfies a given matcher.
|
||||
|
||||
:param match: The matcher to satisfy, or an expected value for
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher invokes the :py:func:`len` function on the evaluated object to
|
||||
get its length, passing the result to a given matcher for evaluation.
|
||||
|
||||
If the ``match`` argument is not a matcher, it is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
:equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_length(greater_than(6))
|
||||
has_length(5)
|
||||
|
||||
"""
|
||||
return HasLength(wrap_matcher(match))
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
from typing import Any, Mapping, TypeVar, Union, overload
|
||||
|
||||
from hamcrest import described_as
|
||||
from hamcrest.core import anything
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.core.allof import AllOf
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher as wrap_shortcut
|
||||
from hamcrest.core.matcher import Matcher
|
||||
from hamcrest.core.string_description import StringDescription
|
||||
|
||||
__author__ = "Chris Rose"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
V = TypeVar("V")
|
||||
|
||||
|
||||
class IsObjectWithProperty(BaseMatcher[object]):
|
||||
def __init__(self, property_name: str, value_matcher: Matcher[V]) -> None:
|
||||
self.property_name = property_name
|
||||
self.value_matcher = value_matcher
|
||||
|
||||
def _matches(self, item: object) -> bool:
|
||||
if item is None:
|
||||
return False
|
||||
|
||||
if not hasattr(item, self.property_name):
|
||||
return False
|
||||
|
||||
value = getattr(item, self.property_name)
|
||||
return self.value_matcher.matches(value)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("an object with a property '").append_text(
|
||||
self.property_name
|
||||
).append_text("' matching ").append_description_of(self.value_matcher)
|
||||
|
||||
def describe_mismatch(self, item: object, mismatch_description: Description) -> None:
|
||||
if item is None:
|
||||
mismatch_description.append_text("was None")
|
||||
return
|
||||
|
||||
if not hasattr(item, self.property_name):
|
||||
mismatch_description.append_description_of(item).append_text(
|
||||
" did not have the "
|
||||
).append_description_of(self.property_name).append_text(" property")
|
||||
return
|
||||
|
||||
mismatch_description.append_text("property ").append_description_of(
|
||||
self.property_name
|
||||
).append_text(" ")
|
||||
value = getattr(item, self.property_name)
|
||||
self.value_matcher.describe_mismatch(value, mismatch_description)
|
||||
|
||||
def __str__(self):
|
||||
d = StringDescription()
|
||||
self.describe_to(d)
|
||||
return str(d)
|
||||
|
||||
|
||||
def has_property(name: str, match: Union[None, Matcher[V], V] = None) -> Matcher[object]:
|
||||
"""Matches if object has a property with a given name whose value satisfies
|
||||
a given matcher.
|
||||
|
||||
:param name: The name of the property.
|
||||
:param match: Optional matcher to satisfy.
|
||||
|
||||
This matcher determines if the evaluated object has a property with a given
|
||||
name. If no such property is found, ``has_property`` is not satisfied.
|
||||
|
||||
If the property is found, its value is passed to a given matcher for
|
||||
evaluation. If the ``match`` argument is not a matcher, it is implicitly
|
||||
wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to
|
||||
check for equality.
|
||||
|
||||
If the ``match`` argument is not provided, the
|
||||
:py:func:`~hamcrest.core.core.isanything.anything` matcher is used so that
|
||||
``has_property`` is satisfied if a matching property is found.
|
||||
|
||||
Examples::
|
||||
|
||||
has_property('name', starts_with('J'))
|
||||
has_property('name', 'Jon')
|
||||
has_property('name')
|
||||
|
||||
"""
|
||||
|
||||
if match is None:
|
||||
match = anything()
|
||||
|
||||
return IsObjectWithProperty(name, wrap_shortcut(match))
|
||||
|
||||
|
||||
# Keyword argument form
|
||||
@overload
|
||||
def has_properties(**keys_valuematchers: Union[Matcher[V], V]) -> Matcher[object]:
|
||||
...
|
||||
|
||||
|
||||
# Name to matcher dict form
|
||||
@overload
|
||||
def has_properties(keys_valuematchers: Mapping[str, Union[Matcher[V], V]]) -> Matcher[object]:
|
||||
...
|
||||
|
||||
|
||||
# Alternating name/matcher form
|
||||
@overload
|
||||
def has_properties(*keys_valuematchers: Any) -> Matcher[object]:
|
||||
...
|
||||
|
||||
|
||||
def has_properties(*keys_valuematchers, **kv_args):
|
||||
"""Matches if an object has properties satisfying all of a dictionary
|
||||
of string property names and corresponding value matchers.
|
||||
|
||||
:param matcher_dict: A dictionary mapping keys to associated value matchers,
|
||||
or to expected values for
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Note that the keys must be actual keys, not matchers. Any value argument
|
||||
that is not a matcher is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_properties({'foo':equal_to(1), 'bar':equal_to(2)})
|
||||
has_properties({'foo':1, 'bar':2})
|
||||
|
||||
``has_properties`` also accepts a list of keyword arguments:
|
||||
|
||||
.. function:: has_properties(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]])
|
||||
|
||||
:param keyword1: A keyword to look up.
|
||||
:param valueMatcher1: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Examples::
|
||||
|
||||
has_properties(foo=equal_to(1), bar=equal_to(2))
|
||||
has_properties(foo=1, bar=2)
|
||||
|
||||
Finally, ``has_properties`` also accepts a list of alternating keys and their
|
||||
value matchers:
|
||||
|
||||
.. function:: has_properties(key1, value_matcher1[, ...])
|
||||
|
||||
:param key1: A key (not a matcher) to look up.
|
||||
:param valueMatcher1: The matcher to satisfy for the value, or an expected
|
||||
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
Examples::
|
||||
|
||||
has_properties('foo', equal_to(1), 'bar', equal_to(2))
|
||||
has_properties('foo', 1, 'bar', 2)
|
||||
|
||||
"""
|
||||
if len(keys_valuematchers) == 1:
|
||||
try:
|
||||
base_dict = keys_valuematchers[0].copy()
|
||||
for key in base_dict:
|
||||
base_dict[key] = wrap_shortcut(base_dict[key])
|
||||
except AttributeError:
|
||||
raise ValueError(
|
||||
"single-argument calls to has_properties must pass a dict as the argument"
|
||||
)
|
||||
else:
|
||||
if len(keys_valuematchers) % 2:
|
||||
raise ValueError("has_properties requires key-value pairs")
|
||||
base_dict = {}
|
||||
for index in range(int(len(keys_valuematchers) / 2)):
|
||||
base_dict[keys_valuematchers[2 * index]] = wrap_shortcut(
|
||||
keys_valuematchers[2 * index + 1]
|
||||
)
|
||||
|
||||
for key, value in kv_args.items():
|
||||
base_dict[key] = wrap_shortcut(value)
|
||||
|
||||
if len(base_dict) > 1:
|
||||
description = StringDescription().append_text("an object with properties ")
|
||||
for i, (property_name, property_value_matcher) in enumerate(sorted(base_dict.items())):
|
||||
description.append_description_of(property_name).append_text(
|
||||
" matching "
|
||||
).append_description_of(property_value_matcher)
|
||||
if i < len(base_dict) - 1:
|
||||
description.append_text(" and ")
|
||||
|
||||
return described_as(
|
||||
str(description),
|
||||
AllOf(
|
||||
*[
|
||||
has_property(property_name, property_value_matcher)
|
||||
for property_name, property_value_matcher in sorted(base_dict.items())
|
||||
],
|
||||
describe_all_mismatches=True,
|
||||
describe_matcher_in_mismatch=False,
|
||||
),
|
||||
)
|
||||
else:
|
||||
property_name, property_value_matcher = base_dict.popitem()
|
||||
return has_property(property_name, property_value_matcher)
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class HasString(BaseMatcher[object]):
|
||||
def __init__(self, str_matcher: Matcher[str]) -> None:
|
||||
self.str_matcher = str_matcher
|
||||
|
||||
def _matches(self, item: object) -> bool:
|
||||
return self.str_matcher.matches(str(item))
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("an object with str ").append_description_of(self.str_matcher)
|
||||
|
||||
|
||||
def has_string(match) -> Matcher[object]:
|
||||
"""Matches if ``str(item)`` satisfies a given matcher.
|
||||
|
||||
:param match: The matcher to satisfy, or an expected value for
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
|
||||
|
||||
This matcher invokes the :py:func:`str` function on the evaluated object to
|
||||
get its length, passing the result to a given matcher for evaluation. If
|
||||
the ``match`` argument is not a matcher, it is implicitly wrapped in an
|
||||
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
|
||||
equality.
|
||||
|
||||
Examples::
|
||||
|
||||
has_string(starts_with('foo'))
|
||||
has_string('bar')
|
||||
|
||||
"""
|
||||
return HasString(wrap_matcher(match))
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
"""Matchers that perform text comparisons."""
|
||||
|
||||
from .isequal_ignoring_case import equal_to_ignoring_case
|
||||
from .isequal_ignoring_whitespace import equal_to_ignoring_whitespace
|
||||
from .stringcontains import contains_string
|
||||
from .stringcontainsinorder import string_contains_in_order
|
||||
from .stringendswith import ends_with
|
||||
from .stringmatches import matches_regexp
|
||||
from .stringstartswith import starts_with
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class IsEqualIgnoringCase(BaseMatcher[str]):
|
||||
def __init__(self, string: str) -> None:
|
||||
if not isinstance(string, str):
|
||||
raise TypeError("IsEqualIgnoringCase requires string")
|
||||
self.original_string = string
|
||||
self.lowered_string = string.lower()
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not isinstance(item, str):
|
||||
return False
|
||||
return self.lowered_string == item.lower()
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_description_of(self.original_string).append_text(" ignoring case")
|
||||
|
||||
|
||||
def equal_to_ignoring_case(string: str) -> Matcher[str]:
|
||||
"""Matches if object is a string equal to a given string, ignoring case
|
||||
differences.
|
||||
|
||||
:param string: The string to compare against as the expected value.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it compares it with ``string``, ignoring differences of case.
|
||||
|
||||
Example::
|
||||
|
||||
equal_to_ignoring_case("hello world")
|
||||
|
||||
will match "heLLo WorlD".
|
||||
|
||||
"""
|
||||
return IsEqualIgnoringCase(string)
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
def stripspace(string: str) -> str:
|
||||
result = ""
|
||||
last_was_space = True
|
||||
for character in string:
|
||||
if character.isspace():
|
||||
if not last_was_space:
|
||||
result += " "
|
||||
last_was_space = True
|
||||
else:
|
||||
result += character
|
||||
last_was_space = False
|
||||
return result.strip()
|
||||
|
||||
|
||||
class IsEqualIgnoringWhiteSpace(BaseMatcher[str]):
|
||||
def __init__(self, string) -> None:
|
||||
if not isinstance(string, str):
|
||||
raise TypeError("IsEqualIgnoringWhiteSpace requires string")
|
||||
self.original_string = string
|
||||
self.stripped_string = stripspace(string)
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not isinstance(item, str):
|
||||
return False
|
||||
return self.stripped_string == stripspace(item)
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_description_of(self.original_string).append_text(" ignoring whitespace")
|
||||
|
||||
|
||||
def equal_to_ignoring_whitespace(string: str) -> Matcher[str]:
|
||||
"""Matches if object is a string equal to a given string, ignoring
|
||||
differences in whitespace.
|
||||
|
||||
:param string: The string to compare against as the expected value.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it compares it with ``string``, ignoring differences in runs of whitespace.
|
||||
|
||||
Example::
|
||||
|
||||
equal_to_ignoring_whitespace("hello world")
|
||||
|
||||
will match ``"hello world"``.
|
||||
|
||||
"""
|
||||
return IsEqualIgnoringWhiteSpace(string)
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.matcher import Matcher
|
||||
from hamcrest.library.text.substringmatcher import SubstringMatcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class StringContains(SubstringMatcher):
|
||||
def __init__(self, substring) -> None:
|
||||
super(StringContains, self).__init__(substring)
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not hasmethod(item, "find"):
|
||||
return False
|
||||
return item.find(self.substring) >= 0
|
||||
|
||||
def relationship(self):
|
||||
return "containing"
|
||||
|
||||
|
||||
def contains_string(substring: str) -> Matcher[str]:
|
||||
"""Matches if object is a string containing a given string.
|
||||
|
||||
:param string: The string to search for.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it checks whether it contains ``string``.
|
||||
|
||||
Example::
|
||||
|
||||
contains_string("def")
|
||||
|
||||
will match "abcdefg".
|
||||
|
||||
"""
|
||||
return StringContains(substring)
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Romilly Cocking"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class StringContainsInOrder(BaseMatcher[str]):
|
||||
def __init__(self, *substrings) -> None:
|
||||
for substring in substrings:
|
||||
if not isinstance(substring, str):
|
||||
raise TypeError(self.__class__.__name__ + " requires string arguments")
|
||||
self.substrings = substrings
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not hasmethod(item, "find"):
|
||||
return False
|
||||
from_index = 0
|
||||
for substring in self.substrings:
|
||||
from_index = item.find(substring, from_index)
|
||||
if from_index == -1:
|
||||
return False
|
||||
return True
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_list("a string containing ", ", ", " in order", self.substrings)
|
||||
|
||||
|
||||
def string_contains_in_order(*substrings: str) -> Matcher[str]:
|
||||
"""Matches if object is a string containing a given list of substrings in
|
||||
relative order.
|
||||
|
||||
:param string1,...: A comma-separated list of strings.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it checks whether it contains a given list of strings, in relative order to
|
||||
each other. The searches are performed starting from the beginning of the
|
||||
evaluated string.
|
||||
|
||||
Example::
|
||||
|
||||
string_contains_in_order("bc", "fg", "jkl")
|
||||
|
||||
will match "abcdefghijklm".
|
||||
|
||||
"""
|
||||
return StringContainsInOrder(*substrings)
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.matcher import Matcher
|
||||
from hamcrest.library.text.substringmatcher import SubstringMatcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class StringEndsWith(SubstringMatcher):
|
||||
def __init__(self, substring) -> None:
|
||||
super(StringEndsWith, self).__init__(substring)
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not hasmethod(item, "endswith"):
|
||||
return False
|
||||
return item.endswith(self.substring)
|
||||
|
||||
def relationship(self):
|
||||
return "ending with"
|
||||
|
||||
|
||||
def ends_with(string: str) -> Matcher[str]:
|
||||
"""Matches if object is a string ending with a given string.
|
||||
|
||||
:param string: The string to search for.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it checks if ``string`` matches the ending characters of the evaluated
|
||||
object.
|
||||
|
||||
Example::
|
||||
|
||||
ends_with("bar")
|
||||
|
||||
will match "foobar".
|
||||
|
||||
"""
|
||||
return StringEndsWith(string)
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import re
|
||||
from typing import Pattern, Union
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
from hamcrest.core.matcher import Matcher
|
||||
|
||||
__author__ = "Chris Rose"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class StringMatchesPattern(BaseMatcher[str]):
|
||||
def __init__(self, pattern) -> None:
|
||||
self.pattern = pattern
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a string matching '").append_text(
|
||||
self.pattern.pattern
|
||||
).append_text("'")
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
return self.pattern.search(item) is not None
|
||||
|
||||
|
||||
def matches_regexp(pattern: Union[str, Pattern[str]]) -> Matcher[str]:
|
||||
"""Matches if object is a string containing a match for a given regular
|
||||
expression.
|
||||
|
||||
:param pattern: The regular expression to search for.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it checks if the regular expression ``pattern`` matches anywhere within the
|
||||
evaluated object.
|
||||
|
||||
"""
|
||||
if isinstance(pattern, str):
|
||||
pattern = re.compile(pattern)
|
||||
|
||||
return StringMatchesPattern(pattern)
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
from hamcrest.core.helpers.hasmethod import hasmethod
|
||||
from hamcrest.core.matcher import Matcher
|
||||
from hamcrest.library.text.substringmatcher import SubstringMatcher
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class StringStartsWith(SubstringMatcher):
|
||||
def __init__(self, substring) -> None:
|
||||
super(StringStartsWith, self).__init__(substring)
|
||||
|
||||
def _matches(self, item: str) -> bool:
|
||||
if not hasmethod(item, "startswith"):
|
||||
return False
|
||||
return item.startswith(self.substring)
|
||||
|
||||
def relationship(self):
|
||||
return "starting with"
|
||||
|
||||
|
||||
def starts_with(substring: str) -> Matcher[str]:
|
||||
"""Matches if object is a string starting with a given string.
|
||||
|
||||
:param string: The string to search for.
|
||||
|
||||
This matcher first checks whether the evaluated object is a string. If so,
|
||||
it checks if ``string`` matches the beginning characters of the evaluated
|
||||
object.
|
||||
|
||||
Example::
|
||||
|
||||
starts_with("foo")
|
||||
|
||||
will match "foobar".
|
||||
|
||||
"""
|
||||
return StringStartsWith(substring)
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
from abc import ABCMeta, abstractmethod
|
||||
|
||||
from hamcrest.core.base_matcher import BaseMatcher
|
||||
from hamcrest.core.description import Description
|
||||
|
||||
__author__ = "Jon Reid"
|
||||
__copyright__ = "Copyright 2011 hamcrest.org"
|
||||
__license__ = "BSD, see License.txt"
|
||||
|
||||
|
||||
class SubstringMatcher(BaseMatcher[str], metaclass=ABCMeta):
|
||||
def __init__(self, substring) -> None:
|
||||
if not isinstance(substring, str):
|
||||
raise TypeError(self.__class__.__name__ + " requires string")
|
||||
self.substring = substring
|
||||
|
||||
def describe_to(self, description: Description) -> None:
|
||||
description.append_text("a string ").append_text(self.relationship()).append_text(
|
||||
" "
|
||||
).append_description_of(self.substring)
|
||||
|
||||
@abstractmethod
|
||||
def relationship(self):
|
||||
...
|
||||
Loading…
Add table
Add a link
Reference in a new issue