def has_entries(*keys_valuematchers, **kv_args): """Matches dictionaries containing key-value pairs satisfying a given list of alternating keys and value matchers. :param keys_valuematchers: Alternating pairs of keys and value matchers (or straight values for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. If only one parameter is passed here, it must be a mapping object. In that case, matching will be done against its keys/values. :param kv_args: These name value pairs will be matched by the matcher as well. Any values provided here will supercede those provided in the positional argument list. """ 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)
def has_entry(key, value): """Matches dictionaries containing a key-value pair satisfying a given pair of matchers. :param key: A matcher - or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching - for the key. :param value: A matcher - or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching - for the value. """ return IsDictContaining(wrap_matcher(key), wrap_matcher(value))
def has_effects(amount_of_effects): """ Check if item has effects :param amount_of_effects: amount of effects item should have :type amount_of_effects: int """ return Effects(wrap_matcher(amount_of_effects))
def has_item(item): """Matches a sequence if any element satifies a given matcher. :param item: A matcher, or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. """ return IsSequenceContaining(wrap_matcher(item))
def does_not_have_item(item): """ Check that level does not have given item :param item: name of the item to check :type item: String """ return ContainsItem(item, wrap_matcher(0))
def has_key(key): """Matches dictionaries containing a key satisfying a given matcher. :param key: A matcher - or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching - for the key. """ return IsDictContainingKey(wrap_matcher(key))
def all_of(*items): """Evaluates to ``True`` only if *all* of the passed in matchers evaluate to ``True``. :param items: Each item is a matcher, or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. """ return AllOf(*[wrap_matcher(item) for item in items])
def has_damage(damage_amount=None, damage_type=None): """ Check if weapon makes specific amount and type of damage Both parameters support using matchers has_damage(greater_than(3), 'piercing') is valid call :param damage_amount: amount of damage :type damage_amount: int :param damage_type: type of damage :type damage_type: string """ if damage_amount is not None and damage_type is not None: return HasDamage(wrap_matcher(damage_amount), wrap_matcher(damage_type)) elif damage_amount is None: return HasDamage(anything(), wrap_matcher(damage_type)) else: return HasDamage(wrap_matcher(damage_amount), anything())
def __init__(self, value_matchers=None, **kwargs): base_dict = {} if value_matchers is None: value_matchers = kwargs for key, value in value_matchers.items(): base_dict[key] = wrap_matcher(value) super(IsObjectContainingEntries, self).__init__(base_dict)
def has_value(value): """Matches dictionaries containing a value satisfying a given matcher. :param value: A matcher - or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching - for the value. """ return IsDictContainingValue(wrap_matcher(value))
def has_creature(creature, amount): """ Check if level has given creature :param creature: name of the creature to check :type creature: String :param amount: amount of creatures to expect :type amount: int """ return ContainsCreature(creature, wrap_matcher(amount))
def does_have_item(item, amount): """ Check if level has given item :param item: name of the item to check :type item: String :param amount: amount of items to expect :type amount: int """ return ContainsItem(item, wrap_matcher(amount))
def __init__(self, text): """ Default constructor """ super(LabelMatcher, self).__init__() if hasattr(text, 'matches'): self.text = text else: self.text = wrap_matcher(text)
def contains(*items): """Matches a sequence if its elements, in order, satisfy a list of matchers. :param items: Each item is a matcher, or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceContainingInOrder(matchers)
def has_length(x): """Evaluates whether ``len(item)`` satisfies a given matcher. :param x: A matcher, or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_length(greater_than(6)) has_length(5) """ return HasLength(wrap_matcher(x))
def has_string(x): """Evaluates whether ``str(item)`` satisfies a given matcher. :param x: A matcher, or a value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_string(starts_with('foo')) has_string('bar') """ return HasString(wrap_matcher(x))
def assert_raises(matcher=None, message=""): # Short hand for instance_of matcher if is_matchable_type(matcher): matcher = instance_of(matcher) else: matcher = wrap_matcher(matcher) context = RaisesContext() try: yield context except Exception as e: context.exception = e assert_that(context.exception, matcher, message)
def is_not(x): """Inverts the rule, providing a shortcut to the frequently used ``is_not(equal_to(x))``. For example:: assert_that(cheese, is_not(equal_to(smelly))) vs. :: assert_that(cheese, is_not(smelly)) """ return IsNot(wrap_matcher(x))
def only_contains(*items): """Matches sequences that only contain elements satisfying any of a list of items. For example, ``[3,1,2]`` would satisfy ``only_contains(less_than(4))``. If an item is not a matcher, it is equivalent to ``equal_to(item)``, so the list in the example above would also satisfy ``only_contains(1,2,3)``. """ matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceOnlyContaining(apply(any_of, matchers))
def all_of(*items): """Matches if all of the given matchers evaluate to ``True``. :param matcher1,...: A comma-separated list of matchers. The matchers are evaluated from left to right using short-circuit evaluation, so evaluation stops as soon as a matcher returns ``False``. 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. """ return AllOf(*[wrap_matcher(item) for item in items])
def has_entry(key_match, value_match): """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))
def has_item(match): """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 contains(*items): """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 is_not(match): """Inverts the given matcher to its logical negation. :param match: The matcher to negate. This matcher compares the evaluated object to the negation of the given matcher. 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, and thus matches for inequality. Examples:: assert_that(cheese, is_not(equal_to(smelly))) assert_that(cheese, is_not(smelly)) """ return IsNot(wrap_matcher(match))
def match_equality(matcher): """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))
def has_items(*items): """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)
def has_string(match): """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))
def has_length(match): """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))
def contains_inanyorder(*items): """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)
def has_value(value): """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))
def only_contains(*items): """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(apply(any_of, matchers))
def __init__( self, method: Union[str, Matcher[str]] = ANYTHING, path: Union[furl, str, Matcher[Union[furl, str]]] = ANYTHING, query: Union[Mapping[str, str], Matcher[Mapping[str, str]]] = ANYTHING, headers: Union[Mapping[str, str], Matcher[Mapping[str, str]]] = ANYTHING, body: Union[str, Matcher[str]] = ANYTHING, times: Union[int, Matcher[int]] = ANYTHING, ): if (method != ANYTHING or path != ANYTHING or query != ANYTHING or headers != ANYTHING or body != ANYTHING or times != ANYTHING): # pragma: no cover warnings.warn( "Use builder-style with_X and and_X methods, rather than arguments." ) self.method = wrap_matcher(method) # type: Matcher[str] self.path = wrap_matcher(path) # type: Matcher[Union[furl, str]] self.query = wrap_matcher(query) # type Matcher[Mapping[str, str]] self.headers = wrap_matcher(headers) # type Matcher[Mapping[str, str]] self.body = wrap_matcher(body) # type: Matcher[str] self.times = wrap_matcher(times) # type: Matcher[int]
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)
def __init__( self, matcher: Union[JsonStructure, Matcher[JsonStructure]]) -> None: self.matcher: Matcher[JsonStructure] = wrap_matcher(matcher)
def __init__(self, to=ANYTHING, subject=ANYTHING, body_text=ANYTHING): self.body_text = wrap_matcher(body_text) self.subject = wrap_matcher(subject) self.to = wrap_matcher(to)
def __init__(self, e_type, message, id): self.e_type = wrap_matcher(e_type) self.message = wrap_matcher(message) self.id = wrap_matcher(id)
def __init__(self, expected: Union[str, Matcher[str]]) -> None: self.expected: Matcher[str] = wrap_matcher(expected)
def with_password(self, password: Union[str, Matcher[str]]): self.password = wrap_matcher(password) return self
def with_port(self, port: Union[int, Matcher[int]]): self.port = wrap_matcher(port) return self
def with_times(self, times: Union[int, Matcher[int]]): self.times = wrap_matcher(times) return self
def collected_metric(matcher=None): matcher = anything() if matcher is None else wrap_matcher(matcher) return only_contains(contains(greater_than(1476820876), matcher))
def with_headers(self, headers: Union[Mapping[str, str], Matcher[Mapping[str, str]]]): self.headers = wrap_matcher(headers) return self
def with_body(self, body: Union[str, Matcher[str]]): self.body = wrap_matcher(body) return self
def with_query(self, query: Union[Mapping[str, str], Matcher[Mapping[str, str]]]): self.query = wrap_matcher(query) return self
def with_method(self, method: Union[str, Matcher[str]]): self.method = wrap_matcher(method) return self
def has_items_in_order(*matchers: Any) -> HasItemsInOrder: return HasItemsInOrder([wrap_matcher(matcher) for matcher in matchers])
def with_scheme(self, scheme: Union[str, Matcher[str]]): self.scheme = wrap_matcher(scheme) return self
def with_path_segments(self, path_segments: Union[Sequence[str], Matcher[Sequence[str]]]): self.path_segments = wrap_matcher(path_segments) return self
def with_username(self, username: Union[str, Matcher[str]]): self.username = wrap_matcher(username) return self
def __init__(self, index: int, expected: Any) -> None: super(CallHasPositionalArg, self).__init__() self.index = index self.expected = wrap_matcher(expected)
def with_host(self, host: Union[str, Matcher[str]]): self.host = wrap_matcher(host) return self
def published_inanyorder(*matchers, strict=True): return NonStrictPublishingMatcher([ wrap_matcher(matcher) for matcher in matchers ])
def with_path(self, path: Union[str, Matcher[str]]): self.path = wrap_matcher(path) return self
def has_status(stack_status_matcher): """Check stack has a status.""" return StackStatusMatcher(wrap_matcher(stack_status_matcher))
def with_fragment(self, fragment: Union[str, Matcher[str]]): self.fragment = wrap_matcher(fragment) return self
def has_float(match): return HasFloat(wrap_matcher(match))
def __init__(self, day: Union[int, Matcher[int]]) -> None: self.day = wrap_matcher(day)
def published(*matchers, strict=True): return StrictPublishingMatcher([ wrap_matcher(matcher) for matcher in matchers ])
def wrap_value_or_type(x): if is_matchable_type(x): return instance_of(x) else: return wrap_matcher(x)
def __init__(self, key: str, expected: Any) -> None: super(CallHasKeywordArg, self).__init__() self.key = key self.expected = wrap_matcher(expected)