Skip to content

Commit 46e00ce

Browse files
committed
Add test_services.test_query_service_rollback_on_error
Signed-off-by: David Rapan <[email protected]>
1 parent bb93d46 commit 46e00ce

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tests/components/sql/test_services.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from unittest.mock import patch
88

99
import pytest
10+
from sqlalchemy.exc import SQLAlchemyError
1011
import voluptuous as vol
1112
from voluptuous import MultipleInvalid
1213

@@ -86,6 +87,46 @@ async def test_query_service_external_db(hass: HomeAssistant, tmp_path: Path) ->
8687
}
8788

8889

90+
async def test_query_service_rollback_on_error(
91+
hass: HomeAssistant,
92+
tmp_path: Path,
93+
caplog: pytest.LogCaptureFixture,
94+
) -> None:
95+
"""Test the query service."""
96+
db_path = tmp_path / "test.db"
97+
db_url = f"sqlite:///{db_path}"
98+
99+
# Create and populate the external database
100+
conn = sqlite3.connect(db_path)
101+
conn.execute("CREATE TABLE users (name TEXT, age INTEGER)")
102+
conn.execute("INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25)")
103+
conn.commit()
104+
conn.close()
105+
106+
await async_setup_component(hass, DOMAIN, {})
107+
await hass.async_block_till_done()
108+
109+
with (
110+
patch(
111+
"homeassistant.components.sql.services.generate_lambda_stmt",
112+
side_effect=SQLAlchemyError("Error executing query"),
113+
),
114+
pytest.raises(
115+
ServiceValidationError, match="An error occurred when executing the query"
116+
),
117+
patch("sqlalchemy.orm.session.Session.rollback") as mock_session_rollback,
118+
):
119+
await hass.services.async_call(
120+
DOMAIN,
121+
SERVICE_QUERY,
122+
{"query": "SELECT name, age FROM users ORDER BY age", "db_url": db_url},
123+
blocking=True,
124+
return_response=True,
125+
)
126+
127+
assert mock_session_rollback.call_count == 1
128+
129+
89130
async def test_query_service_data_conversion(
90131
hass: HomeAssistant, tmp_path: Path
91132
) -> None:

0 commit comments

Comments
 (0)