Repository navigation
Expand file tree
/
Copy pathtest_base.py
More file actions
1636 lines (1349 loc) · 52.3 KB
/
Copy pathtest_base.py
File metadata and controls
1636 lines (1349 loc) · 52.3 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=import-outside-toplevel, protected-access
from __future__ import annotations
import json # noqa: TID251
import re
from datetime import timedelta
from textwrap import dedent
from typing import Any, cast
from urllib.parse import parse_qs, urlparse
import pytest
from pytest_mock import MockerFixture
from sqlalchemy import Boolean, Column, Integer, types
from sqlalchemy.dialects import sqlite
from sqlalchemy.engine.url import make_url, URL
from sqlalchemy.sql import sqltypes
from superset.db_engine_specs.base import (
BaseEngineSpec,
BasicParametersType,
convert_inspector_columns,
)
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.exceptions import OAuth2RedirectError
from superset.sql.parse import Table
from superset.superset_typing import (
OAuth2ClientConfig,
OAuth2State,
ResultSetColumnType,
SQLAColumnType,
)
from superset.utils.core import FilterOperator, GenericDataType
from superset.utils.oauth2 import decode_oauth2_state
from tests.conftest import with_config
from tests.unit_tests.db_engine_specs.utils import assert_column_spec
def create_expected_superset_error(
message: str,
error_type: SupersetErrorType = SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
engine_name: str | None = None,
) -> SupersetError:
"""
Helper function to create expected SupersetError objects for testing.
"""
extra = {
"engine_name": engine_name,
"issue_codes": [
{
"code": 1002,
"message": "Issue 1002 - The database returned an unexpected error.",
}
],
}
return SupersetError(
message=message,
error_type=error_type,
level=ErrorLevel.ERROR,
extra=extra,
)
def test_get_text_clause_with_colon() -> None:
"""
Make sure text clauses are correctly escaped
"""
text_clause = BaseEngineSpec.get_text_clause(
"SELECT foo FROM tbl WHERE foo = '123:456')"
)
assert text_clause.text == "SELECT foo FROM tbl WHERE foo = '123\\:456')"
def test_normalize_custom_sql_metric_is_identity_by_default() -> None:
"""Unconfigured engines preserve custom metric SQL exactly."""
expression: str = "DATE_TRUNC('QUARTER', created_at) /* keep */"
assert BaseEngineSpec.normalize_custom_sql_metric(expression) == expression
def test_validate_db_uri(mocker: MockerFixture) -> None:
"""
Ensures that the `validate_database_uri` method invokes the validator correctly
"""
def mock_validate(sqlalchemy_uri: URL) -> None:
raise ValueError("Invalid URI")
mocker.patch(
"flask.current_app.config",
{"DB_SQLA_URI_VALIDATOR": mock_validate},
)
with pytest.raises(ValueError): # noqa: PT011
BaseEngineSpec.validate_database_uri(URL.create("sqlite"))
@pytest.mark.parametrize(
"original,expected",
[
(
dedent(
"""
with currency as
(
select 'INR' as cur
)
select * from currency
"""
),
None,
),
(
"SELECT 1 as cnt",
None,
),
(
dedent(
"""
select 'INR' as cur
union
select 'AUD' as cur
union
select 'USD' as cur
"""
),
None,
),
],
)
def test_cte_query_parsing(original: types.TypeEngine, expected: str) -> None:
actual = BaseEngineSpec.get_cte_query(original)
assert actual == expected
@pytest.mark.parametrize(
"native_type,sqla_type,attrs,generic_type,is_dttm",
[
("SMALLINT", types.SmallInteger, None, GenericDataType.NUMERIC, False),
("INTEGER", types.Integer, None, GenericDataType.NUMERIC, False),
("BIGINT", types.BigInteger, None, GenericDataType.NUMERIC, False),
("DECIMAL", types.Numeric, None, GenericDataType.NUMERIC, False),
("NUMERIC", types.Numeric, None, GenericDataType.NUMERIC, False),
("REAL", types.REAL, None, GenericDataType.NUMERIC, False),
("DOUBLE PRECISION", types.Float, None, GenericDataType.NUMERIC, False),
("MONEY", types.Numeric, None, GenericDataType.NUMERIC, False),
# String
("CHAR", types.String, None, GenericDataType.STRING, False),
("VARCHAR", types.String, None, GenericDataType.STRING, False),
("TEXT", types.String, None, GenericDataType.STRING, False),
# Temporal
("DATE", types.Date, None, GenericDataType.TEMPORAL, True),
("TIMESTAMP", types.TIMESTAMP, None, GenericDataType.TEMPORAL, True),
("TIME", types.Time, None, GenericDataType.TEMPORAL, True),
# Boolean
("BOOLEAN", types.Boolean, None, GenericDataType.BOOLEAN, False),
],
)
def test_get_column_spec(
native_type: str,
sqla_type: type[types.TypeEngine],
attrs: dict[str, Any] | None,
generic_type: GenericDataType,
is_dttm: bool,
) -> None:
from superset.db_engine_specs.databricks import (
DatabricksNativeEngineSpec as spec, # noqa: N813
)
assert_column_spec(spec, native_type, sqla_type, attrs, generic_type, is_dttm)
@pytest.mark.parametrize(
"cols, expected_result",
[
(
[SQLAColumnType(name="John", type="integer", is_dttm=False)],
[
ResultSetColumnType(
column_name="John", name="John", type="integer", is_dttm=False
)
],
),
(
[SQLAColumnType(name="hugh", type="integer", is_dttm=False)],
[
ResultSetColumnType(
column_name="hugh", name="hugh", type="integer", is_dttm=False
)
],
),
],
)
def test_convert_inspector_columns(
cols: list[SQLAColumnType], expected_result: list[ResultSetColumnType]
):
assert convert_inspector_columns(cols) == expected_result
def test_select_star(mocker: MockerFixture) -> None:
"""
Test the ``select_star`` method.
"""
cols: list[ResultSetColumnType] = [
{
"column_name": "a",
"name": "a",
"type": sqltypes.String(),
"nullable": True,
"comment": None,
"default": None,
"precision": None,
"scale": None,
"max_length": None,
"is_dttm": False,
},
]
# mock the database so we can compile the query
database = mocker.MagicMock()
database.compile_sqla_query = lambda query, catalog, schema: str(
query.compile(dialect=sqlite.dialect())
)
dialect = sqlite.dialect()
sql = BaseEngineSpec.select_star(
database=database,
table=Table("my_table", "my_schema", "my_catalog"),
dialect=dialect,
limit=100,
show_cols=True,
indent=True,
latest_partition=False,
cols=cols,
)
assert sql == "SELECT\n a\nFROM my_schema.my_table\nLIMIT ?\nOFFSET ?"
def test_extra_table_metadata(mocker: MockerFixture) -> None:
"""
Test the deprecated `extra_table_metadata` method.
"""
from superset.models.core import Database
class ThirdPartyDBEngineSpec(BaseEngineSpec):
@classmethod
def extra_table_metadata(
cls,
database: Database,
table_name: str,
schema_name: str | None,
) -> dict[str, Any]:
return {"table": table_name, "schema": schema_name}
database = mocker.MagicMock()
warnings = mocker.patch("superset.db_engine_specs.base.warnings")
assert ThirdPartyDBEngineSpec.get_extra_table_metadata(
database,
Table("table", "schema"),
) == {"table": "table", "schema": "schema"}
assert (
ThirdPartyDBEngineSpec.get_extra_table_metadata(
database,
Table("table", "schema", "catalog"),
)
== {}
)
warnings.warn.assert_called()
def test_get_default_catalog(mocker: MockerFixture) -> None:
"""
Test the `get_default_catalog` method.
"""
database = mocker.MagicMock()
assert BaseEngineSpec.get_default_catalog(database) is None
def test_prepare_identifier_returns_name_unchanged() -> None:
name = "physical_column"
assert BaseEngineSpec.prepare_identifier(name, normalize_columns=False) is name
assert BaseEngineSpec.prepare_identifier(name, normalize_columns=True) is name
def test_quote_table() -> None:
"""
Test the `quote_table` function.
"""
dialect = sqlite.dialect()
assert BaseEngineSpec.quote_table(Table("table"), dialect) == '"table"'
assert (
BaseEngineSpec.quote_table(Table("table", "schema"), dialect)
== 'schema."table"'
)
assert (
BaseEngineSpec.quote_table(Table("table", "schema", "catalog"), dialect)
== 'catalog.schema."table"'
)
assert (
BaseEngineSpec.quote_table(Table("ta ble", "sche.ma", 'cata"log'), dialect)
== '"cata""log"."sche.ma"."ta ble"'
)
def test_mask_encrypted_extra() -> None:
"""
Test that the private key is masked when the database is edited.
"""
config = json.dumps(
{
"foo": "bar",
"service_account_info": {
"project_id": "black-sanctum-314419",
"private_key": "SECRET",
},
}
)
assert BaseEngineSpec.mask_encrypted_extra(config) == json.dumps(
{
"foo": "XXXXXXXXXX",
"service_account_info": "XXXXXXXXXX",
}
)
def test_unmask_encrypted_extra() -> None:
"""
Test that the private key can be reused from the previous `encrypted_extra`.
"""
old = json.dumps(
{
"foo": "bar",
"service_account_info": {
"project_id": "black-sanctum-314419",
"private_key": "SECRET",
},
}
)
new = json.dumps(
{
"foo": "XXXXXXXXXX",
"service_account_info": "XXXXXXXXXX",
}
)
assert BaseEngineSpec.unmask_encrypted_extra(old, new) == json.dumps(
{
"foo": "bar",
"service_account_info": {
"project_id": "black-sanctum-314419",
"private_key": "SECRET",
},
}
)
def test_mask_encrypted_extra_oauth2_client_info_with_narrow_override() -> None:
"""
Test that the OAuth2 client secret is masked even when an engine spec
overrides `encrypted_extra_sensitive_fields` without including it.
"""
class NarrowFieldsSpec(BaseEngineSpec):
encrypted_extra_sensitive_fields = {"$.auth_params.password"}
config = json.dumps(
{
"auth_params": {"password": "my_password"},
"oauth2_client_info": {
"id": "my_client_id",
"secret": "my_client_secret",
},
}
)
assert NarrowFieldsSpec.mask_encrypted_extra(config) == json.dumps(
{
"auth_params": {"password": "XXXXXXXXXX"},
"oauth2_client_info": {
"id": "my_client_id",
"secret": "XXXXXXXXXX",
},
}
)
def test_mask_encrypted_extra_oauth2_client_info_without_sensitive_fields() -> None:
"""
Test that the OAuth2 client secret is masked even when an engine spec
declares no sensitive fields at all.
"""
class NoFieldsSpec(BaseEngineSpec):
encrypted_extra_sensitive_fields: set[str] = set()
config = json.dumps(
{
"auth_params": {"password": "my_password"},
"oauth2_client_info": {
"id": "my_client_id",
"secret": "my_client_secret",
},
}
)
assert NoFieldsSpec.mask_encrypted_extra(config) == json.dumps(
{
"auth_params": {"password": "my_password"},
"oauth2_client_info": {
"id": "my_client_id",
"secret": "XXXXXXXXXX",
},
}
)
@pytest.mark.parametrize(
"masked_encrypted_extra,expected_result",
[
(
{
"$.credentials_info.private_key": "Private Key",
"$.access_token": "Access Token",
},
{
"$.credentials_info.private_key",
"$.access_token",
"$.oauth2_client_info.secret",
},
),
(
{
"$.credentials_info.private_key",
"$.access_token",
},
{
"$.credentials_info.private_key",
"$.access_token",
"$.oauth2_client_info.secret",
},
),
(
None,
{"$.*", "$.oauth2_client_info.secret"},
),
],
)
def test_encrypted_extra_sensitive_field_paths_from_dict(
masked_encrypted_extra: set[str] | dict[str, str] | None,
expected_result: set[str],
) -> None:
"""
Test that `encrypted_extra_sensitive_field_paths` extracts the keys
when `encrypted_extra_sensitive_fields` is a dict.
"""
class DictFieldsSpec(BaseEngineSpec):
if masked_encrypted_extra:
encrypted_extra_sensitive_fields = masked_encrypted_extra
assert DictFieldsSpec.encrypted_extra_sensitive_field_paths() == expected_result
def test_impersonate_user_backwards_compatible(mocker: MockerFixture) -> None:
"""
Test that the `impersonate_user` method calls the original methods it replaced.
"""
database = mocker.MagicMock()
url = make_url("sqlite://foo.db")
new_url = make_url("sqlite://bar.db")
engine_kwargs = {"connect_args": {"user": "alice"}}
get_url_for_impersonation = mocker.patch.object(
BaseEngineSpec,
"get_url_for_impersonation",
return_value=new_url,
)
update_impersonation_config = mocker.patch.object(
BaseEngineSpec,
"update_impersonation_config",
)
signature = mocker.patch("superset.db_engine_specs.base.signature")
signature().parameters = [
"cls",
"database",
"connect_args",
"uri",
"username",
"access_token",
]
BaseEngineSpec.impersonate_user(database, "alice", "SECRET", url, engine_kwargs)
get_url_for_impersonation.assert_called_once_with(url, True, "alice", "SECRET")
update_impersonation_config.assert_called_once_with(
database,
{"user": "alice"},
new_url,
"alice",
"SECRET",
)
def test_impersonate_user_no_database(mocker: MockerFixture) -> None:
"""
Test `impersonate_user` when `update_impersonation_config` has an old signature.
"""
database = mocker.MagicMock()
url = make_url("sqlite://foo.db")
new_url = make_url("sqlite://bar.db")
engine_kwargs = {"connect_args": {"user": "alice"}}
get_url_for_impersonation = mocker.patch.object(
BaseEngineSpec,
"get_url_for_impersonation",
return_value=new_url,
)
update_impersonation_config = mocker.patch.object(
BaseEngineSpec,
"update_impersonation_config",
)
signature = mocker.patch("superset.db_engine_specs.base.signature")
signature().parameters = [
"cls",
"connect_args",
"uri",
"username",
"access_token",
]
BaseEngineSpec.impersonate_user(database, "alice", "SECRET", url, engine_kwargs)
get_url_for_impersonation.assert_called_once_with(url, True, "alice", "SECRET")
update_impersonation_config.assert_called_once_with(
{"user": "alice"},
new_url,
"alice",
"SECRET",
)
def test_handle_boolean_filter_default_behavior() -> None:
"""
Test that BaseEngineSpec uses IS operators for boolean filters by default.
"""
# Create a mock SQLAlchemy column
bool_col = Column("test_col", Boolean)
# Test IS_TRUE filter - should use IS operator by default
result_true = BaseEngineSpec.handle_boolean_filter(bool_col, "IS TRUE", True)
assert hasattr(result_true, "left") # IS comparison has left/right attributes
assert hasattr(result_true, "right")
# Test IS_FALSE filter - should use IS operator by default
result_false = BaseEngineSpec.handle_boolean_filter(bool_col, "IS FALSE", False)
assert hasattr(result_false, "left")
assert hasattr(result_false, "right")
def test_handle_boolean_filter_with_equality() -> None:
"""
Test that BaseEngineSpec can use equality operators when configured.
"""
# Create a test engine spec that uses equality
class TestEngineSpec(BaseEngineSpec):
use_equality_for_boolean_filters = True
bool_col = Column("test_col", Boolean)
# Test with equality enabled
result_true = TestEngineSpec.handle_boolean_filter(bool_col, "IS TRUE", True)
# Equality comparison should have different structure than IS comparison
assert str(type(result_true)).endswith("BinaryExpression'>")
result_false = TestEngineSpec.handle_boolean_filter(bool_col, "IS FALSE", False)
assert str(type(result_false)).endswith("BinaryExpression'>")
def test_handle_null_filter() -> None:
"""
Test null/not null filter handling.
"""
bool_col = Column("test_col", Boolean)
# Test IS_NULL - use actual FilterOperator values
result_null = BaseEngineSpec.handle_null_filter(bool_col, FilterOperator.IS_NULL)
assert hasattr(result_null, "left")
assert hasattr(result_null, "right")
# Test IS_NOT_NULL
result_not_null = BaseEngineSpec.handle_null_filter(
bool_col, FilterOperator.IS_NOT_NULL
)
assert hasattr(result_not_null, "left")
assert hasattr(result_not_null, "right")
# Test invalid operator
with pytest.raises(ValueError, match="Invalid null filter operator"):
BaseEngineSpec.handle_null_filter(bool_col, "INVALID") # type: ignore[arg-type]
def test_handle_comparison_filter() -> None:
"""
Test comparison filter handling for all operators.
"""
int_col = Column("test_col", Integer)
# Test all comparison operators - use actual FilterOperator values
operators_and_values = [
(FilterOperator.EQUALS, 5),
(FilterOperator.NOT_EQUALS, 5),
(FilterOperator.GREATER_THAN, 5),
(FilterOperator.LESS_THAN, 5),
(FilterOperator.GREATER_THAN_OR_EQUALS, 5),
(FilterOperator.LESS_THAN_OR_EQUALS, 5),
]
for op, value in operators_and_values:
result = BaseEngineSpec.handle_comparison_filter(int_col, op, value)
# All comparison operators should return binary expressions
assert str(type(result)).endswith("BinaryExpression'>")
# Test invalid operator
with pytest.raises(ValueError, match="Invalid comparison filter operator"):
BaseEngineSpec.handle_comparison_filter(int_col, "INVALID", 5) # type: ignore[arg-type]
def test_use_equality_for_boolean_filters_property() -> None:
"""
Test that BaseEngineSpec has the correct default value for boolean filter property.
"""
# Default should be False (use IS operators)
assert BaseEngineSpec.use_equality_for_boolean_filters is False
def test_extract_errors(mocker: MockerFixture) -> None:
"""
Test that error is extracted correctly when no custom error message is provided.
"""
mocker.patch(
"flask.current_app.config",
{},
)
msg = "This connector does not support roles"
result = BaseEngineSpec.extract_errors(Exception(msg))
expected = create_expected_superset_error(
message="This connector does not support roles",
engine_name=None,
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile("This connector does not support roles"): (
"Custom error message",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
}
}
},
)
def test_extract_errors_from_config(mocker: MockerFixture) -> None:
"""
Test that custom error messages are extracted correctly from app config
using database_name.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "This connector does not support roles"
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples")
expected = create_expected_superset_error(
message="Custom error message",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile("This connector does not support roles"): (
"Custom error message",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
}
}
},
)
def test_extract_errors_only_to_specified_database(mocker: MockerFixture) -> None:
"""
Test that custom error messages are only applied to the specified database_name.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "This connector does not support roles"
# database_name doesn't match configured one, so default message is used
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples_2")
expected = create_expected_superset_error(
message="This connector does not support roles",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile(r'message="(?P<message>[^"]*)"'): (
'Unexpected error: "%(message)s"',
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{
"custom_doc_links": [
{
"url": "https://example.com/docs",
"label": "Check documentation",
},
],
"show_issue_info": False,
},
)
}
}
},
)
def test_extract_errors_from_config_with_regex(mocker: MockerFixture) -> None:
"""
Test that custom error messages with regex, custom_doc_links,
and show_issue_info are extracted correctly from config.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = (
"db error: SomeUserError(type=USER_ERROR, name=TABLE_NOT_FOUND, "
'message="line 3:6: Table '
"'example_catalog.example_schema.example_table' does not exist"
'", '
"query_id=20250812_074513_00084_kju62)"
)
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples")
assert result == [
SupersetError(
message=(
'Unexpected error: "line 3:6: Table '
"'example_catalog.example_schema.example_table' does not exist"
'"'
),
error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
level=ErrorLevel.ERROR,
extra={
"engine_name": "ExampleEngine",
"issue_codes": [
{
"code": 1002,
"message": "Issue 1002 - The database returned an unexpected error.", # noqa: E501
}
],
"custom_doc_links": [
{
"url": "https://example.com/docs",
"label": "Check documentation",
},
],
"show_issue_info": False,
},
)
]
@with_config({"CUSTOM_DATABASE_ERRORS": {"examples": "not a dict"}})
def test_extract_errors_with_non_dict_custom_errors(mocker: MockerFixture):
"""
Test that extract_errors doesn't fail when custom database errors
are in wrong format.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "This connector does not support roles"
result = TestEngineSpec.extract_errors(Exception(msg))
expected = create_expected_superset_error(
message="This connector does not support roles",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config({"CUSTOM_DATABASE_ERRORS": {"examples": "not a dict"}})
def test_extract_errors_with_non_dict_engine_custom_errors(mocker: MockerFixture):
"""
Test that extract_errors doesn't fail when database-specific custom errors
are in wrong format.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "This connector does not support roles"
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples")
expected = create_expected_superset_error(
message="This connector does not support roles",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile("This connector does not support roles"): (
"",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
}
}
},
)
def test_extract_errors_with_empty_custom_error_message(mocker: MockerFixture):
"""
Test that when the custom error message is empty,
the original error message is preserved.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "This connector does not support roles"
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples")
expected = create_expected_superset_error(
message="This connector does not support roles",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile("connection error"): (
"Examples DB error message",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
},
"examples_2": {
re.compile("connection error"): (
"Examples_2 DB error message",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
},
}
},
)
def test_extract_errors_matches_database_name_selection(mocker: MockerFixture) -> None:
"""
Test that custom error messages are matched by database_name.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "connection error occurred"
# When database_name is examples_2 we should get that specific message
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples_2")
expected = create_expected_superset_error(
message="Examples_2 DB error message",
engine_name="ExampleEngine",
)
assert result == [expected]
@with_config(
{
"CUSTOM_DATABASE_ERRORS": {
"examples": {
re.compile("connection error"): (
"Examples DB error message",
SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
{},
)
},
}
},
)
def test_extract_errors_no_match_falls_back(mocker: MockerFixture) -> None:
"""
Test that when database_name has no match, the original error message is preserved.
"""
class TestEngineSpec(BaseEngineSpec):
engine_name = "ExampleEngine"
msg = "some other error"
result = TestEngineSpec.extract_errors(Exception(msg), database_name="examples_2")
expected = create_expected_superset_error(
message="some other error",
engine_name="ExampleEngine",
)
assert result == [expected]
def test_get_oauth2_authorization_uri_standard_params(mocker: MockerFixture) -> None:
"""
Test that BaseEngineSpec.get_oauth2_authorization_uri uses standard OAuth 2.0
parameters only and does not include provider-specific params like prompt=consent.
"""
config: OAuth2ClientConfig = {
"id": "client-id",
"secret": "client-secret",
"scope": "read write",
"redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
"authorization_request_uri": "https://oauth.example.com/authorize",
"token_request_uri": "https://oauth.example.com/token",
"request_content_type": "json",
}
state: OAuth2State = {
"database_id": 1,
"user_id": 1,
"default_redirect_uri": "http://localhost:8088/api/v1/oauth2/",
"tab_id": "1234",
}
url = BaseEngineSpec.get_oauth2_authorization_uri(config, state)
parsed = urlparse(url)
assert parsed.netloc == "oauth.example.com"
assert parsed.path == "/authorize"
query = parse_qs(parsed.query)
# Verify standard OAuth 2.0 parameters are included
assert query["scope"][0] == "read write"
assert query["response_type"][0] == "code"
assert query["client_id"][0] == "client-id"
assert query["redirect_uri"][0] == "http://localhost:8088/api/v1/database/oauth2/"
encoded_state = query["state"][0].replace("%2E", ".")
assert decode_oauth2_state(encoded_state) == state
# Verify Google-specific parameters are NOT included (standard OAuth 2.0)
assert "prompt" not in query
assert "access_type" not in query
assert "include_granted_scopes" not in query
# Verify PKCE parameters are NOT included when code_verifier is not provided
assert "code_challenge" not in query
assert "code_challenge_method" not in query