Skip to content
Merged
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
2 changes: 1 addition & 1 deletion src/firebase_functions/db_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def _db_endpoint_handler(
after = event_data["delta"]
# Merge delta into data to generate an 'after' view of the data.
if isinstance(before, dict) and isinstance(after, dict):
after = _util.prune_nones({**before, **after})
after = _util.prune_nones(_util.deep_merge(before, after))
database_event_data = Change(
before=before,
after=after,
Expand Down
11 changes: 11 additions & 0 deletions src/firebase_functions/private/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ def prune_nones(obj: dict) -> dict:
return obj


def deep_merge(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if isinstance(value, dict):
node = result.get(key, {})
result[key] = deep_merge(node, value)
else:
result[key] = value
return result


def valid_on_call_request(request: _Request) -> bool:
"""Validate request"""
if (_on_call_valid_method(request) and
Expand Down
26 changes: 25 additions & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
Internal utils tests.
"""
from os import environ, path
from firebase_functions.private.util import firebase_config, microsecond_timestamp_conversion, nanoseconds_timestamp_conversion, is_precision_timestamp, normalize_path
from firebase_functions.private.util import firebase_config, microsecond_timestamp_conversion, nanoseconds_timestamp_conversion, is_precision_timestamp, normalize_path, deep_merge
import datetime as _dt

test_bucket = "python-functions-testing.appspot.com"
Expand Down Expand Up @@ -121,3 +121,27 @@ def test_normalize_document_path():
test_path2 = "test/document"
assert normalize_path(test_path2) == "test/document", (
"Failure, path should not be changed if it is already normalized.")


def test_toplevel_keys():
dict1 = {"baz": {"answer": 42, "qux": "quux"}, "foo": "bar"}
dict2 = {"baz": {"answer": 33}}
result = deep_merge(dict1, dict2)
assert "foo" in result
assert "baz" in result


def test_nested_merge():
dict1 = {"baz": {"answer": 42, "qux": "quux"}, "foo": "bar"}
dict2 = {"baz": {"answer": 33}}
result = deep_merge(dict1, dict2)
assert result["baz"]["answer"] == 33
assert result["baz"]["qux"] == "quux"


def test_does_not_modify_originals():
dict1 = {"baz": {"answer": 42, "qux": "quux"}, "foo": "bar"}
dict2 = {"baz": {"answer": 33}}
deep_merge(dict1, dict2)
assert dict1["baz"]["answer"] == 42
assert dict2["baz"]["answer"] == 33