|
7 | 7 | from unittest.mock import patch |
8 | 8 |
|
9 | 9 | import pytest |
| 10 | +from sqlalchemy.exc import SQLAlchemyError |
10 | 11 | import voluptuous as vol |
11 | 12 | from voluptuous import MultipleInvalid |
12 | 13 |
|
@@ -86,6 +87,46 @@ async def test_query_service_external_db(hass: HomeAssistant, tmp_path: Path) -> |
86 | 87 | } |
87 | 88 |
|
88 | 89 |
|
| 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 | + |
89 | 130 | async def test_query_service_data_conversion( |
90 | 131 | hass: HomeAssistant, tmp_path: Path |
91 | 132 | ) -> None: |
|
0 commit comments