-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathtest_gbq.py
1734 lines (1527 loc) · 56 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 sys
from datetime import datetime
import numpy as np
import pandas
import pandas.api.types
import pandas.util.testing as tm
from pandas import DataFrame, NaT
import pytest
import pytz
from pandas_gbq import gbq
TABLE_ID = "new_test"
def test_imports():
try:
import pkg_resources # noqa
except ImportError:
raise ImportError("Could not import pkg_resources (setuptools).")
gbq._test_google_api_imports()
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),
)
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_a_bigquery_client(self, gbq_connector):
bigquery_client = gbq_connector.get_client()
assert bigquery_client is not None
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, credentials=credentials)
self.credentials = credentials
def test_should_properly_handle_empty_strings(self, project_id):
query = 'SELECT "" AS empty_string'
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"empty_string": [""]}))
def test_should_properly_handle_null_strings(self, project_id):
query = "SELECT STRING(NULL) AS null_string"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"null_string": [None]}))
def test_should_properly_handle_valid_integers(self, project_id):
query = "SELECT INTEGER(3) AS valid_integer"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"valid_integer": [3]}))
def test_should_properly_handle_nullable_integers(self, project_id):
query = """SELECT * FROM
(SELECT 1 AS nullable_integer),
(SELECT NULL AS nullable_integer)"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"nullable_integer": [1, None]}))
def test_should_properly_handle_valid_longs(self, project_id):
query = "SELECT 1 << 62 AS valid_long"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"valid_long": [1 << 62]}))
def test_should_properly_handle_nullable_longs(self, project_id):
query = """SELECT * FROM
(SELECT 1 << 62 AS nullable_long),
(SELECT NULL AS nullable_long)"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df, DataFrame({"nullable_long": [1 << 62, None]})
)
def test_should_properly_handle_null_integers(self, project_id):
query = "SELECT INTEGER(NULL) AS null_integer"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df,
DataFrame({"null_integer": pandas.Series([None], dtype="object")}),
)
def test_should_properly_handle_valid_floats(self, project_id):
from math import pi
query = "SELECT PI() AS valid_float"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"valid_float": [pi]}))
def test_should_properly_handle_nullable_floats(self, project_id):
from math import pi
query = """SELECT * FROM
(SELECT PI() AS nullable_float),
(SELECT NULL AS nullable_float)"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"nullable_float": [pi, None]}))
def test_should_properly_handle_valid_doubles(self, project_id):
from math import pi
query = "SELECT PI() * POW(10, 307) AS valid_double"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df, DataFrame({"valid_double": [pi * 10 ** 307]})
)
def test_should_properly_handle_nullable_doubles(self, project_id):
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=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df, DataFrame({"nullable_double": [pi * 10 ** 307, None]})
)
def test_should_properly_handle_null_floats(self, project_id):
query = """SELECT null_float
FROM UNNEST(ARRAY<FLOAT64>[NULL, 1.0]) AS null_float
"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
tm.assert_frame_equal(df, DataFrame({"null_float": [np.nan, 1.0]}))
def test_should_properly_handle_timestamp_unix_epoch(self, project_id):
query = 'SELECT TIMESTAMP("1970-01-01 00:00:00") AS unix_epoch'
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
expected = DataFrame(
{"unix_epoch": ["1970-01-01T00:00:00.000000Z"]},
dtype="datetime64[ns]",
)
if expected["unix_epoch"].dt.tz is None:
expected["unix_epoch"] = expected["unix_epoch"].dt.tz_localize(
"UTC"
)
tm.assert_frame_equal(df, expected)
def test_should_properly_handle_arbitrary_timestamp(self, project_id):
query = 'SELECT TIMESTAMP("2004-09-15 05:00:00") AS valid_timestamp'
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
expected = DataFrame(
{"valid_timestamp": ["2004-09-15T05:00:00.000000Z"]},
dtype="datetime64[ns]",
)
if expected["valid_timestamp"].dt.tz is None:
expected["valid_timestamp"] = expected[
"valid_timestamp"
].dt.tz_localize("UTC")
tm.assert_frame_equal(df, expected)
def test_should_properly_handle_datetime_unix_epoch(self, project_id):
query = 'SELECT DATETIME("1970-01-01 00:00:00") AS unix_epoch'
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df,
DataFrame(
{"unix_epoch": ["1970-01-01T00:00:00"]}, dtype="datetime64[ns]"
),
)
def test_should_properly_handle_arbitrary_datetime(self, project_id):
query = 'SELECT DATETIME("2004-09-15 05:00:00") AS valid_timestamp'
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df,
DataFrame(
{"valid_timestamp": [np.datetime64("2004-09-15T05:00:00")]}
),
)
@pytest.mark.parametrize(
"expression, is_expected_dtype",
[
("current_date()", pandas.api.types.is_datetime64_ns_dtype),
("current_timestamp()", pandas.api.types.is_datetime64tz_dtype),
("current_datetime()", pandas.api.types.is_datetime64_ns_dtype),
("TRUE", pandas.api.types.is_bool_dtype),
("FALSE", pandas.api.types.is_bool_dtype),
],
)
def test_return_correct_types(
self, project_id, expression, is_expected_dtype
):
"""
All type checks can be added to this function using additional
parameters, rather than creating additional functions.
We can consolidate the existing functions here in time
TODO: time doesn't currently parse
("time(12,30,00)", "<M8[ns]"),
"""
query = "SELECT {} AS _".format(expression)
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
assert is_expected_dtype(df["_"].dtype)
def test_should_properly_handle_null_timestamp(self, project_id):
query = "SELECT TIMESTAMP(NULL) AS null_timestamp"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
expected = DataFrame({"null_timestamp": [NaT]}, dtype="datetime64[ns]")
expected["null_timestamp"] = expected["null_timestamp"].dt.tz_localize(
"UTC"
)
tm.assert_frame_equal(df, expected)
def test_should_properly_handle_null_datetime(self, project_id):
query = "SELECT CAST(NULL AS DATETIME) AS null_datetime"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
tm.assert_frame_equal(df, DataFrame({"null_datetime": [NaT]}))
def test_should_properly_handle_null_boolean(self, project_id):
query = "SELECT BOOLEAN(NULL) AS null_boolean"
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"null_boolean": [None]}))
def test_should_properly_handle_nullable_booleans(self, project_id):
query = """SELECT * FROM
(SELECT BOOLEAN(TRUE) AS nullable_boolean),
(SELECT NULL AS nullable_boolean)"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(
df, DataFrame({"nullable_boolean": [True, None]}).astype(object)
)
def test_unicode_string_conversion_and_normalization(self, project_id):
correct_test_datatype = DataFrame({"unicode_string": ["éü"]})
unicode_string = "éü"
query = 'SELECT "{0}" AS unicode_string'.format(unicode_string)
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
tm.assert_frame_equal(df, correct_test_datatype)
def test_index_column(self, project_id):
query = "SELECT 'a' AS string_1, 'b' AS string_2"
result_frame = gbq.read_gbq(
query,
project_id=project_id,
index_col="string_1",
credentials=self.credentials,
dialect="legacy",
)
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, project_id):
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=project_id,
col_order=col_order,
credentials=self.credentials,
dialect="legacy",
)
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, project_id):
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=project_id,
col_order=col_order,
credentials=self.credentials,
dialect="legacy",
)
def test_column_order_plus_index(self, project_id):
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=project_id,
index_col="string_1",
col_order=col_order,
credentials=self.credentials,
dialect="legacy",
)
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, project_id):
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=project_id,
index_col="string_bbb",
col_order=col_order,
credentials=self.credentials,
dialect="legacy",
)
def test_malformed_query(self, project_id):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(
"SELCET * FORM [publicdata:samples.shakespeare]",
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
def test_bad_project_id(self):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(
"SELCET * FROM [publicdata:samples.shakespeare]",
project_id="not-my-project",
credentials=self.credentials,
dialect="legacy",
)
def test_bad_table_name(self, project_id):
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(
"SELECT * FROM [publicdata:samples.nope]",
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
def test_download_dataset_larger_than_200k_rows(self, project_id):
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=project_id,
credentials=self.credentials,
dialect="legacy",
)
assert len(df.drop_duplicates()) == test_size
def test_ddl(self, random_dataset, project_id):
# Bug fix for https://github.com/pydata/pandas-gbq/issues/45
df = gbq.read_gbq(
"CREATE OR REPLACE TABLE {}.test_ddl (x INT64)".format(
random_dataset.dataset_id
)
)
assert len(df) == 0
def test_ddl_w_max_results(self, random_dataset, project_id):
df = gbq.read_gbq(
"CREATE OR REPLACE TABLE {}.test_ddl (x INT64)".format(
random_dataset.dataset_id
),
max_results=0,
)
assert df is None
def test_max_results(self, random_dataset, project_id):
df = gbq.read_gbq(
"SELECT * FROM UNNEST(GENERATE_ARRAY(1, 100))", max_results=10
)
assert len(df) == 10
def test_zero_rows(self, project_id):
# Bug fix for https://github.com/pandas-dev/pandas/issues/10273
df = gbq.read_gbq(
'SELECT name, number, (mlc_class = "HU") is_hurricane, iso_time '
"FROM `bigquery-public-data.noaa_hurricanes.hurricanes` "
'WHERE iso_time = TIMESTAMP("1900-01-01 00:00:00") ',
project_id=project_id,
credentials=self.credentials,
)
empty_columns = {
"name": pandas.Series([], dtype=object),
"number": pandas.Series([], dtype=np.dtype(int)),
"is_hurricane": pandas.Series([], dtype=np.dtype(bool)),
"iso_time": pandas.Series([], dtype="datetime64[ns]"),
}
expected_result = DataFrame(
empty_columns,
columns=["name", "number", "is_hurricane", "iso_time"],
)
tm.assert_frame_equal(df, expected_result, check_index_type=False)
def test_one_row_one_column(self, project_id):
df = gbq.read_gbq(
"SELECT 3 as v",
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
expected_result = DataFrame(dict(v=[3]))
tm.assert_frame_equal(df, expected_result)
def test_legacy_sql(self, project_id):
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=project_id,
dialect="standard",
credentials=self.credentials,
)
# Test that a legacy sql statement succeeds when
# setting dialect='legacy'
df = gbq.read_gbq(
legacy_sql,
project_id=project_id,
dialect="legacy",
credentials=self.credentials,
)
assert len(df.drop_duplicates()) == 10
def test_standard_sql(self, project_id):
standard_sql = (
"SELECT DISTINCT id FROM "
"`publicdata.samples.wikipedia` LIMIT 10"
)
# Test that a standard sql statement fails when using
# the legacy SQL dialect.
with pytest.raises(gbq.GenericGBQException):
gbq.read_gbq(
standard_sql,
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
# Test that a standard sql statement succeeds when
# setting dialect='standard'
df = gbq.read_gbq(
standard_sql,
project_id=project_id,
dialect="standard",
credentials=self.credentials,
)
assert len(df.drop_duplicates()) == 10
def test_query_with_parameters(self, project_id):
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=project_id,
credentials=self.credentials,
dialect="legacy",
)
# 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=project_id,
credentials=self.credentials,
configuration=config,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"valid_result": [3]}))
def test_query_inside_configuration(self, project_id):
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=project_id,
credentials=self.credentials,
configuration=config,
dialect="legacy",
)
df = gbq.read_gbq(
None,
project_id=project_id,
credentials=self.credentials,
configuration=config,
dialect="legacy",
)
tm.assert_frame_equal(df, DataFrame({"valid_string": ["PI"]}))
def test_configuration_without_query(self, project_id):
sql_statement = "SELECT 1"
config = {
"copy": {
"sourceTable": {
"projectId": project_id,
"datasetId": "publicdata:samples",
"tableId": "wikipedia",
},
"destinationTable": {
"projectId": 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=project_id,
credentials=self.credentials,
configuration=config,
dialect="legacy",
)
def test_configuration_raises_value_error_with_multiple_config(
self, project_id
):
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=project_id,
credentials=self.credentials,
configuration=config,
dialect="legacy",
)
def test_timeout_configuration(self, project_id):
sql_statement = """
SELECT
SUM(bottles_sold) total_bottles,
UPPER(category_name) category_name,
magnitude,
liquor.zip_code zip_code
FROM `bigquery-public-data.iowa_liquor_sales.sales` liquor
JOIN `bigquery-public-data.geo_us_boundaries.zip_codes` zip_codes
ON liquor.zip_code = zip_codes.zip_code
JOIN `bigquery-public-data.noaa_historic_severe_storms.tornado_paths` tornados
ON liquor.date = tornados.storm_date
WHERE ST_INTERSECTS(tornado_path_geom, zip_code_geom)
GROUP BY category_name, magnitude, zip_code
ORDER BY magnitude ASC, total_bottles DESC
"""
configs = [
{"query": {"useQueryCache": False, "timeoutMs": 1}},
{"query": {"useQueryCache": False}, "jobTimeoutMs": 1},
]
for config in configs:
with pytest.raises(gbq.QueryTimeout):
gbq.read_gbq(
sql_statement,
project_id=project_id,
credentials=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, project_id):
query = """SELECT 1 int_field,
STRUCT("a" as letter, 1 as num) struct_field"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=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, project_id):
query = """select ["a","x","b","y","c","z"] as letters"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
tm.assert_frame_equal(
df,
DataFrame([[["a", "x", "b", "y", "c", "z"]]], columns=["letters"]),
)
def test_array_length_zero(self, project_id):
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=project_id,
credentials=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, project_id):
query = """WITH t as (
SELECT "a" letter, 1 num
UNION ALL
SELECT "b" letter, 2 num
UNION ALL
SELECT "a" letter, 3 num)
select letter, array_agg(num order by num ASC) numbers
from t
group by letter
order by letter ASC"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
tm.assert_frame_equal(
df,
DataFrame(
[["a", [1, 3]], ["b", [2]]], columns=["letter", "numbers"]
),
)
def test_array_of_floats(self, project_id):
query = """select [1.1, 2.2, 3.3] as a, 4 as b"""
df = gbq.read_gbq(
query,
project_id=project_id,
credentials=self.credentials,
dialect="standard",
)
tm.assert_frame_equal(
df, DataFrame([[[1.1, 2.2, 3.3], 4]], columns=["a", "b"])
)
def test_tokyo(self, tokyo_dataset, tokyo_table, project_id):
df = gbq.read_gbq(
"SELECT MAX(year) AS max_year FROM {}.{}".format(
tokyo_dataset, tokyo_table
),
dialect="standard",
location="asia-northeast1",
project_id=project_id,
credentials=self.credentials,
)
assert df["max_year"][0] >= 2000
class TestToGBQIntegration(object):
@pytest.fixture(autouse=True, scope="function")
def setup(self, project, credentials, random_dataset_id):
from google.cloud import bigquery
# - PER-TEST FIXTURES -
# put here any instruction you want to be run *BEFORE* *EVERY* test is
# executed.
self.table = gbq._Table(
project, random_dataset_id, credentials=credentials
)
self.destination_table = "{}.{}".format(random_dataset_id, TABLE_ID)
self.credentials = credentials
self.bqclient = bigquery.Client(
project=project, credentials=credentials
)
def test_upload_data(self, project_id):
test_id = "1"
test_size = 20001
df = make_mixed_dataframe_v2(test_size)
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
chunksize=10000,
credentials=self.credentials,
)
result = gbq.read_gbq(
"SELECT COUNT(*) AS num_rows FROM {0}".format(
self.destination_table + test_id
),
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
assert result["num_rows"][0] == test_size
def test_upload_empty_data(self, project_id):
test_id = "data_with_0_rows"
df = DataFrame()
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
credentials=self.credentials,
)
table = self.bqclient.get_table(self.destination_table + test_id)
assert table.num_rows == 0
assert len(table.schema) == 0
def test_upload_empty_data_with_schema(self, project_id):
test_id = "data_with_0_rows"
df = DataFrame(
{
"a": pandas.Series(dtype="int64"),
"b": pandas.Series(dtype="object"),
}
)
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
credentials=self.credentials,
)
table = self.bqclient.get_table(self.destination_table + test_id)
assert table.num_rows == 0
schema = table.schema
assert schema[0].field_type == "INTEGER"
assert schema[1].field_type == "STRING"
def test_upload_data_if_table_exists_fail(self, project_id):
test_id = "2"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
self.table.create(TABLE_ID + test_id, gbq._generate_bq_schema(df))
# Test the default value of if_exists is 'fail'
with pytest.raises(gbq.TableCreationError):
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
credentials=self.credentials,
)
# Test the if_exists parameter with value 'fail'
with pytest.raises(gbq.TableCreationError):
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
if_exists="fail",
credentials=self.credentials,
)
def test_upload_data_if_table_exists_append(self, project_id):
test_id = "3"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
df_different_schema = tm.makeMixedDataFrame()
# Initialize table with sample data
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
chunksize=10000,
credentials=self.credentials,
)
# Test the if_exists parameter with value 'append'
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
if_exists="append",
credentials=self.credentials,
)
result = gbq.read_gbq(
"SELECT COUNT(*) AS num_rows FROM {0}".format(
self.destination_table + test_id
),
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
assert result["num_rows"][0] == test_size * 2
# Try inserting with a different schema, confirm failure
with pytest.raises(gbq.InvalidSchema):
gbq.to_gbq(
df_different_schema,
self.destination_table + test_id,
project_id,
if_exists="append",
credentials=self.credentials,
)
def test_upload_subset_columns_if_table_exists_append(self, project_id):
# Issue 24: Upload is succesful if dataframe has columns
# which are a subset of the current schema
test_id = "16"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
df_subset_cols = df.iloc[:, :2]
# Initialize table with sample data
gbq.to_gbq(