-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtest_bigquery.py
More file actions
3309 lines (2679 loc) · 130 KB
/
test_bigquery.py
File metadata and controls
3309 lines (2679 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
from concurrent import futures
import contextlib
import copy
import json
import os
import pathlib
import re
import sys
import tempfile
from unittest import mock
import warnings
import IPython
from IPython.testing import globalipapp
import IPython.utils.io as io
from google.api_core import exceptions
import google.auth.credentials
from google.cloud import bigquery
from google.cloud.bigquery import exceptions as bq_exceptions
from google.cloud.bigquery import job, table
import google.cloud.bigquery._http
import google.cloud.bigquery.exceptions
from google.cloud.bigquery.retry import DEFAULT_TIMEOUT
import pandas
import pytest
import bigquery_magics
import bigquery_magics.bigquery as magics
import bigquery_magics.graph_server as graph_server
try:
import google.cloud.bigquery_storage as bigquery_storage
except ImportError:
bigquery_storage = None
try:
import bigframes.pandas as bpd
except ImportError:
bpd = None
try:
import spanner_graphs.graph_visualization as graph_visualization
except ImportError:
graph_visualization = None
try:
import geopandas as gpd
except ImportError:
gpd = None
Path = pathlib.Path
def make_connection(*args):
# TODO(tswast): Remove this in favor of a mock google.cloud.bigquery.Client
# in tests.
conn = mock.create_autospec(google.cloud.bigquery._http.Connection, instance=True)
conn.api_request.side_effect = args
return conn
PROJECT_ID = "its-a-project-eh"
JOB_ID = "some-random-id"
JOB_REFERENCE_RESOURCE = {"projectId": PROJECT_ID, "jobId": JOB_ID}
DATASET_ID = "dest_dataset"
TABLE_ID = "dest_table"
TABLE_REFERENCE_RESOURCE = {
"projectId": PROJECT_ID,
"datasetId": DATASET_ID,
"tableId": TABLE_ID,
}
QUERY_STRING = "SELECT 42 AS the_answer FROM `life.the_universe.and_everything`;"
QUERY_RESOURCE = {
"jobReference": JOB_REFERENCE_RESOURCE,
"configuration": {
"query": {
"destinationTable": TABLE_REFERENCE_RESOURCE,
"query": QUERY_STRING,
"queryParameters": [],
"useLegacySql": False,
}
},
"status": {"state": "DONE"},
}
QUERY_RESULTS_RESOURCE = {
"jobReference": JOB_REFERENCE_RESOURCE,
"totalRows": 1,
"jobComplete": True,
"schema": {"fields": [{"name": "the_answer", "type": "INTEGER"}]},
}
def test_context_with_default_connection():
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
bigquery_magics.context._credentials = None
bigquery_magics.context._project = None
bigquery_magics.context._connection = None
default_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
credentials_patch = mock.patch(
"google.auth.default", return_value=(default_credentials, "project-from-env")
)
default_conn = make_connection(QUERY_RESOURCE, QUERY_RESULTS_RESOURCE)
conn_patch = mock.patch("google.cloud.bigquery.client.Connection", autospec=True)
list_rows_patch = mock.patch(
"google.cloud.bigquery.client.Client._list_rows_from_query_results",
return_value=google.cloud.bigquery.table._EmptyRowIterator(),
)
with conn_patch as conn, credentials_patch, list_rows_patch as list_rows:
conn.return_value = default_conn
ip.run_cell_magic("bigquery", "", QUERY_STRING)
# Check that query actually starts the job.
conn.assert_called()
list_rows.assert_called()
begin_call = mock.call(
method="POST",
path="/projects/project-from-env/jobs",
data=mock.ANY,
timeout=DEFAULT_TIMEOUT,
)
query_results_call = mock.call(
method="GET",
path=f"/projects/{PROJECT_ID}/queries/{JOB_ID}",
query_params=mock.ANY,
timeout=mock.ANY,
headers=mock.ANY,
)
default_conn.api_request.assert_has_calls([begin_call, query_results_call])
def test_context_with_custom_connection():
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
bigquery_magics.context._project = None
bigquery_magics.context._credentials = None
context_conn = bigquery_magics.context._connection = make_connection(
QUERY_RESOURCE, QUERY_RESULTS_RESOURCE
)
default_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
credentials_patch = mock.patch(
"google.auth.default", return_value=(default_credentials, "project-from-env")
)
default_conn = make_connection()
conn_patch = mock.patch("google.cloud.bigquery.client.Connection", autospec=True)
list_rows_patch = mock.patch(
"google.cloud.bigquery.client.Client._list_rows_from_query_results",
return_value=google.cloud.bigquery.table._EmptyRowIterator(),
)
with conn_patch as conn, credentials_patch, list_rows_patch as list_rows:
conn.return_value = default_conn
ip.run_cell_magic("bigquery", "", QUERY_STRING)
list_rows.assert_called()
default_conn.api_request.assert_not_called()
begin_call = mock.call(
method="POST",
path="/projects/project-from-env/jobs",
data=mock.ANY,
timeout=DEFAULT_TIMEOUT,
)
query_results_call = mock.call(
method="GET",
path=f"/projects/{PROJECT_ID}/queries/{JOB_ID}",
query_params=mock.ANY,
timeout=mock.ANY,
headers=mock.ANY,
)
context_conn.api_request.assert_has_calls([begin_call, query_results_call])
def test__run_query():
bigquery_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("bigquery_magics.bigquery.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)
def test__run_query_dry_run_without_errors_is_silent():
bigquery_magics.context._credentials = None
sql = "SELECT 17"
client_patch = mock.patch("bigquery_magics.bigquery.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__get_graph_schema_exception():
bq_client = mock.create_autospec(bigquery.Client, instance=True)
bq_client.query.side_effect = Exception("error")
query_text = "GRAPH foo.bar"
query_job = mock.Mock()
graph_ref = mock.Mock()
graph_ref.project = "my-project"
graph_ref.dataset_id = "dataset"
graph_ref.property_graph_id = "graph"
query_job.referenced_property_graphs = [graph_ref]
assert magics._get_graph_schema(bq_client, query_text, query_job) is None
def test__get_graph_schema_zero_references():
bq_client = mock.create_autospec(bigquery.Client, instance=True)
query_job = mock.Mock()
query_job.referenced_property_graphs = []
assert magics._get_graph_schema(bq_client, "SELECT 1", query_job) is None
def test__get_graph_schema_two_references():
bq_client = mock.create_autospec(bigquery.Client, instance=True)
query_job = mock.Mock()
ref1 = mock.Mock()
ref2 = mock.Mock()
query_job.referenced_property_graphs = [ref1, ref2]
assert magics._get_graph_schema(bq_client, "SELECT 1", query_job) is None
def test__get_graph_schema_success():
bq_client = mock.create_autospec(bigquery.Client, instance=True)
query_job = mock.Mock()
graph_ref = mock.Mock()
graph_ref.project = "my-project"
graph_ref.dataset_id = "dataset"
graph_ref.property_graph_id = "graph"
query_job.referenced_property_graphs = [graph_ref]
mock_df = mock.MagicMock()
mock_df.shape = (1, 1)
mock_df.iloc.__getitem__.return_value = "schema_json"
bq_client.query.return_value.to_dataframe.return_value = mock_df
with mock.patch(
"bigquery_magics.bigquery.graph_server._convert_schema"
) as convert_mock:
convert_mock.return_value = {"nodes": [], "edges": []}
result = magics._get_graph_schema(bq_client, "SELECT 1", query_job)
assert result == {"nodes": [], "edges": []}
convert_mock.assert_called_once_with("schema_json")
called_query = bq_client.query.call_args[0][0]
assert (
"FROM `my-project.dataset`.INFORMATION_SCHEMA.PROPERTY_GRAPHS"
in called_query
)
called_config = bq_client.query.call_args[1]["job_config"]
called_params = called_config.query_parameters
assert len(called_params) == 1
assert called_params[0].name == "graph_id"
assert called_params[0].value == "graph"
@pytest.mark.skipif(
bigquery_storage is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test__make_bqstorage_client():
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
test_client = bigquery.Client(
project="test_project", credentials=credentials_mock, location="test_location"
)
got = magics._make_bqstorage_client(test_client, {})
assert isinstance(got, bigquery_storage.BigQueryReadClient)
def test__make_bqstorage_client_true_raises_import_error(missing_bq_storage):
"""When package `google-cloud-bigquery-storage` is not installed, reports
ImportError.
"""
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
test_client = bigquery.Client(
project="test_project", credentials=credentials_mock, location="test_location"
)
with pytest.raises(ImportError) as exc_context, missing_bq_storage:
magics._make_bqstorage_client(test_client, {})
error_msg = str(exc_context.value)
assert "google-cloud-bigquery-storage" in error_msg
assert "pyarrow" in error_msg
@pytest.mark.skipif(
bigquery_storage is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test__make_bqstorage_client_true_obsolete_dependency():
"""When package `google-cloud-bigquery-storage` is installed but has outdated
version, returns None, and raises a warning.
"""
credentials_mock = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
test_client = bigquery.Client(
project="test_project", credentials=credentials_mock, location="test_location"
)
patcher = mock.patch(
"bigquery_magics._versions_helpers.BQ_STORAGE_VERSIONS.try_import",
side_effect=bq_exceptions.LegacyBigQueryStorageError(
"google-cloud-bigquery-storage is outdated"
),
)
with patcher, pytest.raises(
google.cloud.bigquery.exceptions.LegacyBigQueryStorageError
):
magics._make_bqstorage_client(test_client, {})
@pytest.mark.skipif(
bigquery_storage is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test__make_bqstorage_client_true_missing_gapic(missing_grpcio_lib):
with pytest.raises(ImportError) as exc_context, missing_grpcio_lib:
magics._make_bqstorage_client(True, {})
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("bigquery_magics.bigquery.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("bigquery_magics.bigquery.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.parametrize(
("magic_name",),
(("bigquery",),),
)
def test_extension_load(magic_name):
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
# verify that the magic is registered and has the correct source
magic = ip.magics_manager.magics["cell"].get(magic_name)
assert magic.__module__ == "bigquery_magics.bigquery"
@pytest.mark.skipif(
bigquery_storage is None, reason="Requires `google-cloud-bigquery-storage`"
)
def test_bigquery_magic_without_optional_arguments(monkeypatch):
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
sql = "SELECT 17 AS num"
result = pandas.DataFrame([17], columns=["num"])
run_query_patch = mock.patch("bigquery_magics.bigquery._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 bqstorage_mock.called # BQ storage client was used
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.skipif(
graph_visualization is not None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` to be missing and `google-cloud-bigquery-storage` to be present",
)
def test_bigquery_graph_spanner_graph_notebook_missing(monkeypatch):
"""If `spanner-graph-notebook` is not installed, the graph visualizer
widget cannot be displayed.
"""
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
display_patch = mock.patch("IPython.display.display", autospec=True)
sql = "SELECT 3 AS result"
result = pandas.DataFrame(["abc"], columns=["s"])
run_query_patch = mock.patch("bigquery_magics.bigquery._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
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
# Since the query result is not valid JSON, the visualizer should not be displayed.
display_mock.assert_not_called()
assert bqstorage_mock.called # BQ storage client was used
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.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_int_result(monkeypatch):
"""Graph visualization of integer scalars is supported."""
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
display_patch = mock.patch("IPython.display.display", autospec=True)
sql = "SELECT 3 AS result"
result = pandas.DataFrame(["abc"], columns=["s"])
run_query_patch = mock.patch("bigquery_magics.bigquery._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
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
# Since the query result is not valid JSON, the visualizer should not be displayed.
display_mock.assert_not_called()
assert bqstorage_mock.called # BQ storage client was used
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.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_str_result(monkeypatch):
"""Graph visualization of string scalars is supported."""
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
display_patch = mock.patch("IPython.display.display", autospec=True)
sql = "SELECT 'abc' AS s"
result = pandas.DataFrame(["abc"], columns=["s"])
run_query_patch = mock.patch("bigquery_magics.bigquery._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
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
# Since the query result is not valid JSON, the visualizer should not be displayed.
display_mock.assert_not_called()
assert bqstorage_mock.called # BQ storage client was used
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.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_json_json_result(monkeypatch):
"""Graph visualization of JSON objects with valid JSON string fields is supported."""
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
monkeypatch.setattr(bigquery_magics.context, "_project", PROJECT_ID)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
display_patch = mock.patch("IPython.display.display", autospec=True)
sql = "SELECT graph_json, graph_json AS graph_json2 FROM t"
graph_json_rows = [
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQI=","kind":"node","labels":["Person"],"properties":{"birthday":"1991-12-21T08:00:00Z","city":"Adelaide","country":"Australia","id":1,"name":"Alex"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEO","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJECkQ6ZRmluR3JhcGguUGVyc29uAHiRAplGaW5HcmFwaC5BY2NvdW50AHiRDg==","kind":"edge","labels":["Owns"],"properties":{"account_id":7,"create_time":"2020-01-10T14:22:20.222Z","id":1},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQI="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEO","kind":"node","labels":["Account"],"properties":{"create_time":"2020-01-10T14:22:20.222Z","id":7,"is_blocked":false,"nick_name":"Vacation Fund"}}]
""",
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQY=","kind":"node","labels":["Person"],"properties":{"birthday":"1986-12-07T08:00:00Z","city":"Kollam","country":"India","id":3,"name":"Lee"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEg","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJEGkSCZRmluR3JhcGguUGVyc29uAHiRBplGaW5HcmFwaC5BY2NvdW50AHiRIA==","kind":"edge","labels":["Owns"],"properties":{"account_id":16,"create_time":"2020-02-18T13:44:20.655Z","id":3},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQY="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEg","kind":"node","labels":["Account"],"properties":{"create_time":"2020-01-28T01:55:09.206Z","id":16,"is_blocked":true,"nick_name":"Vacation Fund"}}]
""",
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQQ=","kind":"node","labels":["Person"],"properties":{"birthday":"1980-10-31T08:00:00Z","city":"Moravia","country":"Czech_Republic","id":2,"name":"Dana"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEo","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJEEkSiZRmluR3JhcGguUGVyc29uAHiRBJlGaW5HcmFwaC5BY2NvdW50AHiRKA==","kind":"edge","labels":["Owns"],"properties":{"account_id":20,"create_time":"2020-01-28T01:55:09.206Z","id":2},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQQ="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEo","kind":"node","labels":["Account"],"properties":{"create_time":"2020-02-18T13:44:20.655Z","id":20,"is_blocked":false,"nick_name":"Rainy Day Fund"}}]
""",
]
result = pandas.DataFrame(
{"graph_json": graph_json_rows, "graph_json2": graph_json_rows},
columns=["graph_json", "graph_json2"],
)
run_query_patch = mock.patch("bigquery_magics.bigquery._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
query_job_mock.configuration.destination.project = PROJECT_ID
query_job_mock.configuration.destination.dataset_id = DATASET_ID
query_job_mock.configuration.destination.table_id = TABLE_ID
with run_query_patch as run_query_mock, (
bqstorage_client_patch
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
try:
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
finally:
graph_server.graph_server.stop_server()
display_mock.assert_called()
assert bqstorage_mock.called # BQ storage client was used
assert return_value is None
@pytest.mark.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_json_result(monkeypatch):
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
monkeypatch.setattr(bigquery_magics.context, "_project", PROJECT_ID)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
sql = "SELECT graph_json FROM t"
graph_json_rows = [
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQI=","kind":"node","labels":["Person"],"properties":{"birthday":"1991-12-21T08:00:00Z","city":"Adelaide","country":"Australia","id":1,"name":"Alex"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEO","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJECkQ6ZRmluR3JhcGguUGVyc29uAHiRAplGaW5HcmFwaC5BY2NvdW50AHiRDg==","kind":"edge","labels":["Owns"],"properties":{"account_id":7,"create_time":"2020-01-10T14:22:20.222Z","id":1},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQI="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEO","kind":"node","labels":["Account"],"properties":{"create_time":"2020-01-10T14:22:20.222Z","id":7,"is_blocked":false,"nick_name":"Vacation Fund"}}]
""",
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQY=","kind":"node","labels":["Person"],"properties":{"birthday":"1986-12-07T08:00:00Z","city":"Kollam","country":"India","id":3,"name":"Lee"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEg","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJEGkSCZRmluR3JhcGguUGVyc29uAHiRBplGaW5HcmFwaC5BY2NvdW50AHiRIA==","kind":"edge","labels":["Owns"],"properties":{"account_id":16,"create_time":"2020-02-18T13:44:20.655Z","id":3},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQY="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEg","kind":"node","labels":["Account"],"properties":{"create_time":"2020-01-28T01:55:09.206Z","id":16,"is_blocked":true,"nick_name":"Vacation Fund"}}]
""",
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQQ=","kind":"node","labels":["Person"],"properties":{"birthday":"1980-10-31T08:00:00Z","city":"Moravia","country":"Czech_Republic","id":2,"name":"Dana"}},{"destination_node_identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEo","identifier":"mUZpbkdyYXBoLlBlcnNvbk93bkFjY291bnQAeJEEkSiZRmluR3JhcGguUGVyc29uAHiRBJlGaW5HcmFwaC5BY2NvdW50AHiRKA==","kind":"edge","labels":["Owns"],"properties":{"account_id":20,"create_time":"2020-01-28T01:55:09.206Z","id":2},"source_node_identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQQ="},{"identifier":"mUZpbkdyYXBoLkFjY291bnQAeJEo","kind":"node","labels":["Account"],"properties":{"create_time":"2020-02-18T13:44:20.655Z","id":20,"is_blocked":false,"nick_name":"Rainy Day Fund"}}]
""",
]
result = pandas.DataFrame(graph_json_rows, columns=["graph_json"])
run_query_patch = mock.patch("bigquery_magics.bigquery._run_query", autospec=True)
display_patch = mock.patch("IPython.display.display", autospec=True)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
query_job_mock.configuration.destination.project = PROJECT_ID
query_job_mock.configuration.destination.dataset_id = DATASET_ID
query_job_mock.configuration.destination.table_id = TABLE_ID
with run_query_patch as run_query_mock, (
bqstorage_client_patch
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
assert len(display_mock.call_args_list) == 1
assert len(display_mock.call_args_list[0]) == 2
# Sanity check that the HTML content looks like graph visualization. Minimal check
# to allow Spanner to change its implementation without breaking this test.
html_content = display_mock.call_args_list[0][0][0].data
assert "<script>" in html_content
assert "</script>" in html_content
# Verify that the query results are embedded into the HTML, allowing them to be visualized.
# Due to escaping, it is not possible check for graph_json_rows exactly, so we check for a few
# sentinel strings within the query results, instead.
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQI=" in html_content
) # identifier in 1st row of query result
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQY=" in html_content
) # identifier in 2nd row of query result
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQQ=" in html_content
) # identifier in 3rd row of query result
# Verify that args are present in the HTML.
assert '\\"args\\": {' in html_content
assert '\\"bigquery_api_endpoint\\": null' in html_content
assert '\\"project\\": null' in html_content
assert '\\"location\\": null' in html_content
# Make sure we can run a second graph query, after the graph server is already running.
try:
return_value = ip.run_cell_magic("bigquery", "--graph", sql)
finally:
graph_server.graph_server.stop_server()
# Sanity check that the HTML content looks like graph visualization. Minimal check
# to allow Spanner to change its implementation without breaking this test.
html_content = display_mock.call_args_list[0][0][0].data
assert "<script>" in html_content
assert "</script>" in html_content
# Verify that the query results are embedded into the HTML, allowing them to be visualized.
# Due to escaping, it is not possible check for graph_json_rows exactly, so we check for a few
# sentinel strings within the query results, instead.
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQI=" in html_content
) # identifier in 1st row of query result
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQY=" in html_content
) # identifier in 2nd row of query result
assert (
"mUZpbkdyYXBoLlBlcnNvbgB4kQQ=" in html_content
) # identifier in 3rd row of query result
# Verify that args are present in the HTML.
assert '\\"args\\": {' in html_content
assert '\\"bigquery_api_endpoint\\": null' in html_content
assert '\\"project\\": null' in html_content
assert '\\"location\\": null' in html_content
assert bqstorage_mock.called # BQ storage client was used
assert return_value is None
@pytest.mark.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_size_exceeds_max(monkeypatch):
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
monkeypatch.setattr(bigquery_magics.context, "_credentials", mock_credentials)
monkeypatch.setattr(bigquery_magics.context, "_project", PROJECT_ID)
# Set threshold to a very small value to trigger the error.
monkeypatch.setattr(magics, "MAX_GRAPH_VISUALIZATION_SIZE", 5)
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
sql = "SELECT graph_json FROM t"
result = pandas.DataFrame(['{"id": 1}'], columns=["graph_json"])
run_query_patch = mock.patch("bigquery_magics.bigquery._run_query", autospec=True)
display_patch = mock.patch("IPython.display.display", autospec=True)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
query_job_mock.configuration.destination.project = PROJECT_ID
query_job_mock.configuration.destination.dataset_id = DATASET_ID
query_job_mock.configuration.destination.table_id = TABLE_ID
with run_query_patch as run_query_mock, (
bqstorage_client_patch
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
ip.run_cell_magic("bigquery", "--graph", sql)
# Should display error message
assert display_mock.called
html_content = display_mock.call_args[0][0].data
assert (
"Error:</b> The query result is too large for graph visualization."
in html_content
)
@pytest.mark.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_size_exceeds_query_result_max(monkeypatch):
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
mock_credentials = mock.create_autospec(
google.auth.credentials.Credentials, instance=True
)
monkeypatch.setattr(bigquery_magics.context, "_credentials", mock_credentials)
monkeypatch.setattr(bigquery_magics.context, "_project", PROJECT_ID)
# Set threshold to a very small value, but larger than the other one.
# We want estimated_size > MAX_GRAPH_VISUALIZATION_QUERY_RESULT_SIZE
# and estimated_size <= MAX_GRAPH_VISUALIZATION_SIZE
monkeypatch.setattr(magics, "MAX_GRAPH_VISUALIZATION_SIZE", 1000000)
monkeypatch.setattr(magics, "MAX_GRAPH_VISUALIZATION_QUERY_RESULT_SIZE", 5)
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
sql = "SELECT graph_json FROM t"
result = pandas.DataFrame(['{"id": 1977323800}'], columns=["graph_json"])
run_query_patch = mock.patch("bigquery_magics.bigquery._run_query", autospec=True)
display_patch = mock.patch("IPython.display.display", autospec=True)
query_job_mock = mock.create_autospec(
google.cloud.bigquery.job.QueryJob, instance=True
)
query_job_mock.to_dataframe.return_value = result
query_job_mock.configuration.destination.project = PROJECT_ID
query_job_mock.configuration.destination.dataset_id = DATASET_ID
query_job_mock.configuration.destination.table_id = TABLE_ID
with run_query_patch as run_query_mock, (
bqstorage_client_patch
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock
ip.run_cell_magic("bigquery", "--graph", sql)
# Should display visualization but without query_result embedded.
assert display_mock.called
html_content = display_mock.call_args[0][0].data
assert "<script>" in html_content
assert "1977323800" not in html_content
@pytest.mark.skipif(
graph_visualization is None or bigquery_storage is None,
reason="Requires `spanner-graph-notebook` and `google-cloud-bigquery-storage`",
)
def test_bigquery_graph_with_args_serialization(monkeypatch):
monkeypatch.setattr(
"bigquery_magics.bigquery._get_graph_schema", lambda *args: None
)
globalipapp.start_ipython()
ip = globalipapp.get_ipython()
ip.extension_manager.load_extension("bigquery_magics")
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(bigquery_magics.context, "_credentials", mock_credentials)
monkeypatch.setattr(bigquery_magics.context, "_project", PROJECT_ID)
# Mock out the BigQuery Storage API.
bqstorage_mock = mock.create_autospec(bigquery_storage.BigQueryReadClient)
bqstorage_instance_mock = mock.create_autospec(
bigquery_storage.BigQueryReadClient, instance=True
)
bqstorage_instance_mock._transport = mock.Mock()
bqstorage_mock.return_value = bqstorage_instance_mock
bqstorage_client_patch = mock.patch(
"google.cloud.bigquery_storage.BigQueryReadClient", bqstorage_mock
)
display_patch = mock.patch("IPython.display.display", autospec=True)
sql = "SELECT graph_json FROM t"
graph_json_rows = [
"""
[{"identifier":"mUZpbkdyYXBoLlBlcnNvbgB4kQI=","kind":"node","labels":["Person"],"properties":{"id":1}}]
"""
]
result = pandas.DataFrame(graph_json_rows, columns=["graph_json"])
run_query_patch = mock.patch("bigquery_magics.bigquery._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
query_job_mock.configuration.destination.project = PROJECT_ID
query_job_mock.configuration.destination.dataset_id = DATASET_ID
query_job_mock.configuration.destination.table_id = TABLE_ID
with run_query_patch as run_query_mock, (
bqstorage_client_patch
), display_patch as display_mock:
run_query_mock.return_value = query_job_mock