diff --git a/esphome/components/version/text_sensor.py b/esphome/components/version/text_sensor.py index cad239dc41..189d18256f 100644 --- a/esphome/components/version/text_sensor.py +++ b/esphome/components/version/text_sensor.py @@ -35,5 +35,8 @@ CONFIG_SCHEMA = ( async def to_code(config: ConfigType) -> None: var = await text_sensor.new_text_sensor(config) await cg.register_component(var, config) - cg.add(var.set_hide_hash(config[CONF_HIDE_HASH])) - cg.add(var.set_hide_timestamp(config[CONF_HIDE_TIMESTAMP])) + # Both flags default to false in C++, so only true needs a setter. + if config[CONF_HIDE_HASH]: + cg.add(var.set_hide_hash(True)) + if config[CONF_HIDE_TIMESTAMP]: + cg.add(var.set_hide_timestamp(True)) diff --git a/esphome/components/version/version_text_sensor.h b/esphome/components/version/version_text_sensor.h index 7ff6ac4d35..8537435079 100644 --- a/esphome/components/version/version_text_sensor.h +++ b/esphome/components/version/version_text_sensor.h @@ -15,8 +15,8 @@ class VersionTextSensor final : public text_sensor::TextSensor, public Component void dump_config() override; protected: - bool hide_hash_{false}; - bool hide_timestamp_{false}; + bool hide_hash_{false}; // Must match the setter check in text_sensor.py + bool hide_timestamp_{false}; // Must match the setter check in text_sensor.py }; } // namespace esphome::version diff --git a/tests/component_tests/version/__init__.py b/tests/component_tests/version/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/component_tests/version/config/version.yaml b/tests/component_tests/version/config/version.yaml new file mode 100644 index 0000000000..c602f88183 --- /dev/null +++ b/tests/component_tests/version/config/version.yaml @@ -0,0 +1,16 @@ +--- +esphome: + name: test + +esp8266: + board: d1_mini + +text_sensor: + - platform: version + id: default_version + name: Default Version + - platform: version + id: hidden_version + name: Hidden Version + hide_hash: true + hide_timestamp: true diff --git a/tests/component_tests/version/test_version.py b/tests/component_tests/version/test_version.py new file mode 100644 index 0000000000..14886264a2 --- /dev/null +++ b/tests/component_tests/version/test_version.py @@ -0,0 +1,17 @@ +"""Tests for the version text sensor codegen.""" + +from collections.abc import Callable +from pathlib import Path + + +def test_default_hide_flags_are_not_emitted( + generate_main: Callable[[str | Path], str], + component_config_path: Callable[[str], Path], +) -> None: + """Both flags are false in C++, so only true reaches the setters.""" + main_cpp = generate_main(component_config_path("version.yaml")) + + assert "default_version->set_hide_hash(" not in main_cpp + assert "default_version->set_hide_timestamp(" not in main_cpp + assert "hidden_version->set_hide_hash(true);" in main_cpp + assert "hidden_version->set_hide_timestamp(true);" in main_cpp