/
test_magics.py
1389 lines (1116 loc) · 49 KB
/
test_magics.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 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import re
from concurrent import futures
import mock
import pytest
import six
try:
import pandas
except ImportError: # pragma: NO COVER
pandas = None
try:
import IPython
from IPython.utils import io
from IPython.testing import tools
from IPython.terminal import interactiveshell
except ImportError: # pragma: NO COVER
IPython = None
from google.api_core import exceptions
import google.auth.credentials
try:
from google.cloud import bigquery_storage_v1beta1
except ImportError: # pragma: NO COVER
bigquery_storage_v1beta1 = None
from google.cloud import bigquery
from google.cloud.bigquery import job
from google.cloud.bigquery import table
from google.cloud.bigquery import magics
from tests.unit.helpers import make_connection
from test_utils.imports import maybe_fail_import
pytestmark = pytest.mark.skipif(IPython is None, reason="Requires `ipython`")
@pytest.fixture(scope="session")
def ipython():
config = tools.default_config()
config.TerminalInteractiveShell.simple_prompt = True
shell = interactiveshell.TerminalInteractiveShell.instance(config=config)
return shell
@pytest.fixture()
def ipython_interactive(request, ipython):
"""Activate IPython's builtin hooks
for the duration of the test scope.
"""
with ipython.builtin_trap:
yield ipython
@pytest.fixture(scope="session")
def missing_bq_storage():
"""Provide a patcher that can make the bigquery storage import to fail."""
def fail_if(name, globals, locals, fromlist, level):
# NOTE: *very* simplified, assuming a straightforward absolute import
return "bigquery_storage_v1beta1" in name or (
fromlist is not None and "bigquery_storage_v1beta1" in fromlist
)
return maybe_fail_import(predicate=fail_if)
@pytest.fixture(scope="session")
def missing_grpcio_lib():
"""Provide a patcher that can make the gapic library import to fail."""
def fail_if(name, globals, locals, fromlist, level):
# NOTE: *very* simplified, assuming a straightforward absolute import
return "gapic_v1" in name or (fromlist is not None and "gapic_v1" in fromlist)
return maybe_fail_import(predicate=fail_if)
JOB_REFERENCE_RESOURCE = {"projectId": "its-a-project-eh", "jobId": "some-random-id"}
TABLE_REFERENCE_RESOURCE = {
"projectId": "its-a-project-eh",
"datasetId": "ds",
"tableId": "persons",
}
QUERY_RESOURCE = {
"jobReference": JOB_REFERENCE_RESOURCE,
"configuration": {
"query": {
"destinationTable": TABLE_REFERENCE_RESOURCE,
"query": "SELECT 42 FROM `life.the_universe.and_everything`;",
"queryParameters": [],
"useLegacySql": False,
}
},
"status": {"state": "DONE"},
}
def test_context_credentials_auto_set_w_application_default_credentials():
"""When Application Default Credentials are set, the context credentials
will be created the first time it is called
"""
assert magics.context._credentials is None
assert magics.context._project is None
project = "prahj-ekt"
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, project)
)
with default_patch as default_mock:
assert magics.context.credentials is credentials_mock
assert magics.context.project == project
assert default_mock.call_count == 2
def test_context_credentials_and_project_can_be_set_explicitly():
project1 = "one-project-55564"
project2 = "other-project-52569"
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, project1)
)
with default_patch as default_mock:
magics.context.credentials = credentials_mock
magics.context.project = project2
assert magics.context.project == project2
assert magics.context.credentials is credentials_mock
# default should not be called if credentials & project are explicitly set
assert default_mock.call_count == 0
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_context_connection_can_be_overriden():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
magics.context._credentials = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
project = "project-123"
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, project)
)
job_reference = copy.deepcopy(JOB_REFERENCE_RESOURCE)
job_reference["projectId"] = project
query = "select * from persons"
resource = copy.deepcopy(QUERY_RESOURCE)
resource["jobReference"] = job_reference
resource["configuration"]["query"]["query"] = query
data = {"jobReference": job_reference, "totalRows": 0, "rows": []}
conn = magics.context._connection = make_connection(resource, data)
list_rows_patch = mock.patch(
"google.cloud.bigquery.client.Client.list_rows",
return_value=google.cloud.bigquery.table._EmptyRowIterator(),
)
with list_rows_patch as list_rows, default_patch:
ip.run_cell_magic("bigquery", "", query)
# Check that query actually starts the job.
list_rows.assert_called()
assert len(conn.api_request.call_args_list) == 2
_, req = conn.api_request.call_args_list[0]
assert req["method"] == "POST"
assert req["path"] == "/projects/{}/jobs".format(project)
sent = req["data"]
assert isinstance(sent["jobReference"]["jobId"], six.string_types)
sent_config = sent["configuration"]["query"]
assert sent_config["query"] == query
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_context_no_connection():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
magics.context._credentials = None
magics.context._connection = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
project = "project-123"
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, project)
)
job_reference = copy.deepcopy(JOB_REFERENCE_RESOURCE)
job_reference["projectId"] = project
query = "select * from persons"
resource = copy.deepcopy(QUERY_RESOURCE)
resource["jobReference"] = job_reference
resource["configuration"]["query"]["query"] = query
data = {"jobReference": job_reference, "totalRows": 0, "rows": []}
conn_mock = make_connection(resource, data, data, data)
conn_patch = mock.patch("google.cloud.bigquery.client.Connection", autospec=True)
list_rows_patch = mock.patch(
"google.cloud.bigquery.client.Client.list_rows",
return_value=google.cloud.bigquery.table._EmptyRowIterator(),
)
with conn_patch as conn, list_rows_patch as list_rows, default_patch:
conn.return_value = conn_mock
ip.run_cell_magic("bigquery", "", query)
# Check that query actually starts the job.
list_rows.assert_called()
assert len(conn_mock.api_request.call_args_list) == 2
_, req = conn_mock.api_request.call_args_list[0]
assert req["method"] == "POST"
assert req["path"] == "/projects/{}/jobs".format(project)
sent = req["data"]
assert isinstance(sent["jobReference"]["jobId"], six.string_types)
sent_config = sent["configuration"]["query"]
assert sent_config["query"] == query
def test__run_query():
magics.context._credentials = None
job_id = "job_1234"
sql = "SELECT 17"
responses = [
futures.TimeoutError,
futures.TimeoutError,
[table.Row((17,), {"num": 0})],
]
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
with client_patch as client_mock, io.capture_output() as captured:
client_mock().query(sql).result.side_effect = responses
client_mock().query(sql).job_id = job_id
query_job = magics._run_query(client_mock(), sql)
lines = re.split("\n|\r", captured.stdout)
# Removes blanks & terminal code (result of display clearing)
updates = list(filter(lambda x: bool(x) and x != "\x1b[2K", lines))
assert query_job.job_id == job_id
expected_first_line = "Executing query with job ID: {}".format(job_id)
assert updates[0] == expected_first_line
execution_updates = updates[1:-1]
assert len(execution_updates) == 3 # one update per API response
for line in execution_updates:
assert re.match("Query executing: .*s", line)
assert re.match("Query complete after .*s", updates[-1])
def test__run_query_dry_run_without_errors_is_silent():
magics.context._credentials = None
sql = "SELECT 17"
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
job_config = job.QueryJobConfig()
job_config.dry_run = True
with client_patch as client_mock, io.capture_output() as captured:
client_mock().query(sql).job_id = None
magics._run_query(client_mock(), sql, job_config=job_config)
assert len(captured.stderr) == 0
assert len(captured.stdout) == 0
def test__make_bqstorage_client_false():
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
got = magics._make_bqstorage_client(False, credentials_mock)
assert got is None
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test__make_bqstorage_client_true():
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
got = magics._make_bqstorage_client(True, credentials_mock)
assert isinstance(got, bigquery_storage_v1beta1.BigQueryStorageClient)
def test__make_bqstorage_client_true_raises_import_error(missing_bq_storage):
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
with pytest.raises(ImportError) as exc_context, missing_bq_storage:
magics._make_bqstorage_client(True, credentials_mock)
error_msg = str(exc_context.value)
assert "google-cloud-bigquery-storage" in error_msg
assert "pyarrow" in error_msg
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test__make_bqstorage_client_true_missing_gapic(missing_grpcio_lib):
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
with pytest.raises(ImportError) as exc_context, missing_grpcio_lib:
magics._make_bqstorage_client(True, credentials_mock)
assert "grpcio" in str(exc_context.value)
def test__create_dataset_if_necessary_exists():
project = "project_id"
dataset_id = "dataset_id"
dataset_reference = bigquery.dataset.DatasetReference(project, dataset_id)
dataset = bigquery.Dataset(dataset_reference)
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
with client_patch as client_mock:
client = client_mock()
client.project = project
client.get_dataset.result_value = dataset
magics._create_dataset_if_necessary(client, dataset_id)
client.create_dataset.assert_not_called()
def test__create_dataset_if_necessary_not_exist():
project = "project_id"
dataset_id = "dataset_id"
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
with client_patch as client_mock:
client = client_mock()
client.location = "us"
client.project = project
client.get_dataset.side_effect = exceptions.NotFound("dataset not found")
magics._create_dataset_if_necessary(client, dataset_id)
client.create_dataset.assert_called_once()
@pytest.mark.usefixtures("ipython_interactive")
def test_extension_load():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
# verify that the magic is registered and has the correct source
magic = ip.magics_manager.magics["cell"].get("bigquery")
assert magic.__module__ == "google.cloud.bigquery.magics"
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_bigquery_magic_without_optional_arguments(missing_bq_storage):
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
# Shouldn't fail when BigQuery Storage client isn't installed.
with run_query_patch as run_query_mock, missing_bq_storage:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "", sql)
assert isinstance(return_value, pandas.DataFrame)
assert len(return_value) == len(result) # verify row count
assert list(return_value) == list(result) # verify column names
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_default_connection_user_agent():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._connection = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
conn_patch = mock.patch("google.cloud.bigquery.client.Connection", autospec=True)
with conn_patch as conn, run_query_patch, default_patch:
ip.run_cell_magic("bigquery", "", "SELECT 17 as num")
client_info_arg = conn.call_args.kwargs.get("client_info")
assert client_info_arg is not None
assert client_info_arg.user_agent == "ipython-" + IPython.__version__
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_with_legacy_sql():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
with run_query_patch as run_query_mock:
ip.run_cell_magic("bigquery", "--use_legacy_sql", "SELECT 17 AS num")
job_config_used = run_query_mock.call_args_list[0][1]["job_config"]
assert job_config_used.use_legacy_sql is True
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_bigquery_magic_with_result_saved_to_variable():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
assert "df" not in ip.user_ns
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
with run_query_patch as run_query_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "df", sql)
assert return_value is None
assert "df" in ip.user_ns # verify that variable exists
df = ip.user_ns["df"]
assert len(df) == len(result) # verify row count
assert list(df) == list(result) # verify column names
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_does_not_clear_display_in_verbose_mode():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
clear_patch = mock.patch(
"google.cloud.bigquery.magics.display.clear_output", autospec=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
with clear_patch as clear_mock, run_query_patch:
ip.run_cell_magic("bigquery", "--verbose", "SELECT 17 as num")
assert clear_mock.call_count == 0
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_clears_display_in_verbose_mode():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
clear_patch = mock.patch(
"google.cloud.bigquery.magics.display.clear_output", autospec=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
with clear_patch as clear_mock, run_query_patch:
ip.run_cell_magic("bigquery", "", "SELECT 17 as num")
assert clear_mock.call_count == 1
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test_bigquery_magic_with_bqstorage_from_argument(monkeypatch):
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
# Set up the context with monkeypatch so that it's reset for subsequent
# tests.
monkeypatch.setattr(magics.context, "credentials", mock_credentials)
monkeypatch.setattr(magics.context, "use_bqstorage_api", False)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient
)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient, instance=True
)
bqstorage_instance_mock.transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient", bqstorage_mock
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
with run_query_patch as run_query_mock, bqstorage_client_patch:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--use_bqstorage_api", sql)
assert len(bqstorage_mock.call_args_list) == 1
kwargs = bqstorage_mock.call_args_list[0].kwargs
assert kwargs.get("credentials") is mock_credentials
client_info = kwargs.get("client_info")
assert client_info is not None
assert client_info.user_agent == "ipython-" + IPython.__version__
query_job_mock.to_dataframe.assert_called_once_with(
bqstorage_client=bqstorage_instance_mock
)
assert isinstance(return_value, pandas.DataFrame)
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test_bigquery_magic_with_bqstorage_from_context(monkeypatch):
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
# Set up the context with monkeypatch so that it's reset for subsequent
# tests.
monkeypatch.setattr(magics.context, "credentials", mock_credentials)
monkeypatch.setattr(magics.context, "use_bqstorage_api", True)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient
)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient, instance=True
)
bqstorage_instance_mock.transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient", bqstorage_mock
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
with run_query_patch as run_query_mock, bqstorage_client_patch:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "", sql)
assert len(bqstorage_mock.call_args_list) == 1
kwargs = bqstorage_mock.call_args_list[0].kwargs
assert kwargs.get("credentials") is mock_credentials
client_info = kwargs.get("client_info")
assert client_info is not None
assert client_info.user_agent == "ipython-" + IPython.__version__
query_job_mock.to_dataframe.assert_called_once_with(
bqstorage_client=bqstorage_instance_mock
)
assert isinstance(return_value, pandas.DataFrame)
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test_bigquery_magic_without_bqstorage(monkeypatch):
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
# Set up the context with monkeypatch so that it's reset for subsequent
# tests.
monkeypatch.setattr(magics.context, "credentials", mock_credentials)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient
)
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient", bqstorage_mock
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
with run_query_patch as run_query_mock, bqstorage_client_patch:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "", sql)
bqstorage_mock.assert_not_called()
query_job_mock.to_dataframe.assert_called_once_with(bqstorage_client=None)
assert isinstance(return_value, pandas.DataFrame)
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_w_max_results_invalid():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
client_query_patch = mock.patch(
"google.cloud.bigquery.client.Client.query", autospec=True
)
sql = "SELECT 17 AS num"
with pytest.raises(ValueError), default_patch, client_query_patch:
ip.run_cell_magic("bigquery", "--max_results=abc", sql)
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_w_max_results_valid_calls_queryjob_result():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
client_query_patch = mock.patch(
"google.cloud.bigquery.client.Client.query", autospec=True
)
sql = "SELECT 17 AS num"
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
with client_query_patch as client_query_mock, default_patch:
client_query_mock.return_value = query_job_mock
ip.run_cell_magic("bigquery", "--max_results=5", sql)
query_job_mock.result.assert_called_with(max_results=5)
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_w_max_results_query_job_results_fails():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
client_query_patch = mock.patch(
"google.cloud.bigquery.client.Client.query", autospec=True
)
close_transports_patch = mock.patch(
"google.cloud.bigquery.magics._close_transports", autospec=True,
)
sql = "SELECT 17 AS num"
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.result.side_effect = [[], OSError]
with pytest.raises(
OSError
), client_query_patch as client_query_mock, default_patch, close_transports_patch as close_transports:
client_query_mock.return_value = query_job_mock
ip.run_cell_magic("bigquery", "--max_results=5", sql)
assert close_transports.called
def test_bigquery_magic_w_table_id_invalid():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
list_rows_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client.list_rows",
autospec=True,
side_effect=exceptions.BadRequest("Not a valid table ID"),
)
table_id = "not-a-real-table"
with list_rows_patch, default_patch, io.capture_output() as captured_io:
ip.run_cell_magic("bigquery", "df", table_id)
output = captured_io.stderr
assert "Could not save output to variable" in output
assert "400 Not a valid table ID" in output
assert "Traceback (most recent call last)" not in output
def test_bigquery_magic_w_missing_query():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
cell_body = " \n \n \t\t \n "
with io.capture_output() as captured_io:
ip.run_cell_magic("bigquery", "df", cell_body)
output = captured_io.stderr
assert "Could not save output to variable" in output
assert "Query is missing" in output
assert "Traceback (most recent call last)" not in output
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_bigquery_magic_w_table_id_and_destination_var():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
row_iterator_mock = mock.create_autospec(
google.cloud.bigquery.table.RowIterator, instance=True
)
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
table_id = "bigquery-public-data.samples.shakespeare"
result = pandas.DataFrame([17], columns=["num"])
with client_patch as client_mock, default_patch:
client_mock().list_rows.return_value = row_iterator_mock
row_iterator_mock.to_dataframe.return_value = result
ip.run_cell_magic("bigquery", "df", table_id)
assert "df" in ip.user_ns
df = ip.user_ns["df"]
assert isinstance(df, pandas.DataFrame)
@pytest.mark.usefixtures("ipython_interactive")
@pytest.mark.skipif(
bigquery_storage_v1beta1 is None, reason="Requires `google-cloud-bigquery-storage`"
)
@pytest.mark.skipif(pandas is None, reason="Requires `pandas`")
def test_bigquery_magic_w_table_id_and_bqstorage_client():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context._project = None
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
default_patch = mock.patch(
"google.auth.default", return_value=(credentials_mock, "general-project")
)
row_iterator_mock = mock.create_autospec(
google.cloud.bigquery.table.RowIterator, instance=True
)
client_patch = mock.patch(
"google.cloud.bigquery.magics.bigquery.Client", autospec=True
)
bqstorage_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient
)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage_v1beta1.BigQueryStorageClient, instance=True
)
bqstorage_instance_mock.transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage_v1beta1.BigQueryStorageClient", bqstorage_mock
)
table_id = "bigquery-public-data.samples.shakespeare"
with default_patch, client_patch as client_mock, bqstorage_client_patch:
client_mock().list_rows.return_value = row_iterator_mock
ip.run_cell_magic("bigquery", "--use_bqstorage_api --max_results=5", table_id)
row_iterator_mock.to_dataframe.assert_called_once_with(
bqstorage_client=bqstorage_instance_mock
)
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_dryrun_option_sets_job_config():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
sql = "SELECT 17 AS num"
with run_query_patch as run_query_mock:
ip.run_cell_magic("bigquery", "--dry_run", sql)
job_config_used = run_query_mock.call_args_list[0][1]["job_config"]
assert job_config_used.dry_run is True
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_dryrun_option_returns_query_job():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
sql = "SELECT 17 AS num"
with run_query_patch as run_query_mock, io.capture_output() as captured_io:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--dry_run", sql)
assert "Query validated. This query will process" in captured_io.stdout
assert isinstance(return_value, job.QueryJob)
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_dryrun_option_variable_error_message():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query",
autospec=True,
side_effect=exceptions.BadRequest("Syntax error in SQL query"),
)
sql = "SELECT SELECT 17 AS num"
assert "q_job" not in ip.user_ns
with run_query_patch, io.capture_output() as captured:
ip.run_cell_magic("bigquery", "q_job --dry_run", sql)
full_text = captured.stderr
assert "Could not save output to variable 'q_job'." in full_text
@pytest.mark.usefixtures("ipython_interactive")
def test_bigquery_magic_dryrun_option_saves_query_job_to_variable():
ip = IPython.get_ipython()
ip.extension_manager.load_extension("google.cloud.bigquery")
magics.context.credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
run_query_patch = mock.patch(
"google.cloud.bigquery.magics._run_query", autospec=True
)
sql = "SELECT 17 AS num"
assert "q_job" not in ip.user_ns
with run_query_patch as run_query_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "q_job --dry_run", sql)
assert return_value is None
assert "q_job" in ip.user_ns
q_job = ip.user_ns["q_job"]
assert isinstance(q_job, job.QueryJob)