/
test_system.py
1153 lines (932 loc) · 39.6 KB
/
test_system.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import math
import operator
import os
import re
from google.oauth2 import service_account
import pytest
from google.api_core.exceptions import AlreadyExists
from google.api_core.exceptions import FailedPrecondition
from google.api_core.exceptions import InvalidArgument
from google.api_core.exceptions import NotFound
from google.cloud._helpers import _datetime_to_pb_timestamp
from google.cloud._helpers import UTC
from google.cloud import firestore_v1 as firestore
from test_utils.system import unique_resource_id
from time import sleep
FIRESTORE_CREDS = os.environ.get("FIRESTORE_APPLICATION_CREDENTIALS")
FIRESTORE_PROJECT = os.environ.get("GCLOUD_PROJECT")
RANDOM_ID_REGEX = re.compile("^[a-zA-Z0-9]{20}$")
MISSING_DOCUMENT = "No document to update: "
DOCUMENT_EXISTS = "Document already exists: "
UNIQUE_RESOURCE_ID = unique_resource_id("-")
@pytest.fixture(scope=u"module")
def client():
credentials = service_account.Credentials.from_service_account_file(FIRESTORE_CREDS)
project = FIRESTORE_PROJECT or credentials.project_id
yield firestore.Client(project=project, credentials=credentials)
@pytest.fixture
def cleanup():
operations = []
yield operations.append
for operation in operations:
operation()
def test_collections(client):
collections = list(client.collections())
assert isinstance(collections, list)
def test_collections_w_import():
from google.cloud import firestore
client = firestore.Client()
collections = list(client.collections())
assert isinstance(collections, list)
def test_create_document(client, cleanup):
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
collection_id = "doc-create" + UNIQUE_RESOURCE_ID
document_id = "doc" + UNIQUE_RESOURCE_ID
document = client.document(collection_id, document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
data = {
"now": firestore.SERVER_TIMESTAMP,
"eenta-ger": 11,
"bites": b"\xe2\x98\x83 \xe2\x9b\xb5",
"also": {"nestednow": firestore.SERVER_TIMESTAMP, "quarter": 0.25},
}
write_result = document.create(data)
updated = write_result.update_time
delta = updated - now
# Allow a bit of clock skew, but make sure timestamps are close.
assert -300.0 < delta.total_seconds() < 300.0
with pytest.raises(AlreadyExists):
document.create(data)
# Verify the server times.
snapshot = document.get()
stored_data = snapshot.to_dict()
server_now = stored_data["now"]
delta = updated - server_now
# NOTE: We could check the ``transform_results`` from the write result
# for the document transform, but this value gets dropped. Instead
# we make sure the timestamps are close.
# TODO(microgen): this was 0.0 - 5.0 before. After microgen, This started
# getting very small negative times.
assert -0.2 <= delta.total_seconds() < 5.0
expected_data = {
"now": server_now,
"eenta-ger": data["eenta-ger"],
"bites": data["bites"],
"also": {"nestednow": server_now, "quarter": data["also"]["quarter"]},
}
assert stored_data == expected_data
def test_create_document_w_subcollection(client, cleanup):
collection_id = "doc-create-sub" + UNIQUE_RESOURCE_ID
document_id = "doc" + UNIQUE_RESOURCE_ID
document = client.document(collection_id, document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
data = {"now": firestore.SERVER_TIMESTAMP}
document.create(data)
child_ids = ["child1", "child2"]
for child_id in child_ids:
subcollection = document.collection(child_id)
_, subdoc = subcollection.add({"foo": "bar"})
cleanup(subdoc.delete)
children = document.collections()
assert sorted(child.id for child in children) == sorted(child_ids)
def test_cannot_use_foreign_key(client, cleanup):
document_id = "cannot" + UNIQUE_RESOURCE_ID
document = client.document("foreign-key", document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
other_client = firestore.Client(
project="other-prahj", credentials=client._credentials, database="dee-bee"
)
assert other_client._database_string != client._database_string
fake_doc = other_client.document("foo", "bar")
with pytest.raises(InvalidArgument):
document.create({"ref": fake_doc})
def assert_timestamp_less(timestamp_pb1, timestamp_pb2):
assert timestamp_pb1 < timestamp_pb2
def test_no_document(client):
document_id = "no_document" + UNIQUE_RESOURCE_ID
document = client.document("abcde", document_id)
snapshot = document.get()
assert snapshot.to_dict() is None
def test_document_set(client, cleanup):
document_id = "for-set" + UNIQUE_RESOURCE_ID
document = client.document("i-did-it", document_id)
# Add to clean-up before API request (in case ``set()`` fails).
cleanup(document.delete)
# 0. Make sure the document doesn't exist yet
snapshot = document.get()
assert snapshot.to_dict() is None
# 1. Use ``create()`` to create the document.
data1 = {"foo": 88}
write_result1 = document.create(data1)
snapshot1 = document.get()
assert snapshot1.to_dict() == data1
# Make sure the update is what created the document.
assert snapshot1.create_time == snapshot1.update_time
assert snapshot1.update_time == write_result1.update_time
# 2. Call ``set()`` again to overwrite.
data2 = {"bar": None}
write_result2 = document.set(data2)
snapshot2 = document.get()
assert snapshot2.to_dict() == data2
# Make sure the create time hasn't changed.
assert snapshot2.create_time == snapshot1.create_time
assert snapshot2.update_time == write_result2.update_time
def test_document_integer_field(client, cleanup):
document_id = "for-set" + UNIQUE_RESOURCE_ID
document = client.document("i-did-it", document_id)
# Add to clean-up before API request (in case ``set()`` fails).
cleanup(document.delete)
data1 = {"1a": {"2b": "3c", "ab": "5e"}, "6f": {"7g": "8h", "cd": "0j"}}
document.create(data1)
data2 = {"1a.ab": "4d", "6f.7g": "9h"}
document.update(data2)
snapshot = document.get()
expected = {"1a": {"2b": "3c", "ab": "4d"}, "6f": {"7g": "9h", "cd": "0j"}}
assert snapshot.to_dict() == expected
def test_document_set_merge(client, cleanup):
document_id = "for-set" + UNIQUE_RESOURCE_ID
document = client.document("i-did-it", document_id)
# Add to clean-up before API request (in case ``set()`` fails).
cleanup(document.delete)
# 0. Make sure the document doesn't exist yet
snapshot = document.get()
assert not snapshot.exists
# 1. Use ``create()`` to create the document.
data1 = {"name": "Sam", "address": {"city": "SF", "state": "CA"}}
write_result1 = document.create(data1)
snapshot1 = document.get()
assert snapshot1.to_dict() == data1
# Make sure the update is what created the document.
assert snapshot1.create_time == snapshot1.update_time
assert snapshot1.update_time == write_result1.update_time
# 2. Call ``set()`` to merge
data2 = {"address": {"city": "LA"}}
write_result2 = document.set(data2, merge=True)
snapshot2 = document.get()
assert snapshot2.to_dict() == {
"name": "Sam",
"address": {"city": "LA", "state": "CA"},
}
# Make sure the create time hasn't changed.
assert snapshot2.create_time == snapshot1.create_time
assert snapshot2.update_time == write_result2.update_time
def test_document_set_w_int_field(client, cleanup):
document_id = "set-int-key" + UNIQUE_RESOURCE_ID
document = client.document("i-did-it", document_id)
# Add to clean-up before API request (in case ``set()`` fails).
cleanup(document.delete)
# 0. Make sure the document doesn't exist yet
snapshot = document.get()
assert not snapshot.exists
# 1. Use ``create()`` to create the document.
before = {"testing": "1"}
document.create(before)
# 2. Replace using ``set()``.
data = {"14": {"status": "active"}}
document.set(data)
# 3. Verify replaced data.
snapshot1 = document.get()
assert snapshot1.to_dict() == data
def test_document_update_w_int_field(client, cleanup):
# Attempt to reproduce #5489.
document_id = "update-int-key" + UNIQUE_RESOURCE_ID
document = client.document("i-did-it", document_id)
# Add to clean-up before API request (in case ``set()`` fails).
cleanup(document.delete)
# 0. Make sure the document doesn't exist yet
snapshot = document.get()
assert not snapshot.exists
# 1. Use ``create()`` to create the document.
before = {"testing": "1"}
document.create(before)
# 2. Add values using ``update()``.
data = {"14": {"status": "active"}}
document.update(data)
# 3. Verify updated data.
expected = before.copy()
expected.update(data)
snapshot1 = document.get()
assert snapshot1.to_dict() == expected
def test_update_document(client, cleanup):
document_id = "for-update" + UNIQUE_RESOURCE_ID
document = client.document("made", document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
# 0. Try to update before the document exists.
with pytest.raises(NotFound) as exc_info:
document.update({"not": "there"})
assert exc_info.value.message.startswith(MISSING_DOCUMENT)
assert document_id in exc_info.value.message
# 1. Try to update before the document exists (now with an option).
with pytest.raises(NotFound) as exc_info:
document.update({"still": "not-there"})
assert exc_info.value.message.startswith(MISSING_DOCUMENT)
assert document_id in exc_info.value.message
# 2. Update and create the document (with an option).
data = {"foo": {"bar": "baz"}, "scoop": {"barn": 981}, "other": True}
write_result2 = document.create(data)
# 3. Send an update without a field path (no option).
field_updates3 = {"foo": {"quux": 800}}
write_result3 = document.update(field_updates3)
assert_timestamp_less(write_result2.update_time, write_result3.update_time)
snapshot3 = document.get()
expected3 = {
"foo": field_updates3["foo"],
"scoop": data["scoop"],
"other": data["other"],
}
assert snapshot3.to_dict() == expected3
# 4. Send an update **with** a field path and a delete and a valid
# "last timestamp" option.
field_updates4 = {"scoop.silo": None, "other": firestore.DELETE_FIELD}
option4 = client.write_option(last_update_time=snapshot3.update_time)
write_result4 = document.update(field_updates4, option=option4)
assert_timestamp_less(write_result3.update_time, write_result4.update_time)
snapshot4 = document.get()
expected4 = {
"foo": field_updates3["foo"],
"scoop": {"barn": data["scoop"]["barn"], "silo": field_updates4["scoop.silo"]},
}
assert snapshot4.to_dict() == expected4
# 5. Call ``update()`` with invalid (in the past) "last timestamp" option.
assert_timestamp_less(option4._last_update_time, snapshot4.update_time)
with pytest.raises(FailedPrecondition) as exc_info:
document.update({"bad": "time-past"}, option=option4)
# 6. Call ``update()`` with invalid (in future) "last timestamp" option.
timestamp_pb = _datetime_to_pb_timestamp(snapshot4.update_time)
timestamp_pb.seconds += 3600
option6 = client.write_option(last_update_time=timestamp_pb)
# TODO(microgen):invalid argument thrown after microgen.
# with pytest.raises(FailedPrecondition) as exc_info:
with pytest.raises(InvalidArgument) as exc_info:
document.update({"bad": "time-future"}, option=option6)
def check_snapshot(snapshot, document, data, write_result):
assert snapshot.reference is document
assert snapshot.to_dict() == data
assert snapshot.exists
assert snapshot.create_time == write_result.update_time
assert snapshot.update_time == write_result.update_time
def test_document_get(client, cleanup):
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
document_id = "for-get" + UNIQUE_RESOURCE_ID
document = client.document("created", document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
# First make sure it doesn't exist.
assert not document.get().exists
ref_doc = client.document("top", "middle1", "middle2", "bottom")
data = {
"turtle": "power",
"cheese": 19.5,
"fire": 199099299,
"referee": ref_doc,
"gio": firestore.GeoPoint(45.5, 90.0),
"deep": [u"some", b"\xde\xad\xbe\xef"],
"map": {"ice": True, "water": None, "vapor": {"deeper": now}},
}
write_result = document.create(data)
snapshot = document.get()
check_snapshot(snapshot, document, data, write_result)
def test_document_delete(client, cleanup):
document_id = "deleted" + UNIQUE_RESOURCE_ID
document = client.document("here-to-be", document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document.delete)
document.create({"not": "much"})
# 1. Call ``delete()`` with invalid (in the past) "last timestamp" option.
snapshot1 = document.get()
timestamp_pb = _datetime_to_pb_timestamp(snapshot1.update_time)
timestamp_pb.seconds += 3600
option1 = client.write_option(last_update_time=timestamp_pb)
# TODO(microgen):invalid argument thrown after microgen.
# with pytest.raises(FailedPrecondition):
with pytest.raises(InvalidArgument):
document.delete(option=option1)
# 2. Call ``delete()`` with invalid (in future) "last timestamp" option.
timestamp_pb = _datetime_to_pb_timestamp(snapshot1.update_time)
timestamp_pb.seconds += 3600
option2 = client.write_option(last_update_time=timestamp_pb)
# TODO(microgen):invalid argument thrown after microgen.
# with pytest.raises(FailedPrecondition):
with pytest.raises(InvalidArgument):
document.delete(option=option2)
# 3. Actually ``delete()`` the document.
delete_time3 = document.delete()
# 4. ``delete()`` again, even though we know the document is gone.
delete_time4 = document.delete()
assert_timestamp_less(delete_time3, delete_time4)
def test_collection_add(client, cleanup):
# TODO(microgen): list_documents is returning a generator, not a list.
# Consider if this is desired. Also, Document isn't hashable.
collection_id = "coll-add" + UNIQUE_RESOURCE_ID
collection1 = client.collection(collection_id)
collection2 = client.collection(collection_id, "doc", "child")
collection3 = client.collection(collection_id, "table", "child")
explicit_doc_id = "hula" + UNIQUE_RESOURCE_ID
assert set(collection1.list_documents()) == set()
assert set(collection2.list_documents()) == set()
assert set(collection3.list_documents()) == set()
# Auto-ID at top-level.
data1 = {"foo": "bar"}
update_time1, document_ref1 = collection1.add(data1)
cleanup(document_ref1.delete)
assert set(collection1.list_documents()) == {document_ref1}
assert set(collection2.list_documents()) == set()
assert set(collection3.list_documents()) == set()
snapshot1 = document_ref1.get()
assert snapshot1.to_dict() == data1
assert snapshot1.update_time == update_time1
assert RANDOM_ID_REGEX.match(document_ref1.id)
# Explicit ID at top-level.
data2 = {"baz": 999}
update_time2, document_ref2 = collection1.add(data2, document_id=explicit_doc_id)
cleanup(document_ref2.delete)
assert set(collection1.list_documents()) == {document_ref1, document_ref2}
assert set(collection2.list_documents()) == set()
assert set(collection3.list_documents()) == set()
snapshot2 = document_ref2.get()
assert snapshot2.to_dict() == data2
assert snapshot2.create_time == update_time2
assert snapshot2.update_time == update_time2
assert document_ref2.id == explicit_doc_id
nested_ref = collection1.document("doc")
# Auto-ID for nested collection.
data3 = {"quux": b"\x00\x01\x02\x03"}
update_time3, document_ref3 = collection2.add(data3)
cleanup(document_ref3.delete)
assert set(collection1.list_documents()) == {
document_ref1,
document_ref2,
nested_ref,
}
assert set(collection2.list_documents()) == {document_ref3}
assert set(collection3.list_documents()) == set()
snapshot3 = document_ref3.get()
assert snapshot3.to_dict() == data3
assert snapshot3.update_time == update_time3
assert RANDOM_ID_REGEX.match(document_ref3.id)
# Explicit for nested collection.
data4 = {"kazaam": None, "bad": False}
update_time4, document_ref4 = collection2.add(data4, document_id=explicit_doc_id)
cleanup(document_ref4.delete)
assert set(collection1.list_documents()) == {
document_ref1,
document_ref2,
nested_ref,
}
assert set(collection2.list_documents()) == {document_ref3, document_ref4}
assert set(collection3.list_documents()) == set()
snapshot4 = document_ref4.get()
assert snapshot4.to_dict() == data4
assert snapshot4.create_time == update_time4
assert snapshot4.update_time == update_time4
assert document_ref4.id == explicit_doc_id
# Exercise "missing" document (no doc, but subcollection).
data5 = {"bam": 123, "folyk": False}
update_time5, document_ref5 = collection3.add(data5)
cleanup(document_ref5.delete)
missing_ref = collection1.document("table")
assert set(collection1.list_documents()) == {
document_ref1,
document_ref2,
nested_ref,
missing_ref,
}
assert set(collection2.list_documents()) == {document_ref3, document_ref4}
assert set(collection3.list_documents()) == {document_ref5}
@pytest.fixture
def query_docs(client):
collection_id = "qs" + UNIQUE_RESOURCE_ID
sub_collection = "child" + UNIQUE_RESOURCE_ID
collection = client.collection(collection_id, "doc", sub_collection)
cleanup = []
stored = {}
num_vals = 5
allowed_vals = range(num_vals)
for a_val in allowed_vals:
for b_val in allowed_vals:
document_data = {
"a": a_val,
"b": b_val,
"c": [a_val, num_vals * 100],
"stats": {"sum": a_val + b_val, "product": a_val * b_val},
}
_, doc_ref = collection.add(document_data)
# Add to clean-up.
cleanup.append(doc_ref.delete)
stored[doc_ref.id] = document_data
yield collection, stored, allowed_vals
for operation in cleanup:
operation()
def test_query_stream_w_simple_field_eq_op(query_docs):
collection, stored, allowed_vals = query_docs
query = collection.where("a", "==", 1)
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == len(allowed_vals)
for key, value in values.items():
assert stored[key] == value
assert value["a"] == 1
def test_query_stream_w_simple_field_array_contains_op(query_docs):
collection, stored, allowed_vals = query_docs
query = collection.where("c", "array_contains", 1)
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == len(allowed_vals)
for key, value in values.items():
assert stored[key] == value
assert value["a"] == 1
def test_query_stream_w_simple_field_in_op(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
query = collection.where("a", "in", [1, num_vals + 100])
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == len(allowed_vals)
for key, value in values.items():
assert stored[key] == value
assert value["a"] == 1
def test_query_stream_w_simple_field_array_contains_any_op(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
query = collection.where("c", "array_contains_any", [1, num_vals * 200])
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == len(allowed_vals)
for key, value in values.items():
assert stored[key] == value
assert value["a"] == 1
def test_query_stream_w_order_by(query_docs):
collection, stored, allowed_vals = query_docs
query = collection.order_by("b", direction=firestore.Query.DESCENDING)
values = [(snapshot.id, snapshot.to_dict()) for snapshot in query.stream()]
assert len(values) == len(stored)
b_vals = []
for key, value in values:
assert stored[key] == value
b_vals.append(value["b"])
# Make sure the ``b``-values are in DESCENDING order.
assert sorted(b_vals, reverse=True) == b_vals
def test_query_stream_w_field_path(query_docs):
collection, stored, allowed_vals = query_docs
query = collection.where("stats.sum", ">", 4)
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == 10
ab_pairs2 = set()
for key, value in values.items():
assert stored[key] == value
ab_pairs2.add((value["a"], value["b"]))
expected_ab_pairs = set(
[
(a_val, b_val)
for a_val in allowed_vals
for b_val in allowed_vals
if a_val + b_val > 4
]
)
assert expected_ab_pairs == ab_pairs2
def test_query_stream_w_start_end_cursor(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
query = (
collection.order_by("a")
.start_at({"a": num_vals - 2})
.end_before({"a": num_vals - 1})
)
values = [(snapshot.id, snapshot.to_dict()) for snapshot in query.stream()]
assert len(values) == num_vals
for key, value in values:
assert stored[key] == value
assert value["a"] == num_vals - 2
def test_query_stream_wo_results(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
query = collection.where("b", "==", num_vals + 100)
values = list(query.stream())
assert len(values) == 0
def test_query_stream_w_projection(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
query = collection.where("b", "<=", 1).select(["a", "stats.product"])
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
assert len(values) == num_vals * 2 # a ANY, b in (0, 1)
for key, value in values.items():
expected = {
"a": stored[key]["a"],
"stats": {"product": stored[key]["stats"]["product"]},
}
assert expected == value
def test_query_stream_w_multiple_filters(query_docs):
collection, stored, allowed_vals = query_docs
query = collection.where("stats.product", ">", 5).where("stats.product", "<", 10)
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
matching_pairs = [
(a_val, b_val)
for a_val in allowed_vals
for b_val in allowed_vals
if 5 < a_val * b_val < 10
]
assert len(values) == len(matching_pairs)
for key, value in values.items():
assert stored[key] == value
pair = (value["a"], value["b"])
assert pair in matching_pairs
def test_query_stream_w_offset(query_docs):
collection, stored, allowed_vals = query_docs
num_vals = len(allowed_vals)
offset = 3
query = collection.where("b", "==", 2).offset(offset)
values = {snapshot.id: snapshot.to_dict() for snapshot in query.stream()}
# NOTE: We don't check the ``a``-values, since that would require
# an ``order_by('a')``, which combined with the ``b == 2``
# filter would necessitate an index.
assert len(values) == num_vals - offset
for key, value in values.items():
assert stored[key] == value
assert value["b"] == 2
def test_query_with_order_dot_key(client, cleanup):
db = client
collection_id = "collek" + unique_resource_id("-")
collection = db.collection(collection_id)
for index in range(100, -1, -1):
doc = collection.document("test_{:09d}".format(index))
data = {"count": 10 * index, "wordcount": {"page1": index * 10 + 100}}
doc.set(data)
cleanup(doc.delete)
query = collection.order_by("wordcount.page1").limit(3)
data = [doc.to_dict()["wordcount"]["page1"] for doc in query.stream()]
assert [100, 110, 120] == data
for snapshot in collection.order_by("wordcount.page1").limit(3).stream():
last_value = snapshot.get("wordcount.page1")
cursor_with_nested_keys = {"wordcount": {"page1": last_value}}
found = list(
collection.order_by("wordcount.page1")
.start_after(cursor_with_nested_keys)
.limit(3)
.stream()
)
found_data = [
{u"count": 30, u"wordcount": {u"page1": 130}},
{u"count": 40, u"wordcount": {u"page1": 140}},
{u"count": 50, u"wordcount": {u"page1": 150}},
]
assert found_data == [snap.to_dict() for snap in found]
cursor_with_dotted_paths = {"wordcount.page1": last_value}
cursor_with_key_data = list(
collection.order_by("wordcount.page1")
.start_after(cursor_with_dotted_paths)
.limit(3)
.stream()
)
assert found_data == [snap.to_dict() for snap in cursor_with_key_data]
def test_query_unary(client, cleanup):
collection_name = "unary" + UNIQUE_RESOURCE_ID
collection = client.collection(collection_name)
field_name = "foo"
_, document0 = collection.add({field_name: None})
# Add to clean-up.
cleanup(document0.delete)
nan_val = float("nan")
_, document1 = collection.add({field_name: nan_val})
# Add to clean-up.
cleanup(document1.delete)
# 0. Query for null.
query0 = collection.where(field_name, "==", None)
values0 = list(query0.stream())
assert len(values0) == 1
snapshot0 = values0[0]
assert snapshot0.reference._path == document0._path
assert snapshot0.to_dict() == {field_name: None}
# 1. Query for a NAN.
query1 = collection.where(field_name, "==", nan_val)
values1 = list(query1.stream())
assert len(values1) == 1
snapshot1 = values1[0]
assert snapshot1.reference._path == document1._path
data1 = snapshot1.to_dict()
assert len(data1) == 1
assert math.isnan(data1[field_name])
def test_collection_group_queries(client, cleanup):
collection_group = "b" + UNIQUE_RESOURCE_ID
doc_paths = [
"abc/123/" + collection_group + "/cg-doc1",
"abc/123/" + collection_group + "/cg-doc2",
collection_group + "/cg-doc3",
collection_group + "/cg-doc4",
"def/456/" + collection_group + "/cg-doc5",
collection_group + "/virtual-doc/nested-coll/not-cg-doc",
"x" + collection_group + "/not-cg-doc",
collection_group + "x/not-cg-doc",
"abc/123/" + collection_group + "x/not-cg-doc",
"abc/123/x" + collection_group + "/not-cg-doc",
"abc/" + collection_group,
]
batch = client.batch()
for doc_path in doc_paths:
doc_ref = client.document(doc_path)
batch.set(doc_ref, {"x": 1})
cleanup(doc_ref.delete)
batch.commit()
query = client.collection_group(collection_group)
snapshots = list(query.stream())
found = [snapshot.id for snapshot in snapshots]
expected = ["cg-doc1", "cg-doc2", "cg-doc3", "cg-doc4", "cg-doc5"]
assert found == expected
def test_collection_group_queries_startat_endat(client, cleanup):
collection_group = "b" + UNIQUE_RESOURCE_ID
doc_paths = [
"a/a/" + collection_group + "/cg-doc1",
"a/b/a/b/" + collection_group + "/cg-doc2",
"a/b/" + collection_group + "/cg-doc3",
"a/b/c/d/" + collection_group + "/cg-doc4",
"a/c/" + collection_group + "/cg-doc5",
collection_group + "/cg-doc6",
"a/b/nope/nope",
]
batch = client.batch()
for doc_path in doc_paths:
doc_ref = client.document(doc_path)
batch.set(doc_ref, {"x": doc_path})
cleanup(doc_ref.delete)
batch.commit()
query = (
client.collection_group(collection_group)
.order_by("__name__")
.start_at([client.document("a/b")])
.end_at([client.document("a/b0")])
)
snapshots = list(query.stream())
found = set(snapshot.id for snapshot in snapshots)
assert found == set(["cg-doc2", "cg-doc3", "cg-doc4"])
query = (
client.collection_group(collection_group)
.order_by("__name__")
.start_after([client.document("a/b")])
.end_before([client.document("a/b/" + collection_group + "/cg-doc3")])
)
snapshots = list(query.stream())
found = set(snapshot.id for snapshot in snapshots)
assert found == set(["cg-doc2"])
def test_collection_group_queries_filters(client, cleanup):
collection_group = "b" + UNIQUE_RESOURCE_ID
doc_paths = [
"a/a/" + collection_group + "/cg-doc1",
"a/b/a/b/" + collection_group + "/cg-doc2",
"a/b/" + collection_group + "/cg-doc3",
"a/b/c/d/" + collection_group + "/cg-doc4",
"a/c/" + collection_group + "/cg-doc5",
collection_group + "/cg-doc6",
"a/b/nope/nope",
]
batch = client.batch()
for index, doc_path in enumerate(doc_paths):
doc_ref = client.document(doc_path)
batch.set(doc_ref, {"x": index})
cleanup(doc_ref.delete)
batch.commit()
query = (
client.collection_group(collection_group)
.where(
firestore.field_path.FieldPath.document_id(), ">=", client.document("a/b")
)
.where(
firestore.field_path.FieldPath.document_id(), "<=", client.document("a/b0")
)
)
snapshots = list(query.stream())
found = set(snapshot.id for snapshot in snapshots)
assert found == set(["cg-doc2", "cg-doc3", "cg-doc4"])
query = (
client.collection_group(collection_group)
.where(
firestore.field_path.FieldPath.document_id(), ">", client.document("a/b")
)
.where(
firestore.field_path.FieldPath.document_id(),
"<",
client.document("a/b/{}/cg-doc3".format(collection_group)),
)
)
snapshots = list(query.stream())
found = set(snapshot.id for snapshot in snapshots)
assert found == set(["cg-doc2"])
def test_get_all(client, cleanup):
collection_name = "get-all" + UNIQUE_RESOURCE_ID
document1 = client.document(collection_name, "a")
document2 = client.document(collection_name, "b")
document3 = client.document(collection_name, "c")
# Add to clean-up before API requests (in case ``create()`` fails).
cleanup(document1.delete)
cleanup(document3.delete)
data1 = {"a": {"b": 2, "c": 3}, "d": 4, "e": 0}
write_result1 = document1.create(data1)
data3 = {"a": {"b": 5, "c": 6}, "d": 7, "e": 100}
write_result3 = document3.create(data3)
# 0. Get 3 unique documents, one of which is missing.
snapshots = list(client.get_all([document1, document2, document3]))
assert snapshots[0].exists
assert snapshots[1].exists
assert not snapshots[2].exists
snapshots = [snapshot for snapshot in snapshots if snapshot.exists]
id_attr = operator.attrgetter("id")
snapshots.sort(key=id_attr)
snapshot1, snapshot3 = snapshots
check_snapshot(snapshot1, document1, data1, write_result1)
check_snapshot(snapshot3, document3, data3, write_result3)
# 1. Get 2 colliding documents.
document1_also = client.document(collection_name, "a")
snapshots = list(client.get_all([document1, document1_also]))
assert len(snapshots) == 1
assert document1 is not document1_also
check_snapshot(snapshots[0], document1_also, data1, write_result1)
# 2. Use ``field_paths`` / projection in ``get_all()``.
snapshots = list(client.get_all([document1, document3], field_paths=["a.b", "d"]))
assert len(snapshots) == 2
snapshots.sort(key=id_attr)
snapshot1, snapshot3 = snapshots
restricted1 = {"a": {"b": data1["a"]["b"]}, "d": data1["d"]}
check_snapshot(snapshot1, document1, restricted1, write_result1)
restricted3 = {"a": {"b": data3["a"]["b"]}, "d": data3["d"]}
check_snapshot(snapshot3, document3, restricted3, write_result3)
def test_batch(client, cleanup):
collection_name = "batch" + UNIQUE_RESOURCE_ID
document1 = client.document(collection_name, "abc")
document2 = client.document(collection_name, "mno")
document3 = client.document(collection_name, "xyz")
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(document1.delete)
cleanup(document2.delete)
cleanup(document3.delete)
data2 = {"some": {"deep": "stuff", "and": "here"}, "water": 100.0}
document2.create(data2)
document3.create({"other": 19})
batch = client.batch()
data1 = {"all": True}
batch.create(document1, data1)
new_value = "there"
batch.update(document2, {"some.and": new_value})
batch.delete(document3)
write_results = batch.commit()
assert len(write_results) == 3
write_result1 = write_results[0]
write_result2 = write_results[1]
write_result3 = write_results[2]
assert not write_result3._pb.HasField("update_time")
snapshot1 = document1.get()
assert snapshot1.to_dict() == data1
assert snapshot1.create_time == write_result1.update_time
assert snapshot1.update_time == write_result1.update_time
snapshot2 = document2.get()
assert snapshot2.to_dict() != data2
data2["some"]["and"] = new_value
assert snapshot2.to_dict() == data2
assert_timestamp_less(snapshot2.create_time, write_result2.update_time)
assert snapshot2.update_time == write_result2.update_time
assert not document3.get().exists
def test_watch_document(client, cleanup):
db = client
collection_ref = db.collection(u"wd-users" + UNIQUE_RESOURCE_ID)
doc_ref = collection_ref.document(u"alovelace")
# Initial setting
doc_ref.set({u"first": u"Jane", u"last": u"Doe", u"born": 1900})
cleanup(doc_ref.delete)
sleep(1)
# Setup listener
def on_snapshot(docs, changes, read_time):
on_snapshot.called_count += 1
on_snapshot.called_count = 0
doc_ref.on_snapshot(on_snapshot)
# Alter document
doc_ref.set({u"first": u"Ada", u"last": u"Lovelace", u"born": 1815})
sleep(1)
for _ in range(10):
if on_snapshot.called_count > 0: