Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions dpath/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,13 +347,21 @@ def merger(dst, src, _segments=()):
continue

if flags & MergeType.REPLACE:
try:
target[""]
except TypeError:
segments.set(dst, current_path, found)
if isinstance(target, MutableMapping):
# Mappings are always deep-merged, even under
# REPLACE, so that existing keys (including an
# empty-string key) are preserved. The previous
# implementation probed the target with target[""]
# to detect mappings; on a mapping that raised
# KeyError (or, when the mapping contained an
# empty-string key, succeeded) and silently
# skipped the path, dropping the source data.
merger(dst, found, current_path)
continue
except Exception:
raise
# Sequences and other non-mapping targets are replaced
# wholesale by the source.
segments.set(dst, current_path, found)
continue
except Exception:
# We have a dictionary like thing and we need to attempt to
# recursively merge it.
Expand Down
15 changes: 15 additions & 0 deletions tests/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,21 @@ def test_merge_replace_2():
assert d1['a'][0] == 'a'


def test_merge_replace_empty_string_key_in_dst():
# Regression: a destination mapping that contains an empty-string key
# must not cause merge(REPLACE) to silently drop the source data.
# The old implementation probed the target with target[""], which
# succeeded on such a mapping and skipped the path entirely.
dst = {"a": {"": "keep", "x": 1}}
src = {"a": {"y": 2}}

dpath.merge(dst, copy.deepcopy(src), flags=dpath.MergeType.REPLACE)

assert dst["a"]["y"] == 2, "source data was dropped: %r" % (dst,)
assert dst["a"][""] == "keep", "existing empty-string key lost: %r" % (dst,)
assert dst["a"]["x"] == 1, "existing key lost: %r" % (dst,)


def test_merge_list():
src = {"l": [1]}
p1 = {"l": [2], "v": 1}
Expand Down