-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathtest_table.py
6083 lines (5156 loc) · 229 KB
/
test_table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 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 copy
import datetime
import logging
import re
from sys import version_info
import time
import types
import unittest
from unittest import mock
import warnings
import pytest
import google.api_core.exceptions
from test_utils.imports import maybe_fail_import
from google.cloud.bigquery import _versions_helpers
from google.cloud.bigquery import exceptions
from google.cloud.bigquery import external_config
from google.cloud.bigquery.table import TableReference
from google.cloud.bigquery.dataset import DatasetReference
def _mock_client():
from google.cloud.bigquery import client
mock_client = mock.create_autospec(client.Client)
mock_client.project = "my-project"
return mock_client
class _SchemaBase(object):
def _verify_field(self, field, r_field):
self.assertEqual(field.name, r_field["name"])
self.assertEqual(field.field_type, r_field["type"])
self.assertEqual(field.mode, r_field.get("mode", "NULLABLE"))
def _verifySchema(self, schema, resource):
r_fields = resource["schema"]["fields"]
self.assertEqual(len(schema), len(r_fields))
for field, r_field in zip(schema, r_fields):
self._verify_field(field, r_field)
class TestEncryptionConfiguration(unittest.TestCase):
KMS_KEY_NAME = "projects/1/locations/us/keyRings/1/cryptoKeys/1"
@staticmethod
def _get_target_class():
from google.cloud.bigquery.table import EncryptionConfiguration
return EncryptionConfiguration
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor_defaults(self):
encryption_config = self._make_one()
self.assertIsNone(encryption_config.kms_key_name)
def test_ctor_with_key(self):
encryption_config = self._make_one(kms_key_name=self.KMS_KEY_NAME)
self.assertEqual(encryption_config.kms_key_name, self.KMS_KEY_NAME)
class TestTableBase:
@staticmethod
def _get_target_class():
from google.cloud.bigquery.table import _TableBase
return _TableBase
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor_defaults(self):
instance = self._make_one()
assert instance._properties == {}
def test_project(self):
instance = self._make_one()
instance._properties = {"tableReference": {"projectId": "p_1"}}
assert instance.project == "p_1"
def test_dataset_id(self):
instance = self._make_one()
instance._properties = {"tableReference": {"datasetId": "ds_1"}}
assert instance.dataset_id == "ds_1"
def test_table_id(self):
instance = self._make_one()
instance._properties = {"tableReference": {"tableId": "tbl_1"}}
assert instance.table_id == "tbl_1"
def test_path(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
assert instance.path == "/projects/p_1/datasets/ds_1/tables/tbl_1"
def test___eq___wrong_type(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
class TableWannabe:
pass
wannabe_other = TableWannabe()
wannabe_other._properties = instance._properties
wannabe_other.project = "p_1"
wannabe_other.dataset_id = "ds_1"
wannabe_other.table_id = "tbl_1"
assert instance != wannabe_other # Can't fake it.
assert instance == mock.ANY # ...but delegation to other object works.
def test___eq___project_mismatch(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
other = self._make_one()
other._properties = {
"projectId": "p_2",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
assert instance != other
def test___eq___dataset_mismatch(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
other = self._make_one()
other._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_2",
"tableId": "tbl_1",
}
}
assert instance != other
def test___eq___table_mismatch(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
other = self._make_one()
other._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_2",
}
}
assert instance != other
def test___eq___equality(self):
instance = self._make_one()
instance._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
other = self._make_one()
other._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
assert instance == other
def test___hash__set_equality(self):
instance_1 = self._make_one()
instance_1._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
instance_2 = self._make_one()
instance_2._properties = {
"tableReference": {
"projectId": "p_2",
"datasetId": "ds_2",
"tableId": "tbl_2",
}
}
set_one = {instance_1, instance_2}
set_two = {instance_1, instance_2}
assert set_one == set_two
def test___hash__sets_not_equal(self):
instance_1 = self._make_one()
instance_1._properties = {
"tableReference": {
"projectId": "p_1",
"datasetId": "ds_1",
"tableId": "tbl_1",
}
}
instance_2 = self._make_one()
instance_2._properties = {
"tableReference": {
"projectId": "p_2",
"datasetId": "ds_2",
"tableId": "tbl_2",
}
}
set_one = {instance_1}
set_two = {instance_2}
assert set_one != set_two
class TestTableReference(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.bigquery.table import TableReference
return TableReference
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor_defaults(self):
dataset_ref = DatasetReference("project_1", "dataset_1")
table_ref = self._make_one(dataset_ref, "table_1")
self.assertEqual(table_ref.dataset_id, dataset_ref.dataset_id)
self.assertEqual(table_ref.table_id, "table_1")
def test_to_api_repr(self):
dataset_ref = DatasetReference("project_1", "dataset_1")
table_ref = self._make_one(dataset_ref, "table_1")
resource = table_ref.to_api_repr()
self.assertEqual(
resource,
{"projectId": "project_1", "datasetId": "dataset_1", "tableId": "table_1"},
)
def test_from_api_repr(self):
from google.cloud.bigquery.table import TableReference
dataset_ref = DatasetReference("project_1", "dataset_1")
expected = self._make_one(dataset_ref, "table_1")
got = TableReference.from_api_repr(
{"projectId": "project_1", "datasetId": "dataset_1", "tableId": "table_1"}
)
self.assertEqual(expected, got)
def test_from_string(self):
cls = self._get_target_class()
got = cls.from_string("string-project.string_dataset.string_table")
self.assertEqual(got.project, "string-project")
self.assertEqual(got.dataset_id, "string_dataset")
self.assertEqual(got.table_id, "string_table")
def test_from_string_w_prefix(self):
cls = self._get_target_class()
got = cls.from_string("google.com:string-project.string_dataset.string_table")
self.assertEqual(got.project, "google.com:string-project")
self.assertEqual(got.dataset_id, "string_dataset")
self.assertEqual(got.table_id, "string_table")
def test_from_string_legacy_string(self):
cls = self._get_target_class()
with self.assertRaises(ValueError):
cls.from_string("string-project:string_dataset.string_table")
def test_from_string_w_incorrect_prefix(self):
cls = self._get_target_class()
with self.assertRaises(ValueError):
cls.from_string("google.com.string-project.string_dataset.string_table")
def test_from_string_not_fully_qualified(self):
cls = self._get_target_class()
with self.assertRaises(ValueError):
cls.from_string("string_table")
with self.assertRaises(ValueError):
cls.from_string("string_dataset.string_table")
with self.assertRaises(ValueError):
cls.from_string("a.b.c.d")
def test_from_string_with_default_project(self):
cls = self._get_target_class()
got = cls.from_string(
"string_dataset.string_table", default_project="default-project"
)
self.assertEqual(got.project, "default-project")
self.assertEqual(got.dataset_id, "string_dataset")
self.assertEqual(got.table_id, "string_table")
def test_from_string_ignores_default_project(self):
cls = self._get_target_class()
got = cls.from_string(
"string-project.string_dataset.string_table",
default_project="default-project",
)
self.assertEqual(got.project, "string-project")
self.assertEqual(got.dataset_id, "string_dataset")
self.assertEqual(got.table_id, "string_table")
def test___repr__(self):
dataset = DatasetReference("project1", "dataset1")
table1 = self._make_one(dataset, "table1")
expected = (
"TableReference(DatasetReference('project1', 'dataset1'), " "'table1')"
)
self.assertEqual(repr(table1), expected)
def test___str__(self):
dataset = DatasetReference("project1", "dataset1")
table1 = self._make_one(dataset, "table1")
self.assertEqual(str(table1), "project1.dataset1.table1")
class TestTable(unittest.TestCase, _SchemaBase):
PROJECT = "prahj-ekt"
DS_ID = "dataset-name"
TABLE_NAME = "table-name"
KMS_KEY_NAME = "projects/1/locations/us/keyRings/1/cryptoKeys/1"
@staticmethod
def _get_target_class():
from google.cloud.bigquery.table import Table
return Table
def _make_one(self, *args, **kw):
if len(args) == 0:
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
args = (table_ref,)
return self._get_target_class()(*args, **kw)
def _setUpConstants(self):
import datetime
from google.cloud._helpers import UTC
self.WHEN_TS = 1437767599.006
self.WHEN = datetime.datetime.utcfromtimestamp(self.WHEN_TS).replace(tzinfo=UTC)
self.ETAG = "ETAG"
self.TABLE_FULL_ID = "%s:%s.%s" % (self.PROJECT, self.DS_ID, self.TABLE_NAME)
self.RESOURCE_URL = "http://example.com/path/to/resource"
self.NUM_BYTES = 12345
self.NUM_ROWS = 67
self.NUM_EST_BYTES = 1234
self.NUM_EST_ROWS = 23
def _make_resource(self):
self._setUpConstants()
return {
"creationTime": self.WHEN_TS * 1000,
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_NAME,
},
"schema": {
"fields": [
{"name": "full_name", "type": "STRING", "mode": "REQUIRED"},
{"name": "age", "type": "INTEGER", "mode": "REQUIRED"},
]
},
"etag": "ETAG",
"id": self.TABLE_FULL_ID,
"lastModifiedTime": self.WHEN_TS * 1000,
"location": "US",
"selfLink": self.RESOURCE_URL,
"numRows": self.NUM_ROWS,
"numBytes": self.NUM_BYTES,
"type": "TABLE",
"streamingBuffer": {
"estimatedRows": str(self.NUM_EST_ROWS),
"estimatedBytes": str(self.NUM_EST_BYTES),
"oldestEntryTime": self.WHEN_TS * 1000,
},
"externalDataConfiguration": {
"sourceFormat": "CSV",
"csvOptions": {"allowJaggedRows": True, "encoding": "encoding"},
},
"labels": {"x": "y"},
}
def _verifyReadonlyResourceProperties(self, table, resource):
if "creationTime" in resource:
self.assertEqual(table.created, self.WHEN)
else:
self.assertIsNone(table.created)
if "etag" in resource:
self.assertEqual(table.etag, self.ETAG)
else:
self.assertIsNone(table.etag)
if "numRows" in resource:
self.assertEqual(table.num_rows, self.NUM_ROWS)
else:
self.assertIsNone(table.num_rows)
if "numBytes" in resource:
self.assertEqual(table.num_bytes, self.NUM_BYTES)
else:
self.assertIsNone(table.num_bytes)
if "selfLink" in resource:
self.assertEqual(table.self_link, self.RESOURCE_URL)
else:
self.assertIsNone(table.self_link)
if "streamingBuffer" in resource:
self.assertEqual(table.streaming_buffer.estimated_rows, self.NUM_EST_ROWS)
self.assertEqual(table.streaming_buffer.estimated_bytes, self.NUM_EST_BYTES)
self.assertEqual(table.streaming_buffer.oldest_entry_time, self.WHEN)
else:
self.assertIsNone(table.streaming_buffer)
self.assertEqual(table.full_table_id, self.TABLE_FULL_ID)
self.assertEqual(
table.table_type, "TABLE" if "view" not in resource else "VIEW"
)
def _verifyResourceProperties(self, table, resource):
self._verifyReadonlyResourceProperties(table, resource)
if "expirationTime" in resource:
self.assertEqual(table.expires, self.EXP_TIME)
else:
self.assertIsNone(table.expires)
self.assertEqual(table.description, resource.get("description"))
self.assertEqual(table.friendly_name, resource.get("friendlyName"))
self.assertEqual(table.location, resource.get("location"))
if "view" in resource:
self.assertEqual(table.view_query, resource["view"]["query"])
self.assertEqual(
table.view_use_legacy_sql, resource["view"].get("useLegacySql", True)
)
else:
self.assertIsNone(table.view_query)
self.assertIsNone(table.view_use_legacy_sql)
if "schema" in resource:
self._verifySchema(table.schema, resource)
else:
self.assertEqual(table.schema, [])
if "externalDataConfiguration" in resource:
edc = table.external_data_configuration
self.assertEqual(edc.source_format, "CSV")
self.assertEqual(edc.options.allow_jagged_rows, True)
if "labels" in resource:
self.assertEqual(table.labels, {"x": "y"})
else:
self.assertEqual(table.labels, {})
if "encryptionConfiguration" in resource:
self.assertIsNotNone(table.encryption_configuration)
self.assertEqual(
table.encryption_configuration.kms_key_name,
resource["encryptionConfiguration"]["kmsKeyName"],
)
else:
self.assertIsNone(table.encryption_configuration)
def test_ctor(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
self.assertEqual(table.table_id, self.TABLE_NAME)
self.assertEqual(table.project, self.PROJECT)
self.assertEqual(table.dataset_id, self.DS_ID)
self.assertEqual(table.reference.table_id, self.TABLE_NAME)
self.assertEqual(table.reference.project, self.PROJECT)
self.assertEqual(table.reference.dataset_id, self.DS_ID)
self.assertEqual(
table.path,
"/projects/%s/datasets/%s/tables/%s"
% (self.PROJECT, self.DS_ID, self.TABLE_NAME),
)
self.assertEqual(table.schema, [])
self.assertIsNone(table.created)
self.assertIsNone(table.etag)
self.assertIsNone(table.modified)
self.assertIsNone(table.num_bytes)
self.assertIsNone(table.num_rows)
self.assertIsNone(table.self_link)
self.assertIsNone(table.full_table_id)
self.assertIsNone(table.table_type)
self.assertIsNone(table.description)
self.assertIsNone(table.expires)
self.assertIsNone(table.friendly_name)
self.assertIsNone(table.location)
self.assertIsNone(table.view_query)
self.assertIsNone(table.view_use_legacy_sql)
self.assertIsNone(table.external_data_configuration)
self.assertEqual(table.labels, {})
self.assertIsNone(table.encryption_configuration)
self.assertIsNone(table.time_partitioning)
self.assertIsNone(table.clustering_fields)
self.assertIsNone(table.table_constraints)
def test_ctor_w_schema(self):
from google.cloud.bigquery.schema import SchemaField
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
full_name = SchemaField("full_name", "STRING", mode="REQUIRED")
age = SchemaField("age", "INTEGER", mode="REQUIRED")
table = self._make_one(table_ref, schema=[full_name, age])
self.assertEqual(table.schema, [full_name, age])
def test_ctor_string(self):
table = self._make_one("some-project.some_dset.some_tbl")
self.assertEqual(table.project, "some-project")
self.assertEqual(table.dataset_id, "some_dset")
self.assertEqual(table.table_id, "some_tbl")
def test_ctor_tablelistitem(self):
from google.cloud.bigquery.table import Table, TableListItem
import datetime
from google.cloud._helpers import _millis, UTC
self.WHEN_TS = 1437767599.125
self.EXP_TIME = datetime.datetime(2015, 8, 1, 23, 59, 59, tzinfo=UTC)
project = "test-project"
dataset_id = "test_dataset"
table_id = "coffee_table"
resource = {
"creationTime": self.WHEN_TS * 1000,
"expirationTime": _millis(self.EXP_TIME),
"kind": "bigquery#table",
"id": "{}:{}.{}".format(project, dataset_id, table_id),
"tableReference": {
"projectId": project,
"datasetId": dataset_id,
"tableId": table_id,
},
"friendlyName": "Mahogany Coffee Table",
"type": "TABLE",
"timePartitioning": {
"type": "DAY",
"field": "mycolumn",
"expirationMs": "10000",
},
"labels": {"some-stuff": "this-is-a-label"},
"clustering": {"fields": ["string"]},
}
table_list_item = TableListItem(resource)
table = Table(table_list_item)
self.assertIsNone(table.created)
self.assertEqual(table.reference.project, project)
self.assertEqual(table.reference.dataset_id, dataset_id)
self.assertEqual(table.reference.table_id, table_id)
def test_ctor_string_wo_project_id(self):
with pytest.raises(ValueError):
# Project ID is missing.
self._make_one("some_dset.some_tbl")
def test_num_bytes_getter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
# Check with no value set.
self.assertIsNone(table.num_bytes)
num_bytes = 1337
# Check with integer value set.
table._properties = {"numBytes": num_bytes}
self.assertEqual(table.num_bytes, num_bytes)
# Check with a string value set.
table._properties = {"numBytes": str(num_bytes)}
self.assertEqual(table.num_bytes, num_bytes)
# Check with invalid int value.
table._properties = {"numBytes": "x"}
with self.assertRaises(ValueError):
getattr(table, "num_bytes")
def test_num_rows_getter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
# Check with no value set.
self.assertIsNone(table.num_rows)
num_rows = 42
# Check with integer value set.
table._properties = {"numRows": num_rows}
self.assertEqual(table.num_rows, num_rows)
# Check with a string value set.
table._properties = {"numRows": str(num_rows)}
self.assertEqual(table.num_rows, num_rows)
# Check with invalid int value.
table._properties = {"numRows": "x"}
with self.assertRaises(ValueError):
getattr(table, "num_rows")
def test__eq__same_table_property_different(self):
table_1 = self._make_one("project_foo.dataset_bar.table_baz")
table_1.description = "This is table baz"
table_2 = self._make_one("project_foo.dataset_bar.table_baz")
table_2.description = "This is also table baz"
assert table_1 == table_2 # Still equal, only table reference is important.
def test_hashable(self):
table_1 = self._make_one("project_foo.dataset_bar.table_baz")
table_1.description = "This is a table"
table_1b = self._make_one("project_foo.dataset_bar.table_baz")
table_1b.description = "Metadata is irrelevant for hashes"
assert hash(table_1) == hash(table_1b)
def test_schema_setter_non_sequence(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(TypeError):
table.schema = object()
def test_schema_setter_invalid_field(self):
from google.cloud.bigquery.schema import SchemaField
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
full_name = SchemaField("full_name", "STRING", mode="REQUIRED")
with self.assertRaises(ValueError):
table.schema = [full_name, object()]
def test_schema_setter_valid_fields(self):
from google.cloud.bigquery.schema import SchemaField
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
full_name = SchemaField("full_name", "STRING", mode="REQUIRED")
age = SchemaField("age", "INTEGER", mode="REQUIRED")
table.schema = [full_name, age]
self.assertEqual(table.schema, [full_name, age])
def test_schema_setter_allows_unknown_properties(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
schema = [
{
"name": "full_name",
"type": "STRING",
"mode": "REQUIRED",
"someNewProperty": "test-value",
},
{
"name": "age",
# Note: This type should be included, too. Avoid client-side
# validation, as it could prevent backwards-compatible
# evolution of the server-side behavior.
"typo": "INTEGER",
"mode": "REQUIRED",
"anotherNewProperty": "another-test",
},
]
# Make sure the setter doesn't mutate schema.
expected_schema = copy.deepcopy(schema)
table.schema = schema
# _properties should include all fields, including unknown ones.
assert table._properties["schema"]["fields"] == expected_schema
def test_schema_setter_valid_mapping_representation(self):
from google.cloud.bigquery.schema import SchemaField
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
full_name = {"name": "full_name", "type": "STRING", "mode": "REQUIRED"}
job_status = {
"name": "is_employed",
"type": "STRUCT",
"mode": "NULLABLE",
"fields": [
{"name": "foo", "type": "DATE", "mode": "NULLABLE"},
{"name": "bar", "type": "BYTES", "mode": "REQUIRED"},
],
}
table.schema = [full_name, job_status]
expected_schema = [
SchemaField("full_name", "STRING", mode="REQUIRED"),
SchemaField(
"is_employed",
"STRUCT",
mode="NULLABLE",
fields=[
SchemaField("foo", "DATE", mode="NULLABLE"),
SchemaField("bar", "BYTES", mode="REQUIRED"),
],
),
]
self.assertEqual(table.schema, expected_schema)
def test_props_set_by_server(self):
import datetime
from google.cloud._helpers import UTC
from google.cloud._helpers import _millis
CREATED = datetime.datetime(2015, 7, 29, 12, 13, 22, tzinfo=UTC)
MODIFIED = datetime.datetime(2015, 7, 29, 14, 47, 15, tzinfo=UTC)
TABLE_FULL_ID = "%s:%s.%s" % (self.PROJECT, self.DS_ID, self.TABLE_NAME)
URL = "http://example.com/projects/%s/datasets/%s/tables/%s" % (
self.PROJECT,
self.DS_ID,
self.TABLE_NAME,
)
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table._properties["creationTime"] = _millis(CREATED)
table._properties["etag"] = "ETAG"
table._properties["lastModifiedTime"] = _millis(MODIFIED)
table._properties["numBytes"] = 12345
table._properties["numRows"] = 66
table._properties["selfLink"] = URL
table._properties["id"] = TABLE_FULL_ID
table._properties["type"] = "TABLE"
self.assertEqual(table.created, CREATED)
self.assertEqual(table.etag, "ETAG")
self.assertEqual(table.modified, MODIFIED)
self.assertEqual(table.num_bytes, 12345)
self.assertEqual(table.num_rows, 66)
self.assertEqual(table.self_link, URL)
self.assertEqual(table.full_table_id, TABLE_FULL_ID)
self.assertEqual(table.table_type, "TABLE")
def test_snapshot_definition_not_set(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
assert table.snapshot_definition is None
def test_snapshot_definition_set(self):
from google.cloud._helpers import UTC
from google.cloud.bigquery.table import SnapshotDefinition
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table._properties["snapshotDefinition"] = {
"baseTableReference": {
"projectId": "project_x",
"datasetId": "dataset_y",
"tableId": "table_z",
},
"snapshotTime": "2010-09-28T10:20:30.123Z",
}
snapshot = table.snapshot_definition
assert isinstance(snapshot, SnapshotDefinition)
assert snapshot.base_table_reference.path == (
"/projects/project_x/datasets/dataset_y/tables/table_z"
)
assert snapshot.snapshot_time == datetime.datetime(
2010, 9, 28, 10, 20, 30, 123000, tzinfo=UTC
)
def test_clone_definition_not_set(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
assert table.clone_definition is None
def test_clone_definition_set(self):
from google.cloud._helpers import UTC
from google.cloud.bigquery.table import CloneDefinition
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table._properties["cloneDefinition"] = {
"baseTableReference": {
"projectId": "project_x",
"datasetId": "dataset_y",
"tableId": "table_z",
},
"cloneTime": "2010-09-28T10:20:30.123Z",
}
clone = table.clone_definition
assert isinstance(clone, CloneDefinition)
assert clone.base_table_reference.path == (
"/projects/project_x/datasets/dataset_y/tables/table_z"
)
assert clone.clone_time == datetime.datetime(
2010, 9, 28, 10, 20, 30, 123000, tzinfo=UTC
)
def test_table_constraints_property_getter(self):
from google.cloud.bigquery.table import PrimaryKey, TableConstraints
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table._properties["tableConstraints"] = {
"primaryKey": {"columns": ["id"]},
}
table_constraints = table.table_constraints
assert isinstance(table_constraints, TableConstraints)
assert table_constraints.primary_key == PrimaryKey(columns=["id"])
def test_description_setter_bad_value(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(ValueError):
table.description = 12345
def test_description_setter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.description = "DESCRIPTION"
self.assertEqual(table.description, "DESCRIPTION")
def test_expires_setter_bad_value(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(ValueError):
table.expires = object()
def test_expires_setter(self):
import datetime
from google.cloud._helpers import UTC
WHEN = datetime.datetime(2015, 7, 28, 16, 39, tzinfo=UTC)
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.expires = WHEN
self.assertEqual(table.expires, WHEN)
def test_friendly_name_setter_bad_value(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(ValueError):
table.friendly_name = 12345
def test_friendly_name_setter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.friendly_name = "FRIENDLY"
self.assertEqual(table.friendly_name, "FRIENDLY")
def test_view_query_setter_bad_value(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(ValueError):
table.view_query = 12345
def test_view_query_setter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.view_query = "select * from foo"
self.assertEqual(table.view_query, "select * from foo")
self.assertEqual(table.view_use_legacy_sql, False)
table.view_use_legacy_sql = True
self.assertEqual(table.view_use_legacy_sql, True)
def test_view_query_deleter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.view_query = "select * from foo"
del table.view_query
self.assertIsNone(table.view_query)
self.assertIsNone(table.view_use_legacy_sql)
def test_view_use_legacy_sql_setter_bad_value(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
with self.assertRaises(ValueError):
table.view_use_legacy_sql = 12345
def test_view_use_legacy_sql_setter(self):
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.view_use_legacy_sql = True
table.view_query = "select * from foo"
self.assertEqual(table.view_use_legacy_sql, True)
self.assertEqual(table.view_query, "select * from foo")
def test_external_data_configuration_setter(self):
from google.cloud.bigquery.external_config import ExternalConfig
external_config = ExternalConfig("CSV")
dataset = DatasetReference(self.PROJECT, self.DS_ID)
table_ref = dataset.table(self.TABLE_NAME)
table = self._make_one(table_ref)
table.external_data_configuration = external_config
self.assertEqual(
table.external_data_configuration.source_format,
external_config.source_format,
)
def test_external_data_configuration_setter_none(self):