-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathtest_client.py
5357 lines (4687 loc) · 195 KB
/
test_client.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 decimal
import email
import gzip
import io
import json
import unittest
import warnings
import mock
import requests
import six
from six.moves import http_client
import pytest
import pytz
try:
import pandas
except (ImportError, AttributeError): # pragma: NO COVER
pandas = None
try:
import pyarrow
except (ImportError, AttributeError): # pragma: NO COVER
pyarrow = None
import google.api_core.exceptions
from google.api_core.gapic_v1 import client_info
import google.cloud._helpers
from tests.unit.helpers import make_connection
from google.cloud.bigquery.dataset import DatasetReference
def _make_credentials():
import google.auth.credentials
return mock.Mock(spec=google.auth.credentials.Credentials)
def _make_list_partitons_meta_info(project, dataset_id, table_id, num_rows=0):
return {
"tableReference": {
"projectId": project,
"datasetId": dataset_id,
"tableId": "{}$__PARTITIONS_SUMMARY__".format(table_id),
},
"schema": {
"fields": [
{"name": "project_id", "type": "STRING", "mode": "NULLABLE"},
{"name": "dataset_id", "type": "STRING", "mode": "NULLABLE"},
{"name": "table_id", "type": "STRING", "mode": "NULLABLE"},
{"name": "partition_id", "type": "STRING", "mode": "NULLABLE"},
]
},
"etag": "ETAG",
"numRows": num_rows,
}
class TestClient(unittest.TestCase):
PROJECT = "PROJECT"
DS_ID = "DATASET_ID"
TABLE_ID = "TABLE_ID"
MODEL_ID = "MODEL_ID"
TABLE_REF = DatasetReference(PROJECT, DS_ID).table(TABLE_ID)
KMS_KEY_NAME = "projects/1/locations/global/keyRings/1/cryptoKeys/1"
LOCATION = "us-central"
@staticmethod
def _get_target_class():
from google.cloud.bigquery.client import Client
return Client
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def _make_table_resource(self):
return {
"id": "%s:%s:%s" % (self.PROJECT, self.DS_ID, self.TABLE_ID),
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_ID,
},
}
def test_ctor_defaults(self):
from google.cloud.bigquery._http import Connection
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
self.assertIsInstance(client._connection, Connection)
self.assertIs(client._connection.credentials, creds)
self.assertIs(client._connection.http, http)
self.assertIsNone(client.location)
def test_ctor_w_location(self):
from google.cloud.bigquery._http import Connection
creds = _make_credentials()
http = object()
location = "us-central"
client = self._make_one(
project=self.PROJECT, credentials=creds, _http=http, location=location
)
self.assertIsInstance(client._connection, Connection)
self.assertIs(client._connection.credentials, creds)
self.assertIs(client._connection.http, http)
self.assertEqual(client.location, location)
def test_ctor_w_query_job_config(self):
from google.cloud.bigquery._http import Connection
from google.cloud.bigquery import QueryJobConfig
creds = _make_credentials()
http = object()
location = "us-central"
job_config = QueryJobConfig()
job_config.dry_run = True
client = self._make_one(
project=self.PROJECT,
credentials=creds,
_http=http,
location=location,
default_query_job_config=job_config,
)
self.assertIsInstance(client._connection, Connection)
self.assertIs(client._connection.credentials, creds)
self.assertIs(client._connection.http, http)
self.assertEqual(client.location, location)
self.assertIsInstance(client._default_query_job_config, QueryJobConfig)
self.assertTrue(client._default_query_job_config.dry_run)
def test__get_query_results_miss_w_explicit_project_and_timeout(self):
from google.cloud.exceptions import NotFound
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
conn = client._connection = make_connection()
with self.assertRaises(NotFound):
client._get_query_results(
"nothere",
None,
project="other-project",
location=self.LOCATION,
timeout_ms=500,
)
conn.api_request.assert_called_once_with(
method="GET",
path="/projects/other-project/queries/nothere",
query_params={"maxResults": 0, "timeoutMs": 500, "location": self.LOCATION},
)
def test__get_query_results_miss_w_client_location(self):
from google.cloud.exceptions import NotFound
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds, location=self.LOCATION)
conn = client._connection = make_connection()
with self.assertRaises(NotFound):
client._get_query_results("nothere", None)
conn.api_request.assert_called_once_with(
method="GET",
path="/projects/PROJECT/queries/nothere",
query_params={"maxResults": 0, "location": self.LOCATION},
)
def test__get_query_results_hit(self):
job_id = "query_job"
data = {
"kind": "bigquery#getQueryResultsResponse",
"etag": "some-tag",
"schema": {
"fields": [
{"name": "title", "type": "STRING", "mode": "NULLABLE"},
{"name": "unique_words", "type": "INTEGER", "mode": "NULLABLE"},
]
},
"jobReference": {"projectId": self.PROJECT, "jobId": job_id},
"totalRows": "10",
"totalBytesProcessed": "2464625",
"jobComplete": True,
"cacheHit": False,
}
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
client._connection = make_connection(data)
query_results = client._get_query_results(job_id, None)
self.assertEqual(query_results.total_rows, 10)
self.assertTrue(query_results.complete)
def test_get_service_account_email(self):
path = "/projects/%s/serviceAccount" % (self.PROJECT,)
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
email = "[email protected]"
resource = {"kind": "bigquery#getServiceAccountResponse", "email": email}
conn = client._connection = make_connection(resource)
service_account_email = client.get_service_account_email()
conn.api_request.assert_called_once_with(method="GET", path=path)
self.assertEqual(service_account_email, email)
def test_get_service_account_email_w_alternate_project(self):
project = "my-alternate-project"
path = "/projects/%s/serviceAccount" % (project,)
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
email = "[email protected]"
resource = {"kind": "bigquery#getServiceAccountResponse", "email": email}
conn = client._connection = make_connection(resource)
service_account_email = client.get_service_account_email(project=project)
conn.api_request.assert_called_once_with(method="GET", path=path)
self.assertEqual(service_account_email, email)
def test_list_projects_defaults(self):
from google.cloud.bigquery.client import Project
PROJECT_1 = "PROJECT_ONE"
PROJECT_2 = "PROJECT_TWO"
TOKEN = "TOKEN"
DATA = {
"nextPageToken": TOKEN,
"projects": [
{
"kind": "bigquery#project",
"id": PROJECT_1,
"numericId": 1,
"projectReference": {"projectId": PROJECT_1},
"friendlyName": "One",
},
{
"kind": "bigquery#project",
"id": PROJECT_2,
"numericId": 2,
"projectReference": {"projectId": PROJECT_2},
"friendlyName": "Two",
},
],
}
creds = _make_credentials()
client = self._make_one(PROJECT_1, creds)
conn = client._connection = make_connection(DATA)
iterator = client.list_projects()
page = six.next(iterator.pages)
projects = list(page)
token = iterator.next_page_token
self.assertEqual(len(projects), len(DATA["projects"]))
for found, expected in zip(projects, DATA["projects"]):
self.assertIsInstance(found, Project)
self.assertEqual(found.project_id, expected["id"])
self.assertEqual(found.numeric_id, expected["numericId"])
self.assertEqual(found.friendly_name, expected["friendlyName"])
self.assertEqual(token, TOKEN)
conn.api_request.assert_called_once_with(
method="GET", path="/projects", query_params={}
)
def test_list_projects_explicit_response_missing_projects_key(self):
TOKEN = "TOKEN"
DATA = {}
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
conn = client._connection = make_connection(DATA)
iterator = client.list_projects(max_results=3, page_token=TOKEN)
page = six.next(iterator.pages)
projects = list(page)
token = iterator.next_page_token
self.assertEqual(len(projects), 0)
self.assertIsNone(token)
conn.api_request.assert_called_once_with(
method="GET",
path="/projects",
query_params={"maxResults": 3, "pageToken": TOKEN},
)
def test_list_datasets_defaults(self):
from google.cloud.bigquery.dataset import DatasetListItem
DATASET_1 = "dataset_one"
DATASET_2 = "dataset_two"
PATH = "projects/%s/datasets" % self.PROJECT
TOKEN = "TOKEN"
DATA = {
"nextPageToken": TOKEN,
"datasets": [
{
"kind": "bigquery#dataset",
"id": "%s:%s" % (self.PROJECT, DATASET_1),
"datasetReference": {
"datasetId": DATASET_1,
"projectId": self.PROJECT,
},
"friendlyName": None,
},
{
"kind": "bigquery#dataset",
"id": "%s:%s" % (self.PROJECT, DATASET_2),
"datasetReference": {
"datasetId": DATASET_2,
"projectId": self.PROJECT,
},
"friendlyName": "Two",
},
],
}
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
conn = client._connection = make_connection(DATA)
iterator = client.list_datasets()
page = six.next(iterator.pages)
datasets = list(page)
token = iterator.next_page_token
self.assertEqual(len(datasets), len(DATA["datasets"]))
for found, expected in zip(datasets, DATA["datasets"]):
self.assertIsInstance(found, DatasetListItem)
self.assertEqual(found.full_dataset_id, expected["id"])
self.assertEqual(found.friendly_name, expected["friendlyName"])
self.assertEqual(token, TOKEN)
conn.api_request.assert_called_once_with(
method="GET", path="/%s" % PATH, query_params={}
)
def test_list_datasets_w_project(self):
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
conn = client._connection = make_connection({})
list(client.list_datasets(project="other-project"))
conn.api_request.assert_called_once_with(
method="GET", path="/projects/other-project/datasets", query_params={}
)
def test_list_datasets_explicit_response_missing_datasets_key(self):
PATH = "projects/%s/datasets" % self.PROJECT
TOKEN = "TOKEN"
FILTER = "FILTER"
DATA = {}
creds = _make_credentials()
client = self._make_one(self.PROJECT, creds)
conn = client._connection = make_connection(DATA)
iterator = client.list_datasets(
include_all=True, filter=FILTER, max_results=3, page_token=TOKEN
)
page = six.next(iterator.pages)
datasets = list(page)
token = iterator.next_page_token
self.assertEqual(len(datasets), 0)
self.assertIsNone(token)
conn.api_request.assert_called_once_with(
method="GET",
path="/%s" % PATH,
query_params={
"all": True,
"filter": FILTER,
"maxResults": 3,
"pageToken": TOKEN,
},
)
def test_dataset_with_specified_project(self):
from google.cloud.bigquery.dataset import DatasetReference
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
dataset = client.dataset(self.DS_ID, self.PROJECT)
self.assertIsInstance(dataset, DatasetReference)
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
def test_dataset_with_default_project(self):
from google.cloud.bigquery.dataset import DatasetReference
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
dataset = client.dataset(self.DS_ID)
self.assertIsInstance(dataset, DatasetReference)
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
def test_get_dataset(self):
from google.cloud.exceptions import ServerError
path = "projects/%s/datasets/%s" % (self.PROJECT, self.DS_ID)
creds = _make_credentials()
http = object()
client = self._make_one(project=self.PROJECT, credentials=creds, _http=http)
resource = {
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
}
conn = client._connection = make_connection(resource)
dataset_ref = client.dataset(self.DS_ID)
dataset = client.get_dataset(dataset_ref)
conn.api_request.assert_called_once_with(method="GET", path="/%s" % path)
self.assertEqual(dataset.dataset_id, self.DS_ID)
# Test retry.
# Not a cloud API exception (missing 'errors' field).
client._connection = make_connection(Exception(""), resource)
with self.assertRaises(Exception):
client.get_dataset(dataset_ref)
# Zero-length errors field.
client._connection = make_connection(ServerError(""), resource)
with self.assertRaises(ServerError):
client.get_dataset(dataset_ref)
# Non-retryable reason.
client._connection = make_connection(
ServerError("", errors=[{"reason": "serious"}]), resource
)
with self.assertRaises(ServerError):
client.get_dataset(dataset_ref)
# Retryable reason, but retry is disabled.
client._connection = make_connection(
ServerError("", errors=[{"reason": "backendError"}]), resource
)
with self.assertRaises(ServerError):
client.get_dataset(dataset_ref, retry=None)
# Retryable reason, default retry: success.
client._connection = make_connection(
ServerError("", errors=[{"reason": "backendError"}]), resource
)
dataset = client.get_dataset(
# Test with a string for dataset ID.
dataset_ref.dataset_id
)
self.assertEqual(dataset.dataset_id, self.DS_ID)
def test_create_dataset_minimal(self):
from google.cloud.bigquery.dataset import Dataset
PATH = "projects/%s/datasets" % self.PROJECT
RESOURCE = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
}
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
conn = client._connection = make_connection(RESOURCE)
ds_ref = client.dataset(self.DS_ID)
before = Dataset(ds_ref)
after = client.create_dataset(before)
self.assertEqual(after.dataset_id, self.DS_ID)
self.assertEqual(after.project, self.PROJECT)
self.assertEqual(after.etag, RESOURCE["etag"])
self.assertEqual(after.full_dataset_id, RESOURCE["id"])
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % PATH,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
},
)
def test_create_dataset_w_attrs(self):
from google.cloud.bigquery.dataset import Dataset, AccessEntry
PATH = "projects/%s/datasets" % self.PROJECT
DESCRIPTION = "DESC"
FRIENDLY_NAME = "FN"
LOCATION = "US"
USER_EMAIL = "[email protected]"
LABELS = {"color": "red"}
VIEW = {
"projectId": "my-proj",
"datasetId": "starry-skies",
"tableId": "northern-hemisphere",
}
RESOURCE = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"description": DESCRIPTION,
"friendlyName": FRIENDLY_NAME,
"location": LOCATION,
"defaultTableExpirationMs": "3600",
"labels": LABELS,
"access": [{"role": "OWNER", "userByEmail": USER_EMAIL}, {"view": VIEW}],
}
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
conn = client._connection = make_connection(RESOURCE)
entries = [
AccessEntry("OWNER", "userByEmail", USER_EMAIL),
AccessEntry(None, "view", VIEW),
]
ds_ref = client.dataset(self.DS_ID)
before = Dataset(ds_ref)
before.access_entries = entries
before.description = DESCRIPTION
before.friendly_name = FRIENDLY_NAME
before.default_table_expiration_ms = 3600
before.location = LOCATION
before.labels = LABELS
after = client.create_dataset(before)
self.assertEqual(after.dataset_id, self.DS_ID)
self.assertEqual(after.project, self.PROJECT)
self.assertEqual(after.etag, RESOURCE["etag"])
self.assertEqual(after.full_dataset_id, RESOURCE["id"])
self.assertEqual(after.description, DESCRIPTION)
self.assertEqual(after.friendly_name, FRIENDLY_NAME)
self.assertEqual(after.location, LOCATION)
self.assertEqual(after.default_table_expiration_ms, 3600)
self.assertEqual(after.labels, LABELS)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % PATH,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"description": DESCRIPTION,
"friendlyName": FRIENDLY_NAME,
"location": LOCATION,
"defaultTableExpirationMs": "3600",
"access": [
{"role": "OWNER", "userByEmail": USER_EMAIL},
{"view": VIEW},
],
"labels": LABELS,
},
)
def test_create_dataset_w_custom_property(self):
# The library should handle sending properties to the API that are not
# yet part of the library
from google.cloud.bigquery.dataset import Dataset
path = "/projects/%s/datasets" % self.PROJECT
resource = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"newAlphaProperty": "unreleased property",
}
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
conn = client._connection = make_connection(resource)
ds_ref = client.dataset(self.DS_ID)
before = Dataset(ds_ref)
before._properties["newAlphaProperty"] = "unreleased property"
after = client.create_dataset(before)
self.assertEqual(after.dataset_id, self.DS_ID)
self.assertEqual(after.project, self.PROJECT)
self.assertEqual(after._properties["newAlphaProperty"], "unreleased property")
conn.api_request.assert_called_once_with(
method="POST",
path=path,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"newAlphaProperty": "unreleased property",
"labels": {},
},
)
def test_create_dataset_w_client_location_wo_dataset_location(self):
from google.cloud.bigquery.dataset import Dataset
PATH = "projects/%s/datasets" % self.PROJECT
RESOURCE = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"location": self.LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(RESOURCE)
ds_ref = client.dataset(self.DS_ID)
before = Dataset(ds_ref)
after = client.create_dataset(before)
self.assertEqual(after.dataset_id, self.DS_ID)
self.assertEqual(after.project, self.PROJECT)
self.assertEqual(after.etag, RESOURCE["etag"])
self.assertEqual(after.full_dataset_id, RESOURCE["id"])
self.assertEqual(after.location, self.LOCATION)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % PATH,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": self.LOCATION,
},
)
def test_create_dataset_w_client_location_w_dataset_location(self):
from google.cloud.bigquery.dataset import Dataset
PATH = "projects/%s/datasets" % self.PROJECT
OTHER_LOCATION = "EU"
RESOURCE = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"location": OTHER_LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(RESOURCE)
ds_ref = client.dataset(self.DS_ID)
before = Dataset(ds_ref)
before.location = OTHER_LOCATION
after = client.create_dataset(before)
self.assertEqual(after.dataset_id, self.DS_ID)
self.assertEqual(after.project, self.PROJECT)
self.assertEqual(after.etag, RESOURCE["etag"])
self.assertEqual(after.full_dataset_id, RESOURCE["id"])
self.assertEqual(after.location, OTHER_LOCATION)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % PATH,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": OTHER_LOCATION,
},
)
def test_create_dataset_w_reference(self):
path = "/projects/%s/datasets" % self.PROJECT
resource = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"location": self.LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(resource)
dataset = client.create_dataset(client.dataset(self.DS_ID))
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
self.assertEqual(dataset.etag, resource["etag"])
self.assertEqual(dataset.full_dataset_id, resource["id"])
self.assertEqual(dataset.location, self.LOCATION)
conn.api_request.assert_called_once_with(
method="POST",
path=path,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": self.LOCATION,
},
)
def test_create_dataset_w_fully_qualified_string(self):
path = "/projects/%s/datasets" % self.PROJECT
resource = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"location": self.LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(resource)
dataset = client.create_dataset("{}.{}".format(self.PROJECT, self.DS_ID))
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
self.assertEqual(dataset.etag, resource["etag"])
self.assertEqual(dataset.full_dataset_id, resource["id"])
self.assertEqual(dataset.location, self.LOCATION)
conn.api_request.assert_called_once_with(
method="POST",
path=path,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": self.LOCATION,
},
)
def test_create_dataset_w_string(self):
path = "/projects/%s/datasets" % self.PROJECT
resource = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "%s:%s" % (self.PROJECT, self.DS_ID),
"location": self.LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(resource)
dataset = client.create_dataset(self.DS_ID)
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
self.assertEqual(dataset.etag, resource["etag"])
self.assertEqual(dataset.full_dataset_id, resource["id"])
self.assertEqual(dataset.location, self.LOCATION)
conn.api_request.assert_called_once_with(
method="POST",
path=path,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": self.LOCATION,
},
)
def test_create_dataset_alreadyexists_w_exists_ok_false(self):
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
client._connection = make_connection(
google.api_core.exceptions.AlreadyExists("dataset already exists")
)
with pytest.raises(google.api_core.exceptions.AlreadyExists):
client.create_dataset(self.DS_ID)
def test_create_dataset_alreadyexists_w_exists_ok_true(self):
post_path = "/projects/{}/datasets".format(self.PROJECT)
get_path = "/projects/{}/datasets/{}".format(self.PROJECT, self.DS_ID)
resource = {
"datasetReference": {"projectId": self.PROJECT, "datasetId": self.DS_ID},
"etag": "etag",
"id": "{}:{}".format(self.PROJECT, self.DS_ID),
"location": self.LOCATION,
}
creds = _make_credentials()
client = self._make_one(
project=self.PROJECT, credentials=creds, location=self.LOCATION
)
conn = client._connection = make_connection(
google.api_core.exceptions.AlreadyExists("dataset already exists"), resource
)
dataset = client.create_dataset(self.DS_ID, exists_ok=True)
self.assertEqual(dataset.dataset_id, self.DS_ID)
self.assertEqual(dataset.project, self.PROJECT)
self.assertEqual(dataset.etag, resource["etag"])
self.assertEqual(dataset.full_dataset_id, resource["id"])
self.assertEqual(dataset.location, self.LOCATION)
conn.api_request.assert_has_calls(
[
mock.call(
method="POST",
path=post_path,
data={
"datasetReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
},
"labels": {},
"location": self.LOCATION,
},
),
mock.call(method="GET", path=get_path),
]
)
def test_create_table_w_day_partition(self):
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TimePartitioning
path = "projects/%s/datasets/%s/tables" % (self.PROJECT, self.DS_ID)
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
resource = self._make_table_resource()
conn = client._connection = make_connection(resource)
table = Table(self.TABLE_REF)
table.time_partitioning = TimePartitioning()
got = client.create_table(table)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % path,
data={
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_ID,
},
"timePartitioning": {"type": "DAY"},
"labels": {},
},
)
self.assertEqual(table.time_partitioning.type_, "DAY")
self.assertEqual(got.table_id, self.TABLE_ID)
def test_create_table_w_custom_property(self):
# The library should handle sending properties to the API that are not
# yet part of the library
from google.cloud.bigquery.table import Table
path = "projects/%s/datasets/%s/tables" % (self.PROJECT, self.DS_ID)
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
resource = self._make_table_resource()
resource["newAlphaProperty"] = "unreleased property"
conn = client._connection = make_connection(resource)
table = Table(self.TABLE_REF)
table._properties["newAlphaProperty"] = "unreleased property"
got = client.create_table(table)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % path,
data={
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_ID,
},
"newAlphaProperty": "unreleased property",
"labels": {},
},
)
self.assertEqual(got._properties["newAlphaProperty"], "unreleased property")
self.assertEqual(got.table_id, self.TABLE_ID)
def test_create_table_w_encryption_configuration(self):
from google.cloud.bigquery.table import EncryptionConfiguration
from google.cloud.bigquery.table import Table
path = "projects/%s/datasets/%s/tables" % (self.PROJECT, self.DS_ID)
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
resource = self._make_table_resource()
conn = client._connection = make_connection(resource)
table = Table(self.TABLE_REF)
table.encryption_configuration = EncryptionConfiguration(
kms_key_name=self.KMS_KEY_NAME
)
got = client.create_table(table)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % path,
data={
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_ID,
},
"labels": {},
"encryptionConfiguration": {"kmsKeyName": self.KMS_KEY_NAME},
},
)
self.assertEqual(got.table_id, self.TABLE_ID)
def test_create_table_w_day_partition_and_expire(self):
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TimePartitioning
path = "projects/%s/datasets/%s/tables" % (self.PROJECT, self.DS_ID)
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
resource = self._make_table_resource()
conn = client._connection = make_connection(resource)
table = Table(self.TABLE_REF)
table.time_partitioning = TimePartitioning(expiration_ms=100)
got = client.create_table(table)
conn.api_request.assert_called_once_with(
method="POST",
path="/%s" % path,
data={
"tableReference": {
"projectId": self.PROJECT,
"datasetId": self.DS_ID,
"tableId": self.TABLE_ID,
},
"timePartitioning": {"type": "DAY", "expirationMs": "100"},
"labels": {},
},
)
self.assertEqual(table.time_partitioning.type_, "DAY")
self.assertEqual(table.time_partitioning.expiration_ms, 100)
self.assertEqual(got.table_id, self.TABLE_ID)
def test_create_table_w_schema_and_query(self):
from google.cloud.bigquery.table import Table, SchemaField
path = "projects/%s/datasets/%s/tables" % (self.PROJECT, self.DS_ID)
query = "SELECT * from %s:%s" % (self.DS_ID, self.TABLE_ID)
creds = _make_credentials()
client = self._make_one(project=self.PROJECT, credentials=creds)
resource = self._make_table_resource()