forked from googleapis/python-bigquery-pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_gbq.py
1630 lines (1365 loc) · 66.6 KB
/
test_gbq.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
# -*- coding: utf-8 -*-
import os
import re
import sys
from datetime import datetime
from random import randint
from time import sleep
import numpy as np
import pandas.util.testing as tm
import pytest
import pytz
from pandas import DataFrame, NaT, compat
from pandas.compat import range, u
from pandas.compat.numpy import np_datetime64_compat
from pandas_gbq import gbq
try:
import mock
except ImportError:
from unittest import mock
TABLE_ID = 'new_test'
def _skip_local_auth_if_in_travis_env():
if _in_travis_environment():
pytest.skip("Cannot run local auth in travis environment")
def _skip_if_no_private_key_path():
if not _get_private_key_path():
pytest.skip("Cannot run integration tests without a "
"private key json file path")
def _skip_if_no_private_key_contents():
if not _get_private_key_contents():
raise pytest.skip("Cannot run integration tests without a "
"private key json contents")
def _in_travis_environment():
return 'TRAVIS_BUILD_DIR' in os.environ and \
'GBQ_PROJECT_ID' in os.environ
def _get_dataset_prefix_random():
return ''.join(['pandas_gbq_', str(randint(1, 100000))])
def _get_project_id():
project = os.environ.get('GBQ_PROJECT_ID')
if not project:
pytest.skip(
"Cannot run integration tests without a project id")
return project
def _get_private_key_path():
if _in_travis_environment():
return os.path.join(*[os.environ.get('TRAVIS_BUILD_DIR'), 'ci',
'travis_gbq.json'])
else:
return os.environ.get('GBQ_GOOGLE_APPLICATION_CREDENTIALS')
def _get_private_key_contents():
key_path = _get_private_key_path()
if key_path is None:
return None
with open(key_path) as f:
return f.read()
@pytest.fixture(autouse=True, scope='module')
def _test_imports():
try:
import pkg_resources # noqa
except ImportError:
raise ImportError('Could not import pkg_resources (setuptools).')
gbq._test_google_api_imports()
@pytest.fixture
def project():
return _get_project_id()
def _check_if_can_get_correct_default_credentials():
# Checks if "Application Default Credentials" can be fetched
# from the environment the tests are running in.
# See https://github.com/pandas-dev/pandas/issues/13577
import google.auth
from google.auth.exceptions import DefaultCredentialsError
try:
credentials, _ = google.auth.default(scopes=[gbq.GbqConnector.scope])
except (DefaultCredentialsError, IOError):
return False
return gbq._try_credentials(_get_project_id(), credentials) is not None
def clean_gbq_environment(dataset_prefix, private_key=None):
dataset = gbq._Dataset(_get_project_id(), private_key=private_key)
all_datasets = dataset.datasets()
retry = 3
while retry > 0:
try:
retry = retry - 1
for i in range(1, 10):
dataset_id = dataset_prefix + str(i)
if dataset_id in all_datasets:
table = gbq._Table(_get_project_id(), dataset_id,
private_key=private_key)
# Table listing is eventually consistent, so loop until
# all tables no longer appear (max 30 seconds).
table_retry = 30
all_tables = dataset.tables(dataset_id)
while all_tables and table_retry > 0:
for table_id in all_tables:
try:
table.delete(table_id)
except gbq.NotFoundException:
pass
sleep(1)
table_retry = table_retry - 1
all_tables = dataset.tables(dataset_id)
dataset.delete(dataset_id)
retry = 0
except gbq.GenericGBQException as ex:
# Build in retry logic to work around the following errors :
# An internal error occurred and the request could not be...
# Dataset ... is still in use
error_message = str(ex).lower()
if ('an internal error occurred' in error_message or
'still in use' in error_message) and retry > 0:
sleep(30)
else:
raise ex
def make_mixed_dataframe_v2(test_size):
# create df to test for all BQ datatypes except RECORD
bools = np.random.randint(2, size=(1, test_size)).astype(bool)
flts = np.random.randn(1, test_size)
ints = np.random.randint(1, 10, size=(1, test_size))
strs = np.random.randint(1, 10, size=(1, test_size)).astype(str)
times = [datetime.now(pytz.timezone('US/Arizona'))
for t in range(test_size)]
return DataFrame({'bools': bools[0],
'flts': flts[0],
'ints': ints[0],
'strs': strs[0],
'times': times[0]},
index=range(test_size))
def test_generate_bq_schema_deprecated():
# 11121 Deprecation of generate_bq_schema
with pytest.warns(FutureWarning):
df = make_mixed_dataframe_v2(10)
gbq.generate_bq_schema(df)
@pytest.fixture(params=['local', 'service_path', 'service_creds'])
def auth_type(request):
auth = request.param
if auth == 'local':
if _in_travis_environment():
pytest.skip("Cannot run local auth in travis environment")
elif auth == 'service_path':
if _in_travis_environment():
pytest.skip("Only run one auth type in Travis to save time")
_skip_if_no_private_key_path()
elif auth == 'service_creds':
_skip_if_no_private_key_contents()
else:
raise ValueError
return auth
@pytest.fixture()
def credentials(auth_type):
if auth_type == 'local':
return None
elif auth_type == 'service_path':
return _get_private_key_path()
elif auth_type == 'service_creds':
return _get_private_key_contents()
else:
raise ValueError
@pytest.fixture()
def gbq_connector(project, credentials):
return gbq.GbqConnector(project, private_key=credentials)
class TestGBQConnectorIntegration(object):
def test_should_be_able_to_make_a_connector(self, gbq_connector):
assert gbq_connector is not None, 'Could not create a GbqConnector'
def test_should_be_able_to_get_valid_credentials(self, gbq_connector):
credentials = gbq_connector.get_credentials()
assert credentials.valid
def test_should_be_able_to_get_a_bigquery_client(self, gbq_connector):
bigquery_client = gbq_connector.get_client()
assert bigquery_client is not None
def test_should_be_able_to_get_schema_from_query(self, gbq_connector):
schema, pages = gbq_connector.run_query('SELECT 1')
assert schema is not None
def test_should_be_able_to_get_results_from_query(self, gbq_connector):
schema, pages = gbq_connector.run_query('SELECT 1')
assert pages is not None
class TestGBQConnectorIntegrationWithLocalUserAccountAuth(object):
@pytest.fixture(autouse=True)
def setup(self, project):
_skip_local_auth_if_in_travis_env()
self.sut = gbq.GbqConnector(project, auth_local_webserver=True)
def test_get_application_default_credentials_does_not_throw_error(self):
if _check_if_can_get_correct_default_credentials():
# Can get real credentials, so mock it out to fail.
from google.auth.exceptions import DefaultCredentialsError
with mock.patch('google.auth.default',
side_effect=DefaultCredentialsError()):
credentials = self.sut.get_application_default_credentials()
else:
credentials = self.sut.get_application_default_credentials()
assert credentials is None
def test_get_application_default_credentials_returns_credentials(self):
if not _check_if_can_get_correct_default_credentials():
pytest.skip("Cannot get default_credentials "
"from the environment!")
from google.auth.credentials import Credentials
credentials = self.sut.get_application_default_credentials()
assert isinstance(credentials, Credentials)
def test_get_user_account_credentials_bad_file_returns_credentials(self):
from google.auth.credentials import Credentials
with mock.patch('__main__.open', side_effect=IOError()):
credentials = self.sut.get_user_account_credentials()
assert isinstance(credentials, Credentials)
def test_get_user_account_credentials_returns_credentials(self):
from google.auth.credentials import Credentials
credentials = self.sut.get_user_account_credentials()
assert isinstance(credentials, Credentials)
class TestGBQUnit(object):
@pytest.fixture(autouse=True)
def mock_bigquery_client(self, monkeypatch):
import google.cloud.bigquery
import google.cloud.bigquery.table
mock_client = mock.create_autospec(google.cloud.bigquery.Client)
# Mock out SELECT 1 query results.
mock_query = mock.create_autospec(google.cloud.bigquery.QueryJob)
mock_query.state = 'DONE'
mock_rows = mock.create_autospec(
google.cloud.bigquery.table.RowIterator)
mock_rows.total_rows = 1
mock_rows.schema = [
google.cloud.bigquery.SchemaField('_f0', 'INTEGER')]
mock_rows.__iter__.return_value = [(1,)]
mock_query.result.return_value = mock_rows
mock_client.query.return_value = mock_query
monkeypatch.setattr(
gbq.GbqConnector, 'get_client', lambda _: mock_client)
@pytest.fixture(autouse=True)
def no_auth(self, monkeypatch):
import google.auth.credentials
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials)
monkeypatch.setattr(
gbq.GbqConnector,
'get_application_default_credentials',
lambda _: mock_credentials)
monkeypatch.setattr(
gbq.GbqConnector,
'get_user_account_credentials',
lambda _: mock_credentials)
def test_should_return_credentials_path_set_by_env_var(self):
env = {'PANDAS_GBQ_CREDENTIALS_FILE': '/tmp/dummy.dat'}
with mock.patch.dict('os.environ', env):
assert gbq._get_credentials_file() == '/tmp/dummy.dat'
@pytest.mark.parametrize(
('input', 'type_', 'expected'), [
(1, 'INTEGER', int(1)),
(1, 'FLOAT', float(1)),
pytest.param('false', 'BOOLEAN', False, marks=pytest.mark.xfail),
pytest.param(
'0e9', 'TIMESTAMP',
np_datetime64_compat('1970-01-01T00:00:00Z'),
marks=pytest.mark.xfail),
('STRING', 'STRING', 'STRING'),
])
def test_should_return_bigquery_correctly_typed(
self, input, type_, expected):
result = gbq._parse_data(
dict(fields=[dict(name='x', type=type_, mode='NULLABLE')]),
rows=[[input]]).iloc[0, 0]
assert result == expected
def test_to_gbq_should_fail_if_invalid_table_name_passed(self):
with pytest.raises(gbq.NotFoundException):
gbq.to_gbq(DataFrame(), 'invalid_table_name', project_id="1234")
def test_to_gbq_with_no_project_id_given_should_fail(self):
with pytest.raises(TypeError):
gbq.to_gbq(DataFrame(), 'dataset.tablename')
def test_to_gbq_with_verbose_new_pandas_warns_deprecation(self):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with pytest.warns(FutureWarning), \
mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
try:
gbq.to_gbq(
DataFrame(),
'dataset.tablename',
project_id='my-project',
verbose=True)
except gbq.TableCreationError:
pass
def test_to_gbq_with_not_verbose_new_pandas_warns_deprecation(self):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with pytest.warns(FutureWarning), \
mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
try:
gbq.to_gbq(
DataFrame(),
'dataset.tablename',
project_id='my-project',
verbose=False)
except gbq.TableCreationError:
pass
def test_to_gbq_wo_verbose_w_new_pandas_no_warnings(self, recwarn):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
try:
gbq.to_gbq(
DataFrame(), 'dataset.tablename', project_id='my-project')
except gbq.TableCreationError:
pass
assert len(recwarn) == 0
def test_to_gbq_with_verbose_old_pandas_no_warnings(self, recwarn):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.22.0')
with mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
try:
gbq.to_gbq(
DataFrame(),
'dataset.tablename',
project_id='my-project',
verbose=True)
except gbq.TableCreationError:
pass
assert len(recwarn) == 0
def test_read_gbq_with_no_project_id_given_should_fail(self):
with pytest.raises(TypeError):
gbq.read_gbq('SELECT 1')
def test_that_parse_data_works_properly(self):
from google.cloud.bigquery.table import Row
test_schema = {'fields': [
{'mode': 'NULLABLE', 'name': 'column_x', 'type': 'STRING'}]}
field_to_index = {'column_x': 0}
values = ('row_value',)
test_page = [Row(values, field_to_index)]
test_output = gbq._parse_data(test_schema, test_page)
correct_output = DataFrame({'column_x': ['row_value']})
tm.assert_frame_equal(test_output, correct_output)
def test_read_gbq_with_invalid_private_key_json_should_fail(self):
with pytest.raises(gbq.InvalidPrivateKeyFormat):
gbq.read_gbq('SELECT 1', project_id='x', private_key='y')
def test_read_gbq_with_empty_private_key_json_should_fail(self):
with pytest.raises(gbq.InvalidPrivateKeyFormat):
gbq.read_gbq('SELECT 1', project_id='x', private_key='{}')
def test_read_gbq_with_private_key_json_wrong_types_should_fail(self):
with pytest.raises(gbq.InvalidPrivateKeyFormat):
gbq.read_gbq(
'SELECT 1', project_id='x',
private_key='{ "client_email" : 1, "private_key" : True }')
def test_read_gbq_with_empty_private_key_file_should_fail(self):
with tm.ensure_clean() as empty_file_path:
with pytest.raises(gbq.InvalidPrivateKeyFormat):
gbq.read_gbq('SELECT 1', project_id='x',
private_key=empty_file_path)
def test_read_gbq_with_corrupted_private_key_json_should_fail(self):
_skip_if_no_private_key_contents()
with pytest.raises(gbq.InvalidPrivateKeyFormat):
gbq.read_gbq(
'SELECT 1', project_id='x',
private_key=re.sub('[a-z]', '9', _get_private_key_contents()))
def test_read_gbq_with_verbose_new_pandas_warns_deprecation(self):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with pytest.warns(FutureWarning), \
mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
gbq.read_gbq('SELECT 1', project_id='my-project', verbose=True)
def test_read_gbq_with_not_verbose_new_pandas_warns_deprecation(self):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with pytest.warns(FutureWarning), \
mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
gbq.read_gbq('SELECT 1', project_id='my-project', verbose=False)
def test_read_gbq_wo_verbose_w_new_pandas_no_warnings(self, recwarn):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.23.0')
with mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
gbq.read_gbq('SELECT 1', project_id='my-project')
assert len(recwarn) == 0
def test_read_gbq_with_verbose_old_pandas_no_warnings(self, recwarn):
import pkg_resources
min_bq_version = pkg_resources.parse_version('0.29.0')
pandas_version = pkg_resources.parse_version('0.22.0')
with mock.patch(
'pkg_resources.Distribution.parsed_version',
new_callable=mock.PropertyMock) as mock_version:
mock_version.side_effect = [min_bq_version, pandas_version]
gbq.read_gbq('SELECT 1', project_id='my-project', verbose=True)
assert len(recwarn) == 0
def test_should_read(project, credentials):
query = 'SELECT "PI" AS valid_string'
df = gbq.read_gbq(query, project_id=project, private_key=credentials)
tm.assert_frame_equal(df, DataFrame({'valid_string': ['PI']}))
class TestReadGBQIntegration(object):
@pytest.fixture(autouse=True)
def setup(self, project, credentials):
# - PER-TEST FIXTURES -
# put here any instruction you want to be run *BEFORE* *EVERY* test is
# executed.
self.gbq_connector = gbq.GbqConnector(
project, private_key=credentials)
self.credentials = credentials
def test_should_properly_handle_valid_strings(self):
query = 'SELECT "PI" AS valid_string'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'valid_string': ['PI']}))
def test_should_properly_handle_empty_strings(self):
query = 'SELECT "" AS empty_string'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'empty_string': [""]}))
def test_should_properly_handle_null_strings(self):
query = 'SELECT STRING(NULL) AS null_string'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'null_string': [None]}))
def test_should_properly_handle_valid_integers(self):
query = 'SELECT INTEGER(3) AS valid_integer'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'valid_integer': [3]}))
def test_should_properly_handle_nullable_integers(self):
query = '''SELECT * FROM
(SELECT 1 AS nullable_integer),
(SELECT NULL AS nullable_integer)'''
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'nullable_integer': [1, None]}).astype(object))
def test_should_properly_handle_valid_longs(self):
query = 'SELECT 1 << 62 AS valid_long'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'valid_long': [1 << 62]}))
def test_should_properly_handle_nullable_longs(self):
query = '''SELECT * FROM
(SELECT 1 << 62 AS nullable_long),
(SELECT NULL AS nullable_long)'''
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'nullable_long': [1 << 62, None]}).astype(object))
def test_should_properly_handle_null_integers(self):
query = 'SELECT INTEGER(NULL) AS null_integer'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'null_integer': [None]}))
def test_should_properly_handle_valid_floats(self):
from math import pi
query = 'SELECT PI() AS valid_float'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame(
{'valid_float': [pi]}))
def test_should_properly_handle_nullable_floats(self):
from math import pi
query = '''SELECT * FROM
(SELECT PI() AS nullable_float),
(SELECT NULL AS nullable_float)'''
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'nullable_float': [pi, None]}))
def test_should_properly_handle_valid_doubles(self):
from math import pi
query = 'SELECT PI() * POW(10, 307) AS valid_double'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame(
{'valid_double': [pi * 10 ** 307]}))
def test_should_properly_handle_nullable_doubles(self):
from math import pi
query = '''SELECT * FROM
(SELECT PI() * POW(10, 307) AS nullable_double),
(SELECT NULL AS nullable_double)'''
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'nullable_double': [pi * 10 ** 307, None]}))
def test_should_properly_handle_null_floats(self):
query = 'SELECT FLOAT(NULL) AS null_float'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'null_float': [np.nan]}))
def test_should_properly_handle_timestamp_unix_epoch(self):
query = 'SELECT TIMESTAMP("1970-01-01 00:00:00") AS unix_epoch'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame(
{'unix_epoch': [np.datetime64('1970-01-01T00:00:00.000000Z')]}))
def test_should_properly_handle_arbitrary_timestamp(self):
query = 'SELECT TIMESTAMP("2004-09-15 05:00:00") AS valid_timestamp'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({
'valid_timestamp': [np.datetime64('2004-09-15T05:00:00.000000Z')]
}))
def test_should_properly_handle_null_timestamp(self):
query = 'SELECT TIMESTAMP(NULL) AS null_timestamp'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'null_timestamp': [NaT]}))
def test_should_properly_handle_true_boolean(self):
query = 'SELECT BOOLEAN(TRUE) AS true_boolean'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'true_boolean': [True]}))
def test_should_properly_handle_false_boolean(self):
query = 'SELECT BOOLEAN(FALSE) AS false_boolean'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'false_boolean': [False]}))
def test_should_properly_handle_null_boolean(self):
query = 'SELECT BOOLEAN(NULL) AS null_boolean'
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, DataFrame({'null_boolean': [None]}))
def test_should_properly_handle_nullable_booleans(self):
query = '''SELECT * FROM
(SELECT BOOLEAN(TRUE) AS nullable_boolean),
(SELECT NULL AS nullable_boolean)'''
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(
df, DataFrame({'nullable_boolean': [True, None]}).astype(object))
def test_unicode_string_conversion_and_normalization(self):
correct_test_datatype = DataFrame(
{'unicode_string': [u("\xe9\xfc")]}
)
unicode_string = "\xc3\xa9\xc3\xbc"
if compat.PY3:
unicode_string = unicode_string.encode('latin-1').decode('utf8')
query = 'SELECT "{0}" AS unicode_string'.format(unicode_string)
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials)
tm.assert_frame_equal(df, correct_test_datatype)
def test_index_column(self):
query = "SELECT 'a' AS string_1, 'b' AS string_2"
result_frame = gbq.read_gbq(query, project_id=_get_project_id(),
index_col="string_1",
private_key=self.credentials)
correct_frame = DataFrame(
{'string_1': ['a'], 'string_2': ['b']}).set_index("string_1")
assert result_frame.index.name == correct_frame.index.name
def test_column_order(self):
query = "SELECT 'a' AS string_1, 'b' AS string_2, 'c' AS string_3"
col_order = ['string_3', 'string_1', 'string_2']
result_frame = gbq.read_gbq(query, project_id=_get_project_id(),
col_order=col_order,
private_key=self.credentials)
correct_frame = DataFrame({'string_1': ['a'], 'string_2': [
'b'], 'string_3': ['c']})[col_order]
tm.assert_frame_equal(result_frame, correct_frame)
def test_read_gbq_raises_invalid_column_order(self):
query = "SELECT 'a' AS string_1, 'b' AS string_2, 'c' AS string_3"
col_order = ['string_aaa', 'string_1', 'string_2']
# Column string_aaa does not exist. Should raise InvalidColumnOrder
with pytest.raises(gbq.InvalidColumnOrder):
gbq.read_gbq(query, project_id=_get_project_id(),
col_order=col_order,
private_key=self.credentials)
def test_column_order_plus_index(self):
query = "SELECT 'a' AS string_1, 'b' AS string_2, 'c' AS string_3"
col_order = ['string_3', 'string_2']
result_frame = gbq.read_gbq(query, project_id=_get_project_id(),
index_col='string_1', col_order=col_order,
private_key=self.credentials)
correct_frame = DataFrame(
{'string_1': ['a'], 'string_2': ['b'], 'string_3': ['c']})
correct_frame.set_index('string_1', inplace=True)
correct_frame = correct_frame[col_order]
tm.assert_frame_equal(result_frame, correct_frame)
def test_read_gbq_raises_invalid_index_column(self):
query = "SELECT 'a' AS string_1, 'b' AS string_2, 'c' AS string_3"
col_order = ['string_3', 'string_2']
# Column string_bbb does not exist. Should raise InvalidIndexColumn
with pytest.raises(gbq.InvalidIndexColumn):
gbq.read_gbq(query, project_id=_get_project_id(),
index_col='string_bbb', col_order=col_order,
private_key=self.credentials)
def test_malformed_query(self):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq("SELCET * FORM [publicdata:samples.shakespeare]",
project_id=_get_project_id(),
private_key=self.credentials)
def test_bad_project_id(self):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq("SELECT 1", project_id='001',
private_key=self.credentials)
def test_bad_table_name(self):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq("SELECT * FROM [publicdata:samples.nope]",
project_id=_get_project_id(),
private_key=self.credentials)
def test_download_dataset_larger_than_200k_rows(self):
test_size = 200005
# Test for known BigQuery bug in datasets larger than 100k rows
# http://stackoverflow.com/questions/19145587/bq-py-not-paging-results
df = gbq.read_gbq("SELECT id FROM [publicdata:samples.wikipedia] "
"GROUP EACH BY id ORDER BY id ASC LIMIT {0}"
.format(test_size),
project_id=_get_project_id(),
private_key=self.credentials)
assert len(df.drop_duplicates()) == test_size
def test_zero_rows(self):
# Bug fix for https://github.com/pandas-dev/pandas/issues/10273
df = gbq.read_gbq("SELECT title, id, is_bot, "
"SEC_TO_TIMESTAMP(timestamp) ts "
"FROM [publicdata:samples.wikipedia] "
"WHERE timestamp=-9999999",
project_id=_get_project_id(),
private_key=self.credentials)
page_array = np.zeros(
(0,), dtype=[('title', object), ('id', np.dtype(int)),
('is_bot', np.dtype(bool)), ('ts', 'M8[ns]')])
expected_result = DataFrame(
page_array, columns=['title', 'id', 'is_bot', 'ts'])
tm.assert_frame_equal(df, expected_result)
def test_legacy_sql(self):
legacy_sql = "SELECT id FROM [publicdata.samples.wikipedia] LIMIT 10"
# Test that a legacy sql statement fails when
# setting dialect='standard'
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(legacy_sql, project_id=_get_project_id(),
dialect='standard',
private_key=self.credentials)
# Test that a legacy sql statement succeeds when
# setting dialect='legacy'
df = gbq.read_gbq(legacy_sql, project_id=_get_project_id(),
dialect='legacy',
private_key=self.credentials)
assert len(df.drop_duplicates()) == 10
def test_standard_sql(self):
standard_sql = "SELECT DISTINCT id FROM " \
"`publicdata.samples.wikipedia` LIMIT 10"
# Test that a standard sql statement fails when using
# the legacy SQL dialect (default value)
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(standard_sql, project_id=_get_project_id(),
private_key=self.credentials)
# Test that a standard sql statement succeeds when
# setting dialect='standard'
df = gbq.read_gbq(standard_sql, project_id=_get_project_id(),
dialect='standard',
private_key=self.credentials)
assert len(df.drop_duplicates()) == 10
def test_invalid_option_for_sql_dialect(self):
sql_statement = "SELECT DISTINCT id FROM " \
"`publicdata.samples.wikipedia` LIMIT 10"
# Test that an invalid option for `dialect` raises ValueError
with pytest.raises(ValueError):
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
dialect='invalid',
private_key=self.credentials)
# Test that a correct option for dialect succeeds
# to make sure ValueError was due to invalid dialect
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
dialect='standard', private_key=self.credentials)
def test_query_with_parameters(self):
sql_statement = "SELECT @param1 + @param2 AS valid_result"
config = {
'query': {
"useLegacySql": False,
"parameterMode": "named",
"queryParameters": [
{
"name": "param1",
"parameterType": {
"type": "INTEGER"
},
"parameterValue": {
"value": 1
}
},
{
"name": "param2",
"parameterType": {
"type": "INTEGER"
},
"parameterValue": {
"value": 2
}
}
]
}
}
# Test that a query that relies on parameters fails
# when parameters are not supplied via configuration
with pytest.raises(ValueError):
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
private_key=self.credentials)
# Test that the query is successful because we have supplied
# the correct query parameters via the 'config' option
df = gbq.read_gbq(sql_statement, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
tm.assert_frame_equal(df, DataFrame({'valid_result': [3]}))
def test_query_inside_configuration(self):
query_no_use = 'SELECT "PI_WRONG" AS valid_string'
query = 'SELECT "PI" AS valid_string'
config = {
'query': {
"query": query,
"useQueryCache": False,
}
}
# Test that it can't pass query both
# inside config and as parameter
with pytest.raises(ValueError):
gbq.read_gbq(query_no_use, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
df = gbq.read_gbq(None, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
tm.assert_frame_equal(df, DataFrame({'valid_string': ['PI']}))
def test_configuration_without_query(self):
sql_statement = 'SELECT 1'
config = {
'copy': {
"sourceTable": {
"projectId": _get_project_id(),
"datasetId": "publicdata:samples",
"tableId": "wikipedia"
},
"destinationTable": {
"projectId": _get_project_id(),
"datasetId": "publicdata:samples",
"tableId": "wikipedia_copied"
},
}
}
# Test that only 'query' configurations are supported
# nor 'copy','load','extract'
with pytest.raises(ValueError):
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
def test_configuration_raises_value_error_with_multiple_config(self):
sql_statement = 'SELECT 1'
config = {
'query': {
"query": sql_statement,
"useQueryCache": False,
},
'load': {
"query": sql_statement,
"useQueryCache": False,
}
}
# Test that only ValueError is raised with multiple configurations
with pytest.raises(ValueError):
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
def test_timeout_configuration(self):
sql_statement = 'SELECT 1'
config = {
'query': {
"timeoutMs": 1
}
}
# Test that QueryTimeout error raises
with pytest.raises(gbq.QueryTimeout):
gbq.read_gbq(sql_statement, project_id=_get_project_id(),
private_key=self.credentials,
configuration=config)
def test_query_response_bytes(self):
assert self.gbq_connector.sizeof_fmt(999) == "999.0 B"
assert self.gbq_connector.sizeof_fmt(1024) == "1.0 KB"
assert self.gbq_connector.sizeof_fmt(1099) == "1.1 KB"
assert self.gbq_connector.sizeof_fmt(1044480) == "1020.0 KB"
assert self.gbq_connector.sizeof_fmt(1048576) == "1.0 MB"
assert self.gbq_connector.sizeof_fmt(1048576000) == "1000.0 MB"
assert self.gbq_connector.sizeof_fmt(1073741824) == "1.0 GB"
assert self.gbq_connector.sizeof_fmt(1.099512E12) == "1.0 TB"
assert self.gbq_connector.sizeof_fmt(1.125900E15) == "1.0 PB"
assert self.gbq_connector.sizeof_fmt(1.152922E18) == "1.0 EB"
assert self.gbq_connector.sizeof_fmt(1.180592E21) == "1.0 ZB"
assert self.gbq_connector.sizeof_fmt(1.208926E24) == "1.0 YB"
assert self.gbq_connector.sizeof_fmt(1.208926E28) == "10000.0 YB"
def test_struct(self):
query = """SELECT 1 int_field,
STRUCT("a" as letter, 1 as num) struct_field"""
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials,
dialect='standard')
expected = DataFrame([[1, {"letter": "a", "num": 1}]],
columns=["int_field", "struct_field"])
tm.assert_frame_equal(df, expected)
def test_array(self):
query = """select ["a","x","b","y","c","z"] as letters"""
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials,
dialect='standard')
tm.assert_frame_equal(df, DataFrame([[["a", "x", "b", "y", "c", "z"]]],
columns=["letters"]))
def test_array_length_zero(self):
query = """WITH t as (
SELECT "a" letter, [""] as array_field
UNION ALL
SELECT "b" letter, [] as array_field)
select letter, array_field, array_length(array_field) len
from t
order by letter ASC"""
df = gbq.read_gbq(query, project_id=_get_project_id(),
private_key=self.credentials,
dialect='standard')
expected = DataFrame([["a", [""], 1], ["b", [], 0]],
columns=["letter", "array_field", "len"])
tm.assert_frame_equal(df, expected)
def test_array_agg(self):
query = """WITH t as (
SELECT "a" letter, 1 num
UNION ALL
SELECT "b" letter, 2 num
UNION ALL