Skip to content

Commit

Permalink
add list collections to doc reference
Browse files Browse the repository at this point in the history
  • Loading branch information
bschreck committed Feb 5, 2024
1 parent 04b3463 commit 5a917af
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mockfirestore/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ def __init__(self, data: Store, path: List[str],
self._path = path
self.parent = parent

@property
def id(self):
return self._path[-1]

def document(self, document_id: Optional[str] = None) -> DocumentReference:
collection = get_by_path(self._data, self._path)
if document_id is None:
Expand Down
10 changes: 10 additions & 0 deletions mockfirestore/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,13 @@ def collection(self, name) -> 'CollectionReference':
if name not in document:
set_by_path(self._data, new_path, {})
return CollectionReference(self._data, new_path, parent=self)

def collections(self) -> list['CollectionReference']:
from mockfirestore.collection import CollectionReference
document = get_by_path(self._data, self._path)
_collections = []
for collname, values in document.items():
if isinstance(values, dict):
new_path = self._path + [collname]
_collections.append(CollectionReference(self._data, new_path, parent=self))
return _collections
17 changes: 17 additions & 0 deletions tests/test_document_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,23 @@ def test_get_nestedDocument(self):

self.assertEqual({'id': 1.1}, doc)

def test_get_nestedCollections(self):
fs = MockFirestore()
fs._data = {'top_collection': {
'top_document': {
'id': 1,
'nested_collection': {
'nested_document': {'id': 1.1}
}
}
}}
collections = fs.collection('top_collection')\
.document('top_document')\
.collections()

self.assertEqual(1, len(collections))
self.assertEqual(collections[0].id, 'nested_collection')

def test_get_nestedDocument_documentDoesNotExist(self):
fs = MockFirestore()
fs._data = {'top_collection': {
Expand Down

0 comments on commit 5a917af

Please sign in to comment.