diff --git a/esphome/config_validation.py b/esphome/config_validation.py index 713df5452a..ef250927f3 100644 --- a/esphome/config_validation.py +++ b/esphome/config_validation.py @@ -2718,10 +2718,28 @@ SOURCE_SCHEMA = Any( ) -def rename_key(old_key, new_key): +def rename_key( + old_key, new_key, *, removed_in: str | None = None, component: str | None = None +): + """Rename a config key from ``old_key`` to ``new_key``. + + When ``removed_in`` is set, a deprecation warning is logged if the old key is + present. Pass ``component`` (the platform/component name) alongside + ``removed_in`` so the warning identifies where it originates. + """ + def validator(config: dict) -> dict: config = config.copy() if old_key in config: + if removed_in is not None: + prefix = f"[{component}] " if component else "" + _LOGGER.warning( + "%s'%s' is deprecated, use '%s'. Will be removed in %s", + prefix, + old_key, + new_key, + removed_in, + ) config[new_key] = config.pop(old_key) return config diff --git a/tests/unit_tests/test_config_validation.py b/tests/unit_tests/test_config_validation.py index 1da3d5593a..2ad22bc59c 100644 --- a/tests/unit_tests/test_config_validation.py +++ b/tests/unit_tests/test_config_validation.py @@ -1,4 +1,5 @@ import json +import logging from pathlib import Path import string @@ -2915,6 +2916,46 @@ def test_rename_key_absent() -> None: assert cv.rename_key("old", "new")({"other": 5}) == {"other": 5} +def test_rename_key_no_removed_in_is_silent( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger="esphome.config_validation"): + assert cv.rename_key("old", "new")({"old": 5}) == {"new": 5} + assert not caplog.records + + +def test_rename_key_removed_in_renames_and_warns( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger="esphome.config_validation"): + result = cv.rename_key("old", "new", removed_in="2026.8.0")({"old": 5}) + assert result == {"new": 5} + assert "'old' is deprecated, use 'new'. Will be removed in 2026.8.0" in caplog.text + + +def test_rename_key_removed_in_absent_key_no_warning( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger="esphome.config_validation"): + result = cv.rename_key("old", "new", removed_in="2026.8.0")({"other": 5}) + assert result == {"other": 5} + assert not caplog.records + + +def test_rename_key_removed_in_with_component_prefixes_warning( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger="esphome.config_validation"): + result = cv.rename_key( + "old", "new", removed_in="2026.8.0", component="my_component" + )({"old": 5}) + assert result == {"new": 5} + assert ( + "[my_component] 'old' is deprecated, use 'new'. Will be removed in 2026.8.0" + in caplog.text + ) + + def test_file__existing_relative_path(setup_core: Path) -> None: (setup_core / "partitions.csv").write_text("csv\n")