Example #1
0
def has_property(name, match=None):
    """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))
Example #2
0
def has_property(name, match=None):
    """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))
Example #3
0
def has_property(name, value=None):
    """Matches objects that have a property matching the given value matcher.

    :param name: The name of the property that the object must have. If the object
        does not have this property, the matcher will fail.

    :param value: The value to match. If the value is not provided, the
        matcher will match against anything(), which transforms this
        matcher into a property existence check.

    """

    if value is None:
        value = anything()

    return IsObjectWithProperty(name, wrap_shortcut(value))
Example #4
0
def has_method_with_return_value(
    name: str,
    args: Iterable[Any] = None,
    kwargs: Mapping[str, Any] = None,
    match: Optional[Union[Matcher[Any], Any]] = None,
) -> Matcher[object]:
    """
    Match against an object which has a method with the given name that, when
    called with the given args and kwargs, returns the expected value.

    Examples:
        assert_that(
            list(1, 2, 3), has_method_with_return_value("copy", [1, 2, 3])
        )
        assert_that(
            dict((a, "Hello, world!")),
            has_method_with_return_value(
                "get", args=["a"], contains_string("world")
            )
        )

    Args:
        name: the name of the method to call.
        args: the list of args to provide when calling.
        kwargs: a dictionary of kwargs to pass when calling.
        match: the expected value of calling the method.

    Returns:
        Matcher[object]
    """
    if match is None:
        match = not_none()

    return IsObjectWithCallableProducingValue(name,
                                              wrap_shortcut(match),
                                              args=args,
                                              kwargs=kwargs)
Example #5
0
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)

    return all_of(*[has_property(property_name, property_value_matcher) for \
                   property_name, property_value_matcher in base_dict.items()])
Example #6
0
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_value(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)