-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathtest_gbq.py
1342 lines (1164 loc) · 43.3 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
# Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# -*- coding: utf-8 -*-
import datetime
import packaging.version
import sys
import numpy as np
import pandas
import pandas.api.types
import pandas.testing as tm
from pandas import DataFrame
try:
import pkg_resources # noqa
except ImportError:
raise ImportError("Could not import pkg_resources (setuptools).")
import pytest
import pytz
from pandas_gbq import gbq
import pandas_gbq.schema
TABLE_ID = "new_test"
PANDAS_VERSION = pkg_resources.parse_version(pandas.__version__)
def test_imports():
gbq._test_google_api_imports()
def make_mixed_dataframe_v1():
# Re-implementation of private pandas.util.testing.makeMixedDataFrame
return pandas.DataFrame(
{
"A": [0.0, 1.0, 2.0, 3.0, 4.0],
"B": [0.0, 1.0, 0.0, 1.0, 0.0],
"C": ["foo1", "foo2", "foo3", "foo4", "foo5"],
"D": pandas.bdate_range("1/1/2009", periods=5),
}
)
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.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 get_schema(gbq_connector: gbq.GbqConnector, dataset_id: str, table_id: str):
"""Retrieve the schema of the table
Obtain from BigQuery the field names and field types
for the table defined by the parameters
Parameters
----------
dataset_id : str
Name of the BigQuery dataset for the table
table_id : str
Name of the BigQuery table
Returns
-------
list of dicts
Fields representing the schema
"""
from google.cloud import bigquery
bqclient = gbq_connector.client
table_ref = bigquery.TableReference(
bigquery.DatasetReference(bqclient.project, dataset_id),
table_id,
)
try:
table = bqclient.get_table(table_ref)
remote_schema = table.schema
remote_fields = [field_remote.to_api_repr() for field_remote in remote_schema]
for field in remote_fields:
field["type"] = field["type"].upper()
field["mode"] = field["mode"].upper()
return remote_fields
except gbq_connector.http_error as ex:
gbq_connector.process_http_error(ex)
def verify_schema(gbq_connector, dataset_id, table_id, schema):
"""Indicate whether schemas match exactly
Compare the BigQuery table identified in the parameters with
the schema passed in and indicate whether all fields in the former
are present in the latter. Order is not considered.
Parameters
----------
dataset_id :str
Name of the BigQuery dataset for the table
table_id : str
Name of the BigQuery table
schema : list(dict)
Schema for comparison. Each item should have
a 'name' and a 'type'
Returns
-------
bool
Whether the schemas match
"""
fields_remote = pandas_gbq.schema._clean_schema_fields(
get_schema(gbq_connector, dataset_id, table_id)
)
fields_local = pandas_gbq.schema._clean_schema_fields(schema["fields"])
return fields_remote == fields_local
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_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_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]), dtype="Int64")
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]}, dtype="Int64"))
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 count(*) from unnest(generate_array(1,1000000)), unnest(generate_array(1, 10000))
"""
configs = [
# pandas-gbq timeout configuration. Transformed to REST API compatible version.
{"query": {"useQueryCache": False, "timeoutMs": 1}},
# REST API job timeout. See:
# https://cloud.google.com/bigquery/docs/reference/rest/v2/Job#JobConfiguration.FIELDS.job_timeout_ms
{"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_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(
{
"int_field": pandas.Series([1], dtype="Int64"),
"struct_field": [{"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(
{
"letter": ["a", "b"],
"array_field": [[""], []],
"len": pandas.Series([1, 0], dtype="Int64"),
},
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(
{"a": [[1.1, 2.2, 3.3]], "b": pandas.Series([4], dtype="Int64")},
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):
# - PER-TEST FIXTURES -
# put here any instruction you want to be run *BEFORE* *EVERY* test is
# executed.
self.credentials = credentials
self.gbq_connector = gbq.GbqConnector(project, credentials=credentials)
self.bqclient = self.gbq_connector.client
self.table = gbq._Table(project, random_dataset_id, credentials=credentials)
self.destination_table = "{}.{}".format(random_dataset_id, TABLE_ID)
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)
# Initialize table with sample data
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
chunksize=10000,
credentials=self.credentials,
)
# Test the default value of if_exists == '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 = make_mixed_dataframe_v1()
# 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(
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_subset_cols,
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
def test_upload_data_if_table_exists_replace(self, project_id):
test_id = "4"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
df_different_schema = make_mixed_dataframe_v1()
# 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 the value 'replace'.
gbq.to_gbq(
df_different_schema,
self.destination_table + test_id,
project_id,
if_exists="replace",
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] == 5
def test_upload_data_if_table_exists_raises_value_error(self, project_id):
test_id = "4"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
# Test invalid value for if_exists parameter raises value error
with pytest.raises(ValueError):
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
if_exists="xxxxx",
credentials=self.credentials,
)
def test_google_upload_errors_should_raise_exception(self, project_id):
raise pytest.skip("buggy test")
test_id = "5"
test_timestamp = datetime.datetime.now(pytz.timezone("US/Arizona"))
bad_df = DataFrame(
{
"bools": [False, False],
"flts": [0.0, 1.0],
"ints": [0, "1"],
"strs": ["a", 1],
"times": [test_timestamp, test_timestamp],
},
index=range(2),
)
with pytest.raises(gbq.StreamingInsertError):
gbq.to_gbq(
bad_df,
self.destination_table + test_id,
project_id,
credentials=self.credentials,
)
def test_upload_mixed_float_and_int(self, project_id):
"""Test that we can upload a dataframe containing an int64 and float64 column.
See: https://github.com/pydata/pandas-gbq/issues/116
"""
test_id = "mixed_float_and_int"
test_size = 2
df = DataFrame(
[[1, 1.1], [2, 2.2]],
index=["row 1", "row 2"],
columns=["intColumn", "floatColumn"],
)
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id=project_id,
credentials=self.credentials,
)
result_df = gbq.read_gbq(
"SELECT * FROM {0}".format(self.destination_table + test_id),
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
assert len(result_df) == test_size
def test_upload_data_with_newlines(self, project_id):
test_id = "data_with_newlines"
test_size = 2
df = DataFrame({"s": ["abcd", "ef\ngh"]})
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id=project_id,
credentials=self.credentials,
)
result_df = gbq.read_gbq(
"SELECT * FROM {0}".format(self.destination_table + test_id),
project_id=project_id,
credentials=self.credentials,
dialect="legacy",
)
assert len(result_df) == test_size
if sys.version_info.major < 3:
pytest.skip(msg="Unicode comparison in Py2 not working")
result = result_df["s"].sort_values()
expected = df["s"].sort_values()
tm.assert_series_equal(expected, result)
def test_upload_data_flexible_column_order(self, project_id):
test_id = "13"
test_size = 10
df = make_mixed_dataframe_v2(test_size)
# Initialize table with sample data
gbq.to_gbq(
df,
self.destination_table + test_id,
project_id,
chunksize=10000,
credentials=self.credentials,
)
df_columns_reversed = df[df.columns[::-1]]
gbq.to_gbq(
df_columns_reversed,
self.destination_table + test_id,
project_id,
if_exists="append",
credentials=self.credentials,
)
def test_upload_data_with_valid_user_schema(self, project_id):
# Issue #46; tests test scenarios with user-provided
# schemas
df = make_mixed_dataframe_v1()
test_id = "18"
test_schema = [
{"name": "A", "type": "FLOAT"},
{"name": "B", "type": "FLOAT"},
{"name": "C", "type": "STRING"},
{"name": "D", "type": "TIMESTAMP"},
]
destination_table = self.destination_table + test_id
gbq.to_gbq(
df,
destination_table,
project_id,
credentials=self.credentials,
table_schema=test_schema,
)
dataset, table = destination_table.split(".")
assert verify_schema(
self.gbq_connector, dataset, table, dict(fields=test_schema)
)
def test_upload_data_with_invalid_user_schema_raises_error(self, project_id):
df = make_mixed_dataframe_v1()
test_id = "19"
test_schema = [
{"name": "A", "type": "FLOAT"},
{"name": "B", "type": "FLOAT"},
{"name": "C", "type": "FLOAT"},
{"name": "D", "type": "FLOAT"},
]
destination_table = self.destination_table + test_id
with pytest.raises(gbq.GenericGBQException):
gbq.to_gbq(
df,
destination_table,
project_id,
credentials=self.credentials,
table_schema=test_schema,
)
def test_upload_data_with_missing_schema_fields_raises_error(self, project_id):
df = make_mixed_dataframe_v1()
test_id = "20"
test_schema = [
{"name": "A", "type": "FLOAT"},
{"name": "B", "type": "FLOAT"},
{"name": "C", "type": "FLOAT"},
]
destination_table = self.destination_table + test_id
with pytest.raises(gbq.GenericGBQException):
gbq.to_gbq(
df,
destination_table,
project_id,
credentials=self.credentials,
table_schema=test_schema,
)