-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtest_system.py
More file actions
3831 lines (3168 loc) · 134 KB
/
test_system.py
File metadata and controls
3831 lines (3168 loc) · 134 KB
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 itertools
import math
import operator
from time import sleep
from typing import Callable, Dict, List, Optional
import google.auth
import mock
import pytest
from google.api_core.exceptions import (
AlreadyExists,
FailedPrecondition,
InvalidArgument,
NotFound,
)
from google.cloud._helpers import _datetime_to_pb_timestamp
from google.oauth2 import service_account
from test__helpers import (
EMULATOR_CREDS,
ENTERPRISE_MODE_ERROR,
FIRESTORE_CREDS,
FIRESTORE_EMULATOR,
FIRESTORE_ENTERPRISE_DB,
FIRESTORE_PROJECT,
MISSING_DOCUMENT,
RANDOM_ID_REGEX,
TEST_DATABASES,
TEST_DATABASES_W_ENTERPRISE,
UNIQUE_RESOURCE_ID,
)
from google.cloud import firestore_v1 as firestore
from google.cloud.firestore_v1.base_query import And, FieldFilter, Or
from google.cloud.firestore_v1.base_vector_query import DistanceMeasure
from google.cloud.firestore_v1.vector import Vector
def _get_credentials_and_project():
if FIRESTORE_EMULATOR:
credentials = EMULATOR_CREDS
project = FIRESTORE_PROJECT
elif FIRESTORE_CREDS:
credentials = service_account.Credentials.from_service_account_file(
FIRESTORE_CREDS
)
project = FIRESTORE_PROJECT or credentials.project_id
else:
credentials, project = google.auth.default()
return credentials, project
@pytest.fixture(scope="session")
def database(request):
return request.param
@pytest.fixture(scope="module")
def client(database):
credentials, project = _get_credentials_and_project()
yield firestore.Client(project=project, credentials=credentials, database=database)
@pytest.fixture
def cleanup():
operations = []
yield operations.append
for operation in operations:
operation()
def verify_pipeline(query):
"""
This function ensures a pipeline produces the same
results as the query it is derived from
It can be attached to existing query tests to check both
modalities at the same time
"""
from google.cloud.firestore_v1.base_aggregation import BaseAggregationQuery
client = query._client
if FIRESTORE_EMULATOR:
print("skip pipeline verification on emulator")
return
if client._database != FIRESTORE_ENTERPRISE_DB:
print("pipelines only supports enterprise db")
return
def _clean_results(results):
if isinstance(results, dict):
return {k: _clean_results(v) for k, v in results.items()}
elif isinstance(results, list):
return [_clean_results(r) for r in results]
elif isinstance(results, float) and math.isnan(results):
return "__NAN_VALUE__"
else:
return results
query_exception = None
query_results = None
try:
try:
if isinstance(query, BaseAggregationQuery):
# aggregation queries return a list of lists of aggregation results
query_results = _clean_results(
list(
itertools.chain.from_iterable(
[[a._to_dict() for a in s] for s in query.get()]
)
)
)
else:
# other qureies return a simple list of results
query_results = _clean_results([s.to_dict() for s in query.get()])
except Exception as e:
# if we expect the query to fail, capture the exception
query_exception = e
pipeline = client.pipeline().create_from(query)
if query_exception:
# ensure that the pipeline uses same error as query
with pytest.raises(query_exception.__class__):
pipeline.execute()
else:
# ensure results match query
pipeline_results = _clean_results([s.data() for s in pipeline.execute()])
assert query_results == pipeline_results
except FailedPrecondition as e:
# if testing against a non-enterprise db, skip this check
if ENTERPRISE_MODE_ERROR not in e.message:
raise e
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_collections(client, database):
collections = list(client.collections())
assert isinstance(collections, list)
@pytest.mark.parametrize("database", TEST_DATABASES)
def test_collections_w_import(database):
from google.cloud import firestore
credentials, project = _get_credentials_and_project()
client = firestore.Client(
project=project, credentials=credentials, database=database
)
collections = list(client.collections())
assert isinstance(collections, list)
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["stream", "get"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_collection_stream_or_get_w_no_explain_options(database, query_docs, method):
from google.cloud.firestore_v1.query_profile import QueryExplainError
collection, _, _ = query_docs
# Tests either `stream()` or `get()`.
method_under_test = getattr(collection, method)
results = method_under_test()
# verify explain_metrics isn't available
with pytest.raises(
QueryExplainError,
match="explain_options not set on query.",
):
results.get_explain_metrics()
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["get", "stream"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_collection_stream_or_get_w_explain_options_analyze_false(
database, method, query_docs
):
from google.cloud.firestore_v1.query_profile import (
ExplainMetrics,
ExplainOptions,
PlanSummary,
QueryExplainError,
)
collection, _, _ = query_docs
# Tests either `stream()` or `get()`.
method_under_test = getattr(collection, method)
results = method_under_test(explain_options=ExplainOptions(analyze=False))
# Verify explain_metrics and plan_summary.
explain_metrics = results.get_explain_metrics()
assert isinstance(explain_metrics, ExplainMetrics)
plan_summary = explain_metrics.plan_summary
assert isinstance(plan_summary, PlanSummary)
assert len(plan_summary.indexes_used) > 0
assert plan_summary.indexes_used[0]["properties"] == "(__name__ ASC)"
assert plan_summary.indexes_used[0]["query_scope"] == "Collection"
# Verify execution_stats isn't available.
with pytest.raises(
QueryExplainError,
match="execution_stats not available when explain_options.analyze=False",
):
explain_metrics.execution_stats
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["get", "stream"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_collection_stream_or_get_w_explain_options_analyze_true(
database, method, query_docs
):
from google.cloud.firestore_v1.query_profile import (
ExecutionStats,
ExplainMetrics,
ExplainOptions,
PlanSummary,
QueryExplainError,
)
collection, _, _ = query_docs
# Tests either `stream()` or `get()`.
method_under_test = getattr(collection, method)
results = method_under_test(explain_options=ExplainOptions(analyze=True))
# In the case of `stream()`, an exception should be raised when accessing
# explain_metrics before query finishes.
if method == "stream":
with pytest.raises(
QueryExplainError,
match="explain_metrics not available until query is complete",
):
results.get_explain_metrics()
# Finish iterating results, and explain_metrics should be available.
num_results = len(list(results))
# Verify explain_metrics and plan_summary.
explain_metrics = results.get_explain_metrics()
assert isinstance(explain_metrics, ExplainMetrics)
plan_summary = explain_metrics.plan_summary
assert isinstance(plan_summary, PlanSummary)
assert len(plan_summary.indexes_used) > 0
assert plan_summary.indexes_used[0]["properties"] == "(__name__ ASC)"
assert plan_summary.indexes_used[0]["query_scope"] == "Collection"
# Verify execution_stats.
execution_stats = explain_metrics.execution_stats
assert isinstance(execution_stats, ExecutionStats)
assert execution_stats.results_returned == num_results
assert execution_stats.read_operations == num_results
duration = execution_stats.execution_duration.total_seconds()
assert duration > 0
assert duration < 1 # we expect a number closer to 0.05
assert isinstance(execution_stats.debug_stats, dict)
assert "billing_details" in execution_stats.debug_stats
assert "documents_scanned" in execution_stats.debug_stats
assert "index_entries_scanned" in execution_stats.debug_stats
assert len(execution_stats.debug_stats) > 0
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_collections_w_read_time(client, cleanup, database):
first_collection_id = "doc-create" + UNIQUE_RESOURCE_ID
first_document_id = "doc" + UNIQUE_RESOURCE_ID
first_document = client.document(first_collection_id, first_document_id)
# Add to clean-up before API request (in case ``create()`` fails).
cleanup(first_document.delete)
data = {"status": "new"}
write_result = first_document.create(data)
read_time = write_result.update_time
second_collection_id = "doc-create" + UNIQUE_RESOURCE_ID + "-2"
second_document_id = "doc" + UNIQUE_RESOURCE_ID + "-2"
second_document = client.document(second_collection_id, second_document_id)
cleanup(second_document.delete)
second_document.create(data)
# Test that listing current collections does have the second id.
curr_collections = list(client.collections())
ids = [collection.id for collection in curr_collections]
assert second_collection_id in ids
assert first_collection_id in ids
# We're just testing that we added one collection at read_time, not two.
collections = list(client.collections(read_time=read_time))
ids = [collection.id for collection in collections]
assert second_collection_id not in ids
assert first_collection_id in ids
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_create_document(client, cleanup, database):
now = datetime.datetime.now(tz=datetime.timezone.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
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_create_document_w_vector(client, cleanup, database):
collection_id = "doc-create" + UNIQUE_RESOURCE_ID
document1 = client.document(collection_id, "doc1")
document2 = client.document(collection_id, "doc2")
document3 = client.document(collection_id, "doc3")
data1 = {"embedding": Vector([1.0, 2.0, 3.0])}
data2 = {"embedding": Vector([2, 2, 3.0])}
data3 = {"embedding": Vector([2.0, 2.0])}
document1.create(data1)
document2.create(data2)
document3.create(data3)
assert [
v.to_dict()
for v in client.collection(collection_id).order_by("embedding").get()
] == [data3, data1, data2]
def on_snapshot(docs, changes, read_time):
on_snapshot.results += docs
on_snapshot.results = []
client.collection(collection_id).order_by("embedding").on_snapshot(on_snapshot)
# delay here so initial on_snapshot occurs and isn't combined with set
sleep(1)
assert [v.to_dict() for v in on_snapshot.results] == [data3, data1, data2]
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
@pytest.mark.parametrize(
"distance_measure",
[
DistanceMeasure.EUCLIDEAN,
DistanceMeasure.COSINE,
],
)
def test_vector_search_collection(client, database, distance_measure):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection = client.collection(collection_id)
vector_query = collection.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=distance_measure,
limit=1,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 1
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
@pytest.mark.parametrize(
"distance_measure",
[
DistanceMeasure.EUCLIDEAN,
DistanceMeasure.COSINE,
],
)
def test_vector_search_collection_with_filter(client, database, distance_measure):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection = client.collection(collection_id)
vector_query = collection.where("color", "==", "red").find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=distance_measure,
limit=1,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 1
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_search_collection_with_distance_parameters_euclid(client, database):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection = client.collection(collection_id)
vector_query = collection.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.EUCLIDEAN,
limit=3,
distance_result_field="vector_distance",
distance_threshold=1.0,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 2
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 0.0,
}
assert returned[1].to_dict() == {
"embedding": Vector([2.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 1.0,
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_search_collection_with_distance_parameters_cosine(client, database):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection = client.collection(collection_id)
vector_query = collection.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.COSINE,
limit=3,
distance_result_field="vector_distance",
distance_threshold=0.02,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 2
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 0.0,
}
assert returned[1].to_dict() == {
"embedding": Vector([3.0, 4.0, 5.0]),
"color": "yellow",
"vector_distance": 0.017292370176009153,
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
@pytest.mark.parametrize(
"distance_measure",
[
DistanceMeasure.EUCLIDEAN,
DistanceMeasure.COSINE,
],
)
def test_vector_search_collection_group(client, database, distance_measure):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=distance_measure,
limit=1,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 1
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize(
"distance_measure",
[
DistanceMeasure.EUCLIDEAN,
DistanceMeasure.COSINE,
],
)
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_search_collection_group_with_filter(client, database, distance_measure):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.where("color", "==", "red").find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=distance_measure,
limit=1,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 1
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_search_collection_group_with_distance_parameters_euclid(
client, database
):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.EUCLIDEAN,
limit=3,
distance_result_field="vector_distance",
distance_threshold=1.0,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 2
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 0.0,
}
assert returned[1].to_dict() == {
"embedding": Vector([2.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 1.0,
}
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Require index and seed data")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_search_collection_group_with_distance_parameters_cosine(
client, database
):
# Documents and Indexes are a manual step from util/bootstrap_vector_index.py
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.COSINE,
limit=3,
distance_result_field="vector_distance",
distance_threshold=0.02,
)
returned = vector_query.get()
assert isinstance(returned, list)
assert len(returned) == 2
assert returned[0].to_dict() == {
"embedding": Vector([1.0, 2.0, 3.0]),
"color": "red",
"vector_distance": 0.0,
}
assert returned[1].to_dict() == {
"embedding": Vector([3.0, 4.0, 5.0]),
"color": "yellow",
"vector_distance": 0.017292370176009153,
}
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["stream", "get"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_query_stream_or_get_w_no_explain_options(client, database, method):
from google.cloud.firestore_v1.query_profile import QueryExplainError
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.where("color", "==", "red").find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.EUCLIDEAN,
limit=1,
)
# Tests either `stream()` or `get()`.
method_under_test = getattr(vector_query, method)
results = method_under_test()
# verify explain_metrics isn't available
with pytest.raises(
QueryExplainError,
match="explain_options not set on query.",
):
results.get_explain_metrics()
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["stream", "get"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_query_stream_or_get_w_explain_options_analyze_true(
client, database, method
):
from google.cloud.firestore_v1.query_profile import (
ExecutionStats,
ExplainMetrics,
ExplainOptions,
PlanSummary,
QueryExplainError,
)
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.where("color", "==", "red").find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.EUCLIDEAN,
limit=1,
)
# Tests either `stream()` or `get()`.
method_under_test = getattr(vector_query, method)
results = method_under_test(explain_options=ExplainOptions(analyze=True))
# With `stream()`, an exception should be raised when accessing
# explain_metrics before query finishes.
if method == "stream":
with pytest.raises(
QueryExplainError,
match="explain_metrics not available until query is complete",
):
results.get_explain_metrics()
# Finish iterating results, and explain_metrics should be available.
num_results = len(list(results))
# Verify explain_metrics and plan_summary.
explain_metrics = results.get_explain_metrics()
assert isinstance(explain_metrics, ExplainMetrics)
plan_summary = explain_metrics.plan_summary
assert isinstance(plan_summary, PlanSummary)
assert len(plan_summary.indexes_used) > 0
assert (
plan_summary.indexes_used[0]["properties"]
== "(color ASC, __name__ ASC, embedding VECTOR<3>)"
)
assert plan_summary.indexes_used[0]["query_scope"] == "Collection group"
# Verify execution_stats.
execution_stats = explain_metrics.execution_stats
assert isinstance(execution_stats, ExecutionStats)
assert execution_stats.results_returned == num_results
assert execution_stats.read_operations > 0
duration = execution_stats.execution_duration.total_seconds()
assert duration > 0
assert duration < 1 # we expect a number closer to 0.05
assert isinstance(execution_stats.debug_stats, dict)
assert "billing_details" in execution_stats.debug_stats
assert "documents_scanned" in execution_stats.debug_stats
assert "index_entries_scanned" in execution_stats.debug_stats
assert len(execution_stats.debug_stats) > 0
@pytest.mark.skipif(
FIRESTORE_EMULATOR, reason="Query profile not supported in emulator."
)
@pytest.mark.parametrize("method", ["stream", "get"])
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_vector_query_stream_or_get_w_explain_options_analyze_false(
client, database, method
):
from google.cloud.firestore_v1.query_profile import (
ExplainMetrics,
ExplainOptions,
PlanSummary,
QueryExplainError,
)
collection_id = "vector_search"
collection_group = client.collection_group(collection_id)
vector_query = collection_group.where("color", "==", "red").find_nearest(
vector_field="embedding",
query_vector=Vector([1.0, 2.0, 3.0]),
distance_measure=DistanceMeasure.EUCLIDEAN,
limit=1,
)
# Tests either `stream()` or `get()`.
method_under_test = getattr(vector_query, method)
results = method_under_test(explain_options=ExplainOptions(analyze=False))
results_list = list(results)
assert len(results_list) == 0
# Verify explain_metrics and plan_summary.
explain_metrics = results.get_explain_metrics()
assert isinstance(explain_metrics, ExplainMetrics)
plan_summary = explain_metrics.plan_summary
assert isinstance(plan_summary, PlanSummary)
assert len(plan_summary.indexes_used) > 0
assert (
plan_summary.indexes_used[0]["properties"]
== "(color ASC, __name__ ASC, embedding VECTOR<3>)"
)
assert plan_summary.indexes_used[0]["query_scope"] == "Collection group"
# Verify execution_stats isn't available.
with pytest.raises(
QueryExplainError,
match="execution_stats not available when explain_options.analyze=False",
):
explain_metrics.execution_stats
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_create_document_w_subcollection(client, cleanup, database):
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 assert_timestamp_less(timestamp_pb1, timestamp_pb2):
assert timestamp_pb1 < timestamp_pb2
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_collections_w_read_time(client, cleanup, database):
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)
original_child_ids = ["child1", "child2"]
read_time = None
for child_id in original_child_ids:
subcollection = document.collection(child_id)
update_time, subdoc = subcollection.add({"foo": "bar"})
read_time = (
update_time if read_time is None or update_time > read_time else read_time
)
cleanup(subdoc.delete)
update_time, newdoc = document.collection("child3").add({"foo": "bar"})
cleanup(newdoc.delete)
assert update_time > read_time
# Compare the query at read_time to the query at new update time.
original_children = document.collections(read_time=read_time)
assert sorted(child.id for child in original_children) == sorted(original_child_ids)
original_children = document.collections()
assert sorted(child.id for child in original_children) == sorted(
original_child_ids + ["child3"]
)
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_no_document(client, database):
document_id = "no_document" + UNIQUE_RESOURCE_ID
document = client.document("abcde", document_id)
snapshot = document.get()
assert snapshot.to_dict() is None
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_set(client, cleanup, database):
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
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_integer_field(client, cleanup, database):
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
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_set_merge(client, cleanup, database):
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
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_set_w_int_field(client, cleanup, database):
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
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_document_update_w_int_field(client, cleanup, database):
# 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
@pytest.mark.skipif(FIRESTORE_EMULATOR, reason="Internal Issue b/137867104")
@pytest.mark.parametrize("database", TEST_DATABASES, indirect=True)
def test_update_document(client, cleanup, database):
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)