From 8be40bf1caaf159e89d71397f79f89125c4bfad5 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 29 Aug 2025 18:21:41 -0500 Subject: [PATCH] Fix incorrect entity count when lambdas are present (priority ordering issue) --- esphome/core/config.py | 2 +- tests/unit_tests/core/test_config.py | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/esphome/core/config.py b/esphome/core/config.py index 90768a4b09..b6ff1d8afd 100644 --- a/esphome/core/config.py +++ b/esphome/core/config.py @@ -423,7 +423,7 @@ async def _add_automations(config): DATETIME_SUBTYPES = {"date", "time", "datetime"} -@coroutine_with_priority(-100.0) +@coroutine_with_priority(-1000.0) async def _add_platform_defines() -> None: # Generate compile-time defines for platforms that have actual entities # Only add USE_* and count defines when there are entities diff --git a/tests/unit_tests/core/test_config.py b/tests/unit_tests/core/test_config.py index 46e3b513d7..f5ba5221ed 100644 --- a/tests/unit_tests/core/test_config.py +++ b/tests/unit_tests/core/test_config.py @@ -8,6 +8,7 @@ import pytest from esphome import config_validation as cv, core from esphome.const import CONF_AREA, CONF_AREAS, CONF_DEVICES +from esphome.core import config from esphome.core.config import Area, validate_area_config from .common import load_config_from_fixture @@ -223,3 +224,24 @@ def test_device_duplicate_id( # Check for the specific error message from IDPassValidationStep captured = capsys.readouterr() assert "ID duplicate_device redefined!" in captured.out + + +def test_add_platform_defines_priority() -> None: + """Test that _add_platform_defines runs after globals. + + This ensures the fix for issue #10431 where sensor counts were incorrect + when lambdas were present. The function must run at a lower priority than + globals (-100.0) to ensure all components (including those using globals + in lambdas) have registered their entities before the count defines are + generated. + + Regression test for https://github.com/esphome/esphome/issues/10431 + """ + # Import globals to check its priority + from esphome.components.globals import to_code as globals_to_code + + # _add_platform_defines must run AFTER globals (lower priority number = runs later) + assert config._add_platform_defines.priority < globals_to_code.priority, ( + f"_add_platform_defines priority ({config._add_platform_defines.priority}) must be lower than " + f"globals priority ({globals_to_code.priority}) to fix issue #10431 (sensor count bug with lambdas)" + )