mirror of
https://github.com/esphome/esphome.git
synced 2026-10-07 11:26:39 +00:00
Merge remote-tracking branch 'upstream/dev' into remove_posix_tz_parser
# Conflicts: # esphome/components/time/posix_tz.cpp # esphome/components/time/posix_tz.h
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import esphome.codegen as cg
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
@@ -5,3 +6,16 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# api must run its to_code to define USE_API, USE_API_PLAINTEXT,
|
||||
# and add the noise-c library dependency.
|
||||
manifest.enable_codegen()
|
||||
|
||||
original_to_code = manifest.to_code
|
||||
|
||||
async def to_code(config):
|
||||
await original_to_code(config)
|
||||
# Enable BLE proto message types for benchmarks. The real
|
||||
# bluetooth_proxy component is ESP32-only; a lightweight stub
|
||||
# header in tests/benchmarks/stubs/ satisfies the include.
|
||||
cg.add_define("USE_BLUETOOTH_PROXY")
|
||||
cg.add_define("BLUETOOTH_PROXY_MAX_CONNECTIONS", 3)
|
||||
cg.add_define("BLUETOOTH_PROXY_ADVERTISEMENT_BATCH_SIZE", 16)
|
||||
|
||||
manifest.to_code = to_code
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "esphome/components/socket/socket.h"
|
||||
|
||||
namespace esphome::api::benchmarks {
|
||||
|
||||
// Helper to drain accumulated data from the read side of a socket
|
||||
// to prevent the write side from blocking.
|
||||
inline void drain_socket(int fd) {
|
||||
char buf[65536];
|
||||
while (::read(fd, buf, sizeof(buf)) > 0) {
|
||||
}
|
||||
}
|
||||
|
||||
// Create a TCP loopback socket pair. Returns the write-side Socket
|
||||
// (wrapped for ESPHome) and the raw read-side fd for draining.
|
||||
// Both ends are non-blocking with 16MB buffers.
|
||||
inline std::pair<std::unique_ptr<socket::Socket>, int> create_tcp_loopback() {
|
||||
// Create a TCP listener on loopback
|
||||
int listen_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int opt = 1;
|
||||
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
|
||||
struct sockaddr_in addr {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0; // OS-assigned port
|
||||
::bind(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
::listen(listen_fd, 1);
|
||||
|
||||
// Get the assigned port
|
||||
socklen_t addr_len = sizeof(addr);
|
||||
::getsockname(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), &addr_len);
|
||||
|
||||
// Connect from client side
|
||||
int write_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
::connect(write_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
|
||||
// Accept on server side (this is our read fd)
|
||||
int read_fd = ::accept(listen_fd, nullptr, nullptr);
|
||||
::close(listen_fd);
|
||||
|
||||
// Make both ends non-blocking
|
||||
int flags = ::fcntl(write_fd, F_GETFL, 0);
|
||||
::fcntl(write_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
flags = ::fcntl(read_fd, F_GETFL, 0);
|
||||
::fcntl(read_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
|
||||
// Use large socket buffers so benchmarks never hit WOULD_BLOCK
|
||||
// during a single outer iteration (2000 × ~15B messages = ~30KB).
|
||||
int bufsize = 16 * 1024 * 1024;
|
||||
::setsockopt(write_fd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
|
||||
::setsockopt(read_fd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
|
||||
|
||||
return {std::make_unique<socket::Socket>(write_fd), read_fd};
|
||||
}
|
||||
|
||||
} // namespace esphome::api::benchmarks
|
||||
@@ -2,12 +2,9 @@
|
||||
#ifdef USE_API_PLAINTEXT
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bench_helpers.h"
|
||||
#include "esphome/components/api/api_frame_helper_plaintext.h"
|
||||
#include "esphome/components/api/api_pb2.h"
|
||||
#include "esphome/components/api/api_buffer.h"
|
||||
@@ -16,57 +13,12 @@ namespace esphome::api::benchmarks {
|
||||
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Helper to drain accumulated data from the read side of a socket
|
||||
// to prevent the write side from blocking.
|
||||
static void drain_socket(int fd) {
|
||||
char buf[65536];
|
||||
while (::read(fd, buf, sizeof(buf)) > 0) {
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to create a TCP loopback connection with an APIPlaintextFrameHelper
|
||||
// on the write end. Returns the helper and the read-side fd.
|
||||
// Uses real TCP sockets so TCP_NODELAY succeeds during init().
|
||||
static std::pair<std::unique_ptr<APIPlaintextFrameHelper>, int> create_plaintext_helper() {
|
||||
// Create a TCP listener on loopback
|
||||
int listen_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int opt = 1;
|
||||
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
|
||||
struct sockaddr_in addr {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = 0; // OS-assigned port
|
||||
::bind(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
::listen(listen_fd, 1);
|
||||
|
||||
// Get the assigned port
|
||||
socklen_t addr_len = sizeof(addr);
|
||||
::getsockname(listen_fd, reinterpret_cast<struct sockaddr *>(&addr), &addr_len);
|
||||
|
||||
// Connect from client side
|
||||
int write_fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
::connect(write_fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr));
|
||||
|
||||
// Accept on server side (this is our read fd)
|
||||
int read_fd = ::accept(listen_fd, nullptr, nullptr);
|
||||
::close(listen_fd);
|
||||
|
||||
// Make both ends non-blocking
|
||||
int flags = ::fcntl(write_fd, F_GETFL, 0);
|
||||
::fcntl(write_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
flags = ::fcntl(read_fd, F_GETFL, 0);
|
||||
::fcntl(read_fd, F_SETFL, flags | O_NONBLOCK);
|
||||
|
||||
// Increase socket buffer sizes to reduce drain frequency
|
||||
int bufsize = 1024 * 1024;
|
||||
::setsockopt(write_fd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
|
||||
::setsockopt(read_fd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
|
||||
|
||||
auto sock = std::make_unique<socket::Socket>(write_fd);
|
||||
auto [sock, read_fd] = create_tcp_loopback();
|
||||
auto helper = std::make_unique<APIPlaintextFrameHelper>(std::move(sock));
|
||||
helper->init();
|
||||
|
||||
return {std::move(helper), read_fd};
|
||||
}
|
||||
|
||||
@@ -97,9 +49,6 @@ static void PlaintextFrame_WriteSensorState(benchmark::State &state) {
|
||||
msg.encode(writer);
|
||||
|
||||
helper->write_protobuf_packet(SensorStateResponse::MESSAGE_TYPE, writer);
|
||||
|
||||
if ((i & 0xFF) == 0)
|
||||
drain_socket(read_fd);
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(helper.get());
|
||||
@@ -144,9 +93,6 @@ static void PlaintextFrame_WriteBatch5(benchmark::State &state) {
|
||||
}
|
||||
|
||||
helper->write_protobuf_messages(ProtoWriteBuffer(&buffer, 0), std::span<const MessageInfo>(messages, 5));
|
||||
|
||||
if ((i & 0xFF) == 0)
|
||||
drain_socket(read_fd);
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(helper.get());
|
||||
|
||||
@@ -10,10 +10,9 @@ namespace esphome::api::benchmarks {
|
||||
// sub-microsecond benchmarks.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Helper: encode a message into a buffer and return it.
|
||||
// Benchmarks encode once in setup, then decode the resulting bytes in a loop.
|
||||
// This keeps decode benchmarks in sync with the actual protobuf schema —
|
||||
// hand-encoded byte arrays would silently break when fields change.
|
||||
// Helper: encode a message into an APIBuffer for reuse in decode benchmarks.
|
||||
// Optimization barriers are applied to the decode target objects via
|
||||
// DoNotOptimize/ClobberMemory, not to this buffer.
|
||||
template<typename T> static APIBuffer encode_message(const T &msg) {
|
||||
APIBuffer buffer;
|
||||
uint32_t size = msg.calculate_size();
|
||||
@@ -23,6 +22,12 @@ template<typename T> static APIBuffer encode_message(const T &msg) {
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/// Force a pointer through an asm barrier so the compiler cannot
|
||||
/// prove its contents are unchanged across iterations.
|
||||
/// benchmark::DoNotOptimize/ClobberMemory are insufficient under
|
||||
/// CodSpeed's valgrind-based instrumentation.
|
||||
static void escape(void *p) { asm volatile("" : : "g"(p) : "memory"); }
|
||||
|
||||
// --- HelloRequest decode (string + varint fields) ---
|
||||
|
||||
static void Decode_HelloRequest(benchmark::State &state) {
|
||||
@@ -31,13 +36,18 @@ static void Decode_HelloRequest(benchmark::State &state) {
|
||||
source.api_version_major = 1;
|
||||
source.api_version_minor = 10;
|
||||
auto encoded = encode_message(source);
|
||||
auto *data = encoded.data();
|
||||
auto size = encoded.size();
|
||||
benchmark::DoNotOptimize(data);
|
||||
benchmark::DoNotOptimize(size);
|
||||
|
||||
for (auto _ : state) {
|
||||
HelloRequest msg;
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
msg.decode(encoded.data(), encoded.size());
|
||||
HelloRequest msg;
|
||||
escape(&msg);
|
||||
msg.decode(data, size);
|
||||
escape(&msg);
|
||||
}
|
||||
benchmark::DoNotOptimize(msg.api_version_major);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
@@ -50,13 +60,18 @@ static void Decode_SwitchCommandRequest(benchmark::State &state) {
|
||||
source.key = 0x12345678;
|
||||
source.state = true;
|
||||
auto encoded = encode_message(source);
|
||||
auto *data = encoded.data();
|
||||
auto size = encoded.size();
|
||||
benchmark::DoNotOptimize(data);
|
||||
benchmark::DoNotOptimize(size);
|
||||
|
||||
for (auto _ : state) {
|
||||
SwitchCommandRequest msg;
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
msg.decode(encoded.data(), encoded.size());
|
||||
SwitchCommandRequest msg;
|
||||
escape(&msg);
|
||||
msg.decode(data, size);
|
||||
escape(&msg);
|
||||
}
|
||||
benchmark::DoNotOptimize(msg.state);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
@@ -78,13 +93,18 @@ static void Decode_LightCommandRequest(benchmark::State &state) {
|
||||
source.has_effect = true;
|
||||
source.effect = StringRef::from_lit("rainbow");
|
||||
auto encoded = encode_message(source);
|
||||
auto *data = encoded.data();
|
||||
auto size = encoded.size();
|
||||
benchmark::DoNotOptimize(data);
|
||||
benchmark::DoNotOptimize(size);
|
||||
|
||||
for (auto _ : state) {
|
||||
LightCommandRequest msg;
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
msg.decode(encoded.data(), encoded.size());
|
||||
LightCommandRequest msg;
|
||||
escape(&msg);
|
||||
msg.decode(data, size);
|
||||
escape(&msg);
|
||||
}
|
||||
benchmark::DoNotOptimize(msg.brightness);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
|
||||
@@ -295,4 +295,93 @@ static void CalcAndEncode_DeviceInfoResponse_Fresh(benchmark::State &state) {
|
||||
}
|
||||
BENCHMARK(CalcAndEncode_DeviceInfoResponse_Fresh);
|
||||
|
||||
// --- BluetoothLERawAdvertisementsResponse (12 adverts, highest-volume BLE message) ---
|
||||
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
|
||||
static BluetoothLERawAdvertisementsResponse make_ble_raw_advs_12() {
|
||||
static const uint8_t fake_adv_data[] = {
|
||||
0x02, 0x01, 0x06, 0x03, 0x03, 0x9F, 0xFE, 0x17, 0x16, 0x9F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
};
|
||||
BluetoothLERawAdvertisementsResponse msg;
|
||||
msg.advertisements_len = 12;
|
||||
for (int i = 0; i < 12; i++) {
|
||||
auto &adv = msg.advertisements[i];
|
||||
adv.address = 0xAABBCCDD0000ULL + i;
|
||||
adv.rssi = -60 - i;
|
||||
adv.address_type = 1;
|
||||
memcpy(adv.data, fake_adv_data, sizeof(fake_adv_data));
|
||||
adv.data_len = sizeof(fake_adv_data);
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
static void CalculateSize_BLERawAdvs12(benchmark::State &state) {
|
||||
auto msg = make_ble_raw_advs_12();
|
||||
|
||||
for (auto _ : state) {
|
||||
uint32_t result = 0;
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
result += msg.calculate_size();
|
||||
}
|
||||
benchmark::DoNotOptimize(result);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CalculateSize_BLERawAdvs12);
|
||||
|
||||
static void Encode_BLERawAdvs12(benchmark::State &state) {
|
||||
auto msg = make_ble_raw_advs_12();
|
||||
APIBuffer buffer;
|
||||
uint32_t total_size = msg.calculate_size();
|
||||
buffer.resize(total_size);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
ProtoWriteBuffer writer(&buffer, 0);
|
||||
msg.encode(writer);
|
||||
}
|
||||
benchmark::DoNotOptimize(buffer.data());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(Encode_BLERawAdvs12);
|
||||
|
||||
static void CalcAndEncode_BLERawAdvs12(benchmark::State &state) {
|
||||
auto msg = make_ble_raw_advs_12();
|
||||
APIBuffer buffer;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
uint32_t size = msg.calculate_size();
|
||||
buffer.resize(size);
|
||||
ProtoWriteBuffer writer(&buffer, 0);
|
||||
msg.encode(writer);
|
||||
}
|
||||
benchmark::DoNotOptimize(buffer.data());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CalcAndEncode_BLERawAdvs12);
|
||||
|
||||
static void CalcAndEncode_BLERawAdvs12_Fresh(benchmark::State &state) {
|
||||
auto msg = make_ble_raw_advs_12();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
APIBuffer buffer;
|
||||
uint32_t size = msg.calculate_size();
|
||||
buffer.resize(size);
|
||||
ProtoWriteBuffer writer(&buffer, 0);
|
||||
msg.encode(writer);
|
||||
benchmark::DoNotOptimize(buffer.data());
|
||||
}
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CalcAndEncode_BLERawAdvs12_Fresh);
|
||||
|
||||
#endif // USE_BLUETOOTH_PROXY
|
||||
|
||||
} // namespace esphome::api::benchmarks
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#if defined(USE_API_PLAINTEXT) && defined(USE_SENSOR)
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bench_helpers.h"
|
||||
#include "esphome/components/api/api_connection.h"
|
||||
#include "esphome/components/api/api_server.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
|
||||
namespace esphome::api {
|
||||
|
||||
// Friend functions declared in APIConnection for benchmark access.
|
||||
void bench_enable_immediate_send(APIConnection *conn) { conn->flags_.should_try_send_immediately = true; }
|
||||
void bench_clear_batch(APIConnection *conn) { conn->clear_batch_(); }
|
||||
void bench_process_batch(APIConnection *conn) { conn->process_batch_(); }
|
||||
|
||||
} // namespace esphome::api
|
||||
|
||||
namespace esphome::api::benchmarks {
|
||||
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Helper to create a TCP loopback connection with an APIConnection.
|
||||
// Returns the connection and the read-side fd for draining.
|
||||
static std::pair<std::unique_ptr<APIConnection>, int> create_api_connection() {
|
||||
auto [sock, read_fd] = create_tcp_loopback();
|
||||
auto conn = std::make_unique<APIConnection>(std::move(sock), global_api_server);
|
||||
conn->start();
|
||||
return {std::move(conn), read_fd};
|
||||
}
|
||||
|
||||
// Test subclass to access protected configure_entity_() for benchmark setup.
|
||||
class TestSensor : public sensor::Sensor {
|
||||
public:
|
||||
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
|
||||
};
|
||||
|
||||
// --- send_sensor_state: immediate send path ---
|
||||
// Measures: send_message_smart_ → prepare buffer → dispatch_message_ →
|
||||
// try_send_sensor_state → fill key/device_id + proto encode → frame write →
|
||||
// TCP send. This is the per-client cost when batch_delay=0 and initial states
|
||||
// have been sent.
|
||||
|
||||
static void SendSensorState_Immediate(benchmark::State &state) {
|
||||
auto [conn, read_fd] = create_api_connection();
|
||||
bench_enable_immediate_send(conn.get());
|
||||
// batch_delay must be 0 for should_send_immediately_ to return true
|
||||
uint16_t saved_delay = global_api_server->get_batch_delay();
|
||||
global_api_server->set_batch_delay(0);
|
||||
|
||||
TestSensor sensor;
|
||||
sensor.configure("test_sensor");
|
||||
sensor.publish_state(23.5f);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
conn->send_sensor_state(&sensor);
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(conn.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
global_api_server->set_batch_delay(saved_delay);
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(SendSensorState_Immediate);
|
||||
|
||||
// --- send_sensor_state: batch path (cold — first call allocates) ---
|
||||
// Measures: send_message_smart_ → schedule_message_ → deferred batch add.
|
||||
// Includes one-time vector allocation cost.
|
||||
|
||||
static void SendSensorState_Batch_Cold(benchmark::State &state) {
|
||||
auto [conn, read_fd] = create_api_connection();
|
||||
|
||||
TestSensor sensor;
|
||||
sensor.configure("test_sensor");
|
||||
sensor.publish_state(23.5f);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
conn->send_sensor_state(&sensor);
|
||||
}
|
||||
benchmark::DoNotOptimize(conn.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(SendSensorState_Batch_Cold);
|
||||
|
||||
// --- send_sensor_state: batch path (warm — buffer already allocated) ---
|
||||
// Measures steady-state batch cost after the vector has been allocated
|
||||
// and cleared at least once. This is the typical path during normal
|
||||
// operation after the first batch has been processed.
|
||||
|
||||
static void SendSensorState_Batch_Warm(benchmark::State &state) {
|
||||
auto [conn, read_fd] = create_api_connection();
|
||||
|
||||
TestSensor sensor;
|
||||
sensor.configure("test_sensor");
|
||||
sensor.publish_state(23.5f);
|
||||
|
||||
// Warm up: send once to allocate, then clear to keep capacity
|
||||
conn->send_sensor_state(&sensor);
|
||||
bench_clear_batch(conn.get());
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
conn->send_sensor_state(&sensor);
|
||||
}
|
||||
benchmark::DoNotOptimize(conn.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(SendSensorState_Batch_Warm);
|
||||
|
||||
// --- process_batch_: single sensor state (encode + frame + write) ---
|
||||
// Measures the deferred batch processing path: dispatch_message_ →
|
||||
// try_send_sensor_state → fill + proto encode → send_buffer → frame write.
|
||||
// This is the cost paid on the next loop() after batching.
|
||||
|
||||
static void ProcessBatch_SingleSensor(benchmark::State &state) {
|
||||
auto [conn, read_fd] = create_api_connection();
|
||||
|
||||
TestSensor sensor;
|
||||
sensor.configure("test_sensor");
|
||||
sensor.publish_state(23.5f);
|
||||
|
||||
// Warm up batch vector
|
||||
conn->send_sensor_state(&sensor);
|
||||
bench_process_batch(conn.get());
|
||||
drain_socket(read_fd);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
conn->send_sensor_state(&sensor);
|
||||
bench_process_batch(conn.get());
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(conn.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(ProcessBatch_SingleSensor);
|
||||
|
||||
// --- process_batch_: 5 different sensors ---
|
||||
// Measures batch processing with multiple items queued.
|
||||
// This exercises the multi-message path in process_batch_.
|
||||
|
||||
static void ProcessBatch_5Sensors(benchmark::State &state) {
|
||||
auto [conn, read_fd] = create_api_connection();
|
||||
|
||||
TestSensor sensors[5];
|
||||
for (int i = 0; i < 5; i++) {
|
||||
char name[20];
|
||||
snprintf(name, sizeof(name), "sensor_%d", i);
|
||||
sensors[i].configure(name);
|
||||
sensors[i].publish_state(23.5f + static_cast<float>(i));
|
||||
}
|
||||
|
||||
// Warm up batch vector
|
||||
for (auto &s : sensors)
|
||||
conn->send_sensor_state(&s);
|
||||
bench_process_batch(conn.get());
|
||||
drain_socket(read_fd);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
for (auto &s : sensors)
|
||||
conn->send_sensor_state(&s);
|
||||
bench_process_batch(conn.get());
|
||||
}
|
||||
drain_socket(read_fd);
|
||||
benchmark::DoNotOptimize(conn.get());
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
|
||||
::close(read_fd);
|
||||
}
|
||||
BENCHMARK(ProcessBatch_5Sensors);
|
||||
|
||||
} // namespace esphome::api::benchmarks
|
||||
|
||||
#endif // USE_API_PLAINTEXT && USE_SENSOR
|
||||
@@ -0,0 +1,5 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
manifest.enable_codegen()
|
||||
@@ -0,0 +1,142 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/climate/climate.h"
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Minimal Climate for benchmarking — control() is a no-op.
|
||||
class BenchClimate : public climate::Climate {
|
||||
public:
|
||||
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
|
||||
|
||||
climate::ClimateTraits traits() override { return this->traits_; }
|
||||
|
||||
climate::ClimateTraits traits_;
|
||||
|
||||
protected:
|
||||
void control(const climate::ClimateCall & /*call*/) override {}
|
||||
};
|
||||
|
||||
// Helper to create a typical HVAC climate device for benchmarks.
|
||||
// Note: setup() is not called (no preferences backend), so save_state_()
|
||||
// is effectively a no-op. This benchmarks the call/validation path, not persistence.
|
||||
static void setup_hvac_climate(BenchClimate &climate) {
|
||||
climate.configure("test_climate");
|
||||
climate.traits_.set_supported_modes({
|
||||
climate::CLIMATE_MODE_OFF,
|
||||
climate::CLIMATE_MODE_HEAT_COOL,
|
||||
climate::CLIMATE_MODE_COOL,
|
||||
climate::CLIMATE_MODE_HEAT,
|
||||
climate::CLIMATE_MODE_FAN_ONLY,
|
||||
});
|
||||
climate.traits_.set_supported_fan_modes({
|
||||
climate::CLIMATE_FAN_AUTO,
|
||||
climate::CLIMATE_FAN_LOW,
|
||||
climate::CLIMATE_FAN_MEDIUM,
|
||||
climate::CLIMATE_FAN_HIGH,
|
||||
});
|
||||
climate.traits_.set_supported_swing_modes({
|
||||
climate::CLIMATE_SWING_OFF,
|
||||
climate::CLIMATE_SWING_BOTH,
|
||||
climate::CLIMATE_SWING_VERTICAL,
|
||||
climate::CLIMATE_SWING_HORIZONTAL,
|
||||
});
|
||||
climate.traits_.set_supported_presets({
|
||||
climate::CLIMATE_PRESET_NONE,
|
||||
climate::CLIMATE_PRESET_HOME,
|
||||
climate::CLIMATE_PRESET_AWAY,
|
||||
});
|
||||
climate.traits_.set_visual_min_temperature(16.0f);
|
||||
climate.traits_.set_visual_max_temperature(30.0f);
|
||||
climate.traits_.set_visual_target_temperature_step(0.5f);
|
||||
climate.traits_.set_visual_current_temperature_step(0.1f);
|
||||
climate.traits_.add_feature_flags(climate::CLIMATE_SUPPORTS_CURRENT_TEMPERATURE | climate::CLIMATE_SUPPORTS_ACTION);
|
||||
}
|
||||
|
||||
// --- Climate::publish_state() with temperature update ---
|
||||
// Measures the publish path for a thermostat reporting state —
|
||||
// the hot path during HVAC operation.
|
||||
|
||||
static void ClimatePublish_State(benchmark::State &state) {
|
||||
BenchClimate climate;
|
||||
setup_hvac_climate(climate);
|
||||
climate.mode = climate::CLIMATE_MODE_HEAT;
|
||||
climate.action = climate::CLIMATE_ACTION_HEATING;
|
||||
climate.target_temperature = 22.0f;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
climate.current_temperature = 20.0f + static_cast<float>(i % 100) / 10.0f;
|
||||
climate.publish_state();
|
||||
}
|
||||
benchmark::DoNotOptimize(climate.current_temperature);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(ClimatePublish_State);
|
||||
|
||||
// --- Climate::publish_state() with callback ---
|
||||
// Measures callback dispatch overhead.
|
||||
|
||||
static void ClimatePublish_WithCallback(benchmark::State &state) {
|
||||
BenchClimate climate;
|
||||
setup_hvac_climate(climate);
|
||||
climate.mode = climate::CLIMATE_MODE_HEAT;
|
||||
climate.target_temperature = 22.0f;
|
||||
|
||||
uint64_t callback_count = 0;
|
||||
climate.add_on_state_callback([&callback_count](climate::Climate & /*c*/) { callback_count++; });
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
climate.current_temperature = 20.0f + static_cast<float>(i % 100) / 10.0f;
|
||||
climate.publish_state();
|
||||
}
|
||||
benchmark::DoNotOptimize(callback_count);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(ClimatePublish_WithCallback);
|
||||
|
||||
// --- ClimateCall::perform() set target temperature ---
|
||||
// The most common climate call — adjusting the thermostat setpoint.
|
||||
|
||||
static void ClimateCall_SetTemperature(benchmark::State &state) {
|
||||
BenchClimate climate;
|
||||
setup_hvac_climate(climate);
|
||||
climate.mode = climate::CLIMATE_MODE_HEAT;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
float temp = 18.0f + static_cast<float>(i % 25) * 0.5f;
|
||||
climate.make_call().set_target_temperature(temp).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(climate.target_temperature);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(ClimateCall_SetTemperature);
|
||||
|
||||
// --- ClimateCall::perform() mode change with fan ---
|
||||
// Exercises the validation path with multiple fields set.
|
||||
|
||||
static void ClimateCall_ModeChange(benchmark::State &state) {
|
||||
BenchClimate climate;
|
||||
setup_hvac_climate(climate);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
auto mode = (i % 2 == 0) ? climate::CLIMATE_MODE_HEAT : climate::CLIMATE_MODE_COOL;
|
||||
auto fan = (i % 2 == 0) ? climate::CLIMATE_FAN_HIGH : climate::CLIMATE_FAN_LOW;
|
||||
climate.make_call().set_mode(mode).set_fan_mode(fan).set_target_temperature(22.0f).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(climate.mode);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(ClimateCall_ModeChange);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -0,0 +1 @@
|
||||
climate:
|
||||
@@ -0,0 +1,5 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
manifest.enable_codegen()
|
||||
@@ -0,0 +1,107 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/cover/cover.h"
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Minimal Cover for benchmarking — control() is a no-op.
|
||||
class BenchCover : public cover::Cover {
|
||||
public:
|
||||
cover::CoverTraits get_traits() override { return this->traits_; }
|
||||
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
|
||||
|
||||
cover::CoverTraits traits_;
|
||||
|
||||
protected:
|
||||
void control(const cover::CoverCall & /*call*/) override {}
|
||||
};
|
||||
|
||||
// --- Cover::publish_state() with position updates ---
|
||||
// Measures the publish path for a garage door reporting position
|
||||
// during open/close — the hot path during movement.
|
||||
|
||||
static void CoverPublish_Position(benchmark::State &state) {
|
||||
BenchCover cover;
|
||||
cover.configure("test_cover");
|
||||
cover.traits_.set_supports_position(true);
|
||||
cover.traits_.set_supports_tilt(false);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
cover.position = static_cast<float>(i % 101) / 100.0f;
|
||||
cover.current_operation = (i % 2 == 0) ? cover::COVER_OPERATION_OPENING : cover::COVER_OPERATION_CLOSING;
|
||||
cover.publish_state(false);
|
||||
}
|
||||
benchmark::DoNotOptimize(cover.position);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CoverPublish_Position);
|
||||
|
||||
// --- Cover::publish_state() with callback ---
|
||||
// Measures callback dispatch overhead.
|
||||
|
||||
static void CoverPublish_WithCallback(benchmark::State &state) {
|
||||
BenchCover cover;
|
||||
cover.configure("test_cover");
|
||||
cover.traits_.set_supports_position(true);
|
||||
|
||||
uint64_t callback_count = 0;
|
||||
cover.add_on_state_callback([&callback_count]() { callback_count++; });
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
cover.position = static_cast<float>(i % 101) / 100.0f;
|
||||
cover.publish_state(false);
|
||||
}
|
||||
benchmark::DoNotOptimize(callback_count);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CoverPublish_WithCallback);
|
||||
|
||||
// --- CoverCall::perform() open/close cycle ---
|
||||
// Measures the full call path: validation + control delegation.
|
||||
|
||||
static void CoverCall_OpenClose(benchmark::State &state) {
|
||||
BenchCover cover;
|
||||
cover.configure("test_cover");
|
||||
cover.traits_.set_supports_position(true);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
if (i % 2 == 0) {
|
||||
cover.make_call().set_command_open().perform();
|
||||
} else {
|
||||
cover.make_call().set_command_close().perform();
|
||||
}
|
||||
}
|
||||
benchmark::DoNotOptimize(cover.position);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CoverCall_OpenClose);
|
||||
|
||||
// --- CoverCall::perform() set position ---
|
||||
// Measures the position-setting call path.
|
||||
|
||||
static void CoverCall_SetPosition(benchmark::State &state) {
|
||||
BenchCover cover;
|
||||
cover.configure("test_cover");
|
||||
cover.traits_.set_supports_position(true);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
float pos = static_cast<float>(i % 101) / 100.0f;
|
||||
cover.make_call().set_position(pos).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(cover.position);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(CoverCall_SetPosition);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -0,0 +1 @@
|
||||
cover:
|
||||
@@ -0,0 +1,5 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
manifest.enable_codegen()
|
||||
@@ -0,0 +1,122 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/fan/fan.h"
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Minimal Fan for benchmarking — control() is a no-op.
|
||||
class BenchFan : public fan::Fan {
|
||||
public:
|
||||
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
|
||||
|
||||
fan::FanTraits get_traits() override { return this->traits_; }
|
||||
|
||||
fan::FanTraits traits_;
|
||||
|
||||
protected:
|
||||
void control(const fan::FanCall & /*call*/) override {}
|
||||
};
|
||||
|
||||
// Helper to create a typical fan device for benchmarks.
|
||||
// Note: setup() is not called (no preferences backend), so save_state_()
|
||||
// is effectively a no-op. This benchmarks the call/validation path, not persistence.
|
||||
static void setup_fan(BenchFan &fan) {
|
||||
fan.configure("test_fan");
|
||||
fan.traits_.set_oscillation(true);
|
||||
fan.traits_.set_speed(true);
|
||||
fan.traits_.set_supported_speed_count(6);
|
||||
fan.traits_.set_direction(true);
|
||||
fan.set_restore_mode(fan::FanRestoreMode::NO_RESTORE);
|
||||
fan.traits_.set_supported_preset_modes({
|
||||
"auto",
|
||||
"sleep",
|
||||
"nature",
|
||||
"turbo",
|
||||
});
|
||||
}
|
||||
|
||||
// --- Fan::publish_state() with speed update ---
|
||||
// Measures the publish path for a fan reporting state —
|
||||
// the hot path during fan operation.
|
||||
|
||||
static void FanPublish_State(benchmark::State &state) {
|
||||
BenchFan fan;
|
||||
setup_fan(fan);
|
||||
fan.state = true;
|
||||
fan.direction = fan::FanDirection::FORWARD;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
fan.speed = (i % 6) + 1;
|
||||
fan.publish_state();
|
||||
}
|
||||
benchmark::DoNotOptimize(fan.speed);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FanPublish_State);
|
||||
|
||||
// --- Fan::publish_state() with callback ---
|
||||
// Measures callback dispatch overhead.
|
||||
|
||||
static void FanPublish_WithCallback(benchmark::State &state) {
|
||||
BenchFan fan;
|
||||
setup_fan(fan);
|
||||
fan.state = true;
|
||||
|
||||
uint64_t callback_count = 0;
|
||||
fan.add_on_state_callback([&callback_count]() { callback_count++; });
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
fan.speed = (i % 6) + 1;
|
||||
fan.publish_state();
|
||||
}
|
||||
benchmark::DoNotOptimize(callback_count);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FanPublish_WithCallback);
|
||||
|
||||
// --- FanCall::perform() set speed ---
|
||||
// The most common fan call — adjusting the speed level.
|
||||
|
||||
static void FanCall_SetSpeed(benchmark::State &state) {
|
||||
BenchFan fan;
|
||||
setup_fan(fan);
|
||||
fan.state = true;
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
int speed = (i % 6) + 1;
|
||||
fan.make_call().set_speed(speed).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(fan.speed);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FanCall_SetSpeed);
|
||||
|
||||
// --- FanCall::perform() with multiple fields ---
|
||||
// Exercises the validation path with state, speed, oscillation, and direction.
|
||||
|
||||
static void FanCall_MultiField(benchmark::State &state) {
|
||||
BenchFan fan;
|
||||
setup_fan(fan);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
auto dir = (i % 2 == 0) ? fan::FanDirection::FORWARD : fan::FanDirection::REVERSE;
|
||||
int speed = (i % 6) + 1;
|
||||
fan.make_call().set_state(true).set_speed(speed).set_oscillating(i % 2 == 0).set_direction(dir).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(fan.state);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(FanCall_MultiField);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -0,0 +1 @@
|
||||
fan:
|
||||
@@ -0,0 +1,28 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.light import generate_gamma_table
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# Light benchmarks need USE_LIGHT_GAMMA_LUT defined and a gamma table
|
||||
# with external linkage that the benchmark .cpp can reference.
|
||||
manifest.enable_codegen()
|
||||
original_to_code = manifest.to_code
|
||||
|
||||
async def to_code(config):
|
||||
await original_to_code(config)
|
||||
cg.add_define("USE_LIGHT_GAMMA_LUT")
|
||||
# Use the light component's own generate_gamma_table() so the
|
||||
# benchmark stays in sync with any formula changes.
|
||||
forward = generate_gamma_table(2.8)
|
||||
values = ", ".join(f"0x{int(v):04X}" for v in forward)
|
||||
# Use extern-visible (non-static) array so the benchmark .cpp
|
||||
# can reference it via extern declaration.
|
||||
cg.add_global(
|
||||
cg.RawStatement(
|
||||
f"extern const uint16_t bench_gamma_2_8_fwd[256] PROGMEM = {{{values}}};"
|
||||
)
|
||||
)
|
||||
|
||||
to_code.priority = original_to_code.priority
|
||||
manifest.to_code = to_code
|
||||
@@ -0,0 +1,253 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "esphome/components/light/light_output.h"
|
||||
#include "esphome/components/light/light_state.h"
|
||||
|
||||
// Gamma 2.8 forward LUT generated by the light component's Python codegen
|
||||
// (see tests/benchmarks/components/light/__init__.py which calls generate_gamma_table())
|
||||
extern const uint16_t bench_gamma_2_8_fwd[256];
|
||||
|
||||
namespace esphome::benchmarks {
|
||||
|
||||
// Inner iteration count to amortize CodSpeed instrumentation overhead.
|
||||
static constexpr int kInnerIterations = 2000;
|
||||
|
||||
// Minimal LightOutput for benchmarking — no real hardware interaction.
|
||||
class BenchLightOutput : public light::LightOutput {
|
||||
public:
|
||||
light::LightTraits get_traits() override { return this->traits_; }
|
||||
void write_state(light::LightState * /*state*/) override {}
|
||||
|
||||
light::LightTraits traits_;
|
||||
};
|
||||
|
||||
// Test subclass to access protected configure_entity_() for benchmark setup.
|
||||
class TestLightState : public light::LightState {
|
||||
public:
|
||||
using LightState::LightState;
|
||||
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
|
||||
};
|
||||
|
||||
// Helper to create a configured RGBWW light state for benchmarks.
|
||||
// Note: setup() is not called (no preferences backend), so save_remote_values_()
|
||||
// is effectively a no-op. This benchmarks the call/validation path, not persistence.
|
||||
static void setup_rgbww_light(BenchLightOutput &output, TestLightState &light) {
|
||||
output.traits_.set_supported_color_modes({light::ColorMode::RGB_COLD_WARM_WHITE});
|
||||
output.traits_.set_min_mireds(153.0f);
|
||||
output.traits_.set_max_mireds(500.0f);
|
||||
light.configure("test_light");
|
||||
light.set_default_transition_length(0);
|
||||
light.set_gamma_correct(2.8f);
|
||||
light.set_gamma_table(bench_gamma_2_8_fwd);
|
||||
light.set_restore_mode(light::LIGHT_ALWAYS_OFF);
|
||||
}
|
||||
|
||||
// --- LightCall::perform() with instant RGB color change (Home Assistant API path) ---
|
||||
// Measures the full call path: validation, set_immediately_, publish, and save.
|
||||
// HA sends color_mode explicitly since API 1.6.
|
||||
|
||||
static void LightCall_RGBInstant(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
// Turn on first so subsequent calls are color changes
|
||||
light.make_call().set_state(true).set_brightness(1.0f).set_color_brightness(1.0f).set_transition_length(0).perform();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
float v = static_cast<float>(i % 256) / 255.0f;
|
||||
light.make_call()
|
||||
.set_color_mode(light::ColorMode::RGB_COLD_WARM_WHITE)
|
||||
.set_red(v)
|
||||
.set_green(1.0f - v)
|
||||
.set_blue(v * 0.5f)
|
||||
.set_transition_length(0)
|
||||
.perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_RGBInstant);
|
||||
|
||||
// --- LightCall::perform() turn on/off cycle (Home Assistant API path) ---
|
||||
// HA sends color_mode explicitly since API 1.6, skipping compute_color_mode_().
|
||||
|
||||
static void LightCall_ToggleOnOff(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
light.make_call()
|
||||
.set_state(i % 2 == 0)
|
||||
.set_color_mode(light::ColorMode::RGB_COLD_WARM_WHITE)
|
||||
.set_transition_length(0)
|
||||
.perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_ToggleOnOff);
|
||||
|
||||
// --- LightCall::perform() turn on/off via MQTT ---
|
||||
// MQTT never sends color_mode, so compute_color_mode_() runs every call.
|
||||
|
||||
static void LightCall_ToggleOnOff_MQTT(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
light.make_call().set_state(i % 2 == 0).set_transition_length(0).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_ToggleOnOff_MQTT);
|
||||
|
||||
// --- LightCall::perform() with color temperature via MQTT ---
|
||||
// Exercises the transform_parameters_() path that converts color_temperature
|
||||
// to cold/warm white fractions. MQTT never sends color_mode, so this also
|
||||
// hits compute_color_mode_() every call. Modern HA avoids this path entirely
|
||||
// by converting color temp to CW/WW client-side.
|
||||
|
||||
static void LightCall_ColorTemperature_MQTT(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
light.make_call().set_state(true).set_brightness(1.0f).set_transition_length(0).perform();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
// Sweep through color temperature range
|
||||
float ct = 153.0f + static_cast<float>(i % 348);
|
||||
light.make_call().set_color_temperature(ct).set_transition_length(0).perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_ColorTemperature_MQTT);
|
||||
|
||||
// --- LightCall::perform() with 1s transition (Home Assistant API path) ---
|
||||
// Exercises start_transition_() which allocates a LightTransformer.
|
||||
// This is the default HA path when transition_length > 0.
|
||||
|
||||
static void LightCall_Transition(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
light.make_call().set_state(true).set_brightness(1.0f).set_transition_length(0).perform();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
float v = static_cast<float>(i % 256) / 255.0f;
|
||||
light.make_call()
|
||||
.set_color_mode(light::ColorMode::RGB_COLD_WARM_WHITE)
|
||||
.set_red(v)
|
||||
.set_green(1.0f - v)
|
||||
.set_blue(v * 0.5f)
|
||||
.set_transition_length(1000)
|
||||
.perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_Transition);
|
||||
|
||||
// --- LightCall::perform() with cold/warm white (Home Assistant API path) ---
|
||||
// Mirrors what modern HA sends: explicit color_mode with direct cold_white
|
||||
// and warm_white values. HA converts color temp to CW/WW client-side for
|
||||
// CWWW lights (API >= 1.6), so this is the primary HA path.
|
||||
|
||||
static void LightCall_ColdWarmWhite(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
light.make_call().set_state(true).set_brightness(1.0f).set_transition_length(0).perform();
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
float frac = static_cast<float>(i % 256) / 255.0f;
|
||||
light.make_call()
|
||||
.set_color_mode(light::ColorMode::RGB_COLD_WARM_WHITE)
|
||||
.set_cold_white(1.0f - frac)
|
||||
.set_warm_white(frac)
|
||||
.set_transition_length(0)
|
||||
.perform();
|
||||
}
|
||||
benchmark::DoNotOptimize(light.remote_values);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightCall_ColdWarmWhite);
|
||||
|
||||
// --- LightState::publish_state() with a remote values listener ---
|
||||
// Measures listener notification overhead.
|
||||
|
||||
static void LightPublish_WithListener(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
struct TestListener : public light::LightRemoteValuesListener {
|
||||
void on_light_remote_values_update() override { count_++; }
|
||||
uint64_t count_{0};
|
||||
} listener;
|
||||
light.add_remote_values_listener(&listener);
|
||||
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
light.publish_state();
|
||||
}
|
||||
benchmark::DoNotOptimize(listener.count_);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightPublish_WithListener);
|
||||
|
||||
// --- current_values_as_rgbww output conversion with gamma LUT ---
|
||||
// Measures the output conversion path that real light drivers call
|
||||
// from write_state() to get hardware PWM values, including gamma
|
||||
// table lookups via the LUT generated by Python codegen.
|
||||
|
||||
static void LightOutput_RGBWW(benchmark::State &state) {
|
||||
BenchLightOutput output;
|
||||
TestLightState light(&output);
|
||||
setup_rgbww_light(output, light);
|
||||
|
||||
light.make_call()
|
||||
.set_state(true)
|
||||
.set_brightness(0.8f)
|
||||
.set_color_brightness(0.6f)
|
||||
.set_red(1.0f)
|
||||
.set_green(0.5f)
|
||||
.set_blue(0.2f)
|
||||
.set_cold_white(0.7f)
|
||||
.set_warm_white(0.3f)
|
||||
.set_transition_length(0)
|
||||
.perform();
|
||||
|
||||
float r, g, b, cw, ww;
|
||||
for (auto _ : state) {
|
||||
for (int i = 0; i < kInnerIterations; i++) {
|
||||
light.current_values_as_rgbww(&r, &g, &b, &cw, &ww);
|
||||
}
|
||||
benchmark::DoNotOptimize(r);
|
||||
benchmark::DoNotOptimize(cw);
|
||||
}
|
||||
state.SetItemsProcessed(state.iterations() * kInnerIterations);
|
||||
}
|
||||
BENCHMARK(LightOutput_RGBWW);
|
||||
|
||||
} // namespace esphome::benchmarks
|
||||
@@ -0,0 +1 @@
|
||||
light:
|
||||
@@ -0,0 +1,38 @@
|
||||
// Stub for benchmark builds — provides the minimal interface that
|
||||
// api_connection.cpp needs when USE_BLUETOOTH_PROXY is defined,
|
||||
// without pulling in ESP32 BLE dependencies.
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/api/api_pb2.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace api {
|
||||
class APIConnection;
|
||||
} // namespace api
|
||||
|
||||
namespace bluetooth_proxy {
|
||||
|
||||
class BluetoothProxy {
|
||||
public:
|
||||
api::APIConnection *get_api_connection() const { return nullptr; }
|
||||
void subscribe_api_connection(api::APIConnection *conn, uint32_t flags) {}
|
||||
void unsubscribe_api_connection(api::APIConnection *conn) {}
|
||||
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg) {}
|
||||
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg) {}
|
||||
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg) {}
|
||||
void bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg) {}
|
||||
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg) {}
|
||||
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg) {}
|
||||
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg) {}
|
||||
void send_connections_free(api::APIConnection *conn) {}
|
||||
void bluetooth_scanner_set_mode(bool active) {}
|
||||
void bluetooth_set_connection_params(const api::BluetoothSetConnectionParamsRequest &msg) {}
|
||||
uint32_t get_feature_flags() const { return 0; }
|
||||
void get_bluetooth_mac_address_pretty(char *buf) const { buf[0] = '\0'; }
|
||||
};
|
||||
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
extern BluetoothProxy *global_bluetooth_proxy;
|
||||
|
||||
} // namespace bluetooth_proxy
|
||||
} // namespace esphome
|
||||
@@ -0,0 +1,2 @@
|
||||
*.pcf -text
|
||||
*.ttf -text
|
||||
Binary file not shown.
@@ -0,0 +1,337 @@
|
||||
"""Tests for the font component.
|
||||
|
||||
Focuses on verifying that long multi-byte (Chinese/CJK) glyph strings
|
||||
are correctly processed through the font configuration pipeline.
|
||||
"""
|
||||
|
||||
import functools
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.font import (
|
||||
CONF_BPP,
|
||||
CONF_EXTRAS,
|
||||
CONF_GLYPHSETS,
|
||||
CONF_IGNORE_MISSING_GLYPHS,
|
||||
CONF_RAW_GLYPH_ID,
|
||||
FONT_CACHE,
|
||||
flatten,
|
||||
glyph_comparator,
|
||||
to_code,
|
||||
validate_font_config,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_FILE,
|
||||
CONF_GLYPHS,
|
||||
CONF_ID,
|
||||
CONF_PATH,
|
||||
CONF_RAW_DATA_ID,
|
||||
CONF_SIZE,
|
||||
CONF_TYPE,
|
||||
)
|
||||
|
||||
FONT_DIR = Path(__file__).parent
|
||||
FONT_PATH = FONT_DIR / "NotoSans-Regular.ttf"
|
||||
|
||||
# 200 unique CJK Unified Ideograph characters (U+4E00..U+4EC7)
|
||||
CHINESE_200 = "".join(chr(cp) for cp in range(0x4E00, 0x4EC8))
|
||||
|
||||
|
||||
def _file_conf() -> dict:
|
||||
return {CONF_PATH: str(FONT_PATH), CONF_TYPE: "local"}
|
||||
|
||||
|
||||
def _make_config(
|
||||
glyphs: list[str],
|
||||
*,
|
||||
ignore_missing: bool = False,
|
||||
size: int = 20,
|
||||
bpp: int = 1,
|
||||
extras: list | None = None,
|
||||
glyphsets: list | None = None,
|
||||
) -> dict:
|
||||
"""Build a config dict matching what FONT_SCHEMA produces."""
|
||||
return {
|
||||
CONF_FILE: _file_conf(),
|
||||
CONF_GLYPHS: glyphs,
|
||||
CONF_GLYPHSETS: glyphsets or [],
|
||||
CONF_IGNORE_MISSING_GLYPHS: ignore_missing,
|
||||
CONF_SIZE: size,
|
||||
CONF_BPP: bpp,
|
||||
CONF_EXTRAS: extras or [],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _load_font():
|
||||
"""Load the test font into FONT_CACHE and clean up afterwards."""
|
||||
fc = _file_conf()
|
||||
FONT_CACHE[fc] = FONT_PATH
|
||||
yield
|
||||
FONT_CACHE.store.clear()
|
||||
|
||||
|
||||
# ---------- flatten / glyph_comparator helpers ----------
|
||||
|
||||
|
||||
def test_flatten_splits_chinese_string_into_chars():
|
||||
"""A single string of 200 Chinese characters must become 200 individual chars."""
|
||||
result = flatten([CHINESE_200])
|
||||
assert len(result) == 200
|
||||
assert all(len(c) == 1 for c in result)
|
||||
assert result[0] == "\u4e00"
|
||||
assert result[-1] == "\u4ec7"
|
||||
|
||||
|
||||
def test_flatten_multiple_chinese_strings():
|
||||
"""Multiple glyph strings are concatenated then split correctly."""
|
||||
s1 = CHINESE_200[:100]
|
||||
s2 = CHINESE_200[100:]
|
||||
result = flatten([list(s1), list(s2)])
|
||||
assert len(result) == 200
|
||||
|
||||
|
||||
def test_glyph_comparator_orders_chinese_by_utf8():
|
||||
"""glyph_comparator must order CJK characters by their UTF-8 byte sequence."""
|
||||
chars = list(CHINESE_200[:10])
|
||||
sorted_chars = sorted(chars, key=functools.cmp_to_key(glyph_comparator))
|
||||
# CJK block is contiguous and UTF-8 order matches codepoint order here
|
||||
assert sorted_chars == chars
|
||||
|
||||
|
||||
def test_glyph_comparator_mixed_ascii_and_chinese():
|
||||
"""ASCII characters sort before CJK characters (lower UTF-8 bytes)."""
|
||||
assert glyph_comparator("A", "\u4e00") == -1
|
||||
assert glyph_comparator("\u4e00", "A") == 1
|
||||
assert glyph_comparator("\u4e00", "\u4e00") == 0
|
||||
|
||||
|
||||
# ---------- validate_font_config ----------
|
||||
|
||||
|
||||
def test_long_chinese_glyphs_raises_missing_error():
|
||||
"""200 Chinese chars not present in NotoSans must raise Invalid with the correct count."""
|
||||
config = _make_config([CHINESE_200])
|
||||
with pytest.raises(cv.Invalid, match=r"missing 200 glyphs"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_long_chinese_glyphs_error_mentions_overflow():
|
||||
"""When more than 10 glyphs are missing the error should mention the remainder."""
|
||||
config = _make_config([CHINESE_200])
|
||||
with pytest.raises(cv.Invalid, match=r"and 190 more"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_duplicate_chinese_glyphs_detected():
|
||||
"""Duplicate CJK characters within a single glyph string must be caught."""
|
||||
duped = "\u4e00\u4e01\u4e00" # first char repeated
|
||||
config = _make_config([duped])
|
||||
with pytest.raises(cv.Invalid, match="duplicate"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_duplicate_chinese_across_strings():
|
||||
"""Duplicates across separate glyph strings are also caught."""
|
||||
config = _make_config(["\u4e00\u4e01", "\u4e01\u4e02"])
|
||||
with pytest.raises(cv.Invalid, match="duplicate"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_no_false_duplicates_in_200_unique_chinese():
|
||||
"""200 unique CJK characters must not trigger the duplicate check."""
|
||||
config = _make_config([CHINESE_200])
|
||||
# Should not raise duplicate error — it should reach the missing-glyph check instead
|
||||
with pytest.raises(cv.Invalid, match="missing"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_valid_latin_glyphs_pass_validation():
|
||||
"""Latin characters present in NotoSans-Regular pass validation without error."""
|
||||
config = _make_config(["ABCabc123"])
|
||||
result = validate_font_config(config)
|
||||
assert result is not None
|
||||
assert result[CONF_SIZE] == 20
|
||||
|
||||
|
||||
def test_long_latin_glyphs_pass_validation():
|
||||
"""A long string of supported Latin glyphs passes validation."""
|
||||
# 95 printable ASCII characters that NotoSans supports
|
||||
latin = "".join(chr(cp) for cp in range(0x21, 0x7F))
|
||||
config = _make_config([latin])
|
||||
result = validate_font_config(config)
|
||||
assert result is not None
|
||||
|
||||
|
||||
def test_mixed_latin_and_chinese_glyphs_error():
|
||||
"""Mixing valid Latin and invalid Chinese chars reports missing Chinese glyphs."""
|
||||
chinese_10 = CHINESE_200[:10]
|
||||
config = _make_config(["ABC", chinese_10])
|
||||
with pytest.raises(cv.Invalid, match=r"missing 10 glyphs"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_single_chinese_char_glyph():
|
||||
"""A single Chinese character is correctly handled as one glyph."""
|
||||
config = _make_config(["\u4e00"])
|
||||
with pytest.raises(cv.Invalid, match=r"missing 1 glyph[^s]"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
def test_chinese_glyphs_as_individual_list_items():
|
||||
"""Chinese chars provided as separate list items are handled the same as a single string."""
|
||||
chars_as_list = list(CHINESE_200[:50])
|
||||
config = _make_config(chars_as_list)
|
||||
with pytest.raises(cv.Invalid, match=r"missing 50 glyphs"):
|
||||
validate_font_config(config)
|
||||
|
||||
|
||||
# ---------- YAML parsing ----------
|
||||
|
||||
|
||||
def test_yaml_long_latin_glyphs_parsed_and_validated(tmp_path):
|
||||
"""200 Latin Extended chars on a single YAML line are parsed intact and pass validation."""
|
||||
from esphome.yaml_util import load_yaml
|
||||
|
||||
latin_long = "".join(chr(cp) for cp in range(0x100, 0x1C8))
|
||||
yaml_file = tmp_path / "font_test.yaml"
|
||||
yaml_file.write_text(
|
||||
f'font:\n - file: "NotoSans-Regular.ttf"\n glyphs: "{latin_long}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
parsed = load_yaml(yaml_file)
|
||||
raw_glyphs = parsed["font"][0]["glyphs"]
|
||||
|
||||
# YAML must preserve every Unicode character on the single line
|
||||
assert raw_glyphs == latin_long
|
||||
assert len(raw_glyphs) == 200
|
||||
|
||||
# Feed through validate_font_config to confirm all glyphs are accepted
|
||||
config = _make_config([raw_glyphs])
|
||||
result = validate_font_config(config)
|
||||
assert result is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"glyphs_str",
|
||||
[
|
||||
" ABC", # space at start
|
||||
"AB CD", # space in middle
|
||||
"ABC ", # space at end
|
||||
],
|
||||
ids=["start", "middle", "end"],
|
||||
)
|
||||
def test_yaml_space_in_glyphs_preserved(tmp_path, glyphs_str):
|
||||
"""A space character in a glyphs string must survive YAML round-trip and validation."""
|
||||
from esphome.yaml_util import load_yaml
|
||||
|
||||
yaml_file = tmp_path / "font_test.yaml"
|
||||
yaml_file.write_text(
|
||||
f'font:\n - file: "NotoSans-Regular.ttf"\n glyphs: "{glyphs_str}"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
parsed = load_yaml(yaml_file)
|
||||
raw_glyphs = parsed["font"][0]["glyphs"]
|
||||
|
||||
assert raw_glyphs == glyphs_str
|
||||
assert " " in raw_glyphs
|
||||
|
||||
# Space and ASCII letters are all in NotoSans — validation must pass
|
||||
config = _make_config([raw_glyphs])
|
||||
result = validate_font_config(config)
|
||||
assert result is not None
|
||||
|
||||
|
||||
# ---------- to_code generation ----------
|
||||
|
||||
|
||||
# 200 unique Latin Extended characters (U+0100..U+01C7), all present in NotoSans
|
||||
LATIN_LONG = "".join(chr(cp) for cp in range(0x100, 0x1C8))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cg():
|
||||
"""Mock all cg codegen functions used by to_code."""
|
||||
with (
|
||||
patch("esphome.components.font.cg.add_define") as mock_define,
|
||||
patch("esphome.components.font.cg.progmem_array") as mock_progmem,
|
||||
patch("esphome.components.font.cg.static_const_array") as mock_static,
|
||||
patch("esphome.components.font.cg.new_Pvariable") as mock_new_pvar,
|
||||
):
|
||||
mock_progmem.return_value = MagicMock()
|
||||
mock_static.return_value = MagicMock()
|
||||
yield {
|
||||
"add_define": mock_define,
|
||||
"progmem_array": mock_progmem,
|
||||
"static_const_array": mock_static,
|
||||
"new_Pvariable": mock_new_pvar,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_to_code_long_latin_generates_all_glyphs(mock_cg):
|
||||
"""to_code must generate glyph data for every character in a long Latin string."""
|
||||
glyph_count = len(LATIN_LONG) # 200
|
||||
config = _make_config([LATIN_LONG])
|
||||
config[CONF_ID] = MagicMock()
|
||||
config[CONF_RAW_DATA_ID] = MagicMock()
|
||||
config[CONF_RAW_GLYPH_ID] = MagicMock()
|
||||
|
||||
await to_code(config)
|
||||
|
||||
# USE_FONT define must be emitted
|
||||
mock_cg["add_define"].assert_any_call("USE_FONT")
|
||||
|
||||
# progmem_array receives the combined bitmap data (non-empty)
|
||||
mock_cg["progmem_array"].assert_called_once()
|
||||
bitmap_data = mock_cg["progmem_array"].call_args.args[1]
|
||||
assert len(bitmap_data) > 0
|
||||
|
||||
# static_const_array receives one entry per unique glyph
|
||||
mock_cg["static_const_array"].assert_called_once()
|
||||
glyph_initializer = mock_cg["static_const_array"].call_args.args[1]
|
||||
assert len(glyph_initializer) == glyph_count
|
||||
|
||||
# new_Pvariable is called with the correct glyph count
|
||||
mock_cg["new_Pvariable"].assert_called_once()
|
||||
pvar_args = mock_cg["new_Pvariable"].call_args.args
|
||||
assert pvar_args[2] == glyph_count # len(glyph_initializer)
|
||||
assert pvar_args[8] == 1 # bpp
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_to_code_glyph_entries_contain_expected_fields(mock_cg):
|
||||
"""Each glyph initializer entry must have 7 fields: codepoint, data ptr, advance, offset_x, offset_y, w, h."""
|
||||
config = _make_config([LATIN_LONG])
|
||||
config[CONF_ID] = MagicMock()
|
||||
config[CONF_RAW_DATA_ID] = MagicMock()
|
||||
config[CONF_RAW_GLYPH_ID] = MagicMock()
|
||||
|
||||
await to_code(config)
|
||||
|
||||
glyph_initializer = mock_cg["static_const_array"].call_args.args[1]
|
||||
for entry in glyph_initializer:
|
||||
assert len(entry) == 7, f"Glyph entry should have 7 fields, got {len(entry)}"
|
||||
codepoint = entry[0]
|
||||
assert isinstance(codepoint, int)
|
||||
assert 0x100 <= codepoint <= 0x1C7
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_to_code_glyphs_sorted_by_utf8(mock_cg):
|
||||
"""Glyphs in the initializer must be sorted by UTF-8 byte order."""
|
||||
config = _make_config([LATIN_LONG])
|
||||
config[CONF_ID] = MagicMock()
|
||||
config[CONF_RAW_DATA_ID] = MagicMock()
|
||||
config[CONF_RAW_GLYPH_ID] = MagicMock()
|
||||
|
||||
await to_code(config)
|
||||
|
||||
glyph_initializer = mock_cg["static_const_array"].call_args.args[1]
|
||||
codepoints = [entry[0] for entry in glyph_initializer]
|
||||
assert codepoints == sorted(codepoints)
|
||||
@@ -0,0 +1,280 @@
|
||||
"""Tests for light effect name validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
from contextvars import Token
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.light import (
|
||||
EffectRef,
|
||||
_final_validate,
|
||||
_get_data,
|
||||
available_effects_str,
|
||||
find_effect_index,
|
||||
)
|
||||
from esphome.components.light.automation import _record_effect_ref
|
||||
from esphome.config import Config, path_context
|
||||
from esphome.const import CONF_EFFECT, CONF_EFFECTS, CONF_ID, CONF_NAME
|
||||
from esphome.core import ID, Lambda
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
|
||||
def _make_effects(*names: str) -> list[dict[str, dict[str, str]]]:
|
||||
"""Create a list of effect config dicts from names."""
|
||||
return [{f"effect_{i}": {CONF_NAME: name}} for i, name in enumerate(names)]
|
||||
|
||||
|
||||
# --- find_effect_index ---
|
||||
|
||||
|
||||
def test_find_effect_index_found() -> None:
|
||||
effects = _make_effects("Fast Pulse", "Slow Pulse")
|
||||
assert find_effect_index(effects, "Fast Pulse") == 1
|
||||
assert find_effect_index(effects, "Slow Pulse") == 2
|
||||
|
||||
|
||||
def test_find_effect_index_case_insensitive() -> None:
|
||||
effects = _make_effects("Fast Pulse")
|
||||
assert find_effect_index(effects, "fast pulse") == 1
|
||||
assert find_effect_index(effects, "FAST PULSE") == 1
|
||||
|
||||
|
||||
def test_find_effect_index_not_found() -> None:
|
||||
effects = _make_effects("Fast Pulse", "Slow Pulse")
|
||||
assert find_effect_index(effects, "Missing") is None
|
||||
|
||||
|
||||
def test_find_effect_index_empty() -> None:
|
||||
assert find_effect_index([], "anything") is None
|
||||
|
||||
|
||||
# --- available_effects_str ---
|
||||
|
||||
|
||||
def test_available_effects_str_multiple() -> None:
|
||||
effects = _make_effects("Fast Pulse", "Slow Pulse")
|
||||
assert available_effects_str(effects) == "'Fast Pulse', 'Slow Pulse'"
|
||||
|
||||
|
||||
def test_available_effects_str_single() -> None:
|
||||
effects = _make_effects("Fast Pulse")
|
||||
assert available_effects_str(effects) == "'Fast Pulse'"
|
||||
|
||||
|
||||
def test_available_effects_str_empty() -> None:
|
||||
assert available_effects_str([]) == "none"
|
||||
|
||||
|
||||
# --- _final_validate ---
|
||||
|
||||
|
||||
def _setup_final_validate(
|
||||
effect_refs: list[EffectRef],
|
||||
light_configs: list[ConfigType],
|
||||
declare_ids: list[tuple[ID, list[str | int]]],
|
||||
) -> Token:
|
||||
"""Set up CORE.data and fv.full_config for _final_validate tests."""
|
||||
data = _get_data()
|
||||
data.effect_refs = effect_refs
|
||||
|
||||
full_conf = Config()
|
||||
full_conf["light"] = light_configs
|
||||
for id_, path in declare_ids:
|
||||
full_conf.declare_ids.append((id_, path))
|
||||
|
||||
return fv.full_config.set(full_conf)
|
||||
|
||||
|
||||
def test_final_validate_valid_effect() -> None:
|
||||
"""Valid effect name should not raise."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
token = _setup_final_validate(
|
||||
effect_refs=[
|
||||
EffectRef(
|
||||
light_id=light_id, effect_name="Fast Pulse", component_path=["esphome"]
|
||||
),
|
||||
],
|
||||
light_configs=[
|
||||
{CONF_ID: light_id, CONF_EFFECTS: _make_effects("Fast Pulse", "Slow Pulse")}
|
||||
],
|
||||
declare_ids=[(light_id, ["light", 0, CONF_ID])],
|
||||
)
|
||||
try:
|
||||
_final_validate({})
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
def test_final_validate_invalid_effect_raises() -> None:
|
||||
"""Invalid effect name should raise FinalExternalInvalid."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
token = _setup_final_validate(
|
||||
effect_refs=[
|
||||
EffectRef(
|
||||
light_id=light_id, effect_name="Nonexistent", component_path=["esphome"]
|
||||
),
|
||||
],
|
||||
light_configs=[
|
||||
{CONF_ID: light_id, CONF_EFFECTS: _make_effects("Fast Pulse", "Slow Pulse")}
|
||||
],
|
||||
declare_ids=[(light_id, ["light", 0, CONF_ID])],
|
||||
)
|
||||
try:
|
||||
with pytest.raises(cv.FinalExternalInvalid, match="Nonexistent"):
|
||||
_final_validate({})
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
def test_final_validate_lists_available_effects() -> None:
|
||||
"""Error message should list available effects."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
token = _setup_final_validate(
|
||||
effect_refs=[
|
||||
EffectRef(
|
||||
light_id=light_id, effect_name="Missing", component_path=["esphome"]
|
||||
),
|
||||
],
|
||||
light_configs=[
|
||||
{CONF_ID: light_id, CONF_EFFECTS: _make_effects("Fast Pulse", "Slow Pulse")}
|
||||
],
|
||||
declare_ids=[(light_id, ["light", 0, CONF_ID])],
|
||||
)
|
||||
try:
|
||||
with pytest.raises(cv.FinalExternalInvalid, match="'Fast Pulse', 'Slow Pulse'"):
|
||||
_final_validate({})
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
def test_final_validate_no_effects_on_light() -> None:
|
||||
"""Light with no effects should report 'none' as available."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
token = _setup_final_validate(
|
||||
effect_refs=[
|
||||
EffectRef(
|
||||
light_id=light_id, effect_name="Missing", component_path=["esphome"]
|
||||
),
|
||||
],
|
||||
light_configs=[{CONF_ID: light_id}],
|
||||
declare_ids=[(light_id, ["light", 0, CONF_ID])],
|
||||
)
|
||||
try:
|
||||
with pytest.raises(cv.FinalExternalInvalid, match="Available effects: none"):
|
||||
_final_validate({})
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
def test_final_validate_no_refs_is_noop() -> None:
|
||||
"""No stored refs should pass without error."""
|
||||
data = _get_data()
|
||||
data.effect_refs = []
|
||||
_final_validate({})
|
||||
|
||||
|
||||
def test_final_validate_unknown_light_id_skipped() -> None:
|
||||
"""Refs to unknown light IDs should be silently skipped."""
|
||||
data = _get_data()
|
||||
data.effect_refs = [
|
||||
EffectRef(
|
||||
light_id=ID("nonexistent", is_declaration=True),
|
||||
effect_name="Missing",
|
||||
component_path=["esphome"],
|
||||
)
|
||||
]
|
||||
|
||||
full_conf = Config()
|
||||
token = fv.full_config.set(full_conf)
|
||||
try:
|
||||
_final_validate({})
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
def test_final_validate_drains_refs() -> None:
|
||||
"""Refs should be drained after validation to avoid redundant runs."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
token = _setup_final_validate(
|
||||
effect_refs=[
|
||||
EffectRef(
|
||||
light_id=light_id, effect_name="Fast Pulse", component_path=["esphome"]
|
||||
),
|
||||
],
|
||||
light_configs=[{CONF_ID: light_id, CONF_EFFECTS: _make_effects("Fast Pulse")}],
|
||||
declare_ids=[(light_id, ["light", 0, CONF_ID])],
|
||||
)
|
||||
try:
|
||||
_final_validate({})
|
||||
assert _get_data().effect_refs == []
|
||||
finally:
|
||||
fv.full_config.reset(token)
|
||||
|
||||
|
||||
# --- _record_effect_ref ---
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _path_ctx() -> Generator[None]:
|
||||
"""Set path_context for _record_effect_ref tests."""
|
||||
token = path_context.set(["esphome"])
|
||||
yield
|
||||
path_context.reset(token)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("_path_ctx")
|
||||
def test_record_effect_ref_static() -> None:
|
||||
"""Static effect name should be recorded."""
|
||||
light_id = ID("led1", is_declaration=True)
|
||||
config: ConfigType = {CONF_ID: light_id, CONF_EFFECT: "Fast Pulse"}
|
||||
result = _record_effect_ref(config)
|
||||
assert result is config
|
||||
data = _get_data()
|
||||
assert len(data.effect_refs) == 1
|
||||
assert data.effect_refs[0].effect_name == "Fast Pulse"
|
||||
assert data.effect_refs[0].light_id is light_id
|
||||
assert data.effect_refs[0].component_path == ["esphome"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("_path_ctx")
|
||||
def test_record_effect_ref_skips_lambda() -> None:
|
||||
"""Lambda effect should not be recorded."""
|
||||
config: ConfigType = {
|
||||
CONF_ID: ID("led1", is_declaration=True),
|
||||
CONF_EFFECT: Lambda("return effect;"),
|
||||
}
|
||||
_record_effect_ref(config)
|
||||
assert _get_data().effect_refs == []
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("_path_ctx")
|
||||
def test_record_effect_ref_skips_none() -> None:
|
||||
"""Effect 'None' should not be recorded."""
|
||||
config: ConfigType = {
|
||||
CONF_ID: ID("led1", is_declaration=True),
|
||||
CONF_EFFECT: "None",
|
||||
}
|
||||
_record_effect_ref(config)
|
||||
assert _get_data().effect_refs == []
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("_path_ctx")
|
||||
def test_record_effect_ref_skips_none_case_insensitive() -> None:
|
||||
"""Effect 'none' (lowercase) should not be recorded."""
|
||||
config: ConfigType = {
|
||||
CONF_ID: ID("led1", is_declaration=True),
|
||||
CONF_EFFECT: "none",
|
||||
}
|
||||
_record_effect_ref(config)
|
||||
assert _get_data().effect_refs == []
|
||||
|
||||
|
||||
def test_record_effect_ref_skips_no_effect_key() -> None:
|
||||
"""Config without effect key should be a no-op."""
|
||||
config: ConfigType = {CONF_ID: ID("led1", is_declaration=True)}
|
||||
_record_effect_ref(config)
|
||||
assert _get_data().effect_refs == []
|
||||
@@ -0,0 +1,9 @@
|
||||
sensor:
|
||||
- platform: bmp581_spi
|
||||
cs_pin: ${cs_pin}
|
||||
temperature:
|
||||
name: BMP581 Temperature
|
||||
iir_filter: 2x
|
||||
pressure:
|
||||
name: BMP581 Pressure
|
||||
oversampling: 128x
|
||||
@@ -0,0 +1,7 @@
|
||||
substitutions:
|
||||
cs_pin: GPIO5
|
||||
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,7 @@
|
||||
substitutions:
|
||||
cs_pin: GPIO15
|
||||
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,7 @@
|
||||
substitutions:
|
||||
cs_pin: GPIO5
|
||||
|
||||
packages:
|
||||
spi: !include ../../test_build_components/common/spi/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -69,3 +69,11 @@ esp32_ble_server:
|
||||
- ble_server.descriptor.set_value:
|
||||
id: test_change_descriptor
|
||||
value: !lambda return bytebuffer::ByteBuffer::wrap({0x03, 0x04, 0x05}).get_data();
|
||||
- ble_server.characteristic.set_value:
|
||||
id: test_change_characteristic
|
||||
value:
|
||||
data: [0xfc, 0xef, 0xfe, 0x86]
|
||||
- ble_server.descriptor.set_value:
|
||||
id: test_change_descriptor
|
||||
value:
|
||||
data: [0x01, 0x02, 0x03]
|
||||
|
||||
@@ -14,3 +14,6 @@ esphome:
|
||||
assert(x == 95);
|
||||
x = clamp_at_most(x, 40);
|
||||
assert(x == 40);
|
||||
- lambda: |-
|
||||
float value = 0.0f;
|
||||
sscanf("3.14", "%f", &value);
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
*.pcf -text
|
||||
*.pcf -text
|
||||
*.ttf -text
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
sensor:
|
||||
- platform: hdc2080
|
||||
temperature:
|
||||
name: Temperature
|
||||
humidity:
|
||||
name: Humidity
|
||||
update_interval: 15s
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1 @@
|
||||
<<: !include common.yaml
|
||||
@@ -232,7 +232,7 @@ lvgl:
|
||||
- roller:
|
||||
id: lv_roller
|
||||
visible_row_count: 2
|
||||
anim_time: 500ms
|
||||
anim_duration: 500ms
|
||||
options:
|
||||
- Nov
|
||||
- Dec
|
||||
@@ -288,7 +288,9 @@ lvgl:
|
||||
- label:
|
||||
text: "Hello shiny day"
|
||||
text_color: 0xFFFFFF
|
||||
align: bottom_mid
|
||||
align_to:
|
||||
id: hello_label
|
||||
align: OUT_LEFT_TOP
|
||||
- label:
|
||||
id: setup_lambda_label
|
||||
# Test lambda in widget property during setup (LvContext)
|
||||
@@ -315,20 +317,27 @@ lvgl:
|
||||
align: top_left
|
||||
- container:
|
||||
align: center
|
||||
anim_duration: 1s
|
||||
arc_opa: COVER
|
||||
arc_color: 0xFF0000
|
||||
arc_rounded: false
|
||||
arc_width: 3
|
||||
anim_time: 1s
|
||||
base_dir: auto
|
||||
bg_color: light_blue
|
||||
bg_grad_color: light_blue
|
||||
bg_grad_dir: hor
|
||||
bg_grad_opa: cover
|
||||
bg_grad_stop: 128
|
||||
bg_image_opa: transp
|
||||
bg_image_recolor: light_blue
|
||||
bg_image_recolor_opa: 50%
|
||||
bg_main_opa: cover
|
||||
bg_main_stop: 0
|
||||
bg_opa: 20%
|
||||
blend_mode: normal
|
||||
blur_backdrop: false
|
||||
blur_quality: auto
|
||||
blur_radius: 0
|
||||
border_color: 0x00FF00
|
||||
border_opa: cover
|
||||
border_post: true
|
||||
@@ -336,7 +345,15 @@ lvgl:
|
||||
border_width: 4
|
||||
clip_corner: false
|
||||
color_filter_opa: transp
|
||||
drop_shadow_color: 0x000000
|
||||
drop_shadow_offset_x: 5
|
||||
drop_shadow_offset_y: 5
|
||||
drop_shadow_opa: cover
|
||||
drop_shadow_quality: precision
|
||||
drop_shadow_radius: 10
|
||||
ext_click_area: 100px
|
||||
height: 50%
|
||||
image_opa: cover
|
||||
image_recolor: light_blue
|
||||
image_recolor_opa: cover
|
||||
line_width: 10
|
||||
@@ -344,6 +361,10 @@ lvgl:
|
||||
line_dash_gap: 10
|
||||
line_rounded: false
|
||||
line_color: light_blue
|
||||
margin_bottom: 4
|
||||
margin_left: 4
|
||||
margin_right: 4
|
||||
margin_top: 4
|
||||
opa: cover
|
||||
opa_layered: cover
|
||||
outline_color: light_blue
|
||||
@@ -353,8 +374,12 @@ lvgl:
|
||||
pad_all: 10px
|
||||
pad_bottom: 10px
|
||||
pad_left: 10px
|
||||
pad_radial: 0
|
||||
pad_right: 10px
|
||||
pad_top: 10px
|
||||
recolor: 0xFF0000
|
||||
recolor_opa: transp
|
||||
rotary_sensitivity: 256
|
||||
shadow_color: light_blue
|
||||
shadow_opa: cover
|
||||
shadow_spread: 5
|
||||
@@ -366,6 +391,9 @@ lvgl:
|
||||
text_letter_space: 4
|
||||
text_line_space: 4
|
||||
text_opa: cover
|
||||
text_outline_stroke_color: 0x000000
|
||||
text_outline_stroke_opa: cover
|
||||
text_outline_stroke_width: 2
|
||||
transform_rotation: 90
|
||||
transform_height: 100
|
||||
transform_pivot_x: 50%
|
||||
@@ -375,8 +403,10 @@ lvgl:
|
||||
transform_scale_y: 0.8
|
||||
transform_skew_x: 10
|
||||
transform_skew_y: 20
|
||||
transform_width: 100
|
||||
shadow_offset_x: 3
|
||||
shadow_offset_y: 3
|
||||
translate_radial: 0
|
||||
translate_x: 10
|
||||
translate_y: 10
|
||||
max_height: 100
|
||||
@@ -481,6 +511,7 @@ lvgl:
|
||||
image:
|
||||
src: cat_image
|
||||
align: top_left
|
||||
bitmap_mask_src: alert
|
||||
on_click:
|
||||
- lvgl.widget.focus: spin_up
|
||||
- lvgl.widget.focus: next
|
||||
@@ -559,6 +590,114 @@ lvgl:
|
||||
logger.log: Button clicked
|
||||
on_long_press_repeat:
|
||||
logger.log: Button clicked
|
||||
on_pressing:
|
||||
logger.log: Button pressing
|
||||
on_press_lost:
|
||||
logger.log: Button press lost
|
||||
on_single_click:
|
||||
logger.log: Button single clicked
|
||||
on_double_click:
|
||||
logger.log: Button double clicked
|
||||
on_triple_click:
|
||||
logger.log: Button triple clicked
|
||||
on_scroll_throw_begin:
|
||||
logger.log: Scroll throw begin
|
||||
on_gesture:
|
||||
logger.log: Gesture detected
|
||||
on_key:
|
||||
logger.log: Key event
|
||||
on_rotary:
|
||||
logger.log: Rotary event
|
||||
on_leave:
|
||||
logger.log: Leave event
|
||||
on_hit_test:
|
||||
logger.log: Hit test
|
||||
on_indev_reset:
|
||||
logger.log: Indev reset
|
||||
on_hover_over:
|
||||
logger.log: Hover over
|
||||
on_hover_leave:
|
||||
logger.log: Hover leave
|
||||
on_cover_check:
|
||||
logger.log: Cover check
|
||||
on_refr_ext_draw_size:
|
||||
logger.log: Refr ext draw size
|
||||
on_draw_main_begin:
|
||||
logger.log: Draw main begin
|
||||
on_draw_main:
|
||||
logger.log: Draw main
|
||||
on_draw_main_end:
|
||||
logger.log: Draw main end
|
||||
on_draw_post_begin:
|
||||
logger.log: Draw post begin
|
||||
on_draw_post:
|
||||
logger.log: Draw post
|
||||
on_draw_post_end:
|
||||
logger.log: Draw post end
|
||||
on_draw_task_add:
|
||||
logger.log: Draw task add
|
||||
on_insert:
|
||||
logger.log: Insert event
|
||||
on_refresh:
|
||||
logger.log: Refresh event
|
||||
on_state_change:
|
||||
logger.log: State changed
|
||||
on_create:
|
||||
logger.log: Create event
|
||||
on_delete:
|
||||
logger.log: Delete event
|
||||
on_child_change:
|
||||
logger.log: Child changed
|
||||
on_child_create:
|
||||
logger.log: Child created
|
||||
on_child_delete:
|
||||
logger.log: Child deleted
|
||||
on_screen_unload_start:
|
||||
logger.log: Screen unload start
|
||||
on_screen_load_start:
|
||||
logger.log: Screen load start
|
||||
on_screen_load:
|
||||
logger.log: Screen loaded
|
||||
on_screen_unload:
|
||||
logger.log: Screen unloaded
|
||||
on_size_change:
|
||||
logger.log: Size changed
|
||||
on_style_change:
|
||||
logger.log: Style changed
|
||||
on_layout_change:
|
||||
logger.log: Layout changed
|
||||
on_get_self_size:
|
||||
logger.log: Get self size
|
||||
on_invalidate_area:
|
||||
logger.log: Invalidate area
|
||||
on_resolution_change:
|
||||
logger.log: Resolution changed
|
||||
on_color_format_change:
|
||||
logger.log: Color format changed
|
||||
on_refr_request:
|
||||
logger.log: Refresh request
|
||||
on_refr_start:
|
||||
logger.log: Refresh start
|
||||
on_refr_ready:
|
||||
logger.log: Refresh ready
|
||||
on_render_start:
|
||||
logger.log: Render start
|
||||
on_render_ready:
|
||||
logger.log: Render ready
|
||||
on_flush_start:
|
||||
logger.log: Flush start
|
||||
on_flush_finish:
|
||||
logger.log: Flush finish
|
||||
on_flush_wait_start:
|
||||
logger.log: Flush wait start
|
||||
on_flush_wait_finish:
|
||||
logger.log: Flush wait finish
|
||||
on_update_layout_complete:
|
||||
logger.log: Update layout complete
|
||||
on_vsync:
|
||||
logger.log: Vsync
|
||||
on_vsync_request:
|
||||
logger.log: Vsync request
|
||||
- led:
|
||||
id: lv_led
|
||||
color: 0x00FF00
|
||||
@@ -1051,7 +1190,7 @@ lvgl:
|
||||
- ticks:
|
||||
width: 1
|
||||
count: 61
|
||||
length: 20%
|
||||
length: 20
|
||||
radial_offset: 5
|
||||
color: 0xFFFFFF
|
||||
major:
|
||||
@@ -1159,6 +1298,13 @@ image:
|
||||
type: BINARY
|
||||
transparency: chroma_key
|
||||
|
||||
- id: alert
|
||||
file: $component_dir/logo-text.svg
|
||||
type: grayscale
|
||||
resize: 100x100
|
||||
invert_alpha: true
|
||||
transparency: alpha_channel
|
||||
|
||||
color:
|
||||
- id: light_blue
|
||||
hex: "3340FF"
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
climate:
|
||||
- platform: mitsubishi_cn105
|
||||
name: "AC Test"
|
||||
uart_id: uart_bus
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart_9600_even/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart_9600_even/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
uart: !include ../../test_build_components/common/uart_9600_even/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
@@ -5,3 +5,5 @@ display:
|
||||
intensity: 3
|
||||
lambda: |-
|
||||
it.print("1234");
|
||||
static const uint8_t buf[] = {0x3f, 0x06, 0x5b, 0x4f | 0x80};
|
||||
it.set_buffer(buf, sizeof(buf));
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
esphome:
|
||||
name: test-multi-click
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms
|
||||
services:
|
||||
- service: run_all_tests
|
||||
then:
|
||||
# Prime the binary sensor with an initial OFF state.
|
||||
# trigger_on_initial_state defaults to false, so the first
|
||||
# state change from unknown won't fire callbacks.
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: false
|
||||
- delay: 50ms
|
||||
|
||||
# Test 1: Single click (ON < 50ms, OFF >= 30ms)
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: true
|
||||
- delay: 20ms
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: false
|
||||
# Wait for single click trigger (30ms) + cooldown (100ms) + margin
|
||||
- delay: 200ms
|
||||
|
||||
# Test 2: Double click (ON < 50ms, OFF < 25ms, ON < 50ms, OFF >= 25ms)
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: true
|
||||
- delay: 20ms
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: false
|
||||
- delay: 15ms
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: true
|
||||
- delay: 20ms
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: false
|
||||
# Wait for double click trigger (25ms) + cooldown (100ms) + margin
|
||||
- delay: 200ms
|
||||
|
||||
# Test 3: Long press (ON >= 80ms)
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: true
|
||||
- delay: 100ms
|
||||
- binary_sensor.template.publish:
|
||||
id: test_button
|
||||
state: false
|
||||
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
globals:
|
||||
- id: single_click_count
|
||||
type: int
|
||||
initial_value: "0"
|
||||
- id: double_click_count
|
||||
type: int
|
||||
initial_value: "0"
|
||||
- id: long_press_count
|
||||
type: int
|
||||
initial_value: "0"
|
||||
|
||||
binary_sensor:
|
||||
- platform: template
|
||||
name: "Test Button"
|
||||
id: test_button
|
||||
on_multi_click:
|
||||
# Single press
|
||||
- timing:
|
||||
- ON for at most 50ms
|
||||
- OFF for at least 30ms
|
||||
invalid_cooldown: 100ms
|
||||
then:
|
||||
- lambda: |-
|
||||
id(single_click_count) += 1;
|
||||
ESP_LOGI("multi_click_test", "SINGLE_CLICK count=%d", id(single_click_count));
|
||||
|
||||
# Double press
|
||||
- timing:
|
||||
- ON for at most 50ms
|
||||
- OFF for at most 25ms
|
||||
- ON for at most 50ms
|
||||
- OFF for at least 25ms
|
||||
invalid_cooldown: 100ms
|
||||
then:
|
||||
- lambda: |-
|
||||
id(double_click_count) += 1;
|
||||
ESP_LOGI("multi_click_test", "DOUBLE_CLICK count=%d", id(double_click_count));
|
||||
|
||||
# Long press
|
||||
- timing:
|
||||
- ON for at least 80ms
|
||||
invalid_cooldown: 100ms
|
||||
then:
|
||||
- lambda: |-
|
||||
id(long_press_count) += 1;
|
||||
ESP_LOGI("multi_click_test", "LONG_PRESS count=%d", id(long_press_count));
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Integration test for on_multi_click binary sensor automation.
|
||||
|
||||
Tests that on_multi_click correctly triggers for single click, double click,
|
||||
and long press patterns using a template binary sensor with timing
|
||||
orchestrated entirely in YAML.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multi_click_trigger(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test that on_multi_click triggers for single, double, and long press patterns."""
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
single_click_pattern = re.compile(r"SINGLE_CLICK count=(\d+)")
|
||||
double_click_pattern = re.compile(r"DOUBLE_CLICK count=(\d+)")
|
||||
long_press_pattern = re.compile(r"LONG_PRESS count=(\d+)")
|
||||
|
||||
single_click_future: asyncio.Future[int] = loop.create_future()
|
||||
double_click_future: asyncio.Future[int] = loop.create_future()
|
||||
long_press_future: asyncio.Future[int] = loop.create_future()
|
||||
|
||||
def check_output(line: str) -> None:
|
||||
"""Check log output for multi-click trigger messages."""
|
||||
if m := single_click_pattern.search(line):
|
||||
if not single_click_future.done():
|
||||
single_click_future.set_result(int(m.group(1)))
|
||||
elif m := double_click_pattern.search(line):
|
||||
if not double_click_future.done():
|
||||
double_click_future.set_result(int(m.group(1)))
|
||||
elif (m := long_press_pattern.search(line)) and not long_press_future.done():
|
||||
long_press_future.set_result(int(m.group(1)))
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=check_output),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
_entities, services = await client.list_entities_services()
|
||||
|
||||
test_service = next((s for s in services if s.name == "run_all_tests"), None)
|
||||
assert test_service is not None, "run_all_tests service not found"
|
||||
|
||||
# Kick off the entire test sequence (runs in YAML with delays)
|
||||
await client.execute_service(test_service, {})
|
||||
|
||||
# Wait for all three triggers
|
||||
try:
|
||||
count = await asyncio.wait_for(single_click_future, timeout=5.0)
|
||||
except TimeoutError:
|
||||
pytest.fail(
|
||||
"Timeout waiting for SINGLE_CLICK - on_multi_click did not trigger."
|
||||
)
|
||||
assert count == 1, f"Expected single click count=1, got {count}"
|
||||
|
||||
try:
|
||||
count = await asyncio.wait_for(double_click_future, timeout=5.0)
|
||||
except TimeoutError:
|
||||
pytest.fail(
|
||||
"Timeout waiting for DOUBLE_CLICK - on_multi_click did not trigger."
|
||||
)
|
||||
assert count == 1, f"Expected double click count=1, got {count}"
|
||||
|
||||
try:
|
||||
count = await asyncio.wait_for(long_press_future, timeout=5.0)
|
||||
except TimeoutError:
|
||||
pytest.fail(
|
||||
"Timeout waiting for LONG_PRESS - on_multi_click did not trigger."
|
||||
)
|
||||
assert count == 1, f"Expected long press count=1, got {count}"
|
||||
@@ -73,9 +73,16 @@ async def test_uart_mock_ld2410(
|
||||
],
|
||||
)
|
||||
|
||||
# Signal when we see recovery frame values
|
||||
# Signal when we see ALL recovery frame 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["moving_distance"]
|
||||
lambda: (
|
||||
pytest.approx(50.0) in collector.sensor_states["moving_distance"]
|
||||
and pytest.approx(75.0) in collector.sensor_states["still_distance"]
|
||||
and pytest.approx(100.0) in collector.sensor_states["moving_energy"]
|
||||
and pytest.approx(80.0) in collector.sensor_states["still_energy"]
|
||||
and pytest.approx(127.0) in collector.sensor_states["detection_distance"]
|
||||
)
|
||||
)
|
||||
|
||||
async with (
|
||||
|
||||
@@ -83,11 +83,18 @@ async def test_uart_mock_ld2450(
|
||||
],
|
||||
)
|
||||
|
||||
# Signal when we see recovery frame values (target 1 distance ≈ 500mm)
|
||||
# Signal when we see all recovery frame values
|
||||
# Must wait for ALL values to avoid race where some arrive after the waiter fires
|
||||
recovery_received = collector.add_waiter(
|
||||
lambda: (
|
||||
pytest.approx(500.0, abs=1.0)
|
||||
in collector.sensor_states["target_1_distance"]
|
||||
and pytest.approx(300.0) in collector.sensor_states["target_1_x"]
|
||||
and pytest.approx(400.0) in collector.sensor_states["target_1_y"]
|
||||
and pytest.approx(30.0) in collector.sensor_states["target_1_speed"]
|
||||
and pytest.approx(1.0) in collector.sensor_states["target_count"]
|
||||
and pytest.approx(1.0) in collector.sensor_states["moving_target_count"]
|
||||
and pytest.approx(0.0) in collector.sensor_states["still_target_count"]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Tests for ESP8266 component."""
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp8266 import lambdas_use_scanf_float
|
||||
from esphome.core import Lambda
|
||||
from esphome.types import ConfigType
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("src", "expected"),
|
||||
[
|
||||
# Basic float formats
|
||||
('sscanf(buf, "%f", &v)', True),
|
||||
('sscanf(buf, "%F", &v)', True),
|
||||
('sscanf(buf, "%e", &v)', True),
|
||||
('sscanf(buf, "%E", &v)', True),
|
||||
('sscanf(buf, "%g", &v)', True),
|
||||
('sscanf(buf, "%G", &v)', True),
|
||||
('sscanf(buf, "%a", &v)', True),
|
||||
('sscanf(buf, "%A", &v)', True),
|
||||
# With modifiers
|
||||
('sscanf(buf, "%lf", &v)', True),
|
||||
('sscanf(buf, "%Lf", &v)', True),
|
||||
('sscanf(buf, "%8lf", &v)', True),
|
||||
('sscanf(buf, "%*f")', True),
|
||||
('sscanf(buf, "%.2f", &v)', True),
|
||||
# Mixed formats
|
||||
('sscanf(buf, "%d,%f", &a, &b)', True),
|
||||
# fscanf and std::sscanf
|
||||
('fscanf(fp, "%f", &v)', True),
|
||||
('std::sscanf(buf, "%f", &v)', True),
|
||||
# Multi-line
|
||||
('sscanf(buf,\n"%f", &v)', True),
|
||||
# No float format
|
||||
('sscanf(buf, "%d", &v)', False),
|
||||
('sscanf(buf, "%s", s)', False),
|
||||
# printf not scanf
|
||||
('printf("%f", val)', False),
|
||||
# %f in a different statement after scanf
|
||||
('sscanf(buf, "%d", &x); printf("%f", val);', False),
|
||||
# scanf %f in comment only
|
||||
('// sscanf(buf, "%f", &v)\nsscanf(buf, "%d", &x)', False),
|
||||
('/* sscanf(buf, "%f") */\nsscanf(buf, "%d", &x)', False),
|
||||
],
|
||||
)
|
||||
def test_lambdas_use_scanf_float(src: str, expected: bool) -> None:
|
||||
"""Test scanf float detection in lambda source."""
|
||||
config: ConfigType = {"test": [Lambda(src)]}
|
||||
assert lambdas_use_scanf_float(config) is expected
|
||||
|
||||
|
||||
def test_lambdas_use_scanf_float_no_lambdas() -> None:
|
||||
"""Test with config containing no lambdas."""
|
||||
config: ConfigType = {"key": "value", "list": [1, 2]}
|
||||
assert lambdas_use_scanf_float(config) is False
|
||||
|
||||
|
||||
def test_lambdas_use_scanf_float_nested() -> None:
|
||||
"""Test detection in deeply nested config."""
|
||||
config: ConfigType = {"a": {"b": {"c": [Lambda('sscanf(buf, "%f", &v)')]}}}
|
||||
assert lambdas_use_scanf_float(config) is True
|
||||
@@ -248,6 +248,24 @@ def test_area_id_hash_collision(
|
||||
)
|
||||
|
||||
|
||||
def test_area_singular_hash_collision(
|
||||
yaml_file: Callable[[str], str], capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""Test that area hash collisions between singular area: and areas: list are detected."""
|
||||
result = load_config_from_fixture(
|
||||
yaml_file, "area_singular_hash_collision.yaml", FIXTURES_DIR
|
||||
)
|
||||
assert result is None
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert (
|
||||
"Area ID 'd6ka' with hash 3082558663 collides with existing area ID 'test_2258'"
|
||||
in captured.out
|
||||
)
|
||||
# Error path should point to 'areas' (where the colliding entry is), not 'area'
|
||||
assert "areas" in captured.out
|
||||
|
||||
|
||||
def test_device_duplicate_id(
|
||||
yaml_file: Callable[[str], str], capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
esphome:
|
||||
name: test
|
||||
area:
|
||||
id: test_2258
|
||||
name: "Area 1"
|
||||
areas:
|
||||
- id: d6ka
|
||||
name: "Area 2"
|
||||
|
||||
host:
|
||||
@@ -5,7 +5,13 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.automation import has_non_synchronous_actions
|
||||
from esphome.automation import (
|
||||
TriggerForwarder,
|
||||
TriggerOnFalseForwarder,
|
||||
TriggerOnTrueForwarder,
|
||||
has_non_synchronous_actions,
|
||||
)
|
||||
from esphome.cpp_generator import MockObj, RawExpression
|
||||
from esphome.util import RegistryEntry
|
||||
|
||||
|
||||
@@ -175,3 +181,76 @@ def test_has_non_synchronous_actions_dict_input(
|
||||
"""Direct dict input (single action)."""
|
||||
assert has_non_synchronous_actions({"delay": "1s"}) is True
|
||||
assert has_non_synchronous_actions({"logger.log": "hello"}) is False
|
||||
|
||||
|
||||
def _build_forwarder(
|
||||
automation_name: str,
|
||||
args: list[tuple[str, str]],
|
||||
forwarder: MockObj | None = None,
|
||||
) -> str:
|
||||
"""Build a trigger forwarder expression the same way build_callback_automation does.
|
||||
|
||||
Mirrors the forwarder selection logic in automation.build_callback_automation.
|
||||
"""
|
||||
import esphome.codegen as cg
|
||||
|
||||
obj = MockObj(automation_name, "->")
|
||||
if forwarder is None:
|
||||
arg_types = [RawExpression(t) for t, _ in args]
|
||||
templ = (
|
||||
cg.TemplateArguments(*arg_types) if arg_types else cg.TemplateArguments()
|
||||
)
|
||||
forwarder = TriggerForwarder.template(templ)
|
||||
return f"{forwarder}{{{obj}}}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_no_args() -> None:
|
||||
"""Button on_press: TriggerForwarder<> with no args."""
|
||||
result = _build_forwarder("auto_1", [])
|
||||
assert result == "TriggerForwarder<>{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_single_float_arg() -> None:
|
||||
"""Sensor on_value: TriggerForwarder<float>."""
|
||||
result = _build_forwarder("auto_1", [("float", "x")])
|
||||
assert result == "TriggerForwarder<float>{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_single_bool_arg() -> None:
|
||||
"""Switch on_state: TriggerForwarder<bool>."""
|
||||
result = _build_forwarder("auto_1", [("bool", "x")])
|
||||
assert result == "TriggerForwarder<bool>{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_on_true() -> None:
|
||||
"""Binary_sensor on_press / switch on_turn_on: TriggerOnTrueForwarder."""
|
||||
result = _build_forwarder("auto_1", [], forwarder=TriggerOnTrueForwarder)
|
||||
assert result == "TriggerOnTrueForwarder{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_on_false() -> None:
|
||||
"""Binary_sensor on_release / switch on_turn_off: TriggerOnFalseForwarder."""
|
||||
result = _build_forwarder("auto_1", [], forwarder=TriggerOnFalseForwarder)
|
||||
assert result == "TriggerOnFalseForwarder{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_multiple_args() -> None:
|
||||
"""Binary_sensor on_state_change: TriggerForwarder with two args."""
|
||||
result = _build_forwarder(
|
||||
"auto_1",
|
||||
[("optional<bool>", "x_previous"), ("optional<bool>", "x")],
|
||||
)
|
||||
assert result == "TriggerForwarder<optional<bool>, optional<bool>>{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_string_arg() -> None:
|
||||
"""Text_sensor on_value: TriggerForwarder<std::string>."""
|
||||
result = _build_forwarder("auto_1", [("std::string", "x")])
|
||||
assert result == "TriggerForwarder<std::string>{auto_1}"
|
||||
|
||||
|
||||
def test_trigger_forwarder_custom_type() -> None:
|
||||
"""Custom forwarder type passed directly."""
|
||||
custom = MockObj("MyForwarder", "")
|
||||
result = _build_forwarder("auto_1", [], forwarder=custom)
|
||||
assert result == "MyForwarder{auto_1}"
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import logging
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import const, cpp_helpers as ch
|
||||
from esphome.cpp_helpers import ComponentSourcePool, register_component_source
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -23,7 +25,7 @@ async def test_register_component(monkeypatch):
|
||||
app_mock = Mock(register_component_=Mock(return_value=var))
|
||||
monkeypatch.setattr(ch, "App", app_mock)
|
||||
|
||||
core_mock = Mock(component_ids=["foo.bar"])
|
||||
core_mock = Mock(component_ids=["foo.bar"], data={})
|
||||
monkeypatch.setattr(ch, "CORE", core_mock)
|
||||
|
||||
add_mock = Mock()
|
||||
@@ -59,7 +61,7 @@ async def test_register_component__with_setup_priority(monkeypatch):
|
||||
app_mock = Mock(register_component_=Mock(return_value=var))
|
||||
monkeypatch.setattr(ch, "App", app_mock)
|
||||
|
||||
core_mock = Mock(component_ids=["foo.bar"])
|
||||
core_mock = Mock(component_ids=["foo.bar"], data={})
|
||||
monkeypatch.setattr(ch, "CORE", core_mock)
|
||||
|
||||
add_mock = Mock()
|
||||
@@ -78,3 +80,88 @@ async def test_register_component__with_setup_priority(monkeypatch):
|
||||
assert add_mock.call_count == 4
|
||||
app_mock.register_component_.assert_called_with(var)
|
||||
assert core_mock.component_ids == []
|
||||
|
||||
|
||||
def test_register_component_source_empty_name(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(ch, "CORE", Mock(data={}))
|
||||
assert register_component_source("") == 0
|
||||
|
||||
|
||||
def test_register_component_source_deduplicates(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(ch, "CORE", Mock(data={}))
|
||||
idx1 = register_component_source("wifi")
|
||||
idx2 = register_component_source("api")
|
||||
idx3 = register_component_source("wifi")
|
||||
assert idx1 == 1
|
||||
assert idx2 == 2
|
||||
assert idx3 == 1 # deduplicated
|
||||
|
||||
|
||||
def test_generate_source_table_code_empty() -> None:
|
||||
from esphome.cpp_helpers import _generate_source_table_code
|
||||
|
||||
assert _generate_source_table_code("TBL", "lookup", {}) == ""
|
||||
|
||||
|
||||
def test_generate_source_table_code_non_empty() -> None:
|
||||
from esphome.cpp_helpers import _generate_source_table_code
|
||||
|
||||
code = _generate_source_table_code("TBL", "lookup", {"wifi": 1, "api": 2})
|
||||
assert "PROGMEM" in code
|
||||
assert "wifi" in code
|
||||
assert "api" in code
|
||||
assert "lookup" in code
|
||||
assert "index == 0" in code
|
||||
assert "progmem_read_ptr" in code
|
||||
assert "index > 2" in code
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_component_source_table_empty_pool(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Test that _generate_component_source_table does nothing with an empty pool."""
|
||||
from esphome.cpp_helpers import _generate_component_source_table
|
||||
|
||||
monkeypatch.setattr(ch, "CORE", Mock(data={}))
|
||||
add_global_mock = Mock()
|
||||
monkeypatch.setattr(ch, "add_global", add_global_mock)
|
||||
await _generate_component_source_table()
|
||||
add_global_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_register_component_source_overflow_warns(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
# Pre-fill pool to max
|
||||
pool = ComponentSourcePool(
|
||||
sources={f"comp_{i}": i + 1 for i in range(0xFF)},
|
||||
table_registered=True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ch, "CORE", Mock(data={ch._COMPONENT_SOURCE_DOMAIN: pool}, testing_mode=False)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
idx = register_component_source("overflow_component")
|
||||
assert idx == 0
|
||||
assert "Too many unique component source names" in caplog.text
|
||||
assert "overflow_component" in caplog.text
|
||||
|
||||
|
||||
def test_register_component_source_overflow_suppressed_in_testing_mode(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
# Pre-fill pool to max
|
||||
pool = ComponentSourcePool(
|
||||
sources={f"comp_{i}": i + 1 for i in range(0xFF)},
|
||||
table_registered=True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ch, "CORE", Mock(data={ch._COMPONENT_SOURCE_DOMAIN: pool}, testing_mode=True)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
idx = register_component_source("overflow_component")
|
||||
assert idx == 0
|
||||
assert "Too many unique component source names" not in caplog.text
|
||||
|
||||
@@ -990,6 +990,47 @@ def test_clean_all_ignores_empty_env_vars(
|
||||
assert marker.exists()
|
||||
|
||||
|
||||
@patch("esphome.writer.CORE")
|
||||
def test_clean_all_no_args_with_esphome_dir(
|
||||
mock_core: MagicMock,
|
||||
tmp_path: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test clean_all with no args cleans .esphome in cwd."""
|
||||
esphome_dir = tmp_path / ".esphome"
|
||||
esphome_dir.mkdir()
|
||||
(esphome_dir / "dummy.txt").write_text("x")
|
||||
|
||||
from esphome.writer import clean_all
|
||||
|
||||
with (
|
||||
caplog.at_level("INFO"),
|
||||
patch("esphome.writer.Path.cwd", return_value=tmp_path),
|
||||
):
|
||||
clean_all([])
|
||||
|
||||
assert esphome_dir.exists()
|
||||
assert not (esphome_dir / "dummy.txt").exists()
|
||||
|
||||
|
||||
@patch("esphome.writer.CORE")
|
||||
def test_clean_all_no_args_no_esphome_dir(
|
||||
mock_core: MagicMock,
|
||||
tmp_path: Path,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test clean_all with no args and no .esphome dir warns."""
|
||||
from esphome.writer import clean_all
|
||||
|
||||
with (
|
||||
caplog.at_level("WARNING"),
|
||||
patch("esphome.writer.Path.cwd", return_value=tmp_path),
|
||||
):
|
||||
clean_all([])
|
||||
|
||||
assert "No configuration files specified" in caplog.text
|
||||
|
||||
|
||||
@patch("esphome.writer.CORE")
|
||||
def test_clean_all(
|
||||
mock_core: MagicMock,
|
||||
|
||||
Reference in New Issue
Block a user