forked from tylertreat/BigQuery-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
2902 lines (2284 loc) · 102 KB
/
test_client.py
File metadata and controls
2902 lines (2284 loc) · 102 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
import unittest
import mock
import six
from bigquery import client
from bigquery.errors import (
JobInsertException, JobExecutingException,
BigQueryTimeoutException
)
from googleapiclient.errors import HttpError
from nose.tools import raises
class HttpResponse(object):
def __init__(self, status, reason='There was an error'):
"""
Args:
:param int status: Integer HTTP response status
"""
self.status = status
self.reason = reason
class TestGetClient(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.mock_bq_service = mock.Mock()
self.mock_job_collection = mock.Mock()
self.mock_bq_service.jobs.return_value = self.mock_job_collection
self.client = client.BigQueryClient(self.mock_bq_service, 'project')
def test_no_credentials(self):
"""Ensure an Exception is raised when no credentials are provided."""
self.assertRaises(AssertionError, client.get_client, 'foo')
@mock.patch('bigquery.client._credentials')
@mock.patch('bigquery.client.build')
def test_initialize_readonly(self, mock_build, mock_return_cred):
"""Ensure that a BigQueryClient is initialized and returned with
read-only permissions.
"""
from bigquery.client import BIGQUERY_SCOPE_READ_ONLY
mock_cred = mock.Mock()
mock_http = mock.Mock()
mock_service_url = mock.Mock()
mock_cred.from_p12_keyfile_buffer.return_value.authorize.return_value = mock_http
mock_bq = mock.Mock()
mock_build.return_value = mock_bq
key = 'key'
service_account = 'account'
project_id = 'project'
mock_return_cred.return_value = mock_cred
bq_client = client.get_client(
project_id, service_url=mock_service_url,
service_account=service_account, private_key=key,
readonly=True)
mock_return_cred.assert_called_once_with()
mock_cred.from_p12_keyfile_buffer.assert_called_once_with(
service_account, mock.ANY,
scopes=BIGQUERY_SCOPE_READ_ONLY)
self.assertTrue(
mock_cred.from_p12_keyfile_buffer.return_value.authorize.called)
mock_build.assert_called_once_with('bigquery', 'v2', http=mock_http,
discoveryServiceUrl=mock_service_url)
self.assertEquals(mock_bq, bq_client.bigquery)
self.assertEquals(project_id, bq_client.project_id)
@mock.patch('bigquery.client._credentials')
@mock.patch('bigquery.client.build')
def test_initialize_read_write(self, mock_build, mock_return_cred):
"""Ensure that a BigQueryClient is initialized and returned with
read/write permissions.
"""
from bigquery.client import BIGQUERY_SCOPE
mock_cred = mock.Mock()
mock_http = mock.Mock()
mock_service_url = mock.Mock()
mock_cred.from_p12_keyfile_buffer.return_value.authorize.return_value = mock_http
mock_bq = mock.Mock()
mock_build.return_value = mock_bq
key = 'key'
service_account = 'account'
project_id = 'project'
mock_return_cred.return_value = mock_cred
bq_client = client.get_client(
project_id, service_url=mock_service_url,
service_account=service_account, private_key=key,
readonly=False)
mock_return_cred.assert_called_once_with()
mock_cred.from_p12_keyfile_buffer.assert_called_once_with(
service_account, mock.ANY, scopes=BIGQUERY_SCOPE)
self.assertTrue(
mock_cred.from_p12_keyfile_buffer.return_value.authorize.called)
mock_build.assert_called_once_with('bigquery', 'v2', http=mock_http,
discoveryServiceUrl=mock_service_url)
self.assertEquals(mock_bq, bq_client.bigquery)
self.assertEquals(project_id, bq_client.project_id)
@mock.patch('bigquery.client._credentials')
@mock.patch('bigquery.client.build')
def test_initialize_key_file(self, mock_build, mock_return_cred):
"""Ensure that a BigQueryClient is initialized and returned with
read/write permissions using a private key file.
"""
from bigquery.client import BIGQUERY_SCOPE
mock_cred = mock.Mock()
mock_http = mock.Mock()
mock_service_url = mock.Mock()
mock_cred.from_p12_keyfile.return_value.authorize.return_value = mock_http
mock_bq = mock.Mock()
mock_build.return_value = mock_bq
key_file = 'key.pem'
service_account = 'account'
project_id = 'project'
mock_return_cred.return_value = mock_cred
bq_client = client.get_client(
project_id, service_url=mock_service_url,
service_account=service_account,
private_key_file=key_file, readonly=False)
mock_return_cred.assert_called_once_with()
mock_cred.from_p12_keyfile.assert_called_once_with(service_account,
key_file,
scopes=BIGQUERY_SCOPE)
self.assertTrue(
mock_cred.from_p12_keyfile.return_value.authorize.called)
mock_build.assert_called_once_with('bigquery', 'v2', http=mock_http,
discoveryServiceUrl=mock_service_url)
self.assertEquals(mock_bq, bq_client.bigquery)
self.assertEquals(project_id, bq_client.project_id)
@mock.patch('bigquery.client._credentials')
@mock.patch('bigquery.client.build')
@mock.patch('__builtin__.open' if six.PY2 else 'builtins.open')
def test_initialize_json_key_file(self, mock_open, mock_build, mock_return_cred):
"""Ensure that a BigQueryClient is initialized and returned with
read/write permissions using a JSON key file.
"""
from bigquery.client import BIGQUERY_SCOPE
import json
mock_cred = mock.Mock()
mock_http = mock.Mock()
mock_service_url = mock.Mock()
mock_cred.from_json_keyfile_dict.return_value.authorize.return_value = mock_http
mock_bq = mock.Mock()
mock_build.return_value = mock_bq
json_key_file = 'key.json'
json_key = {'client_email': 'mail', 'private_key': 'pkey'}
mock_open.return_value.__enter__.return_value.read.return_value = json.dumps(json_key)
project_id = 'project'
mock_return_cred.return_value = mock_cred
bq_client = client.get_client(
project_id, service_url=mock_service_url,
json_key_file=json_key_file, readonly=False)
mock_return_cred.assert_called_once_with()
mock_cred.from_json_keyfile_dict.assert_called_once_with(json_key,
scopes=BIGQUERY_SCOPE)
self.assertTrue(
mock_cred.from_json_keyfile_dict.return_value.authorize.called)
mock_build.assert_called_once_with('bigquery', 'v2', http=mock_http,
discoveryServiceUrl=mock_service_url)
self.assertEquals(mock_bq, bq_client.bigquery)
self.assertEquals(project_id, bq_client.project_id)
@mock.patch('bigquery.client._credentials')
@mock.patch('bigquery.client.build')
@mock.patch('__builtin__.open' if six.PY2 else 'builtins.open')
def test_initialize_json_key_file_without_project_id(self, mock_open, mock_build,
mock_return_cred):
"""Ensure that a BigQueryClient is initialized and returned with
read/write permissions using a JSON key file without project_id.
"""
from bigquery.client import BIGQUERY_SCOPE
import json
mock_cred = mock.Mock()
mock_http = mock.Mock()
mock_service_url = mock.Mock()
mock_cred.from_json_keyfile_dict.return_value.authorize.return_value = mock_http
mock_bq = mock.Mock()
mock_build.return_value = mock_bq
json_key_file = 'key.json'
json_key = {'client_email': 'mail', 'private_key': 'pkey', 'project_id': 'project'}
mock_open.return_value.__enter__.return_value.read.return_value = json.dumps(json_key)
mock_return_cred.return_value = mock_cred
bq_client = client.get_client(
service_url=mock_service_url, json_key_file=json_key_file, readonly=False)
mock_open.assert_called_once_with(json_key_file, 'r')
mock_return_cred.assert_called_once_with()
mock_cred.from_json_keyfile_dict.assert_called_once_with(json_key,
scopes=BIGQUERY_SCOPE)
self.assertTrue(
mock_cred.from_json_keyfile_dict.return_value.authorize.called)
mock_build.assert_called_once_with('bigquery', 'v2', http=mock_http,
discoveryServiceUrl=mock_service_url)
self.assertEquals(mock_bq, bq_client.bigquery)
self.assertEquals(json_key['project_id'], bq_client.project_id)
class TestGetProjectIds(unittest.TestCase):
def test_get_project_ids(self):
mock_bq_service = mock.Mock()
mock_bq_service.projects().list().execute.return_value = {
'kind': 'bigquery#projectList',
'projects': [
{
'friendlyName': 'Big Query Test',
'id': 'big-query-test',
'kind': 'bigquery#project',
'numericId': '1435372465',
'projectReference': {'projectId': 'big-query-test'}
},
{
'friendlyName': 'BQ Company project',
'id': 'bq-project',
'kind': 'bigquery#project',
'numericId': '4263574685796',
'projectReference': {'projectId': 'bq-project'}
}
],
'totalItems': 2
}
projects = client.get_projects(mock_bq_service)
expected_projects_data = [
{'id': 'big-query-test', 'name': 'Big Query Test'},
{'id': 'bq-project', 'name': 'BQ Company project'}
]
self.assertEqual(projects, expected_projects_data)
class TestQuery(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.mock_bq_service = mock.Mock()
self.mock_job_collection = mock.Mock()
self.mock_bq_service.jobs.return_value = self.mock_job_collection
self.query = 'foo'
self.project_id = 'project'
self.external_udf_uris = ['gs://bucket/external_udf.js']
self.client = client.BigQueryClient(self.mock_bq_service,
self.project_id)
def test_query(self):
"""Ensure that we retrieve the job id from the query."""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': True
}
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query(self.query, external_udf_uris=self.external_udf_uris)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={
'query': self.query,
'userDefinedFunctionResources': [ {'resourceUri': u} for u in self.external_udf_uris ],
'timeoutMs': 0,
'dryRun': False,
'maxResults': None
}
)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [])
def test_query_max_results_set(self):
"""Ensure that we retrieve the job id from the query and the maxResults
parameter is set.
"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': True,
}
self.mock_job_collection.query.return_value = mock_query_job
max_results = 10
job_id, results = self.client.query(self.query,
max_results=max_results)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': self.query, 'timeoutMs': 0,
'maxResults': max_results, 'dryRun': False}
)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [])
def test_query_timeout_set(self):
"""Ensure that we retrieve the job id from the query and the timeoutMs
parameter is set correctly.
"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': True,
}
self.mock_job_collection.query.return_value = mock_query_job
timeout = 5
job_id, results = self.client.query(self.query, timeout=timeout)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': self.query, 'timeoutMs': timeout * 1000,
'dryRun': False, 'maxResults': None}
)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [])
def test_sync_query_timeout(self):
"""Ensure that exception is raise on timeout for synchronous query"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': False,
}
self.mock_job_collection.query.return_value = mock_query_job
timeout = 5
self.assertRaises(BigQueryTimeoutException, self.client.query,
self.query, None, timeout)
def test_async_query_timeout(self):
"""Ensure that exception is not raise on timeout
for asynchronous query"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': False,
}
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query(self.query)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [])
def test_query_dry_run_valid(self):
"""Ensure that None and an empty list is returned from the query when
dry_run is True and the query is valid.
"""
mock_query_job = mock.Mock()
mock_query_job.execute.return_value = {'jobReference': {},
'jobComplete': True}
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query(self.query, dry_run=True)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': self.query, 'timeoutMs': 0, 'maxResults': None,
'dryRun': True}
)
self.assertIsNone(job_id)
self.assertEqual([], results)
def test_query_dry_run_invalid(self):
"""Ensure that None and a dict is returned from the query when dry_run
is True and the query is invalid.
"""
mock_query_job = mock.Mock()
mock_query_job.execute.side_effect = HttpError(
'crap', '{"message": "Bad query"}'.encode('utf8'))
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query('%s blah' % self.query,
dry_run=True)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': '%s blah' % self.query, 'timeoutMs': 0,
'maxResults': None,
'dryRun': True}
)
self.assertIsNone(job_id)
self.assertEqual({'message': 'Bad query'}, results)
def test_query_with_results(self):
"""Ensure that we retrieve the job id from the query and results if
they are available.
"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'schema': {'fields': [{'name': 'foo', 'type': 'INTEGER'}]},
'rows': [{'f': [{'v': 10}]}],
'jobComplete': True,
}
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query(self.query)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': self.query, 'timeoutMs': 0, 'dryRun': False,
'maxResults': None}
)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [{'foo': 10}])
def test_query_with_using_legacy_sql(self):
"""Ensure that use_legacy_sql bool gets used"""
mock_query_job = mock.Mock()
expected_job_id = 'spiderman'
expected_job_ref = {'jobId': expected_job_id}
mock_query_job.execute.return_value = {
'jobReference': expected_job_ref,
'jobComplete': True
}
self.mock_job_collection.query.return_value = mock_query_job
job_id, results = self.client.query(self.query, use_legacy_sql=False)
self.mock_job_collection.query.assert_called_once_with(
projectId=self.project_id,
body={'query': self.query, 'timeoutMs': 0, 'dryRun': False,
'maxResults': None, 'useLegacySql': False}
)
self.assertEquals(job_id, 'spiderman')
self.assertEquals(results, [])
class TestGetQueryResults(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.mock_bq_service = mock.Mock()
self.mock_job_collection = mock.Mock()
self.mock_bq_service.jobs.return_value = self.mock_job_collection
self.project_id = 'project'
self.client = client.BigQueryClient(self.mock_bq_service,
self.project_id)
def test_get_response(self):
"""Ensure that the query is executed and the query reply is returned.
"""
job_id = 'bar'
mock_query_job = mock.Mock()
mock_query_reply = mock.Mock()
mock_query_job.execute.return_value = mock_query_reply
self.mock_job_collection.getQueryResults.return_value = mock_query_job
offset = 5
limit = 10
page_token = "token"
timeout = 1
actual = self.client.get_query_results(job_id, offset, limit,
page_token, timeout)
self.mock_job_collection.getQueryResults.assert_called_once_with(
projectId=self.project_id, jobId=job_id, startIndex=offset,
maxResults=limit, pageToken=page_token, timeoutMs=1000)
mock_query_job.execute.assert_called_once_with()
self.assertEquals(actual, mock_query_reply)
class TestTransformRow(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.mock_bq_service = mock.Mock()
self.mock_job_collection = mock.Mock()
self.mock_bq_service.jobs.return_value = self.mock_job_collection
self.project_id = 'project'
self.client = client.BigQueryClient(self.mock_bq_service,
self.project_id)
def test_transform_row(self):
"""Ensure that the row dict is correctly transformed to a log dict."""
schema = [{'name': 'foo', 'type': 'INTEGER'},
{'name': 'bar', 'type': 'FLOAT'},
{'name': 'baz', 'type': 'STRING'},
{'name': 'qux', 'type': 'BOOLEAN'},
{'name': 'timestamp', 'type': 'TIMESTAMP'}]
row = {'f': [{'v': '42'}, {'v': None}, {'v': 'batman'},
{'v': 'True'}, {'v': '1.371145650319132E9'}]}
expected = {'foo': 42, 'bar': None, 'baz': 'batman', 'qux': True,
'timestamp': 1371145650.319132}
actual = self.client._transform_row(row, schema)
self.assertEquals(actual, expected)
def test_transform_row_with_nested(self):
"""Ensure that the row dict with nested records is correctly
transformed to a log dict.
"""
schema = [{'name': 'foo', 'type': 'INTEGER'},
{'name': 'bar', 'type': 'FLOAT'},
{'name': 'baz', 'type': 'STRING'},
{'name': 'qux', 'type': 'RECORD', 'mode': 'SINGLE',
'fields': [{'name': 'foobar', 'type': 'INTEGER'},
{'name': 'bazqux', 'type': 'STRING'}]}]
row = {'f': [{'v': '42'}, {'v': '36.98'}, {'v': 'batman'},
{'v': {'f': [{'v': '120'}, {'v': 'robin'}]}}]}
expected = {'foo': 42, 'bar': 36.98, 'baz': 'batman',
'qux': {'foobar': 120, 'bazqux': 'robin'}}
actual = self.client._transform_row(row, schema)
self.assertEquals(actual, expected)
def test_transform_row_with_nested_repeated(self):
"""Ensure that the row dict with nested repeated records is correctly
transformed to a log dict.
"""
schema = [{'name': 'foo', 'type': 'INTEGER'},
{'name': 'bar', 'type': 'FLOAT'},
{'name': 'baz', 'type': 'STRING'},
{'name': 'qux', 'type': 'RECORD', 'mode': 'REPEATED',
'fields': [{'name': 'foobar', 'type': 'INTEGER'},
{'name': 'bazqux', 'type': 'STRING'}]}]
row = {'f': [{'v': '42'}, {'v': '36.98'}, {'v': 'batman'},
{'v': [{'v': {'f': [{'v': '120'}, {'v': 'robin'}]}},
{'v': {'f': [{'v': '300'}, {'v': 'joker'}]}}]}]}
expected = {'foo': 42, 'bar': 36.98, 'baz': 'batman',
'qux': [{'foobar': 120, 'bazqux': 'robin'},
{'foobar': 300, 'bazqux': 'joker'}]}
actual = self.client._transform_row(row, schema)
self.assertEquals(actual, expected)
@mock.patch('bigquery.client.BigQueryClient.get_query_results')
class TestCheckJob(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.project_id = 'project'
self.client = client.BigQueryClient(mock.Mock(), self.project_id)
def test_job_incomplete(self, mock_exec):
"""Ensure that we return None if the job is not yet complete."""
mock_exec.return_value = {'jobComplete': False}
is_completed, total_rows = self.client.check_job(1)
self.assertFalse(is_completed)
self.assertEquals(total_rows, 0)
def test_query_complete(self, mock_exec):
"""Ensure that we can handle a normal query result."""
mock_exec.return_value = {
'jobComplete': True,
'rows': [
{'f': [{'v': 'bar'}, {'v': 'man'}]},
{'f': [{'v': 'abc'}, {'v': 'xyz'}]}
],
'schema': {
'fields': [
{'name': 'foo', 'type': 'STRING'},
{'name': 'spider', 'type': 'STRING'}
]
},
'totalRows': '2'
}
is_completed, total_rows = self.client.check_job(1)
self.assertTrue(is_completed)
self.assertEquals(total_rows, 2)
class TestWaitForJob(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.project_id = 'project'
self.api_mock = mock.Mock()
self.client = client.BigQueryClient(self.api_mock, self.project_id)
def test_completed_jobs(self):
"""Ensure we can detect completed jobs"""
return_values = [{'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}},
{'status': {'state': 'DONE'},
'jobReference': {'jobId': "testJob"}}]
def side_effect(*args, **kwargs):
return return_values.pop(0)
self.api_mock.jobs().get().execute.side_effect = side_effect
job_resource = self.client.wait_for_job(
{'jobReference': {'jobId': "testJob"},
'status': {'state': 'RUNNING'}},
interval=.01,
timeout=.05)
self.assertEqual(self.api_mock.jobs().get().execute.call_count, 2)
self.assertIsInstance(job_resource, dict)
def test_timeout_error(self):
"""Ensure that timeout raise exceptions"""
incomplete_job = {'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}}
self.api_mock.jobs().get().execute.return_value = incomplete_job
self.assertRaises(BigQueryTimeoutException, self.client.wait_for_job,
incomplete_job, .1, .25)
def test_wait_job_http_error(self):
""" Test wait job with http error"""
job = {'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}}
expected_result = {
"error": {
"errors": [{
"domain": "global",
"reason": "required",
"message": "Required parameter is missing"
}],
"code": 400,
"message": "Required parameter is missing"
}
}
self.api_mock.jobs().insert().execute.return_value = expected_result
self.assertRaises(JobExecutingException,
self.client.wait_for_job,
job,
interval=.01,
timeout=.01)
def test_wait_job_error_result(self):
""" Test wait job with error result"""
job = {'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}}
expected_result = {
"status": {
"state": "DONE",
"errorResult": {
"reason": "invalidQuery",
"location": "query",
"message": "Your Error Message Here "
},
},
}
self.api_mock.jobs().insert().execute.return_value = expected_result
self.assertRaises(JobExecutingException,
self.client.wait_for_job,
job,
interval=.01,
timeout=.01)
def test_accepts_job_id(self):
"""Ensure it accepts a job Id rather than a full job resource"""
return_values = [{'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}},
{'status': {'state': 'DONE'},
'jobReference': {'jobId': "testJob"}}]
def side_effect(*args, **kwargs):
return return_values.pop(0)
self.api_mock.jobs().get().execute.side_effect = side_effect
job_resource = self.client.wait_for_job("testJob",
interval=.01,
timeout=5)
self.assertEqual(self.api_mock.jobs().get().execute.call_count, 2)
self.assertIsInstance(job_resource, dict)
def test_accepts_integer_job_id(self):
return_values = [{'status': {'state': 'RUNNING'},
'jobReference': {'jobId': "testJob"}},
{'status': {'state': 'DONE'},
'jobReference': {'jobId': "testJob"}}]
def side_effect(*args, **kwargs):
return return_values.pop(0)
self.api_mock.jobs().get().execute.side_effect = side_effect
job_resource = self.client.wait_for_job(1234567,
interval=.01,
timeout=600)
self.assertEqual(self.api_mock.jobs().get().execute.call_count, 2)
self.assertIsInstance(job_resource, dict)
class TestImportDataFromURIs(unittest.TestCase):
def setUp(self):
client._bq_client = None
self.mock_api = mock.Mock()
self.query = 'foo'
self.project_id = 'project'
self.dataset_id = 'dataset'
self.table_id = 'table'
self.client = client.BigQueryClient(self.mock_api,
self.project_id)
def test_csv_job_body_constructed_correctly(self):
expected_result = {
'status': {'state': 'RUNNING'},
}
body = {
"jobReference": {
"projectId": self.project_id,
"jobId": "job"
},
"configuration": {
"load": {
"sourceUris": ["sourceuri"],
"schema": {"fields": ["schema"]},
"destinationTable": {
"projectId": self.project_id,
"datasetId": self.dataset_id,
"tableId": self.table_id
},
"createDisposition": "a",
"writeDisposition": "b",
"fieldDelimiter": "c",
"skipLeadingRows": "d",
"encoding": "e",
"quote": "f",
"maxBadRecords": "g",
"allowQuotedNewlines": "h",
"sourceFormat": "CSV",
"allowJaggedRows": "j",
"ignoreUnknownValues": "k"
}
}
}
self.mock_api.jobs().insert().execute.return_value = expected_result
result = self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
create_disposition="a",
write_disposition="b",
field_delimiter="c",
skip_leading_rows="d",
encoding="e",
quote="f",
max_bad_records="g",
allow_quoted_newlines="h",
source_format="CSV",
allow_jagged_rows="j",
ignore_unknown_values="k")
self.mock_api.jobs().insert.assert_called_with(
projectId=self.project_id,
body=body
)
self.assertEqual(result, expected_result)
def test_json_job_body_constructed_correctly(self):
expected_result = {
'status': {'state': 'RUNNING'},
}
body = {
"jobReference": {
"projectId": self.project_id,
"jobId": "job"
},
"configuration": {
"load": {
"sourceUris": ["sourceuri"],
"schema": {"fields": ["schema"]},
"destinationTable": {
"projectId": self.project_id,
"datasetId": self.dataset_id,
"tableId": self.table_id
},
"sourceFormat": "JSON"
}
}
}
self.mock_api.jobs().insert().execute.return_value = expected_result
result = self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
source_format="JSON")
self.mock_api.jobs().insert.assert_called_with(
projectId=self.project_id,
body=body
)
self.assertEqual(result, expected_result)
@raises(Exception)
def test_field_delimiter_exception_if_not_csv(self):
"""Raise exception if csv-only parameter is set inappropriately"""
self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
source_format="JSON",
field_delimiter=",")
@raises(Exception)
def test_allow_jagged_rows_exception_if_not_csv(self):
"""Raise exception if csv-only parameter is set inappropriately"""
self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
source_format="JSON",
allow_jagged_rows=True)
@raises(Exception)
def test_allow_quoted_newlines_exception_if_not_csv(self):
"""Raise exception if csv-only parameter is set inappropriately"""
self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
source_format="JSON",
allow_quoted_newlines=True)
@raises(Exception)
def test_quote_exception_if_not_csv(self):
"""Raise exception if csv-only parameter is set inappropriately"""
self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
job="job",
source_format="JSON",
quote="'")
@raises(Exception)
def test_skip_leading_rows_exception_if_not_csv(self):
"""Raise exception if csv-only parameter is set inappropriately"""
self.client.import_data_from_uris(["sourceuri"],
self.dataset_id,
self.table_id,
["schema"],
"job",
source_format="JSON",
skip_leading_rows=10)
def test_accepts_single_source_uri(self):
"""Ensure that a source_uri accepts a non-list"""
expected_result = {
'status': {'state': 'RUNNING'},
}
body = {
"jobReference": {
"projectId": self.project_id,
"jobId": "job"
},
"configuration": {
"load": {
"sourceUris": ["sourceuri"],
"schema": {"fields": ["schema"]},
"destinationTable": {
"projectId": self.project_id,
"datasetId": self.dataset_id,
"tableId": self.table_id
}
}
}
}
self.mock_api.jobs().insert().execute.return_value = expected_result
result = self.client.import_data_from_uris("sourceuri", # not a list!
self.dataset_id,
self.table_id,
schema=["schema"],
job="job")
self.mock_api.jobs().insert.assert_called_with(
projectId=self.project_id,
body=body
)
self.assertEqual(result, expected_result)
def test_import_http_error(self):
""" Test import with http error"""
expected_result = {
"error": {
"errors": [{
"domain": "global",
"reason": "required",
"message": "Required parameter is missing"
}],
"code": 400,
"message": "Required parameter is missing"
}
}
self.mock_api.jobs().insert().execute.return_value = expected_result
self.assertRaises(JobInsertException,
self.client.import_data_from_uris,
["sourceuri"],
self.dataset_id,
self.table_id)
def test_import_error_result(self):
""" Test import with error result"""
expected_result = {
"status": {