diff --git a/tests/unit_tests/test_writer.py b/tests/unit_tests/test_writer.py index cc902ec00f..0e2941a1b2 100644 --- a/tests/unit_tests/test_writer.py +++ b/tests/unit_tests/test_writer.py @@ -2468,29 +2468,37 @@ def test_copy_src_tree_ignores_removed_generated_file( assert new_json["config_hash"] == 0xDEADBEEF -def test_build_info_stale_branches(tmp_path: Path) -> None: +@pytest.mark.parametrize( + ("case", "content", "expected"), + [ + ("files missing", None, True), + ("json missing", "ABSENT", True), + ("json unreadable", "not json", True), + # Valid JSON that is not an object is stale, not an AttributeError + ("json not an object", "[]", True), + ("hash mismatch", {"config_hash": 2, "esphome_version": "CURRENT"}, True), + ("version mismatch", {"config_hash": 1, "esphome_version": "0.0.0"}, True), + ("matching record", {"config_hash": 1, "esphome_version": "CURRENT"}, False), + ], +) +def test_build_info_stale_branches( + tmp_path: Path, case: str, content, expected: bool +) -> None: """Missing files, an unreadable JSON, a hash or version mismatch each regenerate; a matching record does not.""" - import json as json_mod - from esphome.const import __version__ from esphome.writer import _build_info_stale h = tmp_path / "build_info_data.h" cpp = tmp_path / "build_info_data.cpp" info = tmp_path / "build_info.json" - assert _build_info_stale(h, cpp, info, 1) is True # files missing - h.write_text("") - cpp.write_text("") - assert _build_info_stale(h, cpp, info, 1) is True # JSON unreadable - info.write_text("not json") - assert _build_info_stale(h, cpp, info, 1) is True - # Valid JSON that is not an object is stale, not an AttributeError - info.write_text("[]") - assert _build_info_stale(h, cpp, info, 1) is True - info.write_text(json_mod.dumps({"config_hash": 2, "esphome_version": __version__})) - assert _build_info_stale(h, cpp, info, 1) is True # hash mismatch - info.write_text(json_mod.dumps({"config_hash": 1, "esphome_version": "0.0.0"})) - assert _build_info_stale(h, cpp, info, 1) is True # version mismatch - info.write_text(json_mod.dumps({"config_hash": 1, "esphome_version": __version__})) - assert _build_info_stale(h, cpp, info, 1) is False + if content is not None: + h.write_text("") + cpp.write_text("") + if isinstance(content, dict): + if content.get("esphome_version") == "CURRENT": + content["esphome_version"] = __version__ + info.write_text(json.dumps(content)) + elif isinstance(content, str) and content != "ABSENT": + info.write_text(content) + assert _build_info_stale(h, cpp, info, 1) is expected, case