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: 20 additions & 0 deletions mockfirestore/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,26 @@ def nanos(self):
return str(self._timestamp).split('.')[1]


def flatten_for_merge(data: Dict[str, Any], prefix: str = '') -> Dict[str, Any]:
"""Flatten nested dicts into dot-notation keys for set(merge=True).

Firestore's set(merge=True) deep-merges at every nesting level.
The mock's update() already handles dot-notation keys correctly,
so flattening first lets the existing logic work for nested dicts.

Only plain dicts are recursed into; Firestore transform objects
(Sentinel, ArrayUnion, etc.) are treated as leaf values.
"""
result: Dict[str, Any] = {}
for key, value in data.items():
full_key = '{}.{}'.format(prefix, key) if prefix else key
if isinstance(value, dict) and value:
result.update(flatten_for_merge(value, prefix=full_key))
else:
result[full_key] = value
return result


def get_document_iterator(document: Dict[str, Any], prefix: str = '') -> Iterator[Tuple[str, Any]]:
"""
:returns: (dot-delimited path, value,)
Expand Down
5 changes: 4 additions & 1 deletion mockfirestore/_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ def _apply_updates(document: Dict[str, Any], data: Dict[str, Any]):
def _apply_deletes(document: Dict[str, Any], data: List[str]):
for key in data:
path = key.split(".")
delete_by_path(document, path)
try:
delete_by_path(document, path)
except KeyError:
continue


def _apply_arr_deletes(document: Dict[str, Any], data: Dict[str, Any]):
Expand Down
10 changes: 4 additions & 6 deletions mockfirestore/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ def document(self, document_id: Optional[str] = None) -> DocumentReference:
return DocumentReference(self._data, new_path, parent=self)

def get(self) -> Iterable[DocumentSnapshot]:
warnings.warn('Collection.get is deprecated, please use Collection.stream',
category=DeprecationWarning)
return self.stream()
# Stream uses a generator, so we need to convert it to a list for compatibility for .get() method with firestore library
return list(self.stream())

@property
def path(self):
Expand Down Expand Up @@ -127,9 +126,8 @@ def document(self, document_id: Optional[str] = None, path: List[str] = None) ->
return ret

def get(self) -> Iterable[DocumentSnapshot]:
warnings.warn('Collection.get is deprecated, please use Collection.stream',
category=DeprecationWarning)
return self.stream()
# Stream uses a generator, so we need to convert it to a list for compatibility for .get() method with firestore library
return list(self.stream())

def stream(self, transaction=None) -> Iterable[DocumentSnapshot]:
for path in self._path:
Expand Down
5 changes: 3 additions & 2 deletions mockfirestore/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from typing import List, Dict, Any
from mockfirestore import NotFound
from mockfirestore._helpers import (
Timestamp, Document, Store, get_by_path, set_by_path, delete_by_path
Timestamp, Document, Store, get_by_path, set_by_path, delete_by_path,
flatten_for_merge
)
from mockfirestore._transformations import apply_transformations

Expand Down Expand Up @@ -85,7 +86,7 @@ def set(self, data: Dict, merge=False):
data['__name__'] = self.id
if merge:
try:
self.update(data)
self.update(flatten_for_merge(data))
except NotFound:
self.set(data)
else:
Expand Down
7 changes: 3 additions & 4 deletions mockfirestore/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,11 @@ def stream(self, transaction=None) -> Iterator[DocumentSnapshot]:
if self._limit:
doc_snapshots = islice(doc_snapshots, self._limit)

return iter(doc_snapshots)
return iter(list(doc_snapshots))

def get(self) -> Iterator[DocumentSnapshot]:
warnings.warn('Query.get is deprecated, please use Query.stream',
category=DeprecationWarning)
return self.stream()
# Stream uses a generator, so we need to convert it to a list for compatibility for .get() method with firestore library
return list(self.stream())

def _add_field_filter(self, field: str, op: str, value: Any):
compare = self._compare_func(op)
Expand Down
33 changes: 33 additions & 0 deletions tests/test_document_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,39 @@ def test_document_update_transformerSentinel(self):
doc = fs.collection("foo").document("first").get().to_dict()
self.assertEqual(doc, {})

def test_document_update_transformerSentinelNonExistentField(self):
fs = MockFirestore()
fs._data = {'foo': {
'first': {'spicy': 'tuna'}
}}
fs.collection('foo').document('first').update({"nonexistent": firestore.DELETE_FIELD})

doc = fs.collection("foo").document("first").get().to_dict()
self.assertEqual(doc, {'spicy': 'tuna'})

def test_document_update_transformerSentinelNonExistentNestedField(self):
fs = MockFirestore()
fs._data = {'foo': {
'first': {'spicy': 'tuna'}
}}
fs.collection('foo').document('first').update({"stats.student123.field": firestore.DELETE_FIELD})

doc = fs.collection("foo").document("first").get().to_dict()
self.assertEqual(doc, {'spicy': 'tuna'})

def test_document_update_transformerSentinelMixedExistingAndNonExistent(self):
fs = MockFirestore()
fs._data = {'foo': {
'first': {'spicy': 'tuna', 'remove_me': 'gone'}
}}
fs.collection('foo').document('first').update({
"remove_me": firestore.DELETE_FIELD,
"nonexistent": firestore.DELETE_FIELD,
})

doc = fs.collection("foo").document("first").get().to_dict()
self.assertEqual(doc, {'spicy': 'tuna'})

def test_document_update_transformerArrayRemoveBasic(self):
fs = MockFirestore()
fs._data = {"foo": {"first": {"arr": [1, 2, 3, 4]}}}
Expand Down