mirror of
https://github.com/esphome/esphome.git
synced 2026-09-26 22:40:21 +00:00
Merge branch 'dev' into app-loop-optimize-speed
This commit is contained in:
@@ -8,10 +8,16 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp32 import VARIANTS
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
|
||||
from esphome.components.esp32 import VARIANT_ESP32, VARIANTS
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS, KEY_VARIANT
|
||||
from esphome.components.esp32.gpio import validate_gpio_pin
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ESPHOME, PlatformFramework
|
||||
from esphome.const import (
|
||||
CONF_ESPHOME,
|
||||
CONF_IGNORE_PIN_VALIDATION_ERROR,
|
||||
CONF_NUMBER,
|
||||
PlatformFramework,
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from tests.component_tests.types import SetCoreConfigCallable
|
||||
|
||||
@@ -149,6 +155,73 @@ def test_execute_from_psram_p4_sdkconfig(
|
||||
assert "CONFIG_SPIRAM_RODATA" not in sdkconfig
|
||||
|
||||
|
||||
def test_ignore_pin_validation_error_on_clean_pin_warns(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A pin that passes validation but sets `ignore_pin_validation_error: true`
|
||||
should log a warning nudging the user to remove the flag, and not raise."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF, platform_data={KEY_VARIANT: VARIANT_ESP32}
|
||||
)
|
||||
|
||||
pin = {CONF_NUMBER: 4, CONF_IGNORE_PIN_VALIDATION_ERROR: True}
|
||||
with caplog.at_level("WARNING"):
|
||||
result = validate_gpio_pin(pin)
|
||||
|
||||
assert result[CONF_NUMBER] == 4
|
||||
assert "GPIO4 has no validation errors to ignore" in caplog.text
|
||||
|
||||
|
||||
def test_ignore_pin_validation_error_on_dirty_pin_suppresses(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A pin that fails validation with `ignore_pin_validation_error: true` should
|
||||
log the suppression warning and not raise (existing behavior)."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF, platform_data={KEY_VARIANT: VARIANT_ESP32}
|
||||
)
|
||||
|
||||
# GPIO6 is a flash pin on ESP32 -> pin_validation raises cv.Invalid
|
||||
pin = {CONF_NUMBER: 6, CONF_IGNORE_PIN_VALIDATION_ERROR: True}
|
||||
with caplog.at_level("WARNING"):
|
||||
result = validate_gpio_pin(pin)
|
||||
|
||||
assert result[CONF_NUMBER] == 6
|
||||
assert "Ignoring validation error on pin 6" in caplog.text
|
||||
|
||||
|
||||
def test_dirty_pin_without_ignore_flag_raises(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
) -> None:
|
||||
"""A pin that fails validation without the ignore flag should still raise."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF, platform_data={KEY_VARIANT: VARIANT_ESP32}
|
||||
)
|
||||
|
||||
pin = {CONF_NUMBER: 6, CONF_IGNORE_PIN_VALIDATION_ERROR: False}
|
||||
with pytest.raises(cv.Invalid, match="flash interface"):
|
||||
validate_gpio_pin(pin)
|
||||
|
||||
|
||||
def test_clean_pin_without_ignore_flag_does_not_warn(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A clean pin without the ignore flag should pass silently."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF, platform_data={KEY_VARIANT: VARIANT_ESP32}
|
||||
)
|
||||
|
||||
pin = {CONF_NUMBER: 4, CONF_IGNORE_PIN_VALIDATION_ERROR: False}
|
||||
with caplog.at_level("WARNING"):
|
||||
result = validate_gpio_pin(pin)
|
||||
|
||||
assert result[CONF_NUMBER] == 4
|
||||
assert "has no validation errors to ignore" not in caplog.text
|
||||
|
||||
|
||||
def test_execute_from_psram_disabled_sdkconfig(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: arduino
|
||||
|
||||
spi:
|
||||
clk_pin: GPIO18
|
||||
mosi_pin: GPIO23
|
||||
|
||||
display:
|
||||
- platform: ili9xxx
|
||||
id: tft_display
|
||||
model: ST7789V
|
||||
cs_pin: GPIO5
|
||||
dc_pin: GPIO17
|
||||
reset_pin: GPIO16
|
||||
invert_colors: false
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Tests for the ili9xxx component."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_ili9xxx_placement_new_uses_model_subclass(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""Regression test for ili9xxx picking the right constructor under placement new.
|
||||
|
||||
ili9xxx declares the ID as the base ``ILI9XXXDisplay`` but constructs a
|
||||
model-specific subclass (e.g. ``ILI9XXXST7789V``) via ``MODELS[...].new()``.
|
||||
Pvariable must emit placement new for the subclass — otherwise the base
|
||||
default constructor runs and the panel is left with a null init sequence
|
||||
and 0x0 dimensions, producing a silent blank screen.
|
||||
"""
|
||||
main_cpp = generate_main(component_config_path("ili9xxx_test.yaml"))
|
||||
|
||||
# Storage is sized for the subclass so the full object fits.
|
||||
assert "sizeof(ili9xxx::ILI9XXXST7789V)" in main_cpp
|
||||
assert "alignas(ili9xxx::ILI9XXXST7789V)" in main_cpp
|
||||
# Pointer is declared as the base type for polymorphism.
|
||||
assert "static ili9xxx::ILI9XXXDisplay *const tft_display" in main_cpp
|
||||
# Placement new runs the subclass constructor — this is the actual regression fix.
|
||||
assert "new(tft_display) ili9xxx::ILI9XXXST7789V()" in main_cpp
|
||||
# Base-class default constructor must NOT be used.
|
||||
assert "new(tft_display) ili9xxx::ILI9XXXDisplay()" not in main_cpp
|
||||
@@ -7,6 +7,11 @@ import pytest
|
||||
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.esp32 import KEY_BOARD, VARIANT_ESP32P4
|
||||
|
||||
# Importing xl9535 registers its pin schema with pins.PIN_SCHEMA_REGISTRY so that
|
||||
# models (e.g. SEEED-RETERMINAL-D1001) that reference xl9535-backed pins in their
|
||||
# defaults can be validated by the mipi_dsi CONFIG_SCHEMA in this test.
|
||||
import esphome.components.xl9535 # noqa: F401
|
||||
from esphome.const import (
|
||||
CONF_DIMENSIONS,
|
||||
CONF_HEIGHT,
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Tests for the _final_validate buffer size calculation in mipi_spi."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.display import CONF_SHOW_TEST_CARD
|
||||
from esphome.components.esp32 import KEY_BOARD, KEY_VARIANT, VARIANT_ESP32
|
||||
from esphome.components.mipi_spi.display import CONFIG_SCHEMA, FINAL_VALIDATE_SCHEMA
|
||||
from esphome.const import CONF_BUFFER_SIZE, PlatformFramework
|
||||
from esphome.types import ConfigType
|
||||
from tests.component_tests.types import SetCoreConfigCallable
|
||||
|
||||
|
||||
def _validated(config: ConfigType) -> ConfigType:
|
||||
"""Run the component config schema followed by the final validation."""
|
||||
config = CONFIG_SCHEMA(config)
|
||||
FINAL_VALIDATE_SCHEMA(config)
|
||||
return config
|
||||
|
||||
|
||||
def _custom_config(
|
||||
width: int,
|
||||
height: int,
|
||||
color_depth: str | int | None = None,
|
||||
**extra: Any,
|
||||
) -> ConfigType:
|
||||
"""Build a minimal valid custom-model config with the given dimensions."""
|
||||
config: ConfigType = {
|
||||
"model": "custom",
|
||||
"dc_pin": 18,
|
||||
"dimensions": {"width": width, "height": height},
|
||||
"init_sequence": [[0xA0, 0x01]],
|
||||
}
|
||||
if color_depth is not None:
|
||||
config["color_depth"] = color_depth
|
||||
config.update(extra)
|
||||
return config
|
||||
|
||||
|
||||
# The auto buffer-size selection inside _final_validate targets ~20 kB of
|
||||
# pixel buffer. For a buffer of ``depth_bytes * width * height``, it picks the
|
||||
# smallest integer ``x`` in range(2, 8) such that
|
||||
# ``min(20000, buffer // 4) / buffer >= 1 / x`` (falling back to ``x = 8``).
|
||||
# The test cases below cover the full range of possible outcomes (1/4 .. 1/8).
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "color_depth", "expected"),
|
||||
[
|
||||
# 16-bit color depth -- buffer = 2 * width * height
|
||||
# 128*160*2 = 40960 B -> fraction = 10240/40960 = 0.25 -> x = 4
|
||||
pytest.param(128, 160, "16bit", 1.0 / 4, id="16bit_tiny"),
|
||||
# 200*224*2 = 89600 B -> fraction = 20000/89600 ≈ 0.2232 -> x = 5
|
||||
pytest.param(200, 224, "16bit", 1.0 / 5, id="16bit_small"),
|
||||
# 240*224*2 = 107520 B -> fraction ≈ 0.1860 -> x = 6
|
||||
pytest.param(240, 224, "16bit", 1.0 / 6, id="16bit_medium"),
|
||||
# 200*320*2 = 128000 B -> fraction = 0.15625 -> x = 7
|
||||
pytest.param(200, 320, "16bit", 1.0 / 7, id="16bit_large"),
|
||||
# 240*320*2 = 153600 B -> fraction ≈ 0.1302 -> default x = 8
|
||||
pytest.param(240, 320, "16bit", 1.0 / 8, id="16bit_xlarge"),
|
||||
# 320*480*2 = 307200 B -> fraction ≈ 0.0651 -> default x = 8
|
||||
pytest.param(320, 480, "16bit", 1.0 / 8, id="16bit_huge"),
|
||||
# 8-bit color depth -- buffer = width * height
|
||||
# 320*240 = 76800 B -> fraction = 19200/76800 = 0.25 -> x = 4
|
||||
pytest.param(320, 240, "8bit", 1.0 / 4, id="8bit_tiny"),
|
||||
# 400*224 = 89600 B -> fraction ≈ 0.2232 -> x = 5
|
||||
pytest.param(400, 224, "8bit", 1.0 / 5, id="8bit_small"),
|
||||
# 480*224 = 107520 B -> fraction ≈ 0.1860 -> x = 6
|
||||
pytest.param(480, 224, "8bit", 1.0 / 6, id="8bit_medium"),
|
||||
# 400*320 = 128000 B -> fraction = 0.15625 -> x = 7
|
||||
pytest.param(400, 320, "8bit", 1.0 / 7, id="8bit_large"),
|
||||
# 480*320 = 153600 B -> fraction ≈ 0.1302 -> default x = 8
|
||||
pytest.param(480, 320, "8bit", 1.0 / 8, id="8bit_xlarge"),
|
||||
],
|
||||
)
|
||||
def test_buffer_size_auto_selected(
|
||||
width: int,
|
||||
height: int,
|
||||
color_depth: str,
|
||||
expected: float,
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
) -> None:
|
||||
"""Without PSRAM or an explicit buffer_size, a fraction is chosen from the display size.
|
||||
|
||||
Without any drawing method and without LVGL, final validation also auto-enables
|
||||
``show_test_card``, which in turn makes the component require a buffer and therefore
|
||||
triggers the buffer-size selection path.
|
||||
"""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
|
||||
)
|
||||
|
||||
config = _validated(_custom_config(width, height, color_depth))
|
||||
|
||||
# Sanity check: final validation should have enabled the test card for us,
|
||||
# which is what causes the buffer-size calculation to actually run.
|
||||
assert config.get(CONF_SHOW_TEST_CARD) is True
|
||||
assert config[CONF_BUFFER_SIZE] == pytest.approx(expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"buffer_size",
|
||||
[0.125, 0.25, 0.5, 1.0],
|
||||
ids=["one_eighth", "one_quarter", "half", "full"],
|
||||
)
|
||||
def test_explicit_buffer_size_is_preserved(
|
||||
buffer_size: float,
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
) -> None:
|
||||
"""An explicitly configured buffer_size is never overridden by final validation."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
|
||||
)
|
||||
|
||||
config = _validated(
|
||||
_custom_config(240, 320, "16bit", buffer_size=buffer_size),
|
||||
)
|
||||
|
||||
assert config[CONF_BUFFER_SIZE] == pytest.approx(buffer_size)
|
||||
|
||||
|
||||
def test_buffer_size_not_set_when_psram_enabled(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config,
|
||||
) -> None:
|
||||
"""When PSRAM is enabled the auto buffer-size selection is skipped."""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
|
||||
)
|
||||
# Presence of the psram domain in the full config is what _final_validate checks.
|
||||
set_component_config("psram", True)
|
||||
|
||||
config = _validated(_custom_config(240, 320, "16bit"))
|
||||
|
||||
assert CONF_BUFFER_SIZE not in config
|
||||
|
||||
|
||||
def test_buffer_size_not_set_when_buffer_not_required(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config,
|
||||
) -> None:
|
||||
"""With LVGL present and no drawing methods, no buffer fraction is chosen.
|
||||
|
||||
LVGL suppresses the automatic show_test_card injection, which means
|
||||
``requires_buffer`` is False and the early-return branch fires.
|
||||
"""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
|
||||
)
|
||||
set_component_config("lvgl", [])
|
||||
|
||||
config = _validated(_custom_config(240, 320, "16bit"))
|
||||
|
||||
assert CONF_BUFFER_SIZE not in config
|
||||
# And no test card should have been auto-enabled either.
|
||||
assert not config.get(CONF_SHOW_TEST_CARD)
|
||||
|
||||
|
||||
def test_buffer_size_selected_when_lvgl_with_test_card(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config,
|
||||
) -> None:
|
||||
"""LVGL present + an explicit drawing method still triggers buffer sizing.
|
||||
|
||||
When LVGL is enabled, ``show_test_card`` is not injected automatically,
|
||||
but users can still request it explicitly -- in that case ``requires_buffer``
|
||||
is True and the buffer-size heuristic still runs.
|
||||
"""
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
|
||||
)
|
||||
set_component_config("lvgl", [])
|
||||
|
||||
# 128x160 @ 16bit -> expected 1/4 (see test_buffer_size_auto_selected).
|
||||
config = _validated(
|
||||
_custom_config(128, 160, "16bit", show_test_card=True),
|
||||
)
|
||||
|
||||
assert config[CONF_BUFFER_SIZE] == pytest.approx(1.0 / 4)
|
||||
@@ -2,18 +2,20 @@
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import re
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.packages import (
|
||||
CONFIG_SCHEMA,
|
||||
_substitute_package_definition,
|
||||
_walk_packages,
|
||||
do_packages_pass,
|
||||
is_package_definition,
|
||||
merge_packages,
|
||||
)
|
||||
from esphome.components.substitutions import do_substitution_pass
|
||||
from esphome.components.substitutions import ContextVars, do_substitution_pass
|
||||
import esphome.config as config_module
|
||||
from esphome.config import resolve_extend_remove
|
||||
from esphome.config_helpers import Extend, Remove
|
||||
@@ -44,7 +46,7 @@ from esphome.const import (
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from esphome.util import OrderedDict
|
||||
from esphome.yaml_util import IncludeFile, add_context
|
||||
from esphome.yaml_util import IncludeFile, add_context, load_yaml
|
||||
|
||||
# Test strings
|
||||
TEST_DEVICE_NAME = "test_device_name"
|
||||
@@ -1399,3 +1401,85 @@ def test_raw_config_contains_merged_esphome_from_package(tmp_path) -> None:
|
||||
"CORE.raw_config should contain esphome section after package merge"
|
||||
)
|
||||
assert CORE.raw_config[CONF_ESPHOME][CONF_NAME] == TEST_DEVICE_NAME
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _substitute_package_definition
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_substitute_package_definition_local_dict_returned_unchanged() -> None:
|
||||
"""A plain local config dict is not substituted and is returned as-is."""
|
||||
pkg = {CONF_WIFI: {CONF_SSID: "test"}}
|
||||
result = _substitute_package_definition(pkg, ContextVars())
|
||||
assert result is pkg
|
||||
|
||||
|
||||
def test_substitute_package_definition_string_resolved_with_context() -> None:
|
||||
"""A string package definition has its variables substituted."""
|
||||
ctx = ContextVars({"variant": "esp32"})
|
||||
result = _substitute_package_definition("device-${variant}.yaml", ctx)
|
||||
assert result == "device-esp32.yaml"
|
||||
|
||||
|
||||
def test_substitute_package_definition_undefined_in_string() -> None:
|
||||
"""An undefined variable in a package URL string raises cv.Invalid."""
|
||||
with pytest.raises(cv.Invalid, match="Undefined variable in package definition"):
|
||||
_substitute_package_definition(
|
||||
"github://org/repo/${undefined_var}/pkg.yaml", ContextVars()
|
||||
)
|
||||
|
||||
|
||||
def test_substitute_package_definition_undefined_in_remote_dict_field() -> None:
|
||||
"""An undefined variable inside a remote-dict field names the offending field."""
|
||||
with pytest.raises(cv.Invalid) as exc_info:
|
||||
_substitute_package_definition(
|
||||
{CONF_URL: "github://${typo}/repo"}, ContextVars()
|
||||
)
|
||||
err = str(exc_info.value)
|
||||
assert "'typo' is undefined" in err
|
||||
assert CONF_URL in err
|
||||
|
||||
|
||||
def test_substitute_package_definition_undefined_in_remote_dict_non_first_field() -> (
|
||||
None
|
||||
):
|
||||
"""The field path joins correctly for non-first dict fields (e.g. ``ref``)."""
|
||||
with pytest.raises(cv.Invalid) as exc_info:
|
||||
_substitute_package_definition(
|
||||
{
|
||||
CONF_URL: "github://org/repo",
|
||||
CONF_REF: "branch-${branch_typo}",
|
||||
},
|
||||
ContextVars(),
|
||||
)
|
||||
err = str(exc_info.value)
|
||||
assert "'branch_typo' is undefined" in err
|
||||
assert CONF_REF in err
|
||||
|
||||
|
||||
def test_substitute_package_definition_includes_source_location(tmp_path: Path) -> None:
|
||||
"""A package loaded from YAML surfaces file/line/col in the cv.Invalid message.
|
||||
|
||||
Line/column are rendered 1-based (matching config.line_info() and editor
|
||||
line numbering) and point at the offending scalar, not the enclosing dict.
|
||||
"""
|
||||
yaml_file = tmp_path / "main.yaml"
|
||||
yaml_file.write_text(
|
||||
"packages:\n broken: github://org/repo/${undefined_var}/pkg.yaml\n"
|
||||
)
|
||||
config = load_yaml(yaml_file)
|
||||
package_config = config[CONF_PACKAGES]["broken"]
|
||||
|
||||
with pytest.raises(cv.Invalid) as exc_info:
|
||||
_substitute_package_definition(package_config, ContextVars())
|
||||
|
||||
err = str(exc_info.value)
|
||||
assert "main.yaml" in err
|
||||
# The offending value lives on line 2 (1-based). Column depends on the YAML
|
||||
# loader, so we only pin line and check that a 1-based column is present.
|
||||
match = re.search(r"main\.yaml (\d+):(\d+)", err)
|
||||
assert match, err
|
||||
line, col = int(match.group(1)), int(match.group(2))
|
||||
assert line == 2, f"expected 1-based line 2, got {line} (err={err!r})"
|
||||
assert col >= 1, f"expected 1-based column ≥ 1, got {col} (err={err!r})"
|
||||
|
||||
@@ -145,3 +145,19 @@ display:
|
||||
it.filled_rectangle(0, 0, it.get_width(), it.get_height(), Color::WHITE);
|
||||
it.circle(it.get_width() / 2, it.get_height() / 2, 30, Color::BLACK);
|
||||
it.circle(it.get_width() / 2, it.get_height() / 2, 20, Color(255, 0, 0));
|
||||
|
||||
- platform: epaper_spi
|
||||
spi_id: spi_bus
|
||||
model: goodisplay-gdey042t81-4.2
|
||||
cs_pin:
|
||||
allow_other_uses: true
|
||||
number: GPIO5
|
||||
dc_pin:
|
||||
allow_other_uses: true
|
||||
number: GPIO17
|
||||
reset_pin:
|
||||
allow_other_uses: true
|
||||
number: GPIO16
|
||||
busy_pin:
|
||||
allow_other_uses: true
|
||||
number: GPIO4
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
ethernet:
|
||||
type: W5500
|
||||
clk_pin: 6
|
||||
mosi_pin: 7
|
||||
miso_pin: 2
|
||||
cs_pin: 10
|
||||
interrupt_pin: 3
|
||||
reset_pin: 4
|
||||
clock_speed: 10Mhz
|
||||
manual_ip:
|
||||
static_ip: 192.168.178.56
|
||||
gateway: 192.168.178.1
|
||||
subnet: 255.255.255.0
|
||||
domain: .local
|
||||
mac_address: "02:AA:BB:CC:DD:01"
|
||||
on_connect:
|
||||
- logger.log: "Ethernet connected!"
|
||||
on_disconnect:
|
||||
- logger.log: "Ethernet disconnected!"
|
||||
@@ -45,6 +45,11 @@ esphome:
|
||||
args:
|
||||
- response->status_code
|
||||
- body.c_str()
|
||||
- delay: 1s
|
||||
- logger.log:
|
||||
format: "After delay, body still: %s"
|
||||
args:
|
||||
- body.c_str()
|
||||
|
||||
http_request:
|
||||
useragent: esphome/tagreader
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/modbus/modbus_helpers.h"
|
||||
|
||||
namespace esphome::modbus::helpers {
|
||||
|
||||
TEST(ModbusHelpersTest, PayloadToNumberRejectsOffsetAtEndOfBuffer) {
|
||||
const std::vector<uint8_t> data{0x12, 0x34};
|
||||
EXPECT_EQ(payload_to_number(data, SensorValueType::U_WORD, 2, 0xFFFFFFFF), 0);
|
||||
}
|
||||
|
||||
TEST(ModbusHelpersTest, PayloadToNumberRejectsTruncatedMultiRegisterValue) {
|
||||
const std::vector<uint8_t> data{0x12, 0x34, 0x56};
|
||||
EXPECT_EQ(payload_to_number(data, SensorValueType::U_DWORD, 0, 0xFFFFFFFF), 0);
|
||||
}
|
||||
|
||||
TEST(ModbusHelpersTest, PayloadToNumberDecodesValidWord) {
|
||||
const std::vector<uint8_t> data{0x12, 0x34};
|
||||
EXPECT_EQ(payload_to_number(data, SensorValueType::U_WORD, 0, 0xFFFFFFFF), 0x1234);
|
||||
}
|
||||
|
||||
} // namespace esphome::modbus::helpers
|
||||
@@ -3,6 +3,22 @@ esphome:
|
||||
then:
|
||||
- rtttl.play: 'siren:d=8,o=5,b=100:d,e,d,e,d,e,d,e'
|
||||
- rtttl.stop
|
||||
# Test all note features: all notes, denominators (1,2,4,8,16,32), sharp (#), octaves (4-7), dotted (.), note gap (c5,c5), pause (p)
|
||||
- rtttl.play: 'special:d=4,o=5,b=120:1c4,2d#5,4e6.,8f#7,16g4,32a5,8a#5,4b6,8h5,c5,c5,8p,2c4'
|
||||
# Different orders of control parameters
|
||||
- rtttl.play: 'test_odb:o=5,d=8,b=100:c'
|
||||
- rtttl.play: 'test_bod:b=100,o=5,d=8:c'
|
||||
- rtttl.play: 'test_bdo:b=100,d=8,o=5:c'
|
||||
- rtttl.play: 'test_obd:o=5,b=100,d=8:c'
|
||||
- rtttl.play: 'test_dbo:d=8,b=100,o=5:c'
|
||||
# Missing parameters (use defaults)
|
||||
- rtttl.play: 'test_no_d:o=5,b=100:c'
|
||||
- rtttl.play: 'test_no_o:d=8,b=100:c'
|
||||
- rtttl.play: 'test_no_b:d=8,o=5:c'
|
||||
- rtttl.play: 'test_only_d:d=8:c'
|
||||
- rtttl.play: 'test_only_o:o=5:c'
|
||||
- rtttl.play: 'test_only_b:b=100:c'
|
||||
- rtttl.play: 'test_empty::c'
|
||||
|
||||
output:
|
||||
- platform: ${output_platform}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Regression tests for ESPTime::is_valid() optional checks.
|
||||
//
|
||||
// The RTC components (ds1307, bm8563, pcf85063, pcf8563, rx8130) read date/time
|
||||
// fields from hardware but do not populate day_of_year. They call
|
||||
// recalc_timestamp_utc(false) -- which skips day_of_year -- and then is_valid().
|
||||
// These tests ensure the is_valid() overload can skip day_of_year validation so
|
||||
// RTCs don't log "Invalid RTC time, not syncing to system clock." for valid times.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include "esphome/core/time.h"
|
||||
|
||||
namespace esphome::testing {
|
||||
|
||||
// Build an ESPTime that mirrors what the RTC components construct: all fields
|
||||
// populated from hardware except day_of_year (left zero-initialized).
|
||||
static ESPTime make_rtc_like_time() {
|
||||
ESPTime t{};
|
||||
t.second = 30;
|
||||
t.minute = 15;
|
||||
t.hour = 12;
|
||||
t.day_of_week = 4; // thursday
|
||||
t.day_of_month = 15;
|
||||
t.month = 4;
|
||||
t.year = 2026;
|
||||
// day_of_year intentionally left at 0 -- RTCs don't compute it.
|
||||
return t;
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, DefaultRejectsZeroDayOfYear) {
|
||||
// Default is_valid() checks day_of_year; zero-init is out of range.
|
||||
ESPTime t = make_rtc_like_time();
|
||||
EXPECT_FALSE(t.is_valid());
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, SkipDayOfYearAcceptsRTCLikeTime) {
|
||||
// RTC code path: skip day_of_year validation.
|
||||
ESPTime t = make_rtc_like_time();
|
||||
EXPECT_TRUE(t.is_valid(/*check_day_of_week=*/true, /*check_day_of_year=*/false));
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, SkipDayOfYearStillRejectsOutOfRangeFields) {
|
||||
ESPTime t = make_rtc_like_time();
|
||||
t.hour = 25;
|
||||
EXPECT_FALSE(t.is_valid(/*check_day_of_week=*/true, /*check_day_of_year=*/false));
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, SkipDayOfYearStillRejectsYearBefore2019) {
|
||||
ESPTime t = make_rtc_like_time();
|
||||
t.year = 2000;
|
||||
EXPECT_FALSE(t.is_valid(/*check_day_of_week=*/true, /*check_day_of_year=*/false));
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, SkipBothDayChecksAcceptsGPSLikeTime) {
|
||||
// GPS path (gps_time.cpp) populates neither day_of_week nor day_of_year.
|
||||
ESPTime t{};
|
||||
t.second = 30;
|
||||
t.minute = 15;
|
||||
t.hour = 12;
|
||||
t.day_of_month = 15;
|
||||
t.month = 4;
|
||||
t.year = 2026;
|
||||
EXPECT_TRUE(t.is_valid(/*check_day_of_week=*/false, /*check_day_of_year=*/false));
|
||||
EXPECT_FALSE(t.is_valid()); // default still rejects
|
||||
}
|
||||
|
||||
TEST(ESPTimeIsValid, FullyPopulatedAcceptsWithDefaults) {
|
||||
ESPTime t = make_rtc_like_time();
|
||||
t.day_of_year = 105;
|
||||
EXPECT_TRUE(t.is_valid());
|
||||
}
|
||||
|
||||
} // namespace esphome::testing
|
||||
@@ -0,0 +1,10 @@
|
||||
zephyr_ble_server:
|
||||
on_numeric_comparison_request:
|
||||
then:
|
||||
- logger.log:
|
||||
format: "Compare this passkey with the one on your BLE device: %06d"
|
||||
args: [passkey]
|
||||
- ble_server.numeric_comparison_reply:
|
||||
accept: True
|
||||
- ble_server.numeric_comparison_reply:
|
||||
accept: !lambda "return true;"
|
||||
@@ -0,0 +1,27 @@
|
||||
esphome:
|
||||
name: sched-interval-zero
|
||||
|
||||
host:
|
||||
api:
|
||||
logger:
|
||||
level: DEBUG
|
||||
|
||||
globals:
|
||||
- id: fire_count
|
||||
type: int
|
||||
initial_value: "0"
|
||||
|
||||
interval:
|
||||
# Deliberately configure 0ms — this path goes through the C++
|
||||
# Scheduler::set_timer_common_ coercion (not the Python cv.update_interval
|
||||
# path, since interval: doesn't call cv.update_interval — it's an intervals
|
||||
# component schema, not a PollingComponent's update_interval).
|
||||
# Expected: scheduler coerces to 1ms at registration, emits ESP_LOGE,
|
||||
# fires at ~1kHz instead of spinning.
|
||||
- interval: 0ms
|
||||
then:
|
||||
- lambda: |-
|
||||
id(fire_count) += 1;
|
||||
if (id(fire_count) == 50) {
|
||||
ESP_LOGI("test", "ZERO_INTERVAL_50_FIRES_REACHED");
|
||||
}
|
||||
@@ -26,6 +26,7 @@ async def test_runtime_stats(
|
||||
|
||||
# Track component stats
|
||||
component_stats_found = set()
|
||||
main_loop_lines: list[dict[str, str]] = []
|
||||
|
||||
# Patterns to match - need to handle ANSI color codes and timestamps
|
||||
# The log format is: [HH:MM:SS][color codes][I][tag]: message
|
||||
@@ -34,6 +35,14 @@ async def test_runtime_stats(
|
||||
component_pattern = re.compile(
|
||||
r"^\[[^\]]+\].*?\s+([\w.]+):\s+count=(\d+),\s+avg=([\d.]+)ms"
|
||||
)
|
||||
# Main loop overhead line emitted by runtime_stats
|
||||
main_loop_pattern = re.compile(
|
||||
r"main_loop:\s+iters=(?P<iters>\d+),\s+"
|
||||
r"active_avg=(?P<active_avg>[\d.]+)ms,\s+"
|
||||
r"active_max=(?P<active_max>[\d.]+)ms,\s+"
|
||||
r"active_total=(?P<active_total>[\d.]+)ms,\s+"
|
||||
r"overhead_total=(?P<overhead_total>[\d.]+)ms"
|
||||
)
|
||||
|
||||
def check_output(line: str) -> None:
|
||||
"""Check log output for runtime stats messages."""
|
||||
@@ -54,6 +63,11 @@ async def test_runtime_stats(
|
||||
component_name = match.group(1)
|
||||
component_stats_found.add(component_name)
|
||||
|
||||
# Check for main_loop overhead line
|
||||
ml_match = main_loop_pattern.search(line)
|
||||
if ml_match:
|
||||
main_loop_lines.append(ml_match.groupdict())
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=check_output),
|
||||
api_client_connected() as client,
|
||||
@@ -86,3 +100,22 @@ async def test_runtime_stats(
|
||||
assert "template.switch" in component_stats_found, (
|
||||
f"Expected template.switch stats, found: {component_stats_found}"
|
||||
)
|
||||
|
||||
# Verify the main_loop overhead line is emitted (at least once for
|
||||
# the period section and once for the total section, per log cycle).
|
||||
assert len(main_loop_lines) >= 2, (
|
||||
f"Expected at least 2 main_loop lines, got {len(main_loop_lines)}"
|
||||
)
|
||||
for fields in main_loop_lines:
|
||||
assert int(fields["iters"]) > 0, f"iters should be > 0: {fields}"
|
||||
assert float(fields["active_total"]) > 0.0, (
|
||||
f"active_total should be > 0: {fields}"
|
||||
)
|
||||
assert float(fields["active_avg"]) >= 0.0, (
|
||||
f"active_avg should be >= 0: {fields}"
|
||||
)
|
||||
# overhead_total is derived and may be 0 if components dominate,
|
||||
# but the field must still be present and parseable as a float.
|
||||
assert float(fields["overhead_total"]) >= 0.0, (
|
||||
f"overhead_total should be >= 0: {fields}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Test that Scheduler::set_timer_common_ coerces interval=0 to 1ms.
|
||||
|
||||
Regression test for the scheduler busy-loop when interval=0 was passed
|
||||
literally. Without the coercion, Scheduler::call() would spin forever
|
||||
because the item's next_execution == now_64 after re-scheduling, failing
|
||||
the loop's `> now_64` break condition. The device would fail to yield
|
||||
back to the main loop and trigger a WDT reset.
|
||||
|
||||
With the coercion, interval=0 becomes interval=1 and the scheduler
|
||||
fires at ~1kHz (bounded by the loop), the main loop continues to run,
|
||||
and the device stays responsive to API calls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scheduler_interval_zero_coerced(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""interval=0ms must be coerced to 1ms and not starve the main loop."""
|
||||
loop = asyncio.get_running_loop()
|
||||
reached_50: asyncio.Future[None] = loop.create_future()
|
||||
coerce_warning: asyncio.Future[None] = loop.create_future()
|
||||
|
||||
def on_log_line(line: str) -> None:
|
||||
if "ZERO_INTERVAL_50_FIRES_REACHED" in line and not reached_50.done():
|
||||
reached_50.set_result(None)
|
||||
if "would spin main loop" in line and not coerce_warning.done():
|
||||
coerce_warning.set_result(None)
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=on_log_line),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
# The API-client connection itself is evidence that the main loop
|
||||
# is not starved — if set_interval(0) were spinning we could not
|
||||
# get here at all.
|
||||
device_info = await client.device_info()
|
||||
assert device_info is not None
|
||||
assert device_info.name == "sched-interval-zero"
|
||||
|
||||
# Coerce warning must fire at registration
|
||||
try:
|
||||
await asyncio.wait_for(coerce_warning, timeout=5.0)
|
||||
except TimeoutError:
|
||||
pytest.fail("Expected coerce warning 'would spin main loop' not seen")
|
||||
|
||||
# The coerced 1ms interval should fire 50 times quickly — this
|
||||
# confirms the callback actually runs (not just registered) and the
|
||||
# scheduler yields back to the main loop each time.
|
||||
try:
|
||||
await asyncio.wait_for(reached_50, timeout=5.0)
|
||||
except TimeoutError:
|
||||
pytest.fail(
|
||||
"Coerced interval=0→1ms did not reach 50 fires within 5s, "
|
||||
"which would indicate either the coercion failed or the "
|
||||
"main loop is still being starved."
|
||||
)
|
||||
@@ -325,9 +325,13 @@ async def test_uart_mock_ld2412_engineering_truncated(
|
||||
],
|
||||
)
|
||||
|
||||
# Signal when we see Phase 3 recovery values (gate_0_move=50)
|
||||
# Signal when we see ALL Phase 3 recovery values to avoid race where some
|
||||
# arrive after the waiter fires but before we index into the lists
|
||||
recovery_received = collector.add_waiter(
|
||||
lambda: pytest.approx(50.0) in collector.sensor_states["gate_0_move_energy"]
|
||||
lambda: (
|
||||
pytest.approx(50.0) in collector.sensor_states["gate_0_move_energy"]
|
||||
and pytest.approx(42.0) in collector.sensor_states["light"]
|
||||
)
|
||||
)
|
||||
|
||||
async with (
|
||||
|
||||
@@ -1468,3 +1468,159 @@ def test_cache_miss_corrupted_json(
|
||||
result = helpers.create_components_graph()
|
||||
# Should handle corruption gracefully and rebuild
|
||||
assert result == {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# parse_component_metadata / split_conflicting_groups
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_components(tmp_path: Path) -> Path:
|
||||
"""Create a fake esphome/components/ tree and return the repo root.
|
||||
|
||||
Component layout (tested against split_conflicting_groups):
|
||||
|
||||
alpha -- CONFLICTS_WITH=["beta"]
|
||||
beta -- CONFLICTS_WITH=["alpha"]
|
||||
beta_variant -- AUTO_LOAD=["beta"]
|
||||
gamma -- (no metadata)
|
||||
one_sided -- CONFLICTS_WITH=["plain"] (plain does not reject back)
|
||||
plain -- no CONFLICTS_WITH
|
||||
callable_auto -- AUTO_LOAD is a function (not a list literal) -> ignored
|
||||
broken -- __init__.py has a SyntaxError
|
||||
"""
|
||||
components = tmp_path / "esphome" / "components"
|
||||
components.mkdir(parents=True)
|
||||
|
||||
def write(name: str, body: str) -> None:
|
||||
(components / name).mkdir()
|
||||
(components / name / "__init__.py").write_text(body)
|
||||
|
||||
write("alpha", 'CONFLICTS_WITH = ["beta"]\n')
|
||||
write("beta", 'CONFLICTS_WITH = ["alpha"]\n')
|
||||
write("beta_variant", 'AUTO_LOAD = ["beta"]\n')
|
||||
write("gamma", "")
|
||||
write("one_sided", 'CONFLICTS_WITH = ["plain"]\n')
|
||||
write("plain", "")
|
||||
write("callable_auto", "def AUTO_LOAD():\n return ['beta']\n")
|
||||
write("broken", "this is not valid python !!!")
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_parse_component_metadata_list_literals(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
meta = helpers.parse_component_metadata("alpha")
|
||||
assert meta.conflicts_with == frozenset({"beta"})
|
||||
assert meta.auto_load == frozenset()
|
||||
|
||||
variant = helpers.parse_component_metadata("beta_variant")
|
||||
assert variant.auto_load == frozenset({"beta"})
|
||||
assert variant.conflicts_with == frozenset()
|
||||
|
||||
|
||||
def test_parse_component_metadata_missing_empty_and_callable(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
# Unknown component -> empty metadata, not an error.
|
||||
unknown = helpers.parse_component_metadata("does_not_exist")
|
||||
assert unknown == helpers.ComponentMetadata()
|
||||
|
||||
# Empty __init__.py -> empty metadata.
|
||||
assert helpers.parse_component_metadata("gamma") == helpers.ComponentMetadata()
|
||||
|
||||
# Callable AUTO_LOAD cannot be statically evaluated -> empty.
|
||||
callable_meta = helpers.parse_component_metadata("callable_auto")
|
||||
assert callable_meta.auto_load == frozenset()
|
||||
|
||||
# SyntaxError in __init__.py must not raise.
|
||||
assert helpers.parse_component_metadata("broken") == helpers.ComponentMetadata()
|
||||
|
||||
|
||||
def test_split_conflicting_groups_splits_direct_conflict(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
result = helpers.split_conflicting_groups(
|
||||
{("esp32", "i2c"): ["alpha", "beta", "gamma"]}
|
||||
)
|
||||
# alpha and beta must end up in different buckets; gamma has no conflicts.
|
||||
buckets = list(result.values())
|
||||
assert any("alpha" in b for b in buckets)
|
||||
assert any("beta" in b for b in buckets)
|
||||
for bucket in buckets:
|
||||
assert not ({"alpha", "beta"} <= set(bucket))
|
||||
# Gamma sticks with whichever bucket it landed in first (alpha's).
|
||||
all_members = {c for b in buckets for c in b}
|
||||
assert all_members == {"alpha", "beta", "gamma"}
|
||||
|
||||
|
||||
def test_split_conflicting_groups_propagates_through_auto_load(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
"""A component that AUTO_LOADs a conflicting one must also be split out."""
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
result = helpers.split_conflicting_groups(
|
||||
{("esp32", "i2c"): ["alpha", "beta_variant"]}
|
||||
)
|
||||
buckets = list(result.values())
|
||||
for bucket in buckets:
|
||||
assert not ({"alpha", "beta_variant"} <= set(bucket))
|
||||
assert sum(len(b) for b in buckets) == 2
|
||||
|
||||
|
||||
def test_split_conflicting_groups_symmetric_one_sided_declaration(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
"""If only one side declares CONFLICTS_WITH, the pair must still be split."""
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
result = helpers.split_conflicting_groups(
|
||||
{("esp32", "i2c"): ["one_sided", "plain"]}
|
||||
)
|
||||
buckets = list(result.values())
|
||||
for bucket in buckets:
|
||||
assert not ({"one_sided", "plain"} <= set(bucket))
|
||||
|
||||
|
||||
def test_split_conflicting_groups_preserves_non_conflicting_group(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
original = {("esp32", "i2c"): ["alpha", "gamma", "plain"]}
|
||||
result = helpers.split_conflicting_groups(original)
|
||||
# All three are mutually compatible -- the group must not be split.
|
||||
assert result == original
|
||||
|
||||
|
||||
def test_split_conflicting_groups_preserves_original_signature_for_first_bucket(
|
||||
fake_components: Path, monkeypatch: MonkeyPatch
|
||||
) -> None:
|
||||
"""When a group is split, the first bucket keeps the original signature key."""
|
||||
monkeypatch.setattr(helpers, "root_path", str(fake_components))
|
||||
helpers.parse_component_metadata.cache_clear()
|
||||
|
||||
result = helpers.split_conflicting_groups({("esp32", "i2c"): ["alpha", "beta"]})
|
||||
keys = set(result.keys())
|
||||
assert ("esp32", "i2c") in keys
|
||||
# One additional bucket with a disambiguated signature.
|
||||
extra = keys - {("esp32", "i2c")}
|
||||
assert len(extra) == 1
|
||||
platform, signature = next(iter(extra))
|
||||
assert platform == "esp32"
|
||||
assert signature.startswith("i2c__conflict")
|
||||
|
||||
@@ -11,9 +11,9 @@ esp32:
|
||||
logger:
|
||||
<<: !include common/base.yaml
|
||||
|
||||
wifi:
|
||||
ssid: !secret wifi_ssid
|
||||
password: !secret wifi_password
|
||||
# Plain nested !include — deferred as an IncludeFile until the substitution
|
||||
# pass. The bundle must force-resolve it to pick up common/wifi.yaml.
|
||||
wifi: !include common/wifi.yaml
|
||||
|
||||
api:
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ssid: !secret wifi_ssid
|
||||
password: !secret wifi_password
|
||||
@@ -0,0 +1,5 @@
|
||||
substitutions:
|
||||
wifi_password: sub_password
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
password: sub_password
|
||||
@@ -0,0 +1,5 @@
|
||||
substitutions: !include 15-substitutions_inc.yaml
|
||||
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
password: $wifi_password
|
||||
@@ -0,0 +1 @@
|
||||
wifi_password: sub_password
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
substitutions:
|
||||
wifi_password: sub_password
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
password: sub_password
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
substitutions: !include 15-substitutions_inc.yaml
|
||||
|
||||
packages:
|
||||
wifi_pkg:
|
||||
wifi:
|
||||
password: $wifi_password
|
||||
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
@@ -0,0 +1,6 @@
|
||||
substitutions:
|
||||
subs_file: 15-substitutions_inc
|
||||
wifi_password: sub_password
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
password: sub_password
|
||||
@@ -0,0 +1,8 @@
|
||||
command_line_substitutions:
|
||||
subs_file: 15-substitutions_inc
|
||||
|
||||
substitutions: !include ${subs_file}.yaml
|
||||
|
||||
wifi:
|
||||
ssid: main_ssid
|
||||
password: $wifi_password
|
||||
@@ -5,8 +5,10 @@ from __future__ import annotations
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tarfile
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -20,6 +22,7 @@ from esphome.bundle import (
|
||||
_add_bytes_to_tar,
|
||||
_default_target_dir,
|
||||
_find_used_secret_keys,
|
||||
_force_load_include_files,
|
||||
extract_bundle,
|
||||
is_bundle_path,
|
||||
prepare_bundle_for_compile,
|
||||
@@ -485,7 +488,7 @@ def test_read_bundle_manifest_minimal(tmp_path: Path) -> None:
|
||||
|
||||
result = read_bundle_manifest(bundle_path)
|
||||
assert result.esphome_version == "unknown"
|
||||
assert result.files == []
|
||||
assert not result.files
|
||||
assert result.has_secrets is False
|
||||
|
||||
|
||||
@@ -862,6 +865,117 @@ def test_discover_files_skips_missing_directory(tmp_path: Path) -> None:
|
||||
assert len(files) == 1
|
||||
|
||||
|
||||
def test_discover_files_nested_include(tmp_path: Path) -> None:
|
||||
"""Nested !include files (e.g. wifi: !include wifi.yaml) are bundled."""
|
||||
config_dir = _setup_config_dir(tmp_path)
|
||||
(config_dir / "test.yaml").write_text(
|
||||
"esphome:\n name: test\nwifi: !include wifi.yaml\n"
|
||||
)
|
||||
(config_dir / "wifi.yaml").write_text('ssid: "a"\npassword: "b"\n')
|
||||
|
||||
creator = ConfigBundleCreator({})
|
||||
files = creator.discover_files()
|
||||
|
||||
paths = [f.path for f in files]
|
||||
assert "test.yaml" in paths
|
||||
assert "wifi.yaml" in paths
|
||||
|
||||
|
||||
def test_discover_files_deeply_nested_include(tmp_path: Path) -> None:
|
||||
"""Chains of !include (a includes b includes c) are fully resolved."""
|
||||
config_dir = _setup_config_dir(tmp_path)
|
||||
(config_dir / "test.yaml").write_text(
|
||||
"esphome:\n name: test\nwifi: !include level1.yaml\n"
|
||||
)
|
||||
(config_dir / "level1.yaml").write_text("nested: !include level2.yaml\n")
|
||||
(config_dir / "level2.yaml").write_text('value: "leaf"\n')
|
||||
|
||||
creator = ConfigBundleCreator({})
|
||||
files = creator.discover_files()
|
||||
|
||||
paths = [f.path for f in files]
|
||||
assert "level1.yaml" in paths
|
||||
assert "level2.yaml" in paths
|
||||
|
||||
|
||||
def test_discover_files_nested_include_unresolved_substitution(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""!include with substitution vars in path cannot be resolved; skipped gracefully."""
|
||||
config_dir = _setup_config_dir(tmp_path)
|
||||
(config_dir / "test.yaml").write_text(
|
||||
"esphome:\n name: test\nwifi: !include ${platform}.yaml\n"
|
||||
)
|
||||
|
||||
creator = ConfigBundleCreator({})
|
||||
# Should not raise
|
||||
files = creator.discover_files()
|
||||
|
||||
paths = [f.path for f in files]
|
||||
assert "test.yaml" in paths
|
||||
|
||||
|
||||
def test_discover_files_nested_include_load_failure(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A nested !include pointing at a missing file is logged and skipped."""
|
||||
config_dir = _setup_config_dir(tmp_path)
|
||||
(config_dir / "test.yaml").write_text(
|
||||
"esphome:\n name: test\nwifi: !include missing.yaml\n"
|
||||
)
|
||||
|
||||
creator = ConfigBundleCreator({})
|
||||
files = creator.discover_files()
|
||||
|
||||
paths = [f.path for f in files]
|
||||
assert "test.yaml" in paths
|
||||
assert any(
|
||||
"failed to load !include" in r.message and "missing.yaml" in r.message
|
||||
for r in caplog.records
|
||||
)
|
||||
|
||||
|
||||
def test_force_load_skips_duplicate_include_file() -> None:
|
||||
"""The same IncludeFile referenced twice is only loaded once."""
|
||||
|
||||
class _StubInclude:
|
||||
"""Mimics yaml_util.IncludeFile minimally for _force_load testing."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.file = Path("dup.yaml")
|
||||
self.parent_file = Path("root.yaml")
|
||||
self.load_calls = 0
|
||||
|
||||
def has_unresolved_expressions(self) -> bool:
|
||||
return False
|
||||
|
||||
def load(self) -> dict[str, Any]:
|
||||
self.load_calls += 1
|
||||
return {}
|
||||
|
||||
stub = _StubInclude()
|
||||
# Same instance appears twice — second visit must hit the _seen guard.
|
||||
tree = {"a": stub, "b": [stub]}
|
||||
|
||||
with patch("esphome.bundle.yaml_util.IncludeFile", _StubInclude):
|
||||
_force_load_include_files(tree)
|
||||
|
||||
assert stub.load_calls == 1
|
||||
|
||||
|
||||
def test_force_load_handles_cyclic_containers() -> None:
|
||||
"""Cyclic dict/list references don't cause infinite recursion."""
|
||||
cyclic_dict: dict[str, Any] = {}
|
||||
cyclic_dict["self"] = cyclic_dict
|
||||
|
||||
cyclic_list: list[Any] = []
|
||||
cyclic_list.append(cyclic_list)
|
||||
|
||||
# Should return without recursing forever
|
||||
_force_load_include_files(cyclic_dict)
|
||||
_force_load_include_files(cyclic_list)
|
||||
|
||||
|
||||
def test_discover_files_yaml_reload_failure(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
@@ -1008,6 +1122,40 @@ def test_discover_files_walk_tuple_values(tmp_path: Path) -> None:
|
||||
assert "a.pem" in paths
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ConfigBundleCreator - fixture-based end-to-end
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_discover_files_fixture_config(fixture_path: Path, tmp_path: Path) -> None:
|
||||
"""Use the real ``fixtures/bundle/`` tree as an end-to-end reproducer.
|
||||
|
||||
The fixture config uses ``wifi: !include common/wifi.yaml`` — a plain
|
||||
nested !include that is returned as a deferred ``IncludeFile`` and only
|
||||
resolved during the substitution pass. Before this fix, bundle discovery
|
||||
never ran substitutions, so ``common/wifi.yaml`` was silently missing
|
||||
from the bundle.
|
||||
"""
|
||||
# Copy the fixture tree into a tmp dir so the test doesn't rely on the
|
||||
# source repo being writable and so we can set CORE.config_path freely.
|
||||
src = fixture_path / "bundle"
|
||||
dst = tmp_path / "bundle"
|
||||
shutil.copytree(src, dst)
|
||||
|
||||
CORE.config_path = dst / "bundle_test.yaml"
|
||||
|
||||
creator = ConfigBundleCreator({})
|
||||
files = creator.discover_files()
|
||||
paths = {f.path for f in files}
|
||||
|
||||
# Root and top-level !secret-referenced files
|
||||
assert "bundle_test.yaml" in paths
|
||||
assert "secrets.yaml" in paths
|
||||
# The nested !include — this is what regressed when IncludeFile became
|
||||
# deferred (PR #12213).
|
||||
assert "common/wifi.yaml" in paths
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ConfigBundleCreator - create_bundle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -24,6 +24,7 @@ from esphome.const import (
|
||||
PLATFORM_LN882X,
|
||||
PLATFORM_RP2040,
|
||||
PLATFORM_RTL87XX,
|
||||
SCHEDULER_DONT_RUN,
|
||||
)
|
||||
from esphome.core import CORE, HexInt, Lambda
|
||||
|
||||
@@ -765,3 +766,30 @@ def test_percentage_validators__raw_number_above_one_without_percent_sign(
|
||||
config_validation.unbounded_percentage(value)
|
||||
with pytest.raises(Invalid, match="percent sign"):
|
||||
config_validation.unbounded_possibly_negative_percentage(value)
|
||||
|
||||
|
||||
def test_update_interval__coerces_zero_to_one_ms(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""update_interval: 0ms must be coerced to 1ms (not rejected) because a
|
||||
literal 0ms schedule causes Scheduler::call() to spin. Coercion keeps
|
||||
existing configs compiling on upgrade while emitting a user-facing
|
||||
warning that directs them to set a non-zero value."""
|
||||
with caplog.at_level("WARNING"):
|
||||
result = config_validation.update_interval("0ms")
|
||||
assert result.total_milliseconds == 1
|
||||
assert "update_interval of 0ms is not supported" in caplog.text
|
||||
assert "1ms" in caplog.text
|
||||
|
||||
|
||||
def test_update_interval__preserves_nonzero_values() -> None:
|
||||
"""Non-zero update_interval values must pass through unchanged."""
|
||||
assert config_validation.update_interval("1ms").total_milliseconds == 1
|
||||
assert config_validation.update_interval("50ms").total_milliseconds == 50
|
||||
assert config_validation.update_interval("60s").total_milliseconds == 60000
|
||||
|
||||
|
||||
def test_update_interval__never_passes_through() -> None:
|
||||
"""update_interval: never must still map to SCHEDULER_DONT_RUN."""
|
||||
result = config_validation.update_interval("never")
|
||||
assert result.total_milliseconds == SCHEDULER_DONT_RUN
|
||||
|
||||
@@ -14,6 +14,7 @@ from esphome.components.packages import (
|
||||
do_packages_pass,
|
||||
merge_packages,
|
||||
)
|
||||
from esphome.components.substitutions.jinja import UndefinedError
|
||||
from esphome.config import resolve_extend_remove
|
||||
from esphome.config_helpers import Extend, merge_config
|
||||
import esphome.config_validation as cv
|
||||
@@ -675,6 +676,90 @@ def test_include_filename_substitution_undefined_var(tmp_path: Path) -> None:
|
||||
substitutions.do_substitution_pass(config)
|
||||
|
||||
|
||||
def test_raise_first_undefined_logs_extras_at_debug(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Only the first undefined error is raised; extras are logged at debug."""
|
||||
errors: substitutions.ErrList = [
|
||||
(UndefinedError("'a' is undefined"), ["url"], None),
|
||||
(UndefinedError("'b' is undefined"), ["ref"], None),
|
||||
(UndefinedError("'c' is undefined"), ["path"], None),
|
||||
]
|
||||
|
||||
with (
|
||||
caplog.at_level(logging.DEBUG, logger="esphome.components.substitutions"),
|
||||
pytest.raises(cv.Invalid) as exc_info,
|
||||
):
|
||||
substitutions.raise_first_undefined(errors, None, "package definition")
|
||||
|
||||
# First error is surfaced as the cv.Invalid message.
|
||||
raised = str(exc_info.value)
|
||||
assert "'a' is undefined" in raised
|
||||
assert "'b' is undefined" not in raised
|
||||
assert "'c' is undefined" not in raised
|
||||
|
||||
# Remaining errors are captured via debug logging for troubleshooting.
|
||||
assert "Additional undefined variables in package definition" in caplog.text
|
||||
assert "'b' is undefined at 'ref'" in caplog.text
|
||||
assert "'c' is undefined at 'path'" in caplog.text
|
||||
|
||||
|
||||
def test_raise_first_undefined_noop_on_empty() -> None:
|
||||
"""An empty errors list is a no-op — no exception, no log."""
|
||||
substitutions.raise_first_undefined([], None, "package definition")
|
||||
|
||||
|
||||
def test_do_substitution_pass_included_substitutions_must_be_mapping(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""`substitutions: !include list.yaml` where the file holds a list raises cv.Invalid.
|
||||
|
||||
Locks in the shape check that runs after the deferred IncludeFile has been
|
||||
resolved.
|
||||
"""
|
||||
parent = tmp_path / "main.yaml"
|
||||
parent.write_text("")
|
||||
|
||||
def loader(path: Path):
|
||||
return ["not", "a", "mapping"]
|
||||
|
||||
include = yaml_util.IncludeFile(parent, "subs.yaml", None, loader)
|
||||
config = OrderedDict({CONF_SUBSTITUTIONS: include})
|
||||
|
||||
with pytest.raises(
|
||||
cv.Invalid, match="Substitutions must be a key to value mapping"
|
||||
):
|
||||
substitutions.do_substitution_pass(config)
|
||||
|
||||
|
||||
def test_do_packages_pass_included_substitutions_must_be_mapping(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""`substitutions: !include list.yaml` alongside `packages:` raises cv.Invalid.
|
||||
|
||||
Without the shape check, ``UserDict(...)`` would surface a low-level
|
||||
``TypeError``; the explicit ``cv.Invalid`` points at the substitutions path.
|
||||
"""
|
||||
parent = tmp_path / "main.yaml"
|
||||
parent.write_text("")
|
||||
|
||||
def loader(path: Path):
|
||||
return ["not", "a", "mapping"]
|
||||
|
||||
include = yaml_util.IncludeFile(parent, "subs.yaml", None, loader)
|
||||
config = OrderedDict(
|
||||
{
|
||||
CONF_SUBSTITUTIONS: include,
|
||||
"packages": {"noop": {"wifi": {"ssid": "main"}}},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(
|
||||
cv.Invalid, match="Substitutions must be a key to value mapping"
|
||||
):
|
||||
do_packages_pass(config)
|
||||
|
||||
|
||||
def test_resolve_package_undefined_var_in_include_filename(tmp_path: Path) -> None:
|
||||
"""An undefined substitution in a package include filename raises cv.Invalid.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user