-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_sql_execution.py
More file actions
1111 lines (924 loc) · 42.7 KB
/
test_sql_execution.py
File metadata and controls
1111 lines (924 loc) · 42.7 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
import base64
import copy
import datetime
import io
import json
import os
import secrets
import unittest
import warnings
from unittest import TestCase, mock
import duckdb
import pandas as pd
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from deepnote_toolkit.sql.sql_execution import (
_sanitize_dataframe_for_parquet,
execute_sql,
execute_sql_with_connection_json,
)
from .helpers.testing_dataframes import testing_dataframes
class TestExecuteSql(TestCase):
def test_duckdb_group_by_on_date(self):
test_df = pd.DataFrame([{"d": datetime.date(2011, 1, 1)}])
duckdb.register("test_df_view", test_df)
os.environ["SQL_DEEPNOTE_DATAFRAME_SQL"] = (
'{"url":"deepnote+duckdb:///:memory:","params":{},"param_style":"qmark"}'
)
result = execute_sql(
"""SELECT *
FROM test_df group by d
""",
"SQL_DEEPNOTE_DATAFRAME_SQL",
)
assert result is not None
self.assertEqual(len(result), 1, "Result should have exactly one row")
def test_duckdb_concat_with_percentage_sign(self):
from deepnote_toolkit.sql.duckdb_sql import _get_duckdb_connection
test_df = pd.DataFrame([{"value": 25.5}])
duckdb_conn = _get_duckdb_connection()
duckdb_conn.register("test_df_concat", test_df)
os.environ["SQL_DEEPNOTE_DATAFRAME_SQL"] = (
'{"url":"deepnote+duckdb:///:memory:","params":{},"param_style":"qmark"}'
)
result = execute_sql(
"""SELECT
concat(round(value, 1), '%') as percentage_string
FROM test_df_concat
""",
"SQL_DEEPNOTE_DATAFRAME_SQL",
)
assert result is not None
self.assertEqual(result.iloc[0]["percentage_string"], "25.5%")
self.assertNotEqual(result.iloc[0]["percentage_string"], "25.5%%")
def test_duckdb_defaults_to_qmark_param_style(self):
os.environ["SQL_DEEPNOTE_DATAFRAME_SQL"] = (
'{"url":"deepnote+duckdb:///:memory:","params":{},"param_style":null}'
)
result = execute_sql(
"SELECT '%' as value",
"SQL_DEEPNOTE_DATAFRAME_SQL",
)
assert result is not None
self.assertEqual(result.iloc[0]["value"], "%")
@mock.patch("deepnote_toolkit.sql.sql_execution._execute_sql_on_engine")
@mock.patch("sqlalchemy.engine.create_engine")
def test_delete_sql_that_doesnt_produce_a_dataframe(
self, mocked_create_engine, execute_sql_on_engine
):
mocked_create_engine.return_value = mock.Mock()
execute_sql_on_engine.return_value = None
os.environ["SQL_ENV_VAR"] = (
'{"url":"postgresql://postgres:postgres@localhost:5432/postgres","params":{ },"param_style":"qmark", "integration_id": "integration_1"}'
)
result = execute_sql(
"""DELETE FROM mock_table WHERE id = '1'""",
"SQL_ENV_VAR",
)
self.assertIsNone(result)
@mock.patch("deepnote_toolkit.sql.sql_caching._generate_cache_key")
@mock.patch("deepnote_toolkit.sql.sql_caching._request_cache_info_from_webapp")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_sql_executed_with_audit_comment_but_hash_calculated_without_it(
self,
mocked_query_data_source,
mocked_request_cache_info_from_webapp,
mocked_generate_cache_key,
):
mocked_request_cache_info_from_webapp.return_value = None
os.environ["SQL_ENV_VAR"] = (
'{"url":"postgresql://postgres:postgres@localhost:5432/postgres","params":{ },"param_style":"qmark", "integration_id": "integration_1"}'
)
execute_sql(
"SELECT * FROM users",
"SQL_ENV_VAR",
audit_sql_comment="/*audit_comment*/",
sql_cache_mode="read_or_write",
)
# expect mocked_generate_cache_key to be called with a param that doesn't contain /*audit_comment*/
mocked_generate_cache_key.assert_called_with("SELECT * FROM users", mock.ANY)
# expect mocked_query_data_source to be called with param containing /*audit_comment*/
mocked_query_data_source.assert_called_with(
"SELECT * FROM users/*audit_comment*/",
mock.ANY,
mock.ANY,
mock.ANY,
mock.ANY,
mock.ANY,
)
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_return_variable_type_parameter(self, mocked_query_data_source):
# Setup mock return value
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
os.environ["SQL_ENV_VAR"] = (
'{"url":"postgresql://postgres:postgres@localhost:5432/postgres","params":{ },"param_style":"qmark", "integration_id": "integration_1"}'
)
# Test with default return_variable_type
execute_sql(
"SELECT * FROM test_table",
"SQL_ENV_VAR",
)
mocked_query_data_source.assert_called_with(
"SELECT * FROM test_table",
mock.ANY,
mock.ANY,
mock.ANY,
"dataframe",
mock.ANY,
)
# Test with explicit return_variable_type='query_preview'
execute_sql(
"SELECT * FROM test_table",
"SQL_ENV_VAR",
return_variable_type="query_preview",
)
# For query_preview, a LIMIT 100 clause is added to the query
mocked_query_data_source.assert_called_with(
"SELECT * FROM test_table\nLIMIT 100",
mock.ANY,
mock.ANY,
mock.ANY,
"query_preview",
mock.ANY,
)
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_query_preview_preserves_trailing_inline_comment(
self, mocked_query_data_source
):
# Setup mock return value
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
os.environ["SQL_ENV_VAR"] = (
'{"url":"postgresql://postgres:postgres@localhost:5432/postgres","params":{ },"param_style":"qmark", "integration_id": "integration_1"}'
)
# Test that trailing inline comment is preserved before LIMIT clause
execute_sql(
"SELECT * FROM test_table -- trailing",
"SQL_ENV_VAR",
return_variable_type="query_preview",
)
# For query_preview, a LIMIT 100 clause is added after the trailing comment
mocked_query_data_source.assert_called_with(
"SELECT * FROM test_table -- trailing\nLIMIT 100",
mock.ANY,
mock.ANY,
mock.ANY,
"query_preview",
mock.ANY,
)
@mock.patch("deepnote_toolkit.sql.sql_caching._generate_cache_key")
@mock.patch("deepnote_toolkit.sql.sql_caching._request_cache_info_from_webapp")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_sql_executed_with_audit_comment_with_semicolon(
self,
mocked_query_data_source,
mocked_request_cache_info_from_webapp,
mocked_generate_cache_key,
):
mocked_request_cache_info_from_webapp.return_value = None
os.environ["SQL_ENV_VAR"] = (
'{"url":"postgresql://postgres:postgres@localhost:5432/postgres","params":{ },"param_style":"qmark", "integration_id": "integration_1"}'
)
execute_sql(
"SELECT * FROM users;", # Semicolon at the end of the query
"SQL_ENV_VAR",
audit_sql_comment="/*audit_comment*/",
sql_cache_mode="read_or_write",
)
# expect mocked_generate_cache_key to be called with a param that doesn't contain /*audit_comment*/
mocked_generate_cache_key.assert_called_with("SELECT * FROM users;", mock.ANY)
# expect mocked_query_data_source to be called with param containing /*audit_comment*/
mocked_query_data_source.assert_called_with(
"SELECT * FROM users/*audit_comment*/;",
mock.ANY,
mock.ANY,
mock.ANY,
"dataframe",
mock.ANY,
)
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_execute_sql_with_connection_json_with_snowflake_private_key(
self, mock_execute_sql_with_caching
):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_key_b64 = base64.b64encode(
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
).decode("utf-8")
template = "SELECT * FROM table"
sql_alchemy_json = json.dumps(
{
"url": "snowflake://test@test?warehouse=&role=&application=Deepnote_Workspaces",
"params": {
"snowflake_private_key": private_key_b64,
},
"param_style": "pyformat",
}
)
execute_sql_with_connection_json(template, sql_alchemy_json)
args, _ = mock_execute_sql_with_caching.call_args
# the private key is converted to DER format
expected_private_key_der = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
self.assertEqual(args[0], "SELECT * FROM table")
self.assertEqual(
args[2],
{
"url": "snowflake://test@test?warehouse=&role=&application=Deepnote_Workspaces",
"params": {"connect_args": {"private_key": expected_private_key_der}},
"param_style": "pyformat",
},
)
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_execute_sql_with_connection_json_with_snowflake_encrypted_private_key(
self, mock_execute_sql_with_caching
):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
private_key_passphrase = secrets.token_urlsafe(16)
private_key_b64 = base64.b64encode(
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(
private_key_passphrase.encode("utf-8")
),
)
).decode("utf-8")
template = "SELECT * FROM table"
sql_alchemy_json = json.dumps(
{
"url": "snowflake://test@test?warehouse=&role=&application=Deepnote_Workspaces",
"params": {
"snowflake_private_key": private_key_b64,
"snowflake_private_key_passphrase": private_key_passphrase,
},
"param_style": "pyformat",
}
)
execute_sql_with_connection_json(template, sql_alchemy_json)
args, _ = mock_execute_sql_with_caching.call_args
# The private key is loaded with passphrase (decrypted) then converted to DER format without encryption
expected_private_key_der = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
self.assertEqual(args[0], "SELECT * FROM table")
self.assertEqual(
args[2],
{
"url": "snowflake://test@test?warehouse=&role=&application=Deepnote_Workspaces",
"params": {"connect_args": {"private_key": expected_private_key_der}},
"param_style": "pyformat",
},
)
class TestTrinoParamStyleAutoDetection(TestCase):
"""Tests for auto-detection of param_style for Trino connections"""
@mock.patch("deepnote_toolkit.sql.sql_execution.compile_sql_query")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_trino_url_auto_detects_qmark_param_style(
self, mocked_query_data_source, mocked_compile_sql_query
):
"""Test that Trino URLs automatically get 'qmark' param_style when not specified"""
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
mocked_compile_sql_query.return_value = (
"SELECT * FROM test_table",
{},
"SELECT * FROM test_table",
)
sql_alchemy_json = json.dumps(
{
"url": "trino://user@localhost:8080/catalog",
"params": {},
"integration_id": "test_integration",
}
)
execute_sql_with_connection_json("SELECT * FROM test_table", sql_alchemy_json)
# Verify compile_sql_query was called with 'qmark' param_style
mocked_compile_sql_query.assert_called_once()
call_args = mocked_compile_sql_query.call_args[0]
self.assertEqual(call_args[2], "qmark")
@mock.patch("deepnote_toolkit.sql.sql_execution.compile_sql_query")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_non_trino_url_param_style_remains_none(
self, mocked_query_data_source, mocked_compile_sql_query
):
"""Test that non-Trino databases don't get auto-detected param_style"""
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
mocked_compile_sql_query.return_value = (
"SELECT * FROM test_table",
{},
"SELECT * FROM test_table",
)
sql_alchemy_json = json.dumps(
{
"url": "postgresql://user:pass@localhost:5432/mydb",
"params": {},
"integration_id": "test_integration",
}
)
execute_sql_with_connection_json("SELECT * FROM test_table", sql_alchemy_json)
# Verify compile_sql_query was called with None param_style
mocked_compile_sql_query.assert_called_once()
call_args = mocked_compile_sql_query.call_args[0]
self.assertIsNone(call_args[2])
@mock.patch("deepnote_toolkit.sql.sql_execution.compile_sql_query")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_explicit_param_style_not_overridden(
self, mocked_query_data_source, mocked_compile_sql_query
):
"""Test that explicitly set param_style is preserved and not auto-detected"""
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
mocked_compile_sql_query.return_value = (
"SELECT * FROM test_table",
{},
"SELECT * FROM test_table",
)
# Trino URL with explicit pyformat - should NOT be changed to qmark
sql_alchemy_json = json.dumps(
{
"url": "trino://user@localhost:8080/catalog",
"params": {},
"param_style": "pyformat",
"integration_id": "test_integration",
}
)
execute_sql_with_connection_json("SELECT * FROM test_table", sql_alchemy_json)
# Verify compile_sql_query was called with 'pyformat', NOT 'qmark'
mocked_compile_sql_query.assert_called_once()
call_args = mocked_compile_sql_query.call_args[0]
self.assertEqual(call_args[2], "pyformat")
@mock.patch("deepnote_toolkit.sql.sql_execution.compile_sql_query")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_trino_url_with_protocol_suffix_not_matched(
self, mocked_query_data_source, mocked_compile_sql_query
):
"""Test that Trino URL variants like trino+rest:// don't match (drivername must be exactly 'trino')"""
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
mocked_compile_sql_query.return_value = (
"SELECT * FROM test_table",
{},
"SELECT * FROM test_table",
)
sql_alchemy_json = json.dumps(
{
"url": "trino+rest://user@localhost:8080/catalog",
"params": {},
"integration_id": "test_integration",
}
)
execute_sql_with_connection_json("SELECT * FROM test_table", sql_alchemy_json)
# Verify compile_sql_query was called with None param_style
# because "trino+rest" doesn't match "trino" in the dictionary
mocked_compile_sql_query.assert_called_once()
call_args = mocked_compile_sql_query.call_args[0]
self.assertIsNone(call_args[2])
@mock.patch("deepnote_toolkit.sql.sql_execution.render_jinja_sql_template")
@mock.patch("deepnote_toolkit.sql.sql_execution._query_data_source")
def test_trino_with_jinja_templates_uses_qmark(
self, mocked_query_data_source, mocked_render_jinja
):
"""Test that Trino queries with Jinja templates correctly use qmark style"""
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_query_data_source.return_value = mock_df
mocked_render_jinja.return_value = (
"SELECT * FROM test_table WHERE id = ?",
[123],
)
sql_alchemy_json = json.dumps(
{
"url": "trino://user@localhost:8080/catalog",
"params": {},
"integration_id": "test_integration",
}
)
execute_sql_with_connection_json(
"SELECT * FROM test_table WHERE id = {{ user_id }}",
sql_alchemy_json,
)
# Verify render_jinja_sql_template was called with 'qmark' param_style
mocked_render_jinja.assert_called()
call_args = mocked_render_jinja.call_args[0]
self.assertEqual(call_args[1], "qmark")
# Verify bind_params is a list (qmark style) not dict (pyformat style)
call_args = mocked_query_data_source.call_args[0]
bind_params = call_args[1]
self.assertIsInstance(bind_params, list)
self.assertEqual(bind_params, [123])
@mock.patch("pandas.read_sql_query")
def test_list_bind_params_converted_to_tuple_for_pandas(self, mocked_read_sql):
"""Test that list bind_params are converted to tuple for pandas.read_sql_query"""
from deepnote_toolkit.sql.sql_execution import _execute_sql_on_engine
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_read_sql.return_value = mock_df
# Mock engine and connection
mock_engine = mock.Mock()
mock_connection = mock.Mock()
mock_engine.begin.return_value.__enter__ = mock.Mock(
return_value=mock_connection
)
mock_engine.begin.return_value.__exit__ = mock.Mock(return_value=None)
# Test with list bind_params (qmark style for Trino)
list_params = [123, "test"]
_execute_sql_on_engine(
mock_engine,
"SELECT * FROM test_table WHERE id = ? AND name = ?",
list_params,
)
# Verify pandas.read_sql_query was called
self.assertTrue(mocked_read_sql.called)
# Get the params argument passed to pandas.read_sql_query
call_kwargs = mocked_read_sql.call_args[1]
params_arg = call_kwargs.get("params")
# Verify that list was converted to tuple
self.assertIsInstance(params_arg, tuple)
self.assertEqual(params_arg, (123, "test"))
@mock.patch("pandas.read_sql_query")
def test_dict_bind_params_not_converted_for_pandas(self, mocked_read_sql):
"""Test that dict bind_params remain as dict for pandas.read_sql_query"""
from deepnote_toolkit.sql.sql_execution import _execute_sql_on_engine
mock_df = pd.DataFrame({"col1": [1, 2, 3]})
mocked_read_sql.return_value = mock_df
# Mock engine and connection
mock_engine = mock.Mock()
mock_connection = mock.Mock()
mock_engine.begin.return_value.__enter__ = mock.Mock(
return_value=mock_connection
)
mock_engine.begin.return_value.__exit__ = mock.Mock(return_value=None)
# Test with dict bind_params (pyformat style)
dict_params = {"id": 123, "name": "test"}
_execute_sql_on_engine(
mock_engine,
"SELECT * FROM test_table WHERE id = %(id)s AND name = %(name)s",
dict_params,
)
# Verify pandas.read_sql_query was called
self.assertTrue(mocked_read_sql.called)
# Get the params argument passed to pandas.read_sql_query
call_kwargs = mocked_read_sql.call_args[1]
params_arg = call_kwargs.get("params")
# Verify that dict was NOT converted (remains as dict)
self.assertIsInstance(params_arg, dict)
self.assertEqual(params_arg, {"id": 123, "name": "test"})
class TestSanitizeDataframe(unittest.TestCase):
@parameterized.expand([(key, df) for key, df in testing_dataframes.items()])
def test_all_dataframes_serialize_to_parquet(self, key, df):
# these are skipped because we are not expecting it's possible for dataframes like these
# to come out of a SQL query
skipped_dataframes = {
"categorical_columns",
"nested_list_column",
"mixed_column_types",
"multi_level_columns",
"period_index",
"non_serializable_values",
"column_distinct_values_mixed",
}
if key in skipped_dataframes:
return
df_cleaned = df.copy()
_sanitize_dataframe_for_parquet(df_cleaned)
with io.BytesIO() as in_memory_file:
try:
df_cleaned.to_parquet(in_memory_file)
except: # noqa: E722
self.fail(f"serializing to parquet failed for {key}")
class TestFederatedAuth(unittest.TestCase):
@mock.patch("deepnote_toolkit.sql.sql_execution.get_project_auth_headers")
@mock.patch("deepnote_toolkit.sql.sql_execution.get_absolute_userpod_api_url")
@mock.patch("deepnote_toolkit.sql.sql_execution._create_retry_session")
def test_get_federated_auth_credentials_returns_validated_response(
self, mock_create_session, mock_get_url, mock_get_headers
):
"""Test that _get_federated_auth_credentials properly validates and returns response data."""
from deepnote_toolkit.sql.sql_execution import _get_federated_auth_credentials
# Setup mocks
mock_get_url.return_value = "https://api.example.com/integrations/federated-auth-token/test-integration-id"
mock_get_headers.return_value = {"Authorization": "Bearer project-token"}
mock_session = mock.Mock()
mock_response = mock.Mock()
mock_response.json.return_value = {
"integrationType": "trino",
"accessToken": "test-access-token-123",
}
mock_session.post.return_value = mock_response
mock_create_session.return_value = mock_session
# Call the function
result = _get_federated_auth_credentials(
"test-integration-id", "test-auth-context-token"
)
# Verify URL construction
mock_get_url.assert_called_once_with(
"integrations/federated-auth-token/test-integration-id"
)
# Verify headers include both project auth and user pod auth context token
mock_session.post.assert_called_once_with(
"https://api.example.com/integrations/federated-auth-token/test-integration-id",
timeout=10,
headers={
"Authorization": "Bearer project-token",
"UserPodAuthContextToken": "test-auth-context-token",
},
)
# Verify raise_for_status was called
mock_response.raise_for_status.assert_called_once()
# Verify the response is properly validated and returned
self.assertEqual(result.integrationType, "trino")
self.assertEqual(result.accessToken, "test-access-token-123")
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_trino(self, mock_get_credentials):
"""Test that Trino federated auth updates the Authorization header with Bearer token."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return Trino credentials
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="trino",
accessToken="test-trino-access-token",
)
# Create a sql_alchemy_dict with federatedAuthParams and the expected structure
sql_alchemy_dict = {
"url": "trino://user@localhost:8080/catalog",
"params": {
"connect_args": {
"http_headers": {
"Authorization": "Bearer old-token",
}
}
},
"federatedAuthParams": {
"integrationId": "test-integration-id",
"authContextToken": "test-auth-context-token",
},
}
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the API was called with correct params
mock_get_credentials.assert_called_once_with(
"test-integration-id", "test-auth-context-token"
)
# Verify the Authorization header was updated with the new token
self.assertEqual(
sql_alchemy_dict["params"]["connect_args"]["http_headers"]["Authorization"],
"Bearer test-trino-access-token",
)
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_bigquery(self, mock_get_credentials):
"""Test that BigQuery federated auth updates the access_token in params."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return BigQuery credentials
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="big-query",
accessToken="test-bigquery-access-token",
)
# Create a sql_alchemy_dict with federatedAuthParams
sql_alchemy_dict = {
"url": "bigquery://?user_supplied_client=true",
"params": {
"access_token": "old-access-token",
"project": "test-project",
},
"federatedAuthParams": {
"integrationId": "test-bigquery-integration-id",
"authContextToken": "test-bigquery-auth-context-token",
},
}
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the API was called with correct params
mock_get_credentials.assert_called_once_with(
"test-bigquery-integration-id", "test-bigquery-auth-context-token"
)
# Verify the access_token was updated with the new token
self.assertEqual(
sql_alchemy_dict["params"]["access_token"],
"test-bigquery-access-token",
)
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_snowflake(self, mock_get_credentials):
"""Test that Snowflake federated auth doesn't do anything since it's not supported yet."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return Snowflake credentials
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="snowflake",
accessToken="test-snowflake-access-token",
)
# Create a sql_alchemy_dict with federatedAuthParams
sql_alchemy_dict = {
"url": "snowflake://test@test?warehouse=&role=&application=Deepnote_Workspaces",
"params": {},
"federatedAuthParams": {
"integrationId": "test-snowflake-integration-id",
"authContextToken": "test-snowflake-auth-context-token",
},
}
# Store original params to verify they remain unchanged
original_params = copy.deepcopy(sql_alchemy_dict["params"])
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the API was called with correct params
mock_get_credentials.assert_called_once_with(
"test-snowflake-integration-id", "test-snowflake-auth-context-token"
)
# Verify params were NOT modified (snowflake is not supported yet)
self.assertEqual(sql_alchemy_dict["params"], original_params)
def test_federated_auth_params_not_present(self):
"""Test that no action is taken when federatedAuthParams is not present."""
from deepnote_toolkit.sql.sql_execution import _handle_federated_auth_params
# Create a sql_alchemy_dict without federatedAuthParams
sql_alchemy_dict = {
"url": "trino://user@localhost:8080/catalog",
"params": {
"connect_args": {
"http_headers": {"Authorization": "Bearer original-token"}
}
},
}
original_dict = copy.deepcopy(sql_alchemy_dict)
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the dict was not modified
self.assertEqual(sql_alchemy_dict, original_dict)
@mock.patch("deepnote_toolkit.sql.sql_execution.logger")
def test_federated_auth_params_invalid_params(self, mock_logger):
"""Test that invalid federated auth params logs an error and returns early."""
from deepnote_toolkit.sql.sql_execution import _handle_federated_auth_params
# Create a sql_alchemy_dict with invalid federatedAuthParams (missing required fields)
sql_alchemy_dict = {
"url": "trino://user@localhost:8080/catalog",
"params": {},
"federatedAuthParams": {
"invalidField": "value",
},
}
original_dict = copy.deepcopy(sql_alchemy_dict)
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify an exception was logged
mock_logger.exception.assert_called_once()
call_args = mock_logger.exception.call_args
self.assertIn("Invalid federated auth params", call_args[0][0])
self.assertEqual(sql_alchemy_dict, original_dict)
@mock.patch("deepnote_toolkit.sql.sql_execution.logger")
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_unsupported_integration_type(
self, mock_get_credentials, mock_logger
):
"""Test that unsupported integration type logs an error."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return unknown integration type
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="unknown-database",
accessToken="test-token",
)
# Create a sql_alchemy_dict with federatedAuthParams
sql_alchemy_dict = {
"url": "unknown://host/db",
"params": {},
"federatedAuthParams": {
"integrationId": "test-integration-id",
"authContextToken": "test-auth-context-token",
},
}
original_dict = copy.deepcopy(sql_alchemy_dict)
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify an error was logged for unsupported integration type
mock_logger.error.assert_called_once_with(
"Unsupported integration type: %s, try updating toolkit version",
"unknown-database",
)
self.assertEqual(sql_alchemy_dict, original_dict)
@mock.patch("deepnote_toolkit.sql.sql_execution.logger")
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_trino_missing_http_headers(
self, mock_get_credentials, mock_logger
):
"""Test that Trino federated auth logs exception when connect_args is missing http_headers."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return Trino credentials
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="trino",
accessToken="test-trino-access-token",
)
# Create a sql_alchemy_dict with connect_args but missing http_headers
sql_alchemy_dict = {
"url": "trino://user@localhost:8080/catalog",
"params": {
"connect_args": {
# http_headers is missing
}
},
"federatedAuthParams": {
"integrationId": "test-integration-id",
"authContextToken": "test-auth-context-token",
},
}
original_dict = copy.deepcopy(sql_alchemy_dict)
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the API was called with correct params
mock_get_credentials.assert_called_once_with(
"test-integration-id", "test-auth-context-token"
)
# Verify an exception was logged for missing http_headers
mock_logger.exception.assert_called_once()
call_args = mock_logger.exception.call_args
self.assertIn("Invalid federated auth params", call_args[0][0])
# Verify the dict was not modified
self.assertEqual(sql_alchemy_dict, original_dict)
@mock.patch("deepnote_toolkit.sql.sql_execution.logger")
@mock.patch("deepnote_toolkit.sql.sql_execution._get_federated_auth_credentials")
def test_federated_auth_params_bigquery_missing_params(
self, mock_get_credentials, mock_logger
):
"""Test that BigQuery federated auth logs exception when params key is missing."""
from deepnote_toolkit.sql.sql_execution import (
FederatedAuthResponseData,
_handle_federated_auth_params,
)
# Setup mock to return BigQuery credentials
mock_get_credentials.return_value = FederatedAuthResponseData(
integrationType="big-query",
accessToken="test-bigquery-access-token",
)
# Create a sql_alchemy_dict without params key (will cause KeyError)
sql_alchemy_dict = {
"url": "bigquery://?user_supplied_client=true",
# params key is missing entirely
"federatedAuthParams": {
"integrationId": "test-bigquery-integration-id",
"authContextToken": "test-bigquery-auth-context-token",
},
}
original_dict = copy.deepcopy(sql_alchemy_dict)
# Call the function
_handle_federated_auth_params(sql_alchemy_dict)
# Verify the API was called with correct params
mock_get_credentials.assert_called_once_with(
"test-bigquery-integration-id", "test-bigquery-auth-context-token"
)
# Verify an exception was logged for missing params
mock_logger.exception.assert_called_once()
call_args = mock_logger.exception.call_args
self.assertIn("Invalid federated auth params", call_args[0][0])
# Verify the dict was not modified
self.assertEqual(sql_alchemy_dict, original_dict)
class TestSuppressThirdPartyDeprecationWarnings(TestCase):
"""Test suppression of known third-party deprecation warnings."""
def test_suppresses_databricks_user_agent_warning(self):
"""Verify databricks-sqlalchemy '_user_agent_entry' warning is suppressed.
See: https://github.com/databricks/databricks-sqlalchemy/issues/36
"""
from deepnote_toolkit.sql.sql_execution import (
suppress_third_party_deprecation_warnings,
)
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always")
with suppress_third_party_deprecation_warnings():
# Simulate the warning that databricks-sqlalchemy emits
warnings.warn(
"Parameter '_user_agent_entry' is deprecated; "
"use 'user_agent_entry' instead.",
DeprecationWarning,
)
# Warning should be suppressed
databricks_warnings = [
w for w in caught_warnings if "_user_agent_entry" in str(w.message)
]
self.assertEqual(len(databricks_warnings), 0)
def test_does_not_suppress_unrelated_warnings(self):
"""Verify unrelated warnings are not suppressed."""
from deepnote_toolkit.sql.sql_execution import (
suppress_third_party_deprecation_warnings,
)
with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter("always")
with suppress_third_party_deprecation_warnings():
warnings.warn("Some other deprecation", DeprecationWarning)
# Unrelated warning should NOT be suppressed
self.assertEqual(len(caught_warnings), 1)
self.assertIn("Some other deprecation", str(caught_warnings[0].message))
class TestSqlAlchemyDialectRegistration(TestCase):
"""Test that SQL integration dialects are properly installed and registered."""
def test_databricks_dialect_is_registered(self):
"""Verify databricks-sqlalchemy package is installed and dialect is loadable."""
from sqlalchemy.engine.url import make_url