fix: prevent nested transactions (#32401)

This commit is contained in:
Beto Dealmeida
2025-02-28 09:59:03 -05:00
committed by GitHub
parent 4d6b4f8343
commit 128c45e2d3
3 changed files with 61 additions and 0 deletions

View File

@@ -24,6 +24,7 @@ from typing import Any, Optional
from unittest.mock import call, Mock, patch
import pytest
from pytest_mock import MockerFixture
from superset import app
from superset.utils import decorators
@@ -294,3 +295,55 @@ def test_suppress_logging() -> None:
decorated = decorators.suppress_logging("test-logger", logging.CRITICAL + 1)(func)
decorated()
assert len(handler.log_records) == 0
def test_transacation_commit(mocker: MockerFixture) -> None:
"""
Test the `transaction` decorator when the function completes successfully.
"""
db = mocker.patch("superset.db")
@decorators.transaction()
def func() -> int:
return 42
result = func()
assert result == 42
db.session.commit.assert_called_once()
def test_transacation_rollback(mocker: MockerFixture) -> None:
"""
Test the `transaction` decorator when the function raises an exception.
"""
db = mocker.patch("superset.db")
@decorators.transaction()
def func() -> None:
raise ValueError("error")
with pytest.raises(ValueError, match="error"):
func()
db.session.commit.assert_not_called()
db.session.rollback.assert_called_once()
def test_transacation_nested(mocker: MockerFixture) -> None:
"""
Test the `transaction` decorator when the function is nested.
"""
db = mocker.patch("superset.db")
@decorators.transaction()
def func() -> int:
return 42
@decorators.transaction()
def nested() -> int:
func() # should not commit
raise ValueError("error")
with pytest.raises(ValueError, match="error"):
nested()
db.session.commit.assert_not_called()
db.session.rollback.assert_called_once()