mirror of
https://github.com/home-assistant/core.git
synced 2025-12-24 21:06:19 +00:00
Automatically recover when the sqlite3 database is malformed or corrupted (#37949)
* Validate sqlite database on startup and move away if corruption is detected. * do not switch context in test -- its all sync
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
"""Test util methods."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.recorder import util
|
||||
from homeassistant.components.recorder.const import DATA_INSTANCE
|
||||
from homeassistant.components.recorder.const import DATA_INSTANCE, SQLITE_URL_PREFIX
|
||||
|
||||
from tests.async_mock import MagicMock, patch
|
||||
from tests.common import get_test_home_assistant, init_recorder_component
|
||||
@@ -60,3 +62,31 @@ def test_recorder_bad_execute(hass_recorder):
|
||||
util.execute((mck1,), to_native=True)
|
||||
|
||||
assert e_mock.call_count == 2
|
||||
|
||||
|
||||
def test_validate_or_move_away_sqlite_database(hass, tmpdir, caplog):
|
||||
"""Ensure a malformed sqlite database is moved away."""
|
||||
|
||||
test_dir = tmpdir.mkdir("test_validate_or_move_away_sqlite_database")
|
||||
test_db_file = f"{test_dir}/broken.db"
|
||||
dburl = f"{SQLITE_URL_PREFIX}{test_db_file}"
|
||||
|
||||
util.validate_sqlite_database(test_db_file) is True
|
||||
|
||||
assert os.path.exists(test_db_file) is True
|
||||
assert util.validate_or_move_away_sqlite_database(dburl) is True
|
||||
|
||||
_corrupt_db_file(test_db_file)
|
||||
|
||||
assert util.validate_or_move_away_sqlite_database(dburl) is False
|
||||
|
||||
assert "corrupt or malformed" in caplog.text
|
||||
|
||||
assert util.validate_or_move_away_sqlite_database(dburl) is True
|
||||
|
||||
|
||||
def _corrupt_db_file(test_db_file):
|
||||
"""Corrupt an sqlite3 database file."""
|
||||
f = open(test_db_file, "a")
|
||||
f.write("I am a corrupt db")
|
||||
f.close()
|
||||
|
||||
Reference in New Issue
Block a user