chore(tests): Remove unnecessary/problematic app contexts (#28159)

This commit is contained in:
John Bodley 2024-04-24 13:46:35 -07:00 committed by GitHub
parent a9075fdb1f
commit bc65c245fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 880 additions and 980 deletions

View File

@ -81,36 +81,6 @@ DB_ACCESS_ROLE = "db_access_role"
SCHEMA_ACCESS_ROLE = "schema_access_role"
class TestRequestAccess(SupersetTestCase):
@classmethod
def setUpClass(cls):
with app.app_context():
security_manager.add_role("override_me")
security_manager.add_role(TEST_ROLE_1)
security_manager.add_role(TEST_ROLE_2)
security_manager.add_role(DB_ACCESS_ROLE)
security_manager.add_role(SCHEMA_ACCESS_ROLE)
db.session.commit()
@classmethod
def tearDownClass(cls):
with app.app_context():
override_me = security_manager.find_role("override_me")
db.session.delete(override_me)
db.session.delete(security_manager.find_role(TEST_ROLE_1))
db.session.delete(security_manager.find_role(TEST_ROLE_2))
db.session.delete(security_manager.find_role(DB_ACCESS_ROLE))
db.session.delete(security_manager.find_role(SCHEMA_ACCESS_ROLE))
db.session.commit()
def tearDown(self):
override_me = security_manager.find_role("override_me")
override_me.permissions = []
db.session.commit()
db.session.close()
super().tearDown()
@pytest.mark.parametrize(
"username,user_id",
[

View File

@ -14,18 +14,16 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# isort:skip_file
import pytest
from datetime import datetime
from typing import Optional
import pytest
from flask.ctx import AppContext
from superset import db
from superset.models.annotations import Annotation, AnnotationLayer
from tests.integration_tests.test_app import app
ANNOTATION_LAYERS_COUNT = 10
ANNOTATIONS_COUNT = 5
@ -70,13 +68,12 @@ def _insert_annotation(
@pytest.fixture()
def create_annotation_layers():
def create_annotation_layers(app_context: AppContext):
"""
Creates ANNOTATION_LAYERS_COUNT-1 layers with no annotations
and a final one with ANNOTATION_COUNT children
:return:
"""
with app.app_context():
annotation_layers = []
annotations = []
for cx in range(ANNOTATION_LAYERS_COUNT - 1):

View File

@ -23,6 +23,7 @@ from zipfile import is_zipfile, ZipFile
import prison
import pytest
import yaml
from flask.ctx import AppContext
from flask_babel import lazy_gettext as _
from parameterized import parameterized
from sqlalchemy import and_
@ -82,14 +83,12 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
resource_name = "chart"
@pytest.fixture(autouse=True)
def clear_data_cache(self):
with app.app_context():
def clear_data_cache(self, app_context: AppContext):
cache_manager.data_cache.clear()
yield
@pytest.fixture()
def create_charts(self):
with self.create_app().app_context():
charts = []
admin = self.get_user("admin")
for cx in range(CHARTS_FIXTURE_COUNT - 1):
@ -113,7 +112,6 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
@pytest.fixture()
def create_charts_created_by_gamma(self):
with self.create_app().app_context():
charts = []
user = self.get_user("gamma")
for cx in range(CHARTS_FIXTURE_COUNT - 1):
@ -126,7 +124,6 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
@pytest.fixture()
def create_certified_charts(self):
with self.create_app().app_context():
certified_charts = []
admin = self.get_user("admin")
for cx in range(CHARTS_FIXTURE_COUNT):
@ -149,7 +146,6 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
@pytest.fixture()
def create_chart_with_report(self):
with self.create_app().app_context():
admin = self.get_user("admin")
chart = self.insert_chart(f"chart_report", [admin.id], 1)
report_schedule = ReportSchedule(
@ -169,7 +165,6 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
@pytest.fixture()
def add_dashboard_to_chart(self):
with self.create_app().app_context():
admin = self.get_user("admin")
self.chart = self.insert_chart("My chart", [admin.id], 1)
@ -1127,7 +1122,6 @@ class TestChartApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCase):
@pytest.fixture()
def load_energy_charts(self):
with app.app_context():
admin = self.get_user("admin")
energy_table = (
db.session.query(SqlaTable)

View File

@ -27,6 +27,7 @@ from unittest import mock
from zipfile import ZipFile
from flask import Response
from flask.ctx import AppContext
from tests.integration_tests.conftest import with_feature_flags
from superset.charts.data.api import ChartDataRestApi
from superset.models.sql_lab import Query
@ -88,8 +89,7 @@ INCOMPATIBLE_ADHOC_COLUMN_FIXTURE: AdhocColumn = {
@pytest.fixture(autouse=True)
def skip_by_backend():
with app.app_context():
def skip_by_backend(app_context: AppContext):
if backend() == "hive":
pytest.skip("Skipping tests for Hive backend")

View File

@ -118,8 +118,8 @@ def get_or_create_user(get_user, create_user) -> ab_models.User:
@pytest.fixture(autouse=True, scope="session")
def setup_sample_data() -> Any:
# TODO(john-bodley): Determine a cleaner way of setting up the sample data without
# relying on `tests.integration_tests.test_app.app` leveraging an `app` fixture which is purposely
# scoped to the function level to ensure tests remain idempotent.
# relying on `tests.integration_tests.test_app.app` leveraging an `app` fixture
# which is purposely scoped to the function level to ensure tests remain idempotent.
with app.app_context():
setup_presto_if_needed()
@ -135,7 +135,6 @@ def setup_sample_data() -> Any:
with app.app_context():
# drop sqlalchemy tables
db.session.commit()
from sqlalchemy.ext import declarative
@ -163,8 +162,8 @@ def example_db_provider() -> Callable[[], Database]: # type: ignore
_db: Database | None = None
def __call__(self) -> Database:
with app.app_context():
if self._db is None:
with app.app_context():
self._db = get_example_database()
self._load_lazy_data_to_decouple_from_session()

View File

@ -58,10 +58,7 @@ from .base_tests import SupersetTestCase
class TestDashboard(SupersetTestCase):
@pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
table = db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()

View File

@ -2088,8 +2088,6 @@ class TestDashboardApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCas
self.assertNotEqual(result["uuid"], "")
self.assertEqual(result["allowed_domains"], allowed_domains)
db.session.expire_all()
# get returns value
resp = self.get_assert_metric(uri, "get_embedded")
self.assertEqual(resp.status_code, 200)
@ -2110,8 +2108,6 @@ class TestDashboardApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCas
self.assertNotEqual(result["uuid"], "")
self.assertEqual(result["allowed_domains"], [])
db.session.expire_all()
# get returns changed value
resp = self.get_assert_metric(uri, "get_embedded")
self.assertEqual(resp.status_code, 200)
@ -2123,8 +2119,6 @@ class TestDashboardApi(ApiOwnersTestCaseMixin, InsertChartMixin, SupersetTestCas
resp = self.delete_assert_metric(uri, "delete_embedded")
self.assertEqual(resp.status_code, 200)
db.session.expire_all()
# get returns 404
resp = self.get_assert_metric(uri, "get_embedded")
self.assertEqual(resp.status_code, 404)

View File

@ -37,10 +37,7 @@ from tests.integration_tests.fixtures.energy_dashboard import (
class TestDashboardDatasetSecurity(DashboardTestCase):
@pytest.fixture
def load_dashboard(self):
with app.app_context():
table = (
db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
)
table = db.session.query(SqlaTable).filter_by(table_name="energy_usage").one()
# get a slice from the allowed table
slice = db.session.query(Slice).filter_by(slice_name="Energy Sankey").one()

View File

@ -20,6 +20,7 @@ from __future__ import annotations
import json
import pytest
from flask.ctx import AppContext
from superset import db, security_manager
from superset.commands.database.exceptions import (
@ -84,15 +85,13 @@ def get_upload_db():
return db.session.query(Database).filter_by(database_name=CSV_UPLOAD_DATABASE).one()
@pytest.fixture(scope="function")
def setup_csv_upload_with_context():
with app.app_context():
@pytest.fixture()
def setup_csv_upload_with_context(app_context: AppContext):
yield from _setup_csv_upload()
@pytest.fixture(scope="function")
def setup_csv_upload_with_context_schema():
with app.app_context():
@pytest.fixture()
def setup_csv_upload_with_context_schema(app_context: AppContext):
yield from _setup_csv_upload(["public"])

View File

@ -46,6 +46,5 @@ class TestEmbeddedDashboardDAO(SupersetTestCase):
def test_get_by_uuid(self):
dash = db.session.query(Dashboard).filter_by(slug="world_health").first()
uuid = str(EmbeddedDashboardDAO.upsert(dash, ["test.example.com"]).uuid)
db.session.expire_all()
embedded = EmbeddedDashboardDAO.find_by_id(uuid)
self.assertIsNotNone(embedded)

View File

@ -173,8 +173,8 @@ def get_datasource_post() -> dict[str, Any]:
@pytest.fixture()
@pytest.mark.usefixtures("app_conntext")
def load_dataset_with_columns() -> Generator[SqlaTable, None, None]:
with app.app_context():
engine = create_engine(app.config["SQLALCHEMY_DATABASE_URI"], echo=True)
meta = MetaData()
@ -200,8 +200,7 @@ def load_dataset_with_columns() -> Generator[SqlaTable, None, None]:
yield dataset
# cleanup
students_table = meta.tables.get("students")
if students_table is not None:
if (students_table := meta.tables.get("students")) is not None:
base = declarative_base()
# needed for sqlite
db.session.commit()

View File

@ -15,14 +15,14 @@
# specific language governing permissions and limitations
# under the License.
import pytest
from flask.ctx import AppContext
from superset.extensions import db, security_manager
from tests.integration_tests.test_app import app
@pytest.fixture()
def public_role_like_gamma():
with app.app_context():
def public_role_like_gamma(app_context: AppContext):
app.config["PUBLIC_ROLE_LIKE"] = "Gamma"
security_manager.sync_role_definitions()
@ -33,8 +33,7 @@ def public_role_like_gamma():
@pytest.fixture()
def public_role_like_test_role():
with app.app_context():
def public_role_like_test_role(app_context: AppContext):
app.config["PUBLIC_ROLE_LIKE"] = "TestRole"
security_manager.sync_role_definitions()

View File

@ -22,8 +22,8 @@ from tests.integration_tests.test_app import app
@pytest.fixture
@pytest.mark.usefixtures("app_context")
def with_tagging_system_feature():
with app.app_context():
is_enabled = app.config["DEFAULT_FEATURE_FLAGS"]["TAGGING_SYSTEM"]
if not is_enabled:
app.config["DEFAULT_FEATURE_FLAGS"]["TAGGING_SYSTEM"] = True

View File

@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
import pytest
from flask.ctx import AppContext
from flask_appbuilder.security.sqla.models import Role, User
from superset import db, security_manager
@ -23,12 +24,9 @@ from tests.integration_tests.test_app import app
@pytest.fixture()
def create_gamma_sqllab_no_data():
with app.app_context():
def create_gamma_sqllab_no_data(app_context: AppContext):
gamma_role = db.session.query(Role).filter(Role.name == "Gamma").one_or_none()
sqllab_role = (
db.session.query(Role).filter(Role.name == "sql_lab").one_or_none()
)
sqllab_role = db.session.query(Role).filter(Role.name == "sql_lab").one_or_none()
security_manager.add_user(
GAMMA_SQLLAB_NO_DATA_USERNAME,

View File

@ -93,7 +93,6 @@ def load_world_bank_dashboard_with_slices_class_scope(load_world_bank_data):
def create_dashboard_for_loaded_data():
with app.app_context():
table = create_table_metadata(WB_HEALTH_POPULATION, get_example_database())
slices = _create_world_bank_slices(table)
dash = _create_world_bank_dashboard(table)

View File

@ -16,6 +16,8 @@
# under the License.
from importlib import import_module
import pytest
from superset import db
from superset.migrations.shared.security_converge import (
_find_pvm,
@ -34,8 +36,8 @@ upgrade = migration_module.do_upgrade
downgrade = migration_module.do_downgrade
@pytest.mark.usefixtures("app_context")
def test_migration_upgrade():
with app.app_context():
pre_perm = PermissionView(
permission=Permission(name="can_view_and_drill"),
view_menu=db.session.query(ViewMenu).filter_by(name="Dashboard").one(),
@ -52,8 +54,8 @@ def test_migration_upgrade():
assert _find_pvm(db.session, "Dashboard", "can_view_and_drill") is None
@pytest.mark.usefixtures("app_context")
def test_migration_downgrade():
with app.app_context():
downgrade(db.session)
assert _find_pvm(db.session, "Dashboard", "can_view_chart_as_table") is None

View File

@ -20,6 +20,7 @@ from typing import Optional, Union
import pandas as pd
import pytest
from flask.ctx import AppContext
from pytest_mock import MockFixture
from superset.commands.report.exceptions import AlertQueryError
@ -61,13 +62,12 @@ def test_execute_query_as_report_executor(
config: list[ExecutorType],
expected_result: Union[tuple[ExecutorType, str], Exception],
mocker: MockFixture,
app_context: None,
app_context: AppContext,
get_user,
) -> None:
from superset.commands.report.alert import AlertCommand
from superset.reports.models import ReportSchedule
with app.app_context():
original_config = app.config["ALERT_REPORTS_EXECUTE_AS"]
app.config["ALERT_REPORTS_EXECUTE_AS"] = config
owners = [get_user(owner_name) for owner_name in owner_names]
@ -85,9 +85,7 @@ def test_execute_query_as_report_executor(
validator_config_json='{"op": "==", "threshold": 1}',
)
command = AlertCommand(report_schedule=report_schedule)
override_user_mock = mocker.patch(
"superset.commands.report.alert.override_user"
)
override_user_mock = mocker.patch("superset.commands.report.alert.override_user")
cm = (
pytest.raises(type(expected_result))
if isinstance(expected_result, Exception)

View File

@ -23,6 +23,7 @@ from uuid import uuid4
import pytest
from flask import current_app
from flask.ctx import AppContext
from flask_appbuilder.security.sqla.models import User
from flask_sqlalchemy import BaseQuery
from freezegun import freeze_time
@ -162,7 +163,6 @@ def create_test_table_context(database: Database):
@pytest.fixture()
def create_report_email_chart():
with app.app_context():
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
email_target="target@email.com", chart=chart
@ -174,7 +174,6 @@ def create_report_email_chart():
@pytest.fixture()
def create_report_email_chart_alpha_owner(get_user):
with app.app_context():
owners = [get_user("alpha")]
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
@ -187,7 +186,6 @@ def create_report_email_chart_alpha_owner(get_user):
@pytest.fixture()
def create_report_email_chart_force_screenshot():
with app.app_context():
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
email_target="target@email.com", chart=chart, force_screenshot=True
@ -199,7 +197,6 @@ def create_report_email_chart_force_screenshot():
@pytest.fixture()
def create_report_email_chart_with_csv():
with app.app_context():
chart = db.session.query(Slice).first()
chart.query_context = '{"mock": "query_context"}'
report_schedule = create_report_notification(
@ -213,7 +210,6 @@ def create_report_email_chart_with_csv():
@pytest.fixture()
def create_report_email_chart_with_text():
with app.app_context():
chart = db.session.query(Slice).first()
chart.query_context = '{"mock": "query_context"}'
report_schedule = create_report_notification(
@ -227,7 +223,6 @@ def create_report_email_chart_with_text():
@pytest.fixture()
def create_report_email_chart_with_csv_no_query_context():
with app.app_context():
chart = db.session.query(Slice).first()
chart.query_context = None
report_schedule = create_report_notification(
@ -242,7 +237,6 @@ def create_report_email_chart_with_csv_no_query_context():
@pytest.fixture()
def create_report_email_dashboard():
with app.app_context():
dashboard = db.session.query(Dashboard).first()
report_schedule = create_report_notification(
email_target="target@email.com", dashboard=dashboard
@ -254,7 +248,6 @@ def create_report_email_dashboard():
@pytest.fixture()
def create_report_email_dashboard_force_screenshot():
with app.app_context():
dashboard = db.session.query(Dashboard).first()
report_schedule = create_report_notification(
email_target="target@email.com", dashboard=dashboard, force_screenshot=True
@ -266,7 +259,6 @@ def create_report_email_dashboard_force_screenshot():
@pytest.fixture()
def create_report_slack_chart():
with app.app_context():
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
slack_channel="slack_channel", chart=chart
@ -278,7 +270,6 @@ def create_report_slack_chart():
@pytest.fixture()
def create_report_slack_chart_with_csv():
with app.app_context():
chart = db.session.query(Slice).first()
chart.query_context = '{"mock": "query_context"}'
report_schedule = create_report_notification(
@ -293,7 +284,6 @@ def create_report_slack_chart_with_csv():
@pytest.fixture()
def create_report_slack_chart_with_text():
with app.app_context():
chart = db.session.query(Slice).first()
chart.query_context = '{"mock": "query_context"}'
report_schedule = create_report_notification(
@ -308,7 +298,6 @@ def create_report_slack_chart_with_text():
@pytest.fixture()
def create_report_slack_chart_working():
with app.app_context():
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
slack_channel="slack_channel", chart=chart
@ -338,7 +327,6 @@ def create_report_slack_chart_working():
@pytest.fixture()
def create_alert_slack_chart_success():
with app.app_context():
chart = db.session.query(Slice).first()
report_schedule = create_report_notification(
slack_channel="slack_channel",
@ -375,7 +363,6 @@ def create_alert_slack_chart_grace(request):
"validator_config_json": '{"op": "<", "threshold": 10}',
},
}
with app.app_context():
chart = db.session.query(Slice).first()
example_database = get_example_database()
with create_test_table_context(example_database):
@ -386,9 +373,7 @@ def create_alert_slack_chart_grace(request):
database=example_database,
sql=param_config[request.param]["sql"],
validator_type=param_config[request.param]["validator_type"],
validator_config_json=param_config[request.param][
"validator_config_json"
],
validator_config_json=param_config[request.param]["validator_config_json"],
)
report_schedule.last_state = ReportState.GRACE
report_schedule.last_eval_dttm = datetime(2020, 1, 1, 0, 0)
@ -462,7 +447,6 @@ def create_alert_email_chart(request):
"validator_config_json": '{"op": ">", "threshold": 54.999}',
},
}
with app.app_context():
chart = db.session.query(Slice).first()
example_database = get_example_database()
with create_test_table_context(example_database):
@ -473,9 +457,7 @@ def create_alert_email_chart(request):
database=example_database,
sql=param_config[request.param]["sql"],
validator_type=param_config[request.param]["validator_type"],
validator_config_json=param_config[request.param][
"validator_config_json"
],
validator_config_json=param_config[request.param]["validator_config_json"],
force_screenshot=True,
)
yield report_schedule
@ -544,7 +526,6 @@ def create_no_alert_email_chart(request):
"validator_config_json": '{"op": ">", "threshold": 0}',
},
}
with app.app_context():
chart = db.session.query(Slice).first()
example_database = get_example_database()
with create_test_table_context(example_database):
@ -555,9 +536,7 @@ def create_no_alert_email_chart(request):
database=example_database,
sql=param_config[request.param]["sql"],
validator_type=param_config[request.param]["validator_type"],
validator_config_json=param_config[request.param][
"validator_config_json"
],
validator_config_json=param_config[request.param]["validator_config_json"],
)
yield report_schedule
@ -578,7 +557,6 @@ def create_mul_alert_email_chart(request):
"validator_config_json": '{"op": "<", "threshold": 10}',
},
}
with app.app_context():
chart = db.session.query(Slice).first()
example_database = get_example_database()
with create_test_table_context(example_database):
@ -589,9 +567,7 @@ def create_mul_alert_email_chart(request):
database=example_database,
sql=param_config[request.param]["sql"],
validator_type=param_config[request.param]["validator_type"],
validator_config_json=param_config[request.param][
"validator_config_json"
],
validator_config_json=param_config[request.param]["validator_config_json"],
)
yield report_schedule
@ -599,7 +575,7 @@ def create_mul_alert_email_chart(request):
@pytest.fixture(params=["alert1", "alert2"])
def create_invalid_sql_alert_email_chart(request):
def create_invalid_sql_alert_email_chart(request, app_context: AppContext):
param_config = {
"alert1": {
"sql": "SELECT 'string' ",
@ -612,7 +588,6 @@ def create_invalid_sql_alert_email_chart(request):
"validator_config_json": '{"op": "<", "threshold": 10}',
},
}
with app.app_context():
chart = db.session.query(Slice).first()
example_database = get_example_database()
with create_test_table_context(example_database):
@ -623,9 +598,7 @@ def create_invalid_sql_alert_email_chart(request):
database=example_database,
sql=param_config[request.param]["sql"],
validator_type=param_config[request.param]["validator_type"],
validator_config_json=param_config[request.param][
"validator_config_json"
],
validator_config_json=param_config[request.param]["validator_config_json"],
grace_period=60 * 60,
)
yield report_schedule
@ -835,7 +808,8 @@ def test_email_chart_report_dry_run(
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_email_chart_with_csv"
"load_birth_names_dashboard_with_slices",
"create_report_email_chart_with_csv",
)
@patch("superset.utils.csv.urllib.request.urlopen")
@patch("superset.utils.csv.urllib.request.OpenerDirector.open")
@ -923,7 +897,8 @@ def test_email_chart_report_schedule_with_csv_no_query_context(
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_email_chart_with_text"
"load_birth_names_dashboard_with_slices",
"create_report_email_chart_with_text",
)
@patch("superset.utils.csv.urllib.request.urlopen")
@patch("superset.utils.csv.urllib.request.OpenerDirector.open")
@ -1545,7 +1520,8 @@ def test_slack_chart_alert_no_attachment(email_mock, create_alert_email_chart):
@pytest.mark.usefixtures(
"load_birth_names_dashboard_with_slices", "create_report_slack_chart"
"load_birth_names_dashboard_with_slices",
"create_report_slack_chart",
)
@patch("superset.utils.slack.WebClient")
@patch("superset.utils.screenshots.ChartScreenshot.get_screenshot")
@ -1571,7 +1547,7 @@ def test_slack_token_callable_chart_report(
assert_log(ReportState.SUCCESS)
@pytest.mark.usefixtures("create_no_alert_email_chart")
@pytest.mark.usefixtures("app_context")
def test_email_chart_no_alert(create_no_alert_email_chart):
"""
ExecuteReport Command: Test chart email no alert
@ -1583,7 +1559,7 @@ def test_email_chart_no_alert(create_no_alert_email_chart):
assert_log(ReportState.NOOP)
@pytest.mark.usefixtures("create_mul_alert_email_chart")
@pytest.mark.usefixtures("app_context")
def test_email_mul_alert(create_mul_alert_email_chart):
"""
ExecuteReport Command: Test chart email multiple rows
@ -1824,7 +1800,6 @@ def test_email_disable_screenshot(email_mock, create_alert_email_chart):
assert_log(ReportState.SUCCESS)
@pytest.mark.usefixtures("create_invalid_sql_alert_email_chart")
@patch("superset.reports.notifications.email.send_email_smtp")
def test_invalid_sql_alert(email_mock, create_invalid_sql_alert_email_chart):
"""
@ -1841,7 +1816,6 @@ def test_invalid_sql_alert(email_mock, create_invalid_sql_alert_email_chart):
assert_log(ReportState.ERROR)
@pytest.mark.usefixtures("create_invalid_sql_alert_email_chart")
@patch("superset.reports.notifications.email.send_email_smtp")
def test_grace_period_error(email_mock, create_invalid_sql_alert_email_chart):
"""
@ -1884,7 +1858,6 @@ def test_grace_period_error(email_mock, create_invalid_sql_alert_email_chart):
)
@pytest.mark.usefixtures("create_invalid_sql_alert_email_chart")
@patch("superset.reports.notifications.email.send_email_smtp")
@patch("superset.utils.screenshots.ChartScreenshot.get_screenshot")
def test_grace_period_error_flap(

View File

@ -35,13 +35,12 @@ def owners(get_user) -> list[User]:
return [get_user("admin")]
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.tasks.scheduler.execute.apply_async")
def test_scheduler_celery_timeout_ny(execute_mock, owners):
"""
Reports scheduler: Test scheduler setting celery soft and hard timeout
"""
with app.app_context():
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name="report",
@ -58,13 +57,12 @@ def test_scheduler_celery_timeout_ny(execute_mock, owners):
db.session.commit()
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.tasks.scheduler.execute.apply_async")
def test_scheduler_celery_no_timeout_ny(execute_mock, owners):
"""
Reports scheduler: Test scheduler setting celery soft and hard timeout
"""
with app.app_context():
app.config["ALERT_REPORTS_WORKING_TIME_OUT_KILL"] = False
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
@ -82,13 +80,12 @@ def test_scheduler_celery_no_timeout_ny(execute_mock, owners):
app.config["ALERT_REPORTS_WORKING_TIME_OUT_KILL"] = True
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.tasks.scheduler.execute.apply_async")
def test_scheduler_celery_timeout_utc(execute_mock, owners):
"""
Reports scheduler: Test scheduler setting celery soft and hard timeout
"""
with app.app_context():
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name="report",
@ -105,13 +102,12 @@ def test_scheduler_celery_timeout_utc(execute_mock, owners):
db.session.commit()
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.tasks.scheduler.execute.apply_async")
def test_scheduler_celery_no_timeout_utc(execute_mock, owners):
"""
Reports scheduler: Test scheduler setting celery soft and hard timeout
"""
with app.app_context():
app.config["ALERT_REPORTS_WORKING_TIME_OUT_KILL"] = False
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
@ -129,14 +125,13 @@ def test_scheduler_celery_no_timeout_utc(execute_mock, owners):
app.config["ALERT_REPORTS_WORKING_TIME_OUT_KILL"] = True
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.tasks.scheduler.is_feature_enabled")
@patch("superset.tasks.scheduler.execute.apply_async")
def test_scheduler_feature_flag_off(execute_mock, is_feature_enabled, owners):
"""
Reports scheduler: Test scheduler with feature flag off
"""
with app.app_context():
is_feature_enabled.return_value = False
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
@ -153,14 +148,13 @@ def test_scheduler_feature_flag_off(execute_mock, is_feature_enabled, owners):
db.session.commit()
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.commands.report.execute.AsyncExecuteReportScheduleCommand.__init__")
@patch("superset.commands.report.execute.AsyncExecuteReportScheduleCommand.run")
@patch("superset.tasks.scheduler.execute.update_state")
def test_execute_task(update_state_mock, command_mock, init_mock, owners):
from superset.commands.report.exceptions import ReportScheduleUnexpectedError
with app.app_context():
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name=f"report-{randint(0,1000)}",
@ -178,7 +172,7 @@ def test_execute_task(update_state_mock, command_mock, init_mock, owners):
db.session.commit()
@pytest.mark.usefixtures("owners")
@pytest.mark.usefixtures("app_context")
@patch("superset.commands.report.execute.AsyncExecuteReportScheduleCommand.__init__")
@patch("superset.commands.report.execute.AsyncExecuteReportScheduleCommand.run")
@patch("superset.tasks.scheduler.execute.update_state")
@ -188,7 +182,6 @@ def test_execute_task_with_command_exception(
):
from superset.commands.exceptions import CommandException
with app.app_context():
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name=f"report-{randint(0,1000)}",

View File

@ -84,7 +84,6 @@ from tests.integration_tests.test_app import app
def test_check_sqlalchemy_uri(
sqlalchemy_uri: str, error: bool, error_message: Optional[str]
):
with app.app_context():
if error:
with pytest.raises(SupersetSecurityException) as excinfo:
check_sqlalchemy_uri(make_url(sqlalchemy_uri))

View File

@ -24,7 +24,7 @@ import pytest
import numpy as np
import pandas as pd
from flask import Flask
from flask.ctx import AppContext
from pytest_mock import MockFixture
from sqlalchemy.sql import text
from sqlalchemy.sql.elements import TextClause
@ -598,9 +598,8 @@ class TestDatabaseModel(SupersetTestCase):
db.session.commit()
@pytest.fixture
def text_column_table():
with app.app_context():
@pytest.fixture()
def text_column_table(app_context: AppContext):
table = SqlaTable(
table_name="text_column_table",
sql=(
@ -836,6 +835,7 @@ def test_none_operand_in_filter(login_as_admin, physical_dataset):
)
@pytest.mark.usefixtures("app_context")
@pytest.mark.parametrize(
"row,dimension,result",
[
@ -857,7 +857,6 @@ def test_none_operand_in_filter(login_as_admin, physical_dataset):
],
)
def test__normalize_prequery_result_type(
app_context: Flask,
mocker: MockFixture,
row: pd.Series,
dimension: str,
@ -927,7 +926,8 @@ def test__normalize_prequery_result_type(
assert normalized == result
def test__temporal_range_operator_in_adhoc_filter(app_context, physical_dataset):
@pytest.mark.usefixtures("app_context")
def test__temporal_range_operator_in_adhoc_filter(physical_dataset):
result = physical_dataset.query(
{
"columns": ["col1", "col2"],

View File

@ -82,5 +82,4 @@ def test_form_data_to_adhoc_incorrect_clause_type():
form_data = {"where": "1 = 1", "having": "count(*) > 1"}
with pytest.raises(ValueError):
with app.app_context():
form_data_to_adhoc(form_data, "foobar")

View File

@ -685,7 +685,6 @@ class TestUtils(SupersetTestCase):
self.assertIsNotNone(parse_js_uri_path_item("item"))
def test_get_stacktrace(self):
with app.app_context():
app.config["SHOW_STACKTRACE"] = True
try:
raise Exception("NONONO!")
@ -839,7 +838,6 @@ class TestUtils(SupersetTestCase):
)
def test_get_form_data_default(self) -> None:
with app.test_request_context():
form_data, slc = get_form_data()
self.assertEqual(slc, None)

View File

@ -411,7 +411,6 @@ def test_delete_ssh_tunnel(
"""
Test that we can delete SSH Tunnel
"""
with app.app_context():
from superset.daos.database import DatabaseDAO
from superset.databases.api import DatabaseRestApi
from superset.databases.ssh_tunnel.models import SSHTunnel
@ -489,7 +488,6 @@ def test_delete_ssh_tunnel_not_found(
"""
Test that we cannot delete a tunnel that does not exist
"""
with app.app_context():
from superset.daos.database import DatabaseDAO
from superset.databases.api import DatabaseRestApi
from superset.databases.ssh_tunnel.models import SSHTunnel
@ -568,7 +566,6 @@ def test_apply_dynamic_database_filter(
defining a filter function and patching the config to get
the filtered results.
"""
with app.app_context():
from superset.daos.database import DatabaseDAO
from superset.databases.api import DatabaseRestApi
from superset.databases.ssh_tunnel.models import SSHTunnel