blob: e22c4ee46e5b53de7fb6b2892b49bf6a8cb8a068 [file]
# 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=redefined-outer-name, import-outside-toplevel
import functools
import importlib
import os
import unittest.mock
from collections.abc import Iterator
from contextlib import ExitStack
from typing import Any, Callable, Union
from unittest.mock import patch
import pytest
from _pytest.fixtures import SubRequest
from flask_appbuilder.menu import Menu
from pytest_mock import MockerFixture
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
from superset import security_manager
from superset.app import SupersetApp
from superset.common.chart_data import ChartDataResultType
from superset.common.query_object_factory import QueryObjectFactory
from superset.extensions import appbuilder, csrf, feature_flag_manager
from superset.initialization import SupersetAppInitializer
@pytest.fixture
def semantic_layers_enabled(app_context: None) -> Iterator[None]:
"""Enable semantic behavior explicitly and restore the host hook after each test."""
previous: Callable[[str, bool], bool] | None = (
feature_flag_manager._is_feature_enabled_func
)
def resolve(name: str, default: bool) -> bool:
"""Override only the semantic flag and preserve other host decisions."""
if name == "SEMANTIC_LAYERS":
return True
return previous(name, default) if previous else default
with patch.object(feature_flag_manager, "_is_feature_enabled_func", resolve):
yield
@pytest.fixture
def session_engine() -> Engine:
"""
The engine behind ``session``; a module may override it for one test file.
"""
return create_engine("sqlite://")
@pytest.fixture
def get_session(
mocker: MockerFixture, session_engine: Engine
) -> Iterator[Callable[[], Session]]:
"""
Create patched sessions and release their transactions after each test.
"""
engine: Engine = session_engine
cleanup: ExitStack = ExitStack()
def get_session() -> Session:
"""Create and patch a session owned by this fixture's cleanup stack."""
Session_: sessionmaker[Session] = sessionmaker(bind=engine) # pylint: disable=invalid-name # noqa: N806
in_memory_session: Session = Session_()
cleanup.callback(in_memory_session.close)
cleanup.callback(in_memory_session.rollback)
# flask calls db.session.remove()
in_memory_session.remove = lambda: None
# patch session
get_session: unittest.mock.MagicMock = mocker.patch(
"superset.security.SupersetSecurityManager.session",
)
get_session.return_value = in_memory_session
# FAB calls get_session.get_bind() to get a handler to the engine
get_session.get_bind.return_value = engine
# Allow for queries on security manager
get_session.query = in_memory_session.query
mocker.patch("superset.db.session", in_memory_session)
return in_memory_session
# Roll back before closing so version capture releases its units of work.
# Track every factory call, not only the session installed in db.session.
with cleanup:
yield get_session
@pytest.fixture
def session(get_session) -> Iterator[Session]:
return get_session()
@pytest.fixture(scope="session", autouse=True)
def _preload_clock_reading_drivers() -> None:
"""Import third-party drivers that read the clock at import, before any test.
``clickhouse_connect`` normalises the local timezone through ``dateutil``
at module import time, which raises ``AttributeError`` under a frozen
``freeze_time`` clock. Superset's ClickHouse engine spec imports it
lazily, on the first ``load_engine_specs()`` call, so whichever test
first resolves an engine spec pays that import -- and if that test runs
under ``freeze_time`` (seven unit-test files combine ``freeze_time`` with
engine-spec resolution) the import fails. Serially some earlier test
always paid it outside a frozen clock; under pytest-xdist each worker
starts cold, so the failure moves with worker assignment.
Only the third-party module is imported here, deliberately: importing
Superset's own engine-spec modules this early would also cache
app-context-dependent values (the ClickHouse spec resolves its
``product_name`` from ``current_app`` on import), and running full
``load_engine_specs()`` discovery would execute every registered
third-party entry point in every worker. Engine-spec discovery itself
stays lazy, so tests that exercise it still observe a cold state.
"""
# Even a guarded module-top import would tie the driver to collection on
# every invocation, including --collect-only and partial runs. Session setup
# imports it once per worker, after conftest/plugin loading and before any
# test can enter freeze_time. Guard ImportError because the driver is optional.
try:
import clickhouse_connect # noqa: F401
except ImportError:
pass
def build_app(config_overrides: dict[str, Any] | None = None) -> SupersetApp:
"""
Build and initialize a Superset app for the unit tests.
Every test module gets its own app, so this runs hundreds of times in one
xdist worker. Each initialization must replace the previous app in the
process-wide singletons rather than add to them: an app that stays
reachable keeps its views, routing rules, mappers and worker pools alive
for the rest of the worker's life, and the suite's resident memory then
grows with the number of modules until the CI runner is exhausted.
"""
app = SupersetApp(__name__)
app.config.from_object("superset.config")
# ``from_object`` shares ``superset.config``'s dict, and the feature flag
# manager updates it in place with this app's FEATURE_FLAGS. Without a copy,
# one module's flag overrides would stay on for every later module in the
# same xdist worker.
app.config["DEFAULT_FEATURE_FLAGS"] = dict(app.config["DEFAULT_FEATURE_FLAGS"])
app.config["SQLALCHEMY_DATABASE_URI"] = (
os.environ.get("SUPERSET__SQLALCHEMY_DATABASE_URI") or "sqlite://"
)
app.config["WTF_CSRF_ENABLED"] = False
app.config["PREVENT_UNSAFE_DB_CONNECTIONS"] = False
app.config["TESTING"] = True
app.config["RATELIMIT_ENABLED"] = False
app.config["CACHE_CONFIG"] = {}
app.config["DATA_CACHE_CONFIG"] = {}
app.config["SERVER_NAME"] = "example.com"
app.config["APPLICATION_ROOT"] = "/"
app.config["PREFERRED_URL_SCHEME="] = "http"
for key, val in (config_overrides or {}).items():
app.config[key] = val
# ``superset.extensions.appbuilder`` is a singleton, and won't rebuild the
# routes when this runs multiple times; we need to clear the registered
# views to ensure the initialization can happen more than once. The menu
# is reset for the same reason: ``init_views`` adds one set of menu items
# per initialization, and each item's link closure holds the app that
# registered it.
appbuilder.baseviews = []
appbuilder.menu = Menu()
# ``superset.extensions.csrf`` is a singleton too, and accumulates the CSRF
# exemptions of every app built here; reset them so one test's config (e.g.
# FAB_API_KEY_ENABLED) can't leak exempt blueprints into later tests.
csrf._exempt_views = set() # noqa: SLF001
csrf._exempt_blueprints = set() # noqa: SLF001
app_initializer = SupersetAppInitializer(app)
app_initializer.init_app()
# reload base views to ensure error handlers are applied to the app
with app.app_context():
import superset.views.base
importlib.reload(superset.views.base)
return app
@pytest.fixture(scope="module")
def app(request: SubRequest) -> SupersetApp:
"""
A fixture that generates a Superset app.
To override the default configs use:
@pytest.mark.parametrize(
"app",
[{"SOME_CONFIG": "SOME_VALUE"}],
indirect=True,
)
def test_some_test(app_context: None) -> None:
"""
return build_app(getattr(request, "param", None))
@pytest.fixture
def client(app: SupersetApp) -> Any:
with app.test_client() as client:
yield client
@pytest.fixture(autouse=True)
def app_context(app: SupersetApp) -> Iterator[None]:
"""
A fixture that yields and application context.
"""
with app.app_context():
yield
@pytest.fixture
def full_api_access(mocker: MockerFixture) -> Union[Iterator[None], None]:
"""
Allow full access to the API.
TODO (betodealmeida): we should replace this with user-fixtures, eg, ``admin`` or
``gamma``, so that we have granular access to the APIs.
"""
mocker.patch(
"flask_appbuilder.security.decorators.verify_jwt_in_request",
return_value=True,
)
mocker.patch.object(security_manager, "is_item_public", return_value=True)
mocker.patch.object(security_manager, "has_access", return_value=True)
mocker.patch.object(security_manager, "can_access_all_databases", return_value=True)
return None
@pytest.fixture
def dummy_query_object(request, app_context):
query_obj_marker = request.node.get_closest_marker("query_object")
result_type_marker = request.node.get_closest_marker("result_type")
if query_obj_marker is None:
query_object = {}
else:
query_object = query_obj_marker.args[0]
if result_type_marker is None:
result_type = ChartDataResultType.FULL
else:
result_type = result_type_marker.args[0]
return QueryObjectFactory(
app_configurations={
"ROW_LIMIT": 100,
},
_datasource_dao=unittest.mock.Mock(),
).create(parent_result_type=result_type, **query_object)
def with_feature_flags(**mock_feature_flags):
"""
Use this decorator to mock feature flags in tests.integration_tests.
Usage:
class TestYourFeature(SupersetTestCase):
@with_feature_flags(YOUR_FEATURE=True)
def test_your_feature_enabled(self):
self.assertEqual(is_feature_enabled("YOUR_FEATURE"), True)
@with_feature_flags(YOUR_FEATURE=False)
def test_your_feature_disabled(self):
self.assertEqual(is_feature_enabled("YOUR_FEATURE"), False)
"""
def mock_get_feature_flags():
feature_flags = feature_flag_manager._feature_flags or {}
return {**feature_flags, **mock_feature_flags}
def decorate(test_fn):
def wrapper(*args, **kwargs):
with patch.object(
feature_flag_manager,
"get_feature_flags",
side_effect=mock_get_feature_flags,
):
test_fn(*args, **kwargs)
return functools.update_wrapper(wrapper, test_fn)
return decorate