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_table.py
More file actions
2379 lines (1818 loc) · 73.2 KB
/
Copy pathtest_table.py
File metadata and controls
2379 lines (1818 loc) · 73.2 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 2015 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 warnings
import mock
import pytest
from grpc import StatusCode
from google.api_core.exceptions import DeadlineExceeded
from ._testing import _make_credentials
PROJECT_ID = "project-id"
INSTANCE_ID = "instance-id"
INSTANCE_NAME = "projects/" + PROJECT_ID + "/instances/" + INSTANCE_ID
CLUSTER_ID = "cluster-id"
CLUSTER_NAME = INSTANCE_NAME + "/clusters/" + CLUSTER_ID
TABLE_ID = "table-id"
TABLE_NAME = INSTANCE_NAME + "/tables/" + TABLE_ID
BACKUP_ID = "backup-id"
BACKUP_NAME = CLUSTER_NAME + "/backups/" + BACKUP_ID
ROW_KEY = b"row-key"
ROW_KEY_1 = b"row-key-1"
ROW_KEY_2 = b"row-key-2"
ROW_KEY_3 = b"row-key-3"
FAMILY_NAME = "family"
QUALIFIER = b"qualifier"
TIMESTAMP_MICROS = 100
VALUE = b"value"
# RPC Status Codes
SUCCESS = StatusCode.OK.value[0]
RETRYABLE_1 = StatusCode.DEADLINE_EXCEEDED.value[0]
RETRYABLE_2 = StatusCode.ABORTED.value[0]
RETRYABLE_3 = StatusCode.UNAVAILABLE.value[0]
RETRYABLES = (RETRYABLE_1, RETRYABLE_2, RETRYABLE_3)
NON_RETRYABLE = StatusCode.CANCELLED.value[0]
STATUS_INTERNAL = StatusCode.INTERNAL.value[0]
@mock.patch("google.cloud.bigtable.table._MAX_BULK_MUTATIONS", new=3)
def test__compile_mutation_entries_w_too_many_mutations():
from google.cloud.bigtable.row import DirectRow
from google.cloud.bigtable.table import TooManyMutationsError
from google.cloud.bigtable.table import _compile_mutation_entries
table = mock.Mock(name="table", spec=["name"])
table.name = "table"
rows = [
DirectRow(row_key=b"row_key", table=table),
DirectRow(row_key=b"row_key_2", table=table),
]
rows[0].set_cell("cf1", b"c1", 1)
rows[0].set_cell("cf1", b"c1", 2)
rows[1].set_cell("cf1", b"c1", 3)
rows[1].set_cell("cf1", b"c1", 4)
with pytest.raises(TooManyMutationsError):
_compile_mutation_entries("table", rows)
def test__compile_mutation_entries_normal():
from google.cloud.bigtable.row import DirectRow
from google.cloud.bigtable.table import _compile_mutation_entries
from google.cloud.bigtable_v2.types import MutateRowsRequest
from google.cloud.bigtable_v2.types import data
table = mock.Mock(spec=["name"])
table.name = "table"
rows = [
DirectRow(row_key=b"row_key", table=table),
DirectRow(row_key=b"row_key_2"),
]
rows[0].set_cell("cf1", b"c1", b"1")
rows[1].set_cell("cf1", b"c1", b"2")
result = _compile_mutation_entries("table", rows)
entry_1 = MutateRowsRequest.Entry()
entry_1.row_key = b"row_key"
mutations_1 = data.Mutation()
mutations_1.set_cell.family_name = "cf1"
mutations_1.set_cell.column_qualifier = b"c1"
mutations_1.set_cell.timestamp_micros = -1
mutations_1.set_cell.value = b"1"
entry_1.mutations.append(mutations_1)
entry_2 = MutateRowsRequest.Entry()
entry_2.row_key = b"row_key_2"
mutations_2 = data.Mutation()
mutations_2.set_cell.family_name = "cf1"
mutations_2.set_cell.column_qualifier = b"c1"
mutations_2.set_cell.timestamp_micros = -1
mutations_2.set_cell.value = b"2"
entry_2.mutations.append(mutations_2)
assert result == [entry_1, entry_2]
def test__check_row_table_name_w_wrong_table_name():
from google.cloud.bigtable.table import _check_row_table_name
from google.cloud.bigtable.table import TableMismatchError
from google.cloud.bigtable.row import DirectRow
table = mock.Mock(name="table", spec=["name"])
table.name = "table"
row = DirectRow(row_key=b"row_key", table=table)
with pytest.raises(TableMismatchError):
_check_row_table_name("other_table", row)
def test__check_row_table_name_w_right_table_name():
from google.cloud.bigtable.row import DirectRow
from google.cloud.bigtable.table import _check_row_table_name
table = mock.Mock(name="table", spec=["name"])
table.name = "table"
row = DirectRow(row_key=b"row_key", table=table)
assert not _check_row_table_name("table", row)
def test__check_row_type_w_wrong_row_type():
from google.cloud.bigtable.row import ConditionalRow
from google.cloud.bigtable.table import _check_row_type
row = ConditionalRow(row_key=b"row_key", table="table", filter_=None)
with pytest.raises(TypeError):
_check_row_type(row)
def test__check_row_type_w_right_row_type():
from google.cloud.bigtable.row import DirectRow
from google.cloud.bigtable.table import _check_row_type
row = DirectRow(row_key=b"row_key", table="table")
assert not _check_row_type(row)
def _make_client(*args, **kwargs):
from google.cloud.bigtable.client import Client
return Client(*args, **kwargs)
def _make_table(*args, **kwargs):
from google.cloud.bigtable.table import Table
return Table(*args, **kwargs)
def test_table_constructor_defaults():
from google.cloud.bigtable.client import Client
client = mock.create_autospec(Client)
instance = mock.Mock(
_client=client,
instance_id=INSTANCE_ID,
spec=["_client", "instance_id"],
)
table = _make_table(TABLE_ID, instance)
assert table.table_id == TABLE_ID
assert table._instance is instance
assert table.mutation_timeout is None
assert table._app_profile_id is None
assert table._table_impl is client._veneer_data_client.get_table.return_value
client._veneer_data_client.get_table.assert_called_once_with(
INSTANCE_ID,
TABLE_ID,
app_profile_id=None,
)
def test_table_constructor_explicit():
from google.cloud.bigtable.client import Client
client = mock.create_autospec(Client)
instance = mock.Mock(
_client=client,
instance_id=INSTANCE_ID,
spec=["_client", "instance_id"],
)
mutation_timeout = 123
app_profile_id = "profile-123"
table = _make_table(
TABLE_ID,
instance,
mutation_timeout=mutation_timeout,
app_profile_id=app_profile_id,
)
assert table.table_id == TABLE_ID
assert table._instance is instance
assert table.mutation_timeout == mutation_timeout
assert table._app_profile_id == app_profile_id
assert table._table_impl is client._veneer_data_client.get_table.return_value
client._veneer_data_client.get_table.assert_called_once_with(
INSTANCE_ID,
TABLE_ID,
app_profile_id=app_profile_id,
)
def test_table_name():
table_data_client = mock.Mock(spec=["table_path"])
_veneer_data_client = mock.Mock()
client = mock.Mock(
project=PROJECT_ID,
table_data_client=table_data_client,
_veneer_data_client=_veneer_data_client,
spec=["project", "table_data_client", "_veneer_data_client"],
)
instance = mock.Mock(
_client=client,
instance_id=INSTANCE_ID,
spec=["_client", "instance_id"],
)
table = _make_table(TABLE_ID, instance)
assert table.name == table_data_client.table_path.return_value
def _table_row_methods_helper():
client = _make_client(
project="project-id", credentials=_make_credentials(), admin=True
)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
row_key = b"row_key"
return table, row_key
def test_table_row_factory_direct():
from google.cloud.bigtable.row import DirectRow
table, row_key = _table_row_methods_helper()
with warnings.catch_warnings(record=True) as warned:
row = table.row(row_key)
assert isinstance(row, DirectRow)
assert row._row_key == row_key
assert row._table == table
assert len(warned) == 1
assert warned[0].category is PendingDeprecationWarning
def test_table_row_factory_conditional():
from google.cloud.bigtable.row import ConditionalRow
table, row_key = _table_row_methods_helper()
filter_ = object()
with warnings.catch_warnings(record=True) as warned:
row = table.row(row_key, filter_=filter_)
assert isinstance(row, ConditionalRow)
assert row._row_key == row_key
assert row._table == table
assert len(warned) == 1
assert warned[0].category is PendingDeprecationWarning
def test_table_row_factory_append():
from google.cloud.bigtable.row import AppendRow
table, row_key = _table_row_methods_helper()
with warnings.catch_warnings(record=True) as warned:
row = table.row(row_key, append=True)
assert isinstance(row, AppendRow)
assert row._row_key == row_key
assert row._table == table
assert len(warned) == 1
assert warned[0].category is PendingDeprecationWarning
def test_table_row_factory_failure():
table, row_key = _table_row_methods_helper()
with pytest.raises(ValueError):
with warnings.catch_warnings(record=True) as warned:
table.row(row_key, filter_=object(), append=True)
assert len(warned) == 1
assert warned[0].category is PendingDeprecationWarning
def test_table_direct_row():
from google.cloud.bigtable.row import DirectRow
table, row_key = _table_row_methods_helper()
row = table.direct_row(row_key)
assert isinstance(row, DirectRow)
assert row._row_key == row_key
assert row._table == table
def test_table_conditional_row():
from google.cloud.bigtable.row import ConditionalRow
table, row_key = _table_row_methods_helper()
filter_ = object()
row = table.conditional_row(row_key, filter_=filter_)
assert isinstance(row, ConditionalRow)
assert row._row_key == row_key
assert row._table == table
def test_table_append_row():
from google.cloud.bigtable.row import AppendRow
table, row_key = _table_row_methods_helper()
row = table.append_row(row_key)
assert isinstance(row, AppendRow)
assert row._row_key == row_key
assert row._table == table
def test_table___eq__():
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table1 = _make_table(TABLE_ID, instance)
table2 = _make_table(TABLE_ID, instance)
assert table1 == table2
def test_table___eq__type_differ():
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table1 = _make_table(TABLE_ID, instance)
table2 = object()
assert not (table1 == table2)
def test_table___ne__same_value():
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table1 = _make_table(TABLE_ID, instance)
table2 = _make_table(TABLE_ID, instance)
assert not (table1 != table2)
def test_table___ne__():
mock_instance = mock.Mock()
table1 = _make_table("table_id1", mock_instance)
table2 = _make_table("table_id2", mock_instance)
assert table1 != table2
def _make_table_api():
from google.cloud.bigtable.admin.overlay.services.bigtable_table_admin import (
client as bigtable_table_admin,
)
return mock.create_autospec(bigtable_table_admin.BigtableTableAdminClient)
def _create_table_helper(split_keys=[], column_families={}):
from google.cloud.bigtable.admin.types import table as table_pb2
from google.cloud.bigtable.admin.types import (
bigtable_table_admin as table_admin_messages_v2_pb2,
)
from google.cloud.bigtable.column_family import ColumnFamily
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
table_api = client._table_admin_client = _make_table_api()
table.create(column_families=column_families, initial_split_keys=split_keys)
families = {
id: ColumnFamily(id, table, rule).to_pb()
for (id, rule) in column_families.items()
}
split = table_admin_messages_v2_pb2.CreateTableRequest.Split
splits = [split(key=split_key) for split_key in split_keys]
table_api.create_table.assert_called_once_with(
request={
"parent": INSTANCE_NAME,
"table": table_pb2.Table(column_families=families),
"table_id": TABLE_ID,
"initial_splits": splits,
}
)
def test_table_create():
_create_table_helper()
def test_table_create_with_families():
from google.cloud.bigtable.column_family import MaxVersionsGCRule
families = {"family": MaxVersionsGCRule(5)}
_create_table_helper(column_families=families)
def test_table_create_with_split_keys():
_create_table_helper(split_keys=[b"split1", b"split2", b"split3"])
def test_table_exists_hit():
from google.cloud.bigtable.admin.types import ListTablesResponse
from google.cloud.bigtable.admin.types import Table
from google.cloud.bigtable import enums
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = instance.table(TABLE_ID)
response_pb = ListTablesResponse(tables=[Table(name=TABLE_NAME)])
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.return_value = response_pb
assert table.exists()
expected_request = {
"name": table.name,
"view": enums.Table.View.NAME_ONLY,
}
table_api.get_table.assert_called_once_with(request=expected_request)
def test_table_exists_miss():
from google.api_core.exceptions import NotFound
from google.cloud.bigtable import enums
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = instance.table("nonesuch-table-id2")
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.side_effect = NotFound("testing")
assert not table.exists()
expected_request = {
"name": table.name,
"view": enums.Table.View.NAME_ONLY,
}
table_api.get_table.assert_called_once_with(request=expected_request)
def test_table_exists_error():
from google.api_core.exceptions import BadRequest
from google.cloud.bigtable import enums
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.side_effect = BadRequest("testing")
table = instance.table(TABLE_ID)
with pytest.raises(BadRequest):
table.exists()
expected_request = {
"name": table.name,
"view": enums.Table.View.NAME_ONLY,
}
table_api.get_table.assert_called_once_with(request=expected_request)
def test_table_delete():
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
table_api = client._table_admin_client = _make_table_api()
assert table.delete() is None
table_api.delete_table.assert_called_once_with(request={"name": table.name})
def _table_list_column_families_helper():
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
# Create response_pb
COLUMN_FAMILY_ID = "foo"
column_family = _ColumnFamilyPB()
response_pb = _TablePB(column_families={COLUMN_FAMILY_ID: column_family})
# Patch the stub used by the API method.
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.return_value = response_pb
# Create expected_result.
expected_result = {COLUMN_FAMILY_ID: table.column_family(COLUMN_FAMILY_ID)}
# Perform the method and check the result.
result = table.list_column_families()
assert result == expected_result
table_api.get_table.assert_called_once_with(request={"name": table.name})
def test_table_list_column_families():
_table_list_column_families_helper()
def test_table_get_cluster_states():
from google.cloud.bigtable.enums import Table as enum_table
from google.cloud.bigtable.table import ClusterState
INITIALIZING = enum_table.ReplicationState.INITIALIZING
PLANNED_MAINTENANCE = enum_table.ReplicationState.PLANNED_MAINTENANCE
READY = enum_table.ReplicationState.READY
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
response_pb = _TablePB(
cluster_states={
"cluster-id1": _ClusterStatePB(INITIALIZING),
"cluster-id2": _ClusterStatePB(PLANNED_MAINTENANCE),
"cluster-id3": _ClusterStatePB(READY),
}
)
# Patch the stub used by the API method.
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.return_value = response_pb
# build expected result
expected_result = {
"cluster-id1": ClusterState(INITIALIZING),
"cluster-id2": ClusterState(PLANNED_MAINTENANCE),
"cluster-id3": ClusterState(READY),
}
# Perform the method and check the result.
result = table.get_cluster_states()
assert result == expected_result
expected_request = {
"name": table.name,
"view": enum_table.View.REPLICATION_VIEW,
}
table_api.get_table.assert_called_once_with(request=expected_request)
def test_table_get_encryption_info():
from google.rpc.code_pb2 import Code
from google.cloud.bigtable.encryption_info import EncryptionInfo
from google.cloud.bigtable.enums import EncryptionInfo as enum_crypto
from google.cloud.bigtable.enums import Table as enum_table
from google.cloud.bigtable.error import Status
ENCRYPTION_TYPE_UNSPECIFIED = enum_crypto.EncryptionType.ENCRYPTION_TYPE_UNSPECIFIED
GOOGLE_DEFAULT_ENCRYPTION = enum_crypto.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION
CUSTOMER_MANAGED_ENCRYPTION = enum_crypto.EncryptionType.CUSTOMER_MANAGED_ENCRYPTION
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
response_pb = _TablePB(
cluster_states={
"cluster-id1": _ClusterStateEncryptionInfoPB(
encryption_type=ENCRYPTION_TYPE_UNSPECIFIED,
encryption_status=_StatusPB(Code.OK, "Status OK"),
),
"cluster-id2": _ClusterStateEncryptionInfoPB(
encryption_type=GOOGLE_DEFAULT_ENCRYPTION,
),
"cluster-id3": _ClusterStateEncryptionInfoPB(
encryption_type=CUSTOMER_MANAGED_ENCRYPTION,
encryption_status=_StatusPB(
Code.UNKNOWN, "Key version is not yet known."
),
kms_key_version="UNKNOWN",
),
}
)
# Patch the stub used by the API method.
table_api = client._table_admin_client = _make_table_api()
table_api.get_table.return_value = response_pb
# build expected result
expected_result = {
"cluster-id1": (
EncryptionInfo(
encryption_type=ENCRYPTION_TYPE_UNSPECIFIED,
encryption_status=Status(_StatusPB(Code.OK, "Status OK")),
kms_key_version="",
),
),
"cluster-id2": (
EncryptionInfo(
encryption_type=GOOGLE_DEFAULT_ENCRYPTION,
encryption_status=Status(_StatusPB(0, "")),
kms_key_version="",
),
),
"cluster-id3": (
EncryptionInfo(
encryption_type=CUSTOMER_MANAGED_ENCRYPTION,
encryption_status=Status(
_StatusPB(Code.UNKNOWN, "Key version is not yet known.")
),
kms_key_version="UNKNOWN",
),
),
}
# Perform the method and check the result.
result = table.get_encryption_info()
assert result == expected_result
expected_request = {
"name": table.name,
"view": enum_table.View.ENCRYPTION_VIEW,
}
table_api.get_table.assert_called_once_with(request=expected_request)
def _make_data_api(client):
from google.cloud.bigtable.data import BigtableDataClient
data_client_mock = mock.create_autospec(BigtableDataClient)
client._table_data_client = data_client_mock
return data_client_mock
def _make_gapic_api(client):
from google.cloud.bigtable_v2.services.bigtable import BigtableClient
data_client_mock = _make_data_api(client)
gapic_client_mock = mock.create_autospec(BigtableClient)
data_client_mock._gapic_client = gapic_client_mock
return gapic_client_mock
def _table_read_row_helper(chunks, expected_result, app_profile_id=None):
from google.cloud._testing import _Monkey
from google.cloud.bigtable import table as MUT
from google.cloud.bigtable.row_set import RowSet
from google.cloud.bigtable.row_filters import RowSampleFilter
from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance, app_profile_id=app_profile_id)
# Create request_pb
request_pb = object() # Returned by our mock.
mock_created = []
def mock_create_row_request(table_name, **kwargs):
mock_created.append((table_name, kwargs))
return request_pb
# Create response_iterator
if chunks is None:
response_iterator = iter(()) # no responses at all
else:
response_pb = _ReadRowsResponsePB(chunks=chunks)
response_iterator = iter([response_pb])
gapic_api = _make_gapic_api(client)
gapic_api.read_rows.return_value = response_iterator
filter_obj = RowSampleFilter(0.33)
with _Monkey(MUT, _create_row_request=mock_create_row_request):
result = table.read_row(ROW_KEY, filter_=filter_obj)
row_set = RowSet()
row_set.add_row_key(ROW_KEY)
expected_request = [
(
table.name,
{
"end_inclusive": False,
"row_set": row_set,
"app_profile_id": app_profile_id,
"end_key": None,
"limit": None,
"start_key": None,
"filter_": filter_obj,
},
)
]
assert result == expected_result
assert mock_created == expected_request
gapic_api.read_rows.assert_called_once_with(
request_pb, timeout=61.0, retry=DEFAULT_RETRY_READ_ROWS
)
def test_table_read_row_miss_no__responses():
_table_read_row_helper(None, None)
def test_table_read_row_miss_no_chunks_in_response():
chunks = []
_table_read_row_helper(chunks, None)
def test_table_read_row_complete():
from google.cloud.bigtable.row_data import Cell
from google.cloud.bigtable.row_data import PartialRowData
app_profile_id = "app-profile-id"
chunk = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
commit_row=True,
)
chunks = [chunk]
expected_result = PartialRowData(row_key=ROW_KEY)
family = expected_result._cells.setdefault(FAMILY_NAME, {})
column = family.setdefault(QUALIFIER, [])
column.append(Cell.from_pb(chunk))
_table_read_row_helper(chunks, expected_result, app_profile_id)
def test_table_read_row_more_than_one_row_returned():
app_profile_id = "app-profile-id"
chunk_1 = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
commit_row=True,
)._pb
chunk_2 = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY_2,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
commit_row=True,
)._pb
chunks = [chunk_1, chunk_2]
with pytest.raises(ValueError):
_table_read_row_helper(chunks, None, app_profile_id)
def test_table_read_row_still_partial():
chunk = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
)
chunks = [chunk] # No "commit row".
with pytest.raises(ValueError):
_table_read_row_helper(chunks, None)
def _table_mutate_rows_helper(
mutation_timeout=None, app_profile_id=None, retry=None, timeout=None
):
from google.rpc.status_pb2 import Status
from google.cloud.bigtable.table import DEFAULT_RETRY
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
instance = client.instance(instance_id=INSTANCE_ID)
ctor_kwargs = {}
if mutation_timeout is not None:
ctor_kwargs["mutation_timeout"] = mutation_timeout
if app_profile_id is not None:
ctor_kwargs["app_profile_id"] = app_profile_id
table = _make_table(TABLE_ID, instance, **ctor_kwargs)
rows = [mock.MagicMock(), mock.MagicMock()]
response = [Status(code=0), Status(code=1)]
instance_mock = mock.Mock(return_value=response)
klass_mock = mock.patch(
"google.cloud.bigtable.table._RetryableMutateRowsWorker",
new=mock.MagicMock(return_value=instance_mock),
)
call_kwargs = {}
if retry is not None:
call_kwargs["retry"] = retry
if timeout is not None:
expected_timeout = call_kwargs["timeout"] = timeout
else:
expected_timeout = mutation_timeout
with klass_mock:
statuses = table.mutate_rows(rows, **call_kwargs)
result = [status.code for status in statuses]
expected_result = [0, 1]
assert result == expected_result
klass_mock.new.assert_called_once_with(
client,
TABLE_NAME,
rows,
app_profile_id=app_profile_id,
timeout=expected_timeout,
)
if retry is not None:
instance_mock.assert_called_once_with(retry=retry)
else:
instance_mock.assert_called_once_with(retry=DEFAULT_RETRY)
def test_table_mutate_rows_w_default_mutation_timeout_app_profile_id():
_table_mutate_rows_helper()
def test_table_mutate_rows_w_mutation_timeout():
mutation_timeout = 123
_table_mutate_rows_helper(mutation_timeout=mutation_timeout)
def test_table_mutate_rows_w_app_profile_id():
app_profile_id = "profile-123"
_table_mutate_rows_helper(app_profile_id=app_profile_id)
def test_table_mutate_rows_w_retry():
retry = mock.Mock()
_table_mutate_rows_helper(retry=retry)
def test_table_mutate_rows_w_timeout_arg():
timeout = 123
_table_mutate_rows_helper(timeout=timeout)
def test_table_mutate_rows_w_mutation_timeout_and_timeout_arg():
mutation_timeout = 123
timeout = 456
_table_mutate_rows_helper(mutation_timeout=mutation_timeout, timeout=timeout)
def test_table_read_rows():
from google.cloud._testing import _Monkey
from google.cloud.bigtable.row_data import PartialRowsData
from google.cloud.bigtable import table as MUT
from google.cloud.bigtable.row_data import DEFAULT_RETRY_READ_ROWS
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
gapic_api = _make_gapic_api(client)
instance = client.instance(instance_id=INSTANCE_ID)
app_profile_id = "app-profile-id"
table = _make_table(TABLE_ID, instance, app_profile_id=app_profile_id)
# Create request_pb
request_pb = object() # Returned by our mock.
retry = DEFAULT_RETRY_READ_ROWS
mock_created = []
def mock_create_row_request(table_name, **kwargs):
mock_created.append((table_name, kwargs))
return request_pb
# Create expected_result.
expected_result = PartialRowsData(
client._table_data_client._gapic_client.transport.read_rows, request_pb, retry
)
# Perform the method and check the result.
start_key = b"start-key"
end_key = b"end-key"
filter_obj = object()
limit = 22
with _Monkey(MUT, _create_row_request=mock_create_row_request):
result = table.read_rows(
start_key=start_key,
end_key=end_key,
filter_=filter_obj,
limit=limit,
retry=retry,
)
assert result.rows == expected_result.rows
assert result.retry == expected_result.retry
created_kwargs = {
"start_key": start_key,
"end_key": end_key,
"filter_": filter_obj,
"limit": limit,
"end_inclusive": False,
"app_profile_id": app_profile_id,
"row_set": None,
}
assert mock_created == [(table.name, created_kwargs)]
gapic_api.read_rows.assert_called_once_with(request_pb, timeout=61.0, retry=retry)
def test_table_read_retry_rows():
from google.api_core import retry
credentials = _make_credentials()
client = _make_client(project="project-id", credentials=credentials, admin=True)
gapic_api = _make_gapic_api(client)
instance = client.instance(instance_id=INSTANCE_ID)
table = _make_table(TABLE_ID, instance)
retry_read_rows = retry.Retry(predicate=_read_rows_retry_exception)
# Create response_iterator
chunk_1 = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY_1,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
commit_row=True,
)
chunk_2 = _ReadRowsResponseCellChunkPB(
row_key=ROW_KEY_2,
family_name=FAMILY_NAME,
qualifier=QUALIFIER,
timestamp_micros=TIMESTAMP_MICROS,
value=VALUE,
commit_row=True,
)
response_1 = _ReadRowsResponseV2([chunk_1])
response_2 = _ReadRowsResponseV2([chunk_2])
response_failure_iterator_1 = _MockFailureIterator_1()
response_failure_iterator_2 = _MockFailureIterator_2([response_1])
response_iterator = _MockReadRowsIterator(response_2)
gapic_api.table_path.return_value = (
f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/tables/{TABLE_ID}"
)
gapic_api.read_rows.side_effect = [
response_failure_iterator_1,
response_failure_iterator_2,