def matches(self, item, mismatch_description=None):
     """Return whether the item is a valid to-many relationship."""
     if mismatch_description is None:
         mismatch_description = StringDescription()
     if "data" not in item:
         mismatch_description.append('missing key "data"')
         return False
     if not isinstance(item["data"], list):
         mismatch_description.append(
             "to-many relationship is not a `list`\n     "
             f"got: `{item.__class__.__name__}`")
         return False
     if not self.optional and not item["data"]:
         mismatch_description.append(
             "non-optional to-many relationship is ")
         mismatch_description.append_description_of(item["data"])
         return False
     for index, data in enumerate(item["data"]):
         if not super().matches(data):
             mismatch_description.append(
                 f"to-many relationship at index {index}"
                 " does not match. Failed because: ")
             super().matches(data, mismatch_description)
             return False
     return True
 def matches(self, item, mismatch_description=None):
     """Return whether the item is a valid to-one relationship."""
     if mismatch_description is None:
         mismatch_description = StringDescription()
     if "data" not in item:
         mismatch_description.append('missing key "data"')
         return False
     if item["data"] is None:
         if self.optional:
             return True
         mismatch_description.append("non-optional to-one relationship is ")
         mismatch_description.append_description_of(item["data"])
         return False
     return super().matches(item["data"], mismatch_description)
class StringDescriptionTest(unittest.TestCase):
    def setUp(self):
        self.description = StringDescription()

    def testLetsSelfDescribingObjectDescribeItself(self):
        self.description.append_description_of(FakeSelfDescribing())
        self.assertEqual("DESCRIPTION", str(self.description))

    def testDescribesStringInQuotes(self):
        self.description.append_description_of("FOO")
        self.assertEqual("'FOO'", str(self.description))

    def testWrapsNonSelfDescribingObjectInAngleBrackets(self):
        self.description.append_description_of(42)
        self.assertEqual("<42>", str(self.description))

    def testShouldNotAddAngleBracketsIfObjectDescriptionAlreadyHasThem(self):
        self.description.append_description_of(object())
        expected = re.compile("<object object at 0x[0-9a-fA-F]+>")
        self.assertTrue(expected.match(str(self.description)))

    def testDescribeUnicodeStringAsUnicode(self):
        self.description.append_description_of("\u05d0")
        self.assertEqual("'\u05d0'", str(self.description))
 def matches(self, item, mismatch_description=None):
     """Return whether the item is a json:api document."""
     if mismatch_description is None:
         mismatch_description = StringDescription()
     if "data" not in item:
         mismatch_description.append('missing key "data"')
         return False
     if not self.optional and not item["data"]:
         mismatch_description.append('non-optional "data" is ')
         mismatch_description.append_description_of(item["data"])
         return False
     if self.many:
         if not isinstance(item["data"], list):
             mismatch_description.append(
                 f'"data" is not a `list`\n     got: `{item.__class__.__name__}`'
             )
             return False
         for index, data in enumerate(item["data"]):
             if not self._match_resource(
                     data, mismatch_description, index=index):
                 return False
     elif not self._match_resource(item["data"], mismatch_description):
         return False
     return self._matches_includes(item, mismatch_description)
Beispiel #5
0
def assert_description(expected, matcher):
    description = StringDescription()
    description.append_description_of(matcher)
    assert expected == str(description)
Beispiel #6
0
    def testDescriptionIncludesMemoryAddress(self):
        description = StringDescription()
        expected = re.compile("same instance as " + ADDRESS_FORMAT + " 'abc'")

        description.append_description_of(same_instance('abc'));
        self.assertTrue(expected.match(str(description)))
Beispiel #7
0
    def testDescriptionIncludesMemoryAddress(self):
        description = StringDescription()
        expected = re.compile("same instance as " + ADDRESS_FORMAT + " 'abc'")

        description.append_description_of(same_instance("abc"))
        self.assertTrue(expected.match(str(description)))
Beispiel #8
0
 def assert_description(self, expected, matcher):
     description = StringDescription()
     description.append_description_of(matcher)
     self.assertEqual(expected, str(description))
Beispiel #9
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_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)
Beispiel #10
0
def assert_description(expected, matcher):
    description = StringDescription()
    description.append_description_of(matcher)
    assert expected == str(description)
Beispiel #11
0
 def assert_description(self, expected, matcher):
     description = StringDescription()
     description.append_description_of(matcher)
     self.assertEqual(expected, str(description))
Beispiel #12
0
    def testDescriptionIncludesMemoryAddress(self):
        description = StringDescription()
        expected = re.compile("same instance as 0x[0-9a-fA-F]+ 'abc'")

        description.append_description_of(same_instance('abc'))
        self.assertTrue(expected.match(str(description)))