mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
fix(config): never autosave defaults over an unreadable config file
Additional changes The migration copies the old file to the backup instead of moving it and replaces the file atomically, only after the migration succeeded. An explicit save keeps a copy of a file that could not be loaded and serializes the configuration before it opens the file. The configuration guide describes the migration backup and what happens to a file that cannot be loaded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
committed by
Bobby Noelte
co-authored by
Claude Opus 5.5
parent
887bae551b
commit
f3773de8f8
@@ -10,6 +10,7 @@ import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS, GeneralSettings
|
||||
from akkudoktoreos.core.version import __version__
|
||||
from akkudoktoreos.devices.devices import DevicesCommonSettings
|
||||
|
||||
|
||||
@@ -843,6 +844,90 @@ class TestConfigEOSToConfigFile:
|
||||
assert reloaded.server.port == 9000
|
||||
|
||||
|
||||
class TestUnreadableConfigFile:
|
||||
"""A configuration file that can not be loaded is never replaced by the defaults.
|
||||
|
||||
EOS falls back to the default configuration if its configuration file can not be read or
|
||||
migrated. The automatic save must not write these defaults over the file of the user.
|
||||
"""
|
||||
|
||||
# A trailing comma - a typical manual editing error.
|
||||
UNREADABLE = (
|
||||
'{"general": {"version": "' + __version__ + '", "latitude": 48.1},\n'
|
||||
' "server": {"port": 9999},}\n'
|
||||
).encode("utf-8")
|
||||
|
||||
@pytest.fixture
|
||||
def unreadable_config_file(
|
||||
self, uncreated_config: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> Path:
|
||||
"""Write an unreadable config file; get_config(init=True) starts from it."""
|
||||
uncreated_config.write_bytes(self.UNREADABLE)
|
||||
# Forget the last automatic save of another test.
|
||||
monkeypatch.setattr(ConfigEOS, "_config_autosave", "")
|
||||
return uncreated_config
|
||||
|
||||
def test_autosave_keeps_unreadable_file(self, unreadable_config_file: Path) -> None:
|
||||
from akkudoktoreos.core.coreabc import get_config
|
||||
|
||||
config = get_config(init=True)
|
||||
assert config.general.latitude == GeneralSettings.model_fields["latitude"].default
|
||||
|
||||
config.autosave()
|
||||
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
|
||||
config.autosave()
|
||||
|
||||
assert unreadable_config_file.read_bytes() == self.UNREADABLE
|
||||
|
||||
def test_autosave_keeps_file_of_failed_migration(
|
||||
self, uncreated_config: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from akkudoktoreos.config import configmigrate
|
||||
from akkudoktoreos.core.coreabc import get_config
|
||||
|
||||
content = json.dumps({"general": {"version": "0.0.0-old", "latitude": 48.1}}).encode()
|
||||
uncreated_config.write_bytes(content)
|
||||
monkeypatch.setattr(ConfigEOS, "_config_autosave", "")
|
||||
monkeypatch.setattr(
|
||||
configmigrate, "migrate_config_data", Mock(side_effect=RuntimeError("migration failed"))
|
||||
)
|
||||
|
||||
config = get_config(init=True)
|
||||
config.autosave()
|
||||
|
||||
assert uncreated_config.read_bytes() == content
|
||||
|
||||
def test_save_keeps_copy_of_unreadable_file(self, unreadable_config_file: Path) -> None:
|
||||
"""An explicit save replaces the file, but keeps a copy of it."""
|
||||
from akkudoktoreos.core.coreabc import get_config
|
||||
|
||||
config = get_config(init=True)
|
||||
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
|
||||
|
||||
config.to_config_file()
|
||||
|
||||
saved = json.loads(unreadable_config_file.read_text(encoding="utf-8"))
|
||||
assert saved["general"]["longitude"] == 11.5
|
||||
copies = list(unreadable_config_file.parent.glob("EOS.config.unreadable.*"))
|
||||
assert [copy.read_bytes() for copy in copies] == [self.UNREADABLE]
|
||||
|
||||
def test_autosave_resumes_when_file_is_loaded(self, unreadable_config_file: Path) -> None:
|
||||
from akkudoktoreos.core.coreabc import get_config
|
||||
|
||||
config = get_config(init=True)
|
||||
unreadable_config_file.write_text(
|
||||
json.dumps({"general": {"version": __version__, "latitude": 48.1}}), encoding="utf-8"
|
||||
)
|
||||
|
||||
config.reset_settings()
|
||||
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
|
||||
config.autosave()
|
||||
|
||||
saved = json.loads(unreadable_config_file.read_text(encoding="utf-8"))
|
||||
assert saved["general"]["latitude"] == 48.1
|
||||
assert saved["general"]["longitude"] == 11.5
|
||||
|
||||
|
||||
class TestDeviceSettings:
|
||||
def test_device_map_supplies_stable_identity(self):
|
||||
raw = {"batteries": {"house": {"profile_adjustment": {"nominal_capacity_wh": 12000}}}}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
# Test data directory and known migration pairs
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -144,6 +147,49 @@ class TestConfigMigration:
|
||||
assert result is True
|
||||
assert not backup_file.exists(), "No backup should be made if config is already current."
|
||||
|
||||
def test_migrate_config_file_backs_up_by_copy(self, tmp_config_file: Path) -> None:
|
||||
"""The backup is a copy of the old file, the migrated file keeps its permissions."""
|
||||
tmp_config_file.chmod(0o640)
|
||||
mode = stat.S_IMODE(tmp_config_file.stat().st_mode)
|
||||
original = tmp_config_file.read_bytes()
|
||||
backup_file = tmp_config_file.with_suffix(".bak")
|
||||
|
||||
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is True
|
||||
|
||||
assert backup_file.read_bytes() == original
|
||||
migrated_data = json.loads(tmp_config_file.read_text(encoding="utf-8"))
|
||||
assert migrated_data["general"]["version"] == __version__
|
||||
assert stat.S_IMODE(tmp_config_file.stat().st_mode) == mode
|
||||
assert not list(tmp_config_file.parent.glob("*.tmp"))
|
||||
|
||||
def test_migrate_config_file_failure_keeps_original(
|
||||
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A migration that raises leaves the old file in place and needs no backup."""
|
||||
original = tmp_config_file.read_bytes()
|
||||
backup_file = tmp_config_file.with_suffix(".bak")
|
||||
monkeypatch.setattr(
|
||||
configmigrate, "migrate_config_data", Mock(side_effect=RuntimeError("migration failed"))
|
||||
)
|
||||
|
||||
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False
|
||||
|
||||
assert tmp_config_file.read_bytes() == original
|
||||
assert not backup_file.exists()
|
||||
|
||||
def test_migrate_config_file_write_failure_keeps_original(
|
||||
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A migrated file that can not replace the old one leaves the old file in place."""
|
||||
original = tmp_config_file.read_bytes()
|
||||
backup_file = tmp_config_file.with_suffix(".bak")
|
||||
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError("replace failed")))
|
||||
|
||||
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False
|
||||
|
||||
assert tmp_config_file.read_bytes() == original
|
||||
assert not list(tmp_config_file.parent.glob("*.tmp"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("old_file, expected_file", MIGRATION_PAIRS)
|
||||
def test_migrate_old_version_config(self, tmp_path: Path, old_file: Path, expected_file: Path):
|
||||
|
||||
Reference in New Issue
Block a user