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_data_api.py
More file actions
1241 lines (975 loc) · 41.1 KB
/
Copy pathtest_data_api.py
File metadata and controls
1241 lines (975 loc) · 41.1 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 2011 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 operator
import pytest
from google.cloud.bigtable import row_filters
from grpc import UnaryStreamClientInterceptor
from grpc import RpcError
from grpc import StatusCode
from grpc import intercept_channel
COLUMN_FAMILY_ID1 = "col-fam-id1"
COLUMN_FAMILY_ID2 = "col-fam-id2"
COL_NAME1 = b"col-name1"
COL_NAME2 = b"col-name2"
COL_NAME3 = b"col-name3-but-other-fam"
CELL_VAL1 = b"cell-val"
CELL_VAL2 = b"cell-val-newer"
CELL_VAL3 = b"altcol-cell-val"
CELL_VAL4 = b"foo"
CELL_VAL_READ_ROWS_RETRY = b"1" * 512
ROW_KEY = b"row-key"
ROW_KEY_ALT = b"row-key-alt"
CELL_VAL_TRUE = b"true"
CELL_VAL_FALSE = b"false"
INT_COL_NAME = 67890
INT_CELL_VAL = 12345
OVERFLOW_INT_CELL_VAL = 10**100
OVERFLOW_INT_CELL_VAL2 = -(10**100)
FLOAT_CELL_VAL = 1.4
FLOAT_CELL_VAL2 = -1.4
INITIAL_ROW_SPLITS = [b"row_split_1", b"row_split_2", b"row_split_3"]
JOY_EMOJI = "\N{FACE WITH TEARS OF JOY}"
GAP_MARGIN_OF_ERROR = 0.05
PASS_ALL_FILTER = row_filters.PassAllFilter(True)
BLOCK_ALL_FILTER = row_filters.BlockAllFilter(True)
READ_ROWS_METHOD_NAME = "/google.bigtable.v2.Bigtable/ReadRows"
class ReadRowsErrorInjector(UnaryStreamClientInterceptor):
"""An error injector that can be configured to raise errors for the ReadRows method.
The error injector is configured to inject errors off the self.errors_to_inject queue.
Exceptions can be configured to arise either during stream initialization or in the middle
of a stream. If no errors are in the error injection queue, the ReadRows RPC call will behave
normally.
"""
def __init__(self):
self.errors_to_inject = []
def clear(self):
self.errors_to_inject.clear()
@staticmethod
def make_exception(
status_code, message=None, fail_mid_stream=False, successes_before_fail=0
):
# successes_before_fail allows us to test injecting failures mid-iterator iteration.
exc = RpcError(status_code)
exc.code = lambda: status_code
_, status_message = status_code.value
exc.details = lambda: message if message else status_message
exc.initial_metadata = lambda: []
exc.trailing_metadata = lambda: []
exc.fail_mid_stream = fail_mid_stream
exc.successes_before_fail = successes_before_fail
def _result():
raise exc
exc.result = _result
return exc
def intercept_unary_stream(self, continuation, client_call_details, request):
if (
client_call_details.method == READ_ROWS_METHOD_NAME
and self.errors_to_inject
):
error = self.errors_to_inject.pop(0)
if not error.fail_mid_stream:
raise error
response = continuation(client_call_details, request)
if error.fail_mid_stream:
class CallWrapper:
def __init__(self, call, exc_to_raise):
self._call = call
self._exc = exc_to_raise
self._successes_remaining = exc_to_raise.successes_before_fail
self._raised = False
def __iter__(self):
return self
def __next__(self):
if not self._raised and self._successes_remaining == 0:
self._raised = True
if self._exc:
raise self._exc
else:
if self._successes_remaining > 0:
self._successes_remaining -= 1
return self._call.__next__()
def __getattr__(self, name):
return getattr(self._call, name)
return CallWrapper(response, error)
else:
return continuation(client_call_details, request)
@pytest.fixture(scope="module")
def data_table_id():
return "test-data-api"
@pytest.fixture(scope="module")
def data_table(data_instance_populated, data_table_id):
table = data_instance_populated.table(data_table_id)
table.create(initial_split_keys=INITIAL_ROW_SPLITS)
table.column_family(COLUMN_FAMILY_ID1).create()
table.column_family(COLUMN_FAMILY_ID2).create()
yield table
table.delete()
@pytest.fixture(scope="function")
def rows_to_delete():
rows_to_delete = []
yield rows_to_delete
for row in rows_to_delete:
row.clear()
row.delete()
row.commit()
@pytest.fixture(scope="module")
def data_table_read_rows_retry_tests_setup(data_table):
row_keys = [f"row_key_{i}".encode() for i in range(0, 32)]
columns = [f"col_{i}".encode() for i in range(0, 32)]
# Set up the error injector here
data_client = data_table._instance._client.table_data_client
error_injector = ReadRowsErrorInjector()
old_logged_channel = data_client.transport._logged_channel
data_client.transport._logged_channel = intercept_channel(
old_logged_channel, error_injector
)
data_table.error_injector = error_injector
data_client.transport._stubs = {}
data_client.transport._prep_wrapped_messages(None)
# Need to add this here as a class level teardown since rows_to_delete
# is a function level fixture.
rows_to_delete = []
try:
_populate_table(
data_table, rows_to_delete, row_keys, columns, CELL_VAL_READ_ROWS_RETRY
)
yield data_table
finally:
del data_table.error_injector
data_client.transport._logged_channel = old_logged_channel
data_client.transport._stubs = {}
data_client.transport._prep_wrapped_messages(None)
for row in rows_to_delete:
row.clear()
row.delete()
row.commit()
@pytest.fixture(scope="function")
def data_table_read_rows_retry_tests(data_table_read_rows_retry_tests_setup):
yield data_table_read_rows_retry_tests_setup
data_table_read_rows_retry_tests_setup.error_injector.clear()
def test_table_read_rows_filter_millis(data_table):
from google.cloud.bigtable import row_filters
end = datetime.datetime.now()
start = end - datetime.timedelta(minutes=60)
timestamp_range = row_filters.TimestampRange(start=start, end=end)
timefilter = row_filters.TimestampRangeFilter(timestamp_range)
row_data = data_table.read_rows(filter_=timefilter)
row_data.consume_all()
def test_table_direct_row_commit(data_table, rows_to_delete):
from google.rpc import code_pb2
row = data_table.direct_row(ROW_KEY)
# Test set cell
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME2, CELL_VAL1)
status = row.commit()
rows_to_delete.append(row)
assert status.code == code_pb2.Code.OK
row_data = data_table.read_row(ROW_KEY)
assert row_data.cells[COLUMN_FAMILY_ID1][COL_NAME1][0].value == CELL_VAL1
assert row_data.cells[COLUMN_FAMILY_ID1][COL_NAME2][0].value == CELL_VAL1
# Test delete cell
row.delete_cell(COLUMN_FAMILY_ID1, COL_NAME1)
status = row.commit()
assert status.code == code_pb2.Code.OK
row_data = data_table.read_row(ROW_KEY)
assert COL_NAME1 not in row_data.cells[COLUMN_FAMILY_ID1]
assert row_data.cells[COLUMN_FAMILY_ID1][COL_NAME2][0].value == CELL_VAL1
# Test delete row
row.delete()
status = row.commit()
assert status.code == code_pb2.Code.OK
row_data = data_table.read_row(ROW_KEY)
assert row_data is None
def test_table_mutate_rows(data_table, rows_to_delete):
row1 = data_table.direct_row(ROW_KEY)
row1.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
row1.commit()
rows_to_delete.append(row1)
row2 = data_table.direct_row(ROW_KEY_ALT)
row2.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL2)
row2.commit()
rows_to_delete.append(row2)
# Change the contents
row1.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL3)
row2.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL4)
rows = [row1, row2]
statuses = data_table.mutate_rows(rows)
assert len(statuses) == len(rows)
for status in statuses:
assert status.code == 0
# Check the contents
row1_data = data_table.read_row(ROW_KEY)
assert row1_data.cells[COLUMN_FAMILY_ID1][COL_NAME1][0].value == CELL_VAL3
row2_data = data_table.read_row(ROW_KEY_ALT)
assert row2_data.cells[COLUMN_FAMILY_ID1][COL_NAME1][0].value == CELL_VAL4
def _add_test_error_handler(retry):
"""Overwrites the current on_error function to assert that backoff values are within expected bounds."""
import time
curr_time = time.monotonic()
times_triggered = 0
# Assert that the retry handler works properly.
def test_error_handler(exc):
nonlocal curr_time, times_triggered, retry
next_time = time.monotonic()
if times_triggered >= 1:
gap = next_time - curr_time
# Exponential backoff = uniform randomness from 0 to max_gap
max_gap = min(
retry._initial * retry._multiplier**times_triggered,
retry._maximum,
)
assert gap <= max_gap + GAP_MARGIN_OF_ERROR
times_triggered += 1
curr_time = next_time
retry._on_error = test_error_handler
def test_table_mutate_rows_retries_timeout(data_table, rows_to_delete):
import mock
import copy
from google.api_core import retry as retries
from google.api_core.exceptions import InvalidArgument
from google.cloud.bigtable_v2 import MutateRowsResponse
from google.cloud.bigtable.table import DEFAULT_RETRY, _BigtableRetryableError
from google.rpc.code_pb2 import Code
from google.rpc.status_pb2 import Status
# Simulate a server error on row 2, and a normal response on row 1, followed by a bunch of error
# responses on row 2
initial_error_response = [
MutateRowsResponse(
entries=[
MutateRowsResponse.Entry(),
MutateRowsResponse.Entry(
index=1,
status=Status(
code=Code.INTERNAL,
message="Test error",
),
),
]
)
]
followup_error_response = [
MutateRowsResponse(
entries=[
MutateRowsResponse.Entry(
status=Status(
code=Code.INTERNAL,
message="Test error",
)
)
]
)
]
final_success_response = [MutateRowsResponse(entries=[MutateRowsResponse.Entry()])]
with mock.patch.object(
data_table._instance._client.table_data_client, "mutate_rows"
) as mutate_mock:
mutate_mock.side_effect = [
initial_error_response,
followup_error_response,
followup_error_response,
final_success_response,
]
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
row_2 = data_table.direct_row(ROW_KEY_ALT)
rows_to_delete.append(row_2)
row_2.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
# Testing the default retry
default_retry_copy = copy.copy(DEFAULT_RETRY)
_add_test_error_handler(default_retry_copy)
statuses = data_table.mutate_rows([row, row_2], retry=default_retry_copy)
assert statuses[0].code == Code.OK
assert statuses[1].code == Code.OK
# Simulate only server failures for row 2.
with mock.patch.object(
data_table._instance._client.table_data_client, "mutate_rows"
) as mutate_mock:
mutate_mock.side_effect = [initial_error_response] + [
followup_error_response
] * 1000000
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
row_2 = data_table.direct_row(ROW_KEY_ALT)
rows_to_delete.append(row_2)
row_2.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
# Testing the default retry
default_retry_copy = copy.copy(DEFAULT_RETRY)
_add_test_error_handler(default_retry_copy)
statuses = data_table.mutate_rows([row, row_2], retry=default_retry_copy)
assert statuses[0].code == Code.OK
assert statuses[1].code == Code.INTERNAL
# Because of the way the retriable mutate worker class works, unusual things can happen
# when passing in custom retry predicates.
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
row_2 = data_table.direct_row(ROW_KEY_ALT)
rows_to_delete.append(row_2)
retry = DEFAULT_RETRY.with_predicate(
retries.if_exception_type(_BigtableRetryableError, InvalidArgument)
)
_add_test_error_handler(retry)
statuses = data_table.mutate_rows([row, row_2], retry=retry)
assert statuses[0] is None
assert statuses[1] is None
def _populate_table(
data_table, rows_to_delete, row_keys, columns=[COL_NAME1], cell_value=CELL_VAL1
):
for row_key in row_keys:
row = data_table.direct_row(row_key)
for column in columns:
row.set_cell(COLUMN_FAMILY_ID1, column, cell_value)
row.commit()
rows_to_delete.append(row)
def test_table_truncate(data_table, rows_to_delete):
row_keys = [
b"row_key_1",
b"row_key_2",
b"row_key_3",
b"row_key_4",
b"row_key_5",
b"row_key_pr_1",
b"row_key_pr_2",
b"row_key_pr_3",
b"row_key_pr_4",
b"row_key_pr_5",
]
_populate_table(data_table, rows_to_delete, row_keys)
data_table.truncate(timeout=200)
assert list(data_table.read_rows()) == []
def test_table_drop_by_prefix(data_table, rows_to_delete):
row_keys = [
b"row_key_1",
b"row_key_2",
b"row_key_3",
b"row_key_4",
b"row_key_5",
b"row_key_pr_1",
b"row_key_pr_2",
b"row_key_pr_3",
b"row_key_pr_4",
b"row_key_pr_5",
]
_populate_table(data_table, rows_to_delete, row_keys)
data_table.drop_by_prefix(row_key_prefix="row_key_pr", timeout=200)
remaining_row_keys = [
row_key for row_key in row_keys if not row_key.startswith(b"row_key_pr")
]
expected_rows_count = len(remaining_row_keys)
found_rows_count = 0
for row in data_table.read_rows():
if row.row_key in row_keys:
found_rows_count += 1
assert expected_rows_count == found_rows_count
def test_table_mutate_rows_integers(data_table, rows_to_delete):
row = data_table.direct_row(ROW_KEY)
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
row.commit()
rows_to_delete.append(row)
# Change the contents to an integer
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, INT_CELL_VAL)
statuses = data_table.mutate_rows([row])
assert len(statuses) == 1
for status in statuses:
assert status.code == 0
# Check the contents
row1_data = data_table.read_row(ROW_KEY)
assert (
int.from_bytes(
row1_data.cells[COLUMN_FAMILY_ID1][COL_NAME1][0].value, byteorder="big"
)
== INT_CELL_VAL
)
def test_table_mutate_rows_input_errors(data_table, rows_to_delete):
from google.api_core.exceptions import InvalidArgument
from google.cloud.bigtable.table import TooManyMutationsError, _MAX_BULK_MUTATIONS
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
# Mutate row with 0 mutations gives an API error from the service, not
# from the client library.
with pytest.raises(InvalidArgument):
data_table.mutate_rows([row])
row.clear()
# Mutate row with >100k mutations gives a TooManyMutationsError from the
# client library.
for _ in range(0, _MAX_BULK_MUTATIONS + 1):
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1)
with pytest.raises(TooManyMutationsError):
data_table.mutate_rows([row])
def test_table_read_rows_w_row_set(data_table, rows_to_delete):
from google.cloud.bigtable.row_set import RowSet
from google.cloud.bigtable.row_set import RowRange
row_keys = [
b"row_key_1",
b"row_key_2",
b"row_key_3",
b"row_key_4",
b"row_key_5",
b"row_key_6",
b"row_key_7",
b"row_key_8",
b"row_key_9",
]
_populate_table(data_table, rows_to_delete, row_keys)
row_range = RowRange(start_key=b"row_key_3", end_key=b"row_key_7")
row_set = RowSet()
row_set.add_row_range(row_range)
row_set.add_row_key(b"row_key_1")
found_rows = data_table.read_rows(row_set=row_set)
found_row_keys = [row.row_key for row in found_rows]
expected_row_keys = [
row_key for row_key in row_keys[:6] if not row_key.endswith(b"_2")
]
assert found_row_keys == expected_row_keys
def test_rowset_add_row_range_w_pfx(data_table, rows_to_delete):
from google.cloud.bigtable.row_set import RowSet
row_keys = [
b"row_key_1",
b"row_key_2",
b"row_key_3",
b"row_key_4",
b"sample_row_key_1",
b"sample_row_key_2",
]
_populate_table(data_table, rows_to_delete, row_keys)
row_set = RowSet()
row_set.add_row_range_with_prefix("row")
expected_row_keys = [row_key for row_key in row_keys if row_key.startswith(b"row")]
found_rows = data_table.read_rows(row_set=row_set)
found_row_keys = [row.row_key for row in found_rows]
assert found_row_keys == expected_row_keys
def test_table_read_row_large_cell(data_table, rows_to_delete, skip_on_emulator):
# Maximum gRPC received message size for emulator is 4194304 bytes.
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
number_of_bytes = 10 * 1024 * 1024
data = b"1" * number_of_bytes # 10MB of 1's.
row.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, data)
row.commit()
# Read back the contents of the row.
row_data = data_table.read_row(ROW_KEY)
assert row_data.row_key == ROW_KEY
cell = row_data.cells[COLUMN_FAMILY_ID1]
column = cell[COL_NAME1]
assert len(column) == 1
assert column[0].value == data
def _write_to_row(row1, row2, row3, row4):
from google.cloud._helpers import _datetime_from_microseconds
from google.cloud._helpers import _microseconds_from_datetime
from google.cloud._helpers import UTC
from google.cloud.bigtable.row_data import Cell
timestamp1 = datetime.datetime.utcnow().replace(tzinfo=UTC)
timestamp1_micros = _microseconds_from_datetime(timestamp1)
# Truncate to millisecond granularity.
timestamp1_micros -= timestamp1_micros % 1000
timestamp1 = _datetime_from_microseconds(timestamp1_micros)
# 1000 microseconds is a millisecond
timestamp2 = timestamp1 + datetime.timedelta(microseconds=1000)
timestamp2_micros = _microseconds_from_datetime(timestamp2)
timestamp3 = timestamp1 + datetime.timedelta(microseconds=2000)
timestamp3_micros = _microseconds_from_datetime(timestamp3)
timestamp4 = timestamp1 + datetime.timedelta(microseconds=3000)
timestamp4_micros = _microseconds_from_datetime(timestamp4)
if row1 is not None:
row1.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL1, timestamp=timestamp1)
if row2 is not None:
row2.set_cell(COLUMN_FAMILY_ID1, COL_NAME1, CELL_VAL2, timestamp=timestamp2)
if row3 is not None:
row3.set_cell(COLUMN_FAMILY_ID1, COL_NAME2, CELL_VAL3, timestamp=timestamp3)
if row4 is not None:
row4.set_cell(COLUMN_FAMILY_ID2, COL_NAME3, CELL_VAL4, timestamp=timestamp4)
# Create the cells we will check.
cell1 = Cell(CELL_VAL1, timestamp1_micros)
cell2 = Cell(CELL_VAL2, timestamp2_micros)
cell3 = Cell(CELL_VAL3, timestamp3_micros)
cell4 = Cell(CELL_VAL4, timestamp4_micros)
return cell1, cell2, cell3, cell4
def test_table_read_row(data_table, rows_to_delete):
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
cell1, cell2, cell3, cell4 = _write_to_row(row, row, row, row)
row.commit()
partial_row_data = data_table.read_row(ROW_KEY)
assert partial_row_data.row_key == ROW_KEY
# Check the cells match.
ts_attr = operator.attrgetter("timestamp")
expected_row_contents = {
COLUMN_FAMILY_ID1: {
COL_NAME1: sorted([cell1, cell2], key=ts_attr, reverse=True),
COL_NAME2: [cell3],
},
COLUMN_FAMILY_ID2: {COL_NAME3: [cell4]},
}
assert partial_row_data.cells == expected_row_contents
def test_table_read_rows(data_table, rows_to_delete):
from google.cloud.bigtable.row_data import PartialRowData
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
row_alt = data_table.direct_row(ROW_KEY_ALT)
rows_to_delete.append(row_alt)
cell1, cell2, cell3, cell4 = _write_to_row(row, row_alt, row, row_alt)
row.commit()
row_alt.commit()
rows_data = data_table.read_rows()
assert rows_data.rows == {}
rows_data.consume_all()
# NOTE: We should refrain from editing protected data on instances.
# Instead we should make the values public or provide factories
# for constructing objects with them.
row_data = PartialRowData(ROW_KEY)
row_data._chunks_encountered = True
row_data._committed = True
row_data._cells = {COLUMN_FAMILY_ID1: {COL_NAME1: [cell1], COL_NAME2: [cell3]}}
row_alt_data = PartialRowData(ROW_KEY_ALT)
row_alt_data._chunks_encountered = True
row_alt_data._committed = True
row_alt_data._cells = {
COLUMN_FAMILY_ID1: {COL_NAME1: [cell2]},
COLUMN_FAMILY_ID2: {COL_NAME3: [cell4]},
}
expected_rows = {ROW_KEY: row_data, ROW_KEY_ALT: row_alt_data}
assert rows_data.rows == expected_rows
def test_read_with_label_applied(data_table, rows_to_delete, skip_on_emulator):
from google.cloud.bigtable.row_filters import ApplyLabelFilter
from google.cloud.bigtable.row_filters import ColumnQualifierRegexFilter
from google.cloud.bigtable.row_filters import RowFilterChain
from google.cloud.bigtable.row_filters import RowFilterUnion
row = data_table.direct_row(ROW_KEY)
rows_to_delete.append(row)
cell1, _, cell3, _ = _write_to_row(row, None, row, None)
row.commit()
# Combine a label with column 1.
label1 = "label-red"
label1_filter = ApplyLabelFilter(label1)
col1_filter = ColumnQualifierRegexFilter(COL_NAME1)
chain1 = RowFilterChain(filters=[col1_filter, label1_filter])
# Combine a label with column 2.
label2 = "label-blue"
label2_filter = ApplyLabelFilter(label2)
col2_filter = ColumnQualifierRegexFilter(COL_NAME2)
chain2 = RowFilterChain(filters=[col2_filter, label2_filter])
# Bring our two labeled columns together.
row_filter = RowFilterUnion(filters=[chain1, chain2])
partial_row_data = data_table.read_row(ROW_KEY, filter_=row_filter)
assert partial_row_data.row_key == ROW_KEY
cells_returned = partial_row_data.cells
col_fam1 = cells_returned.pop(COLUMN_FAMILY_ID1)
# Make sure COLUMN_FAMILY_ID1 was the only key.
assert len(cells_returned) == 0
(cell1_new,) = col_fam1.pop(COL_NAME1)
(cell3_new,) = col_fam1.pop(COL_NAME2)
# Make sure COL_NAME1 and COL_NAME2 were the only keys.
assert len(col_fam1) == 0
# Check that cell1 has matching values and gained a label.
assert cell1_new.value == cell1.value
assert cell1_new.timestamp == cell1.timestamp
assert cell1.labels == []
assert cell1_new.labels == [label1]
# Check that cell3 has matching values and gained a label.
assert cell3_new.value == cell3.value
assert cell3_new.timestamp == cell3.timestamp
assert cell3.labels == []
assert cell3_new.labels == [label2]
def _assert_data_table_read_rows_retry_correct(rows_data):
for row_num in range(0, 32):
row = rows_data.rows[f"row_key_{row_num}".encode()]
for col_num in range(0, 32):
assert (
row.cells[COLUMN_FAMILY_ID1][f"col_{col_num}".encode()][0].value
== CELL_VAL_READ_ROWS_RETRY
)
def test_table_read_rows_retry_unretriable_error_establishing_stream(
data_table_read_rows_retry_tests,
):
from google.api_core import exceptions
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(StatusCode.ABORTED, fail_mid_stream=False)
]
with pytest.raises(exceptions.Aborted):
data_table_read_rows_retry_tests.read_rows()
def test_table_read_rows_retry_retriable_error_establishing_stream(
data_table_read_rows_retry_tests,
):
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.DEADLINE_EXCEEDED, fail_mid_stream=False
)
] * 3
rows_data = data_table_read_rows_retry_tests.read_rows()
rows_data.consume_all()
_assert_data_table_read_rows_retry_correct(rows_data)
def test_table_read_rows_retry_unretriable_error_mid_stream(
data_table_read_rows_retry_tests,
):
from google.api_core import exceptions
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.DATA_LOSS, fail_mid_stream=True, successes_before_fail=5
)
]
rows_data = data_table_read_rows_retry_tests.read_rows()
with pytest.raises(exceptions.DataLoss):
rows_data.consume_all()
def test_table_read_rows_retry_retriable_errors_mid_stream(
data_table_read_rows_retry_tests,
):
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=4
),
error_injector.make_exception(
StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=0
),
error_injector.make_exception(
StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=0
),
]
rows_data = data_table_read_rows_retry_tests.read_rows()
rows_data.consume_all()
_assert_data_table_read_rows_retry_correct(rows_data)
def test_table_read_rows_retry_retriable_internal_errors_mid_stream(
data_table_read_rows_retry_tests,
):
from google.cloud.bigtable.row_data import RETRYABLE_INTERNAL_ERROR_MESSAGES
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.INTERNAL,
message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0],
fail_mid_stream=True,
successes_before_fail=2,
),
error_injector.make_exception(
StatusCode.INTERNAL,
message=RETRYABLE_INTERNAL_ERROR_MESSAGES[1],
fail_mid_stream=True,
successes_before_fail=1,
),
error_injector.make_exception(
StatusCode.INTERNAL,
message=RETRYABLE_INTERNAL_ERROR_MESSAGES[2],
fail_mid_stream=True,
successes_before_fail=0,
),
]
rows_data = data_table_read_rows_retry_tests.read_rows()
rows_data.consume_all()
_assert_data_table_read_rows_retry_correct(rows_data)
def test_table_read_rows_retry_unretriable_internal_errors_mid_stream(
data_table_read_rows_retry_tests,
):
from google.api_core import exceptions
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.INTERNAL,
message="Don't retry this at home!",
fail_mid_stream=True,
successes_before_fail=2,
),
]
rows_data = data_table_read_rows_retry_tests.read_rows()
with pytest.raises(exceptions.InternalServerError):
rows_data.consume_all()
def test_table_read_rows_retry_retriable_error_mid_stream_unretriable_error_reestablishing_stream(
data_table_read_rows_retry_tests,
):
# Simulate a connection failure mid-stream into an unretriable error when trying to reconnect.
from google.api_core import exceptions
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=5
),
error_injector.make_exception(StatusCode.ABORTED, fail_mid_stream=False),
]
rows_data = data_table_read_rows_retry_tests.read_rows()
with pytest.raises(exceptions.Aborted):
rows_data.consume_all()
def test_table_read_rows_retry_retriable_error_mid_stream_retriable_error_reestablishing_stream(
data_table_read_rows_retry_tests,
):
# Simulate a connection failure mid-stream into retriable errors when trying to reconnect.
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.UNAVAILABLE, fail_mid_stream=True, successes_before_fail=5
),
error_injector.make_exception(StatusCode.UNAVAILABLE, fail_mid_stream=False),
error_injector.make_exception(StatusCode.UNAVAILABLE, fail_mid_stream=False),
error_injector.make_exception(StatusCode.UNAVAILABLE, fail_mid_stream=False),
]
rows_data = data_table_read_rows_retry_tests.read_rows()
rows_data.consume_all()
_assert_data_table_read_rows_retry_correct(rows_data)
def test_table_read_rows_retry_timeout_mid_stream(
data_table_read_rows_retry_tests,
):
# Simulate a read timeout mid stream.
from google.api_core import exceptions
from google.cloud.bigtable.row_data import (
DEFAULT_RETRY_READ_ROWS,
RETRYABLE_INTERNAL_ERROR_MESSAGES,
)
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.INTERNAL,
message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0],
fail_mid_stream=True,
successes_before_fail=5,
),
] + [
error_injector.make_exception(
StatusCode.INTERNAL,
message=RETRYABLE_INTERNAL_ERROR_MESSAGES[0],
fail_mid_stream=True,
successes_before_fail=0,
),
] * 20
# Shorten the deadline so the timeout test is shorter.
rows_data = data_table_read_rows_retry_tests.read_rows(
retry=DEFAULT_RETRY_READ_ROWS.with_deadline(10.0)
)
with pytest.raises(exceptions.RetryError):
rows_data.consume_all()
def test_table_read_rows_retry_timeout_establishing_stream(
data_table_read_rows_retry_tests,
):
# Simulate a read timeout when creating the stream.
from google.api_core import exceptions
from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS
error_injector = data_table_read_rows_retry_tests.error_injector
error_injector.errors_to_inject = [
error_injector.make_exception(
StatusCode.DEADLINE_EXCEEDED, fail_mid_stream=False
),
] + [
error_injector.make_exception(
StatusCode.DEADLINE_EXCEEDED, fail_mid_stream=False
),
] * 20
# Shorten the deadline so the timeout test is shorter.
with pytest.raises(exceptions.RetryError):
data_table_read_rows_retry_tests.read_rows(
retry=DEFAULT_RETRY_READ_ROWS.with_deadline(10.0)
)
def test_table_check_and_mutate_rows(data_table, rows_to_delete):
true_mutation_row_key = b"true_row"
false_mutation_row_key = b"false_row"
columns = [
b"col_1",
b"col_2",
b"col_3",
b"col_4",
b"col_pr_1",
b"col_pr_2",
]
_populate_table(
data_table,
rows_to_delete,
[true_mutation_row_key, false_mutation_row_key],
columns=columns,
)
true_row = data_table.conditional_row(true_mutation_row_key, PASS_ALL_FILTER)
for column in columns:
true_row.set_cell(COLUMN_FAMILY_ID1, column, CELL_VAL_TRUE, state=True)
true_row.set_cell(COLUMN_FAMILY_ID1, column, CELL_VAL_FALSE, state=False)
matched = true_row.commit()
assert matched