Compare commits

...
2 changed files with 54 additions and 4 deletions
+16 -4
View File
@@ -1,3 +1,5 @@
from collections.abc import Callable
import esphome.codegen as cg
from esphome.components.const import CONF_DATA_BITS, CONF_PARITY, CONF_STOP_BITS
from esphome.components.esp32 import VARIANT_ESP32P4, get_esp32_variant
@@ -154,6 +156,19 @@ FILTER_SOURCE_FILES = filter_source_files_from_defines(
)
def _channel_limit(type_: Type) -> Callable[[list], list]:
"""Check the channel count against the type's limit, which depends on the target."""
def validator(value: list) -> list:
if len(value) > (limit := type_.max_channels):
raise cv.Invalid(
f"Device type {type_.name} supports a maximum of {limit} channels"
)
return value
return validator
def channel_schema(type_: "Type") -> cv.Schema:
schema = cv.Schema(
{
@@ -192,10 +207,7 @@ def channel_schema(type_: "Type") -> cv.Schema:
}
)
),
cv.Length(
max=type_.max_channels,
msg=f"Device type {type_.name} supports a maximum of {type_.max_channels} channels",
),
_channel_limit(type_),
),
}
)
@@ -0,0 +1,38 @@
"""Tests for the per-type channel limit, which depends on the target."""
from pathlib import Path
import subprocess
import sys
import pytest
from esphome.components.esp32.const import KEY_VARIANT, VARIANT_ESP32, VARIANT_ESP32P4
from esphome.components.usb_uart import channel_schema, uart_types
import esphome.config_validation as cv
from esphome.const import CONF_BAUD_RATE, CONF_CHANNELS, PlatformFramework
from tests.component_tests.types import SetCoreConfigCallable
CH34X = next(t for t in uart_types if t.name == "CH34X")
def test_import_needs_no_core_config() -> None:
"""The C++ unit test runner imports every component before any config is loaded."""
subprocess.run(
[sys.executable, "-c", "from esphome.components import usb_uart"],
cwd=Path(__file__).parents[3],
check=True,
)
@pytest.mark.parametrize(
("variant", "limit"), [(VARIANT_ESP32, 3), (VARIANT_ESP32P4, 4)]
)
def test_channel_limit_follows_the_target(
set_core_config: SetCoreConfigCallable, variant: str, limit: int
) -> None:
set_core_config(PlatformFramework.ESP32_IDF, platform_data={KEY_VARIANT: variant})
schema = channel_schema(CH34X)
channel = {CONF_BAUD_RATE: 9600}
assert len(schema({CONF_CHANNELS: [channel] * limit})[CONF_CHANNELS]) == limit
with pytest.raises(cv.Invalid, match=f"maximum of {limit} channels"):
schema({CONF_CHANNELS: [channel] * (limit + 1)})