PyHamcrest icon indicating copy to clipboard operation
PyHamcrest copied to clipboard

has_entry with nested matchers does not report excact cause

Open dz0 opened this issue 4 years ago • 4 comments

Hi, simple example

data = {'level1': {'level2': 2}}
matcher_level2 = has_entries({'level2': 42})

Why has_entry does not display (block) deeper cause?:

assert_that(data, has_entry('level1', matcher_level2))

Expected: a dictionary containing ['level1': a dictionary containing {'level2': <42>}]
     but: was <{'level1': {'level2': 2}}>

As has_entries displays deepest cause:

assert_that(data['level1'], matcher_level2)

Expected: a dictionary containing {'level2': <42>}
     but: value for 'level2' was <2>

assert_that(data, has_entries({'level1': matcher_level2}))

Expected: a dictionary containing {'level1': a dictionary containing {'level2': <42>}}
     but: value for 'level1' value for 'level2' was <2>

dz0 avatar Feb 19 '21 14:02 dz0

ps.: I'd expect has_entry to be as

def has_entry(key, value_match):
    return has_entries({key: value_match})

dz0 avatar Feb 22 '21 10:02 dz0

Not quite that simple - has_entry() allows a matcher for the key as well as for the value. I'll take a look when I have some time.

brunns avatar Feb 22 '21 11:02 brunns

Thinking about it, perhaps that's why has_entry() doesn't give better mismatch messages. Imagine that the key was specified as hamcrest.anything() - how should the message read then?

Still, if the key matched exactly once, we could probably give better messages in that special but common case.

brunns avatar Feb 22 '21 12:02 brunns

Does https://github.com/hamcrest/PyHamcrest/pull/157 look any good, @dz0 and @offbyone?

brunns avatar Feb 24 '21 14:02 brunns