This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathtest_system_async.py
More file actions
1388 lines (1268 loc) · 52.9 KB
/
test_system_async.py
File metadata and controls
1388 lines (1268 loc) · 52.9 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 2024 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 pytest
import datetime
import uuid
import os
from google.api_core import retry
from google.api_core.exceptions import ClientError, PermissionDenied
from google.cloud.bigtable.data.execute_query.metadata import SqlType
from google.cloud.bigtable.data.read_modify_write_rules import _MAX_INCREMENT_VALUE
from google.cloud.environment_vars import BIGTABLE_EMULATOR
from google.type import date_pb2
from google.cloud.bigtable.data._cross_sync import CrossSync
from . import TEST_FAMILY, TEST_FAMILY_2, TEST_AGGREGATE_FAMILY
if CrossSync.is_async:
from google.cloud.bigtable_v2.services.bigtable.transports.grpc_asyncio import (
_LoggingClientAIOInterceptor as GapicInterceptor,
)
else:
from google.cloud.bigtable_v2.services.bigtable.transports.grpc import (
_LoggingClientInterceptor as GapicInterceptor,
)
__CROSS_SYNC_OUTPUT__ = "tests.system.data.test_system_autogen"
TARGETS = ["table"]
if not os.environ.get(BIGTABLE_EMULATOR):
# emulator doesn't support authorized views
TARGETS.append("authorized_view")
@CrossSync.convert_class(
sync_name="TempRowBuilder",
add_mapping_for_name="TempRowBuilder",
)
class TempRowBuilderAsync:
"""
Used to add rows to a table for testing purposes.
"""
def __init__(self, target):
self.rows = []
self.target = target
@CrossSync.convert
async def add_row(
self, row_key, *, family=TEST_FAMILY, qualifier=b"q", value=b"test-value"
):
if isinstance(value, str):
value = value.encode("utf-8")
elif isinstance(value, int):
value = value.to_bytes(8, byteorder="big", signed=True)
request = {
"table_name": self.target.table_name,
"row_key": row_key,
"mutations": [
{
"set_cell": {
"family_name": family,
"column_qualifier": qualifier,
"value": value,
}
}
],
}
await self.target.client._gapic_client.mutate_row(request)
self.rows.append(row_key)
@CrossSync.convert
async def add_aggregate_row(
self, row_key, *, family=TEST_AGGREGATE_FAMILY, qualifier=b"q", input=0
):
request = {
"table_name": self.target.table_name,
"row_key": row_key,
"mutations": [
{
"add_to_cell": {
"family_name": family,
"column_qualifier": {"raw_value": qualifier},
"timestamp": {"raw_timestamp_micros": 0},
"input": {"int_value": input},
}
}
],
}
await self.target.client._gapic_client.mutate_row(request)
self.rows.append(row_key)
@CrossSync.convert
async def delete_rows(self):
if self.rows:
request = {
"table_name": self.target.table_name,
"entries": [
{"row_key": row, "mutations": [{"delete_from_row": {}}]}
for row in self.rows
],
}
await self.target.client._gapic_client.mutate_rows(request)
@CrossSync.convert_class(sync_name="TestSystem")
class TestSystemAsync:
def _make_client(self):
project = os.getenv("GOOGLE_CLOUD_PROJECT") or None
return CrossSync.DataClient(project=project)
@CrossSync.convert
@CrossSync.pytest_fixture(scope="session")
async def client(self):
async with self._make_client() as client:
yield client
@CrossSync.convert
@CrossSync.pytest_fixture(scope="session", params=TARGETS)
async def target(self, client, table_id, authorized_view_id, instance_id, request):
"""
This fixture runs twice: once for a standard table, and once with an authorized view
Note: emulator doesn't support authorized views. Only use target
"""
if request.param == "table":
async with client.get_table(instance_id, table_id) as table:
yield table
elif request.param == "authorized_view":
async with client.get_authorized_view(
instance_id, table_id, authorized_view_id
) as view:
yield view
else:
raise ValueError(f"unknown target type: {request.param}")
@pytest.fixture(scope="session")
def column_family_config(self):
"""
specify column families to create when creating a new test table
"""
from google.cloud.bigtable_admin_v2 import types
int_aggregate_type = types.Type.Aggregate(
input_type=types.Type(int64_type={"encoding": {"big_endian_bytes": {}}}),
sum={},
)
return {
TEST_FAMILY: types.ColumnFamily(),
TEST_FAMILY_2: types.ColumnFamily(),
TEST_AGGREGATE_FAMILY: types.ColumnFamily(
value_type=types.Type(aggregate_type=int_aggregate_type)
),
}
@pytest.fixture(scope="session")
def init_table_id(self):
"""
The table_id to use when creating a new test table
"""
return f"test-table-{uuid.uuid4().hex}"
@pytest.fixture(scope="session")
def cluster_config(self, project_id):
"""
Configuration for the clusters to use when creating a new instance
"""
from google.cloud.bigtable_admin_v2 import types
cluster = {
"test-cluster": types.Cluster(
location=f"projects/{project_id}/locations/us-central1-b",
serve_nodes=1,
)
}
return cluster
@CrossSync.convert
@pytest.mark.usefixtures("target")
async def _retrieve_cell_value(self, target, row_key):
"""
Helper to read an individual row
"""
from google.cloud.bigtable.data import ReadRowsQuery
row_list = await target.read_rows(ReadRowsQuery(row_keys=row_key))
assert len(row_list) == 1
row = row_list[0]
cell = row.cells[0]
return cell.value
@CrossSync.convert
async def _create_row_and_mutation(
self, table, temp_rows, *, start_value=b"start", new_value=b"new_value"
):
"""
Helper to create a new row, and a sample set_cell mutation to change its value
"""
from google.cloud.bigtable.data.mutations import SetCell
row_key = uuid.uuid4().hex.encode()
family = TEST_FAMILY
qualifier = b"test-qualifier"
await temp_rows.add_row(
row_key, family=family, qualifier=qualifier, value=start_value
)
# ensure cell is initialized
assert await self._retrieve_cell_value(table, row_key) == start_value
mutation = SetCell(family=TEST_FAMILY, qualifier=qualifier, new_value=new_value)
return row_key, mutation
@CrossSync.convert
@CrossSync.pytest_fixture(scope="function")
async def temp_rows(self, target):
builder = CrossSync.TempRowBuilder(target)
yield builder
await builder.delete_rows()
@pytest.mark.usefixtures("target")
@pytest.mark.usefixtures("client")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=10
)
@CrossSync.pytest
async def test_ping_and_warm_gapic(self, client, target):
"""
Simple ping rpc test
This test ensures channels are able to authenticate with backend
"""
request = {"name": target.instance_name}
await client._gapic_client.ping_and_warm(request)
@pytest.mark.usefixtures("target")
@pytest.mark.usefixtures("client")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_ping_and_warm(self, client, target):
"""
Test ping and warm from handwritten client
"""
results = await client._ping_and_warm_instances()
assert len(results) == 1
assert results[0] is None
@pytest.mark.skipif(
bool(os.environ.get(BIGTABLE_EMULATOR)),
reason="emulator mode doesn't refresh channel",
)
@CrossSync.pytest
async def test_channel_refresh(self, table_id, instance_id, temp_rows):
"""
change grpc channel to refresh after 1 second. Schedule a read_rows call after refresh,
to ensure new channel works
"""
await temp_rows.add_row(b"row_key_1")
await temp_rows.add_row(b"row_key_2")
client = self._make_client()
# start custom refresh task
try:
client._channel_refresh_task = CrossSync.create_task(
client._manage_channel,
refresh_interval_min=1,
refresh_interval_max=1,
sync_executor=client._executor,
)
# let task run
await CrossSync.yield_to_event_loop()
async with client.get_table(instance_id, table_id) as table:
rows = await table.read_rows({})
channel_wrapper = client.transport.grpc_channel
first_channel = client.transport.grpc_channel._channel
assert len(rows) == 2
await CrossSync.sleep(2)
rows_after_refresh = await table.read_rows({})
assert len(rows_after_refresh) == 2
assert client.transport.grpc_channel is channel_wrapper
assert client.transport.grpc_channel._channel is not first_channel
# ensure gapic's logging interceptor is still active
if CrossSync.is_async:
interceptors = (
client.transport.grpc_channel._channel._unary_unary_interceptors
)
assert GapicInterceptor in [type(i) for i in interceptors]
else:
assert isinstance(
client.transport._logged_channel._interceptor, GapicInterceptor
)
finally:
await client.close()
@CrossSync.pytest
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
async def test_mutation_set_cell(self, target, temp_rows):
"""
Ensure cells can be set properly
"""
row_key = b"bulk_mutate"
new_value = uuid.uuid4().hex.encode()
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
await target.mutate_row(row_key, mutation)
# ensure cell is updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
@CrossSync.pytest
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
async def test_mutation_add_to_cell(self, target, temp_rows):
"""
Test add to cell mutation
"""
from google.cloud.bigtable.data.mutations import AddToCell
row_key = b"add_to_cell"
family = TEST_AGGREGATE_FAMILY
qualifier = b"test-qualifier"
# add row to temp_rows, for future deletion
await temp_rows.add_aggregate_row(row_key, family=family, qualifier=qualifier)
# set and check cell value
await target.mutate_row(
row_key, AddToCell(family, qualifier, 1, timestamp_micros=0)
)
encoded_result = await self._retrieve_cell_value(target, row_key)
int_result = int.from_bytes(encoded_result, byteorder="big")
assert int_result == 1
# update again
await target.mutate_row(
row_key, AddToCell(family, qualifier, 9, timestamp_micros=0)
)
encoded_result = await self._retrieve_cell_value(target, row_key)
int_result = int.from_bytes(encoded_result, byteorder="big")
assert int_result == 10
@pytest.mark.skipif(
bool(os.environ.get(BIGTABLE_EMULATOR)), reason="emulator doesn't use splits"
)
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_sample_row_keys(
self, client, target, temp_rows, column_split_config
):
"""
Sample keys should return a single sample in small test targets
"""
await temp_rows.add_row(b"row_key_1")
await temp_rows.add_row(b"row_key_2")
results = await target.sample_row_keys()
assert len(results) == len(column_split_config) + 1
# first keys should match the split config
for idx in range(len(column_split_config)):
assert results[idx][0] == column_split_config[idx]
assert isinstance(results[idx][1], int)
# last sample should be empty key
assert results[-1][0] == b""
assert isinstance(results[-1][1], int)
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.pytest
async def test_bulk_mutations_set_cell(self, client, target, temp_rows):
"""
Ensure cells can be set properly
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value = uuid.uuid4().hex.encode()
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
await target.bulk_mutate_rows([bulk_mutation])
# ensure cell is updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
@CrossSync.pytest
async def test_bulk_mutations_raise_exception(self, client, target):
"""
If an invalid mutation is passed, an exception should be raised
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry, SetCell
from google.cloud.bigtable.data.exceptions import MutationsExceptionGroup
from google.cloud.bigtable.data.exceptions import FailedMutationEntryError
row_key = uuid.uuid4().hex.encode()
mutation = SetCell(
family="nonexistent", qualifier=b"test-qualifier", new_value=b""
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
with pytest.raises(MutationsExceptionGroup) as exc:
await target.bulk_mutate_rows([bulk_mutation])
assert len(exc.value.exceptions) == 1
entry_error = exc.value.exceptions[0]
assert isinstance(entry_error, FailedMutationEntryError)
assert entry_error.index == 0
assert entry_error.entry == bulk_mutation
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_context_manager(self, client, target, temp_rows):
"""
test batcher with context manager. Should flush on exit
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value, new_value2 = [uuid.uuid4().hex.encode() for _ in range(2)]
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
row_key2, mutation2 = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value2
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
bulk_mutation2 = RowMutationEntry(row_key2, [mutation2])
async with target.mutations_batcher() as batcher:
await batcher.append(bulk_mutation)
await batcher.append(bulk_mutation2)
# ensure cell is updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
assert len(batcher._staged_entries) == 0
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_timer_flush(self, client, target, temp_rows):
"""
batch should occur after flush_interval seconds
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value = uuid.uuid4().hex.encode()
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
flush_interval = 0.1
async with target.mutations_batcher(flush_interval=flush_interval) as batcher:
await batcher.append(bulk_mutation)
await CrossSync.yield_to_event_loop()
assert len(batcher._staged_entries) == 1
await CrossSync.sleep(flush_interval + 0.1)
assert len(batcher._staged_entries) == 0
# ensure cell is updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_completed_callback(
self, client, target, temp_rows
):
"""
test batcher with batch completed callback. It should be called when the batcher flushes.
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
from google.rpc import code_pb2, status_pb2
import mock
callback = mock.Mock()
new_value = uuid.uuid4().hex.encode()
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
flush_interval = 0.1
async with target.mutations_batcher(flush_interval=flush_interval) as batcher:
batcher._user_batch_completed_callback = callback
await batcher.append(bulk_mutation)
await CrossSync.yield_to_event_loop()
assert len(batcher._staged_entries) == 1
await CrossSync.sleep(flush_interval + 0.1)
assert len(batcher._staged_entries) == 0
callback.assert_called_once_with([status_pb2.Status(code=code_pb2.OK)])
# ensure cell is updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_count_flush(self, client, target, temp_rows):
"""
batch should flush after flush_limit_mutation_count mutations
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value, new_value2 = [uuid.uuid4().hex.encode() for _ in range(2)]
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
row_key2, mutation2 = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value2
)
bulk_mutation2 = RowMutationEntry(row_key2, [mutation2])
async with target.mutations_batcher(flush_limit_mutation_count=2) as batcher:
await batcher.append(bulk_mutation)
assert len(batcher._flush_jobs) == 0
# should be noop; flush not scheduled
assert len(batcher._staged_entries) == 1
await batcher.append(bulk_mutation2)
# task should now be scheduled
assert len(batcher._flush_jobs) == 1
# let flush complete
for future in list(batcher._flush_jobs):
await future
# for sync version: grab result
future.result()
assert len(batcher._staged_entries) == 0
assert len(batcher._flush_jobs) == 0
# ensure cells were updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
assert (await self._retrieve_cell_value(target, row_key2)) == new_value2
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_bytes_flush(self, client, target, temp_rows):
"""
batch should flush after flush_limit_bytes bytes
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value, new_value2 = [uuid.uuid4().hex.encode() for _ in range(2)]
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
row_key2, mutation2 = await self._create_row_and_mutation(
target, temp_rows, new_value=new_value2
)
bulk_mutation2 = RowMutationEntry(row_key2, [mutation2])
flush_limit = bulk_mutation.size() + bulk_mutation2.size() - 1
async with target.mutations_batcher(flush_limit_bytes=flush_limit) as batcher:
await batcher.append(bulk_mutation)
assert len(batcher._flush_jobs) == 0
assert len(batcher._staged_entries) == 1
await batcher.append(bulk_mutation2)
# task should now be scheduled
assert len(batcher._flush_jobs) == 1
assert len(batcher._staged_entries) == 0
# let flush complete
for future in list(batcher._flush_jobs):
await future
# for sync version: grab result
future.result()
# ensure cells were updated
assert (await self._retrieve_cell_value(target, row_key)) == new_value
assert (await self._retrieve_cell_value(target, row_key2)) == new_value2
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.pytest
async def test_mutations_batcher_no_flush(self, client, target, temp_rows):
"""
test with no flush requirements met
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry
new_value = uuid.uuid4().hex.encode()
start_value = b"unchanged"
row_key, mutation = await self._create_row_and_mutation(
target, temp_rows, start_value=start_value, new_value=new_value
)
bulk_mutation = RowMutationEntry(row_key, [mutation])
row_key2, mutation2 = await self._create_row_and_mutation(
target, temp_rows, start_value=start_value, new_value=new_value
)
bulk_mutation2 = RowMutationEntry(row_key2, [mutation2])
size_limit = bulk_mutation.size() + bulk_mutation2.size() + 1
async with target.mutations_batcher(
flush_limit_bytes=size_limit, flush_limit_mutation_count=3, flush_interval=1
) as batcher:
await batcher.append(bulk_mutation)
assert len(batcher._staged_entries) == 1
await batcher.append(bulk_mutation2)
# flush not scheduled
assert len(batcher._flush_jobs) == 0
await CrossSync.yield_to_event_loop()
assert len(batcher._staged_entries) == 2
assert len(batcher._flush_jobs) == 0
# ensure cells were not updated
assert (await self._retrieve_cell_value(target, row_key)) == start_value
assert (await self._retrieve_cell_value(target, row_key2)) == start_value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_mutations_batcher_large_batch(self, client, target, temp_rows):
"""
test batcher with large batch of mutations
"""
from google.cloud.bigtable.data.mutations import RowMutationEntry, SetCell
add_mutation = SetCell(
family=TEST_FAMILY, qualifier=b"test-qualifier", new_value=b"a"
)
row_mutations = []
for i in range(50_000):
row_key = uuid.uuid4().hex.encode()
row_mutations.append(RowMutationEntry(row_key, [add_mutation]))
# append row key for eventual deletion
temp_rows.rows.append(row_key)
async with target.mutations_batcher() as batcher:
for mutation in row_mutations:
await batcher.append(mutation)
# ensure cell is updated
assert len(batcher._staged_entries) == 0
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@pytest.mark.parametrize(
"start,increment,expected",
[
(0, 0, 0),
(0, 1, 1),
(0, -1, -1),
(1, 0, 1),
(0, -100, -100),
(0, 3000, 3000),
(10, 4, 14),
(_MAX_INCREMENT_VALUE, -_MAX_INCREMENT_VALUE, 0),
(_MAX_INCREMENT_VALUE, 2, -_MAX_INCREMENT_VALUE),
(-_MAX_INCREMENT_VALUE, -2, _MAX_INCREMENT_VALUE),
],
)
@CrossSync.pytest
async def test_read_modify_write_row_increment(
self, client, target, temp_rows, start, increment, expected
):
"""
test read_modify_write_row
"""
from google.cloud.bigtable.data.read_modify_write_rules import IncrementRule
row_key = b"test-row-key"
family = TEST_FAMILY
qualifier = b"test-qualifier"
await temp_rows.add_row(
row_key, value=start, family=family, qualifier=qualifier
)
rule = IncrementRule(family, qualifier, increment)
result = await target.read_modify_write_row(row_key, rule)
assert result.row_key == row_key
assert len(result) == 1
assert result[0].family == family
assert result[0].qualifier == qualifier
assert int(result[0]) == expected
# ensure that reading from server gives same value
assert (await self._retrieve_cell_value(target, row_key)) == result[0].value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@pytest.mark.parametrize(
"start,append,expected",
[
(b"", b"", b""),
("", "", b""),
(b"abc", b"123", b"abc123"),
(b"abc", "123", b"abc123"),
("", b"1", b"1"),
(b"abc", "", b"abc"),
(b"hello", b"world", b"helloworld"),
],
)
@CrossSync.pytest
async def test_read_modify_write_row_append(
self, client, target, temp_rows, start, append, expected
):
"""
test read_modify_write_row
"""
from google.cloud.bigtable.data.read_modify_write_rules import AppendValueRule
row_key = b"test-row-key"
family = TEST_FAMILY
qualifier = b"test-qualifier"
await temp_rows.add_row(
row_key, value=start, family=family, qualifier=qualifier
)
rule = AppendValueRule(family, qualifier, append)
result = await target.read_modify_write_row(row_key, rule)
assert result.row_key == row_key
assert len(result) == 1
assert result[0].family == family
assert result[0].qualifier == qualifier
assert result[0].value == expected
# ensure that reading from server gives same value
assert (await self._retrieve_cell_value(target, row_key)) == result[0].value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.pytest
async def test_read_modify_write_row_chained(self, client, target, temp_rows):
"""
test read_modify_write_row with multiple rules
"""
from google.cloud.bigtable.data.read_modify_write_rules import AppendValueRule
from google.cloud.bigtable.data.read_modify_write_rules import IncrementRule
row_key = b"test-row-key"
family = TEST_FAMILY
qualifier = b"test-qualifier"
start_amount = 1
increment_amount = 10
await temp_rows.add_row(
row_key, value=start_amount, family=family, qualifier=qualifier
)
rule = [
IncrementRule(family, qualifier, increment_amount),
AppendValueRule(family, qualifier, "hello"),
AppendValueRule(family, qualifier, "world"),
AppendValueRule(family, qualifier, "!"),
]
result = await target.read_modify_write_row(row_key, rule)
assert result.row_key == row_key
assert result[0].family == family
assert result[0].qualifier == qualifier
# result should be a bytes number string for the IncrementRules, followed by the AppendValueRule values
assert (
result[0].value
== (start_amount + increment_amount).to_bytes(8, "big", signed=True)
+ b"helloworld!"
)
# ensure that reading from server gives same value
assert (await self._retrieve_cell_value(target, row_key)) == result[0].value
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@pytest.mark.parametrize(
"start_val,predicate_range,expected_result",
[
(1, (0, 2), True),
(-1, (0, 2), False),
],
)
@CrossSync.pytest
async def test_check_and_mutate(
self, client, target, temp_rows, start_val, predicate_range, expected_result
):
"""
test that check_and_mutate_row works applies the right mutations, and returns the right result
"""
from google.cloud.bigtable.data.mutations import SetCell
from google.cloud.bigtable.data.row_filters import ValueRangeFilter
row_key = b"test-row-key"
family = TEST_FAMILY
qualifier = b"test-qualifier"
await temp_rows.add_row(
row_key, value=start_val, family=family, qualifier=qualifier
)
false_mutation_value = b"false-mutation-value"
false_mutation = SetCell(
family=TEST_FAMILY, qualifier=qualifier, new_value=false_mutation_value
)
true_mutation_value = b"true-mutation-value"
true_mutation = SetCell(
family=TEST_FAMILY, qualifier=qualifier, new_value=true_mutation_value
)
predicate = ValueRangeFilter(predicate_range[0], predicate_range[1])
result = await target.check_and_mutate_row(
row_key,
predicate,
true_case_mutations=true_mutation,
false_case_mutations=false_mutation,
)
assert result == expected_result
# ensure cell is updated
expected_value = (
true_mutation_value if expected_result else false_mutation_value
)
assert (await self._retrieve_cell_value(target, row_key)) == expected_value
@pytest.mark.skipif(
bool(os.environ.get(BIGTABLE_EMULATOR)),
reason="emulator doesn't raise InvalidArgument",
)
@pytest.mark.usefixtures("client")
@pytest.mark.usefixtures("target")
@CrossSync.pytest
async def test_check_and_mutate_empty_request(self, client, target):
"""
check_and_mutate with no true or fale mutations should raise an error
"""
from google.api_core import exceptions
with pytest.raises(exceptions.InvalidArgument) as e:
await target.check_and_mutate_row(
b"row_key", None, true_case_mutations=None, false_case_mutations=None
)
assert "No mutations provided" in str(e.value)
@pytest.mark.usefixtures("target")
@CrossSync.convert(replace_symbols={"__anext__": "__next__"})
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows_stream(self, target, temp_rows):
"""
Ensure that the read_rows_stream method works
"""
await temp_rows.add_row(b"row_key_1")
await temp_rows.add_row(b"row_key_2")
# full table scan
generator = await target.read_rows_stream({})
first_row = await generator.__anext__()
second_row = await generator.__anext__()
assert first_row.row_key == b"row_key_1"
assert second_row.row_key == b"row_key_2"
with pytest.raises(CrossSync.StopIteration):
await generator.__anext__()
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows(self, target, temp_rows):
"""
Ensure that the read_rows method works
"""
await temp_rows.add_row(b"row_key_1")
await temp_rows.add_row(b"row_key_2")
# full table scan
row_list = await target.read_rows({})
assert len(row_list) == 2
assert row_list[0].row_key == b"row_key_1"
assert row_list[1].row_key == b"row_key_2"
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows_sharded_simple(self, target, temp_rows):
"""
Test read rows sharded with two queries
"""
from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery
await temp_rows.add_row(b"a")
await temp_rows.add_row(b"b")
await temp_rows.add_row(b"c")
await temp_rows.add_row(b"d")
query1 = ReadRowsQuery(row_keys=[b"a", b"c"])
query2 = ReadRowsQuery(row_keys=[b"b", b"d"])
row_list = await target.read_rows_sharded([query1, query2])
assert len(row_list) == 4
assert row_list[0].row_key == b"a"
assert row_list[1].row_key == b"c"
assert row_list[2].row_key == b"b"
assert row_list[3].row_key == b"d"
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows_sharded_from_sample(self, target, temp_rows):
"""
Test end-to-end sharding
"""
from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery
from google.cloud.bigtable.data.read_rows_query import RowRange
await temp_rows.add_row(b"a")
await temp_rows.add_row(b"b")
await temp_rows.add_row(b"c")
await temp_rows.add_row(b"d")
table_shard_keys = await target.sample_row_keys()
query = ReadRowsQuery(row_ranges=[RowRange(start_key=b"b", end_key=b"z")])
shard_queries = query.shard(table_shard_keys)
row_list = await target.read_rows_sharded(shard_queries)
assert len(row_list) == 3
assert row_list[0].row_key == b"b"
assert row_list[1].row_key == b"c"
assert row_list[2].row_key == b"d"
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows_sharded_filters_limits(self, target, temp_rows):
"""
Test read rows sharded with filters and limits
"""
from google.cloud.bigtable.data.read_rows_query import ReadRowsQuery
from google.cloud.bigtable.data.row_filters import ApplyLabelFilter
await temp_rows.add_row(b"a")
await temp_rows.add_row(b"b")
await temp_rows.add_row(b"c")
await temp_rows.add_row(b"d")
label_filter1 = ApplyLabelFilter("first")
label_filter2 = ApplyLabelFilter("second")
query1 = ReadRowsQuery(row_keys=[b"a", b"c"], limit=1, row_filter=label_filter1)
query2 = ReadRowsQuery(row_keys=[b"b", b"d"], row_filter=label_filter2)
row_list = await target.read_rows_sharded([query1, query2])
assert len(row_list) == 3
assert row_list[0].row_key == b"a"
assert row_list[1].row_key == b"b"
assert row_list[2].row_key == b"d"
assert row_list[0][0].labels == ["first"]
assert row_list[1][0].labels == ["second"]
assert row_list[2][0].labels == ["second"]
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)
@CrossSync.pytest
async def test_read_rows_range_query(self, target, temp_rows):
"""
Ensure that the read_rows method works
"""
from google.cloud.bigtable.data import ReadRowsQuery
from google.cloud.bigtable.data import RowRange
await temp_rows.add_row(b"a")
await temp_rows.add_row(b"b")
await temp_rows.add_row(b"c")
await temp_rows.add_row(b"d")
# full table scan
query = ReadRowsQuery(row_ranges=RowRange(start_key=b"b", end_key=b"d"))
row_list = await target.read_rows(query)
assert len(row_list) == 2
assert row_list[0].row_key == b"b"
assert row_list[1].row_key == b"c"
@pytest.mark.usefixtures("target")
@CrossSync.Retry(
predicate=retry.if_exception_type(ClientError), initial=1, maximum=5
)