Merge remote-tracking branch 'upstream/dev' into enhancement/ethernet-spi-interface

# Conflicts:
#	esphome/components/ethernet/__init__.py
#	esphome/components/ethernet/ethernet_component.cpp
#	esphome/components/ethernet/ethernet_component.h
This commit is contained in:
J. Nick Koston
2026-04-04 00:46:46 -10:00
2232 changed files with 92831 additions and 38195 deletions
+2
View File
@@ -0,0 +1,2 @@
/.esphome/
/secrets.yaml
@@ -0,0 +1,21 @@
import esphome.codegen as cg
from tests.testing_helpers import ComponentManifestOverride
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
@@ -0,0 +1,306 @@
#include "esphome/core/defines.h"
#ifdef USE_API_NOISE
#include <benchmark/benchmark.h>
#include <cstring>
#include <memory>
#include "noise/protocol.h"
namespace esphome::api::benchmarks {
static constexpr int kInnerIterations = 2000;
// Helper to create and initialize a NoiseCipherState with ChaChaPoly.
// Returns nullptr on failure.
static NoiseCipherState *create_cipher() {
NoiseCipherState *cipher = nullptr;
int err = noise_cipherstate_new_by_id(&cipher, NOISE_CIPHER_CHACHAPOLY);
if (err != NOISE_ERROR_NONE || cipher == nullptr)
return nullptr;
// Initialize with a dummy 32-byte key (same pattern as handshake split produces)
uint8_t key[32];
memset(key, 0xAB, sizeof(key));
err = noise_cipherstate_init_key(cipher, key, sizeof(key));
if (err != NOISE_ERROR_NONE) {
noise_cipherstate_free(cipher);
return nullptr;
}
return cipher;
}
// Benchmark helper matching the exact pattern from
// APINoiseFrameHelper::write_protobuf_messages:
// - noise_buffer_init + noise_buffer_set_inout (same as production)
// - No explicit set_nonce (production relies on internal nonce increment)
// - Error checking on encrypt return
static void noise_encrypt_bench(benchmark::State &state, size_t plaintext_size) {
NoiseCipherState *cipher = create_cipher();
if (cipher == nullptr) {
state.SkipWithError("Failed to create cipher state");
return;
}
size_t mac_len = noise_cipherstate_get_mac_length(cipher);
size_t buf_capacity = plaintext_size + mac_len;
auto buffer = std::make_unique<uint8_t[]>(buf_capacity);
memset(buffer.get(), 0x42, plaintext_size);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
// Match production: init buffer, set inout, encrypt
NoiseBuffer mbuf;
noise_buffer_init(mbuf);
noise_buffer_set_inout(mbuf, buffer.get(), plaintext_size, buf_capacity);
int err = noise_cipherstate_encrypt(cipher, &mbuf);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("noise_cipherstate_encrypt failed");
noise_cipherstate_free(cipher);
return;
}
}
benchmark::DoNotOptimize(buffer[0]);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
noise_cipherstate_free(cipher);
}
// --- Encrypt a typical sensor state message (small payload ~14 bytes) ---
// This is the most common message encrypted on every sensor update.
// 4 bytes type+len header + ~10 bytes payload.
static void NoiseEncrypt_SmallMessage(benchmark::State &state) { noise_encrypt_bench(state, 14); }
BENCHMARK(NoiseEncrypt_SmallMessage);
// --- Encrypt a medium message (~128 bytes, typical for LightStateResponse) ---
static void NoiseEncrypt_MediumMessage(benchmark::State &state) { noise_encrypt_bench(state, 128); }
BENCHMARK(NoiseEncrypt_MediumMessage);
// --- Encrypt a large message (~1024 bytes, typical for DeviceInfoResponse) ---
static void NoiseEncrypt_LargeMessage(benchmark::State &state) { noise_encrypt_bench(state, 1024); }
BENCHMARK(NoiseEncrypt_LargeMessage);
// Benchmark helper matching the exact pattern from
// APINoiseFrameHelper::read_packet:
// - noise_buffer_init + noise_buffer_set_inout with capacity == size (decrypt shrinks)
// - Error checking on decrypt return
//
// Pre-encrypts kInnerIterations messages with sequential nonces before the
// timed loop. Each outer iteration re-inits the decrypt key to reset the
// nonce back to 0, then decrypts all pre-encrypted messages in sequence.
// The init_key cost is amortized over kInnerIterations decrypts.
static void noise_decrypt_bench(benchmark::State &state, size_t plaintext_size) {
NoiseCipherState *encrypt_cipher = create_cipher();
NoiseCipherState *decrypt_cipher = create_cipher();
if (encrypt_cipher == nullptr || decrypt_cipher == nullptr) {
state.SkipWithError("Failed to create cipher state");
if (encrypt_cipher)
noise_cipherstate_free(encrypt_cipher);
if (decrypt_cipher)
noise_cipherstate_free(decrypt_cipher);
return;
}
size_t mac_len = noise_cipherstate_get_mac_length(encrypt_cipher);
size_t encrypted_size = plaintext_size + mac_len;
// Pre-encrypt kInnerIterations messages with sequential nonces (0..N-1).
auto ciphertexts = std::make_unique<uint8_t[]>(encrypted_size * kInnerIterations);
for (int i = 0; i < kInnerIterations; i++) {
uint8_t *ct = ciphertexts.get() + i * encrypted_size;
memset(ct, 0x42, plaintext_size);
NoiseBuffer enc_buf;
noise_buffer_init(enc_buf);
noise_buffer_set_inout(enc_buf, ct, plaintext_size, encrypted_size);
int err = noise_cipherstate_encrypt(encrypt_cipher, &enc_buf);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Pre-encrypt failed");
noise_cipherstate_free(encrypt_cipher);
noise_cipherstate_free(decrypt_cipher);
return;
}
}
// Working buffer — decrypt modifies in place
auto buffer = std::make_unique<uint8_t[]>(encrypted_size);
static constexpr uint8_t KEY[32] = {0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB};
for (auto _ : state) {
// Reset nonce to 0 by re-initing the key (amortized over kInnerIterations)
noise_cipherstate_init_key(decrypt_cipher, KEY, sizeof(KEY));
for (int i = 0; i < kInnerIterations; i++) {
// Copy ciphertext into working buffer (decrypt modifies in place)
memcpy(buffer.get(), ciphertexts.get() + i * encrypted_size, encrypted_size);
// Decrypt matching production pattern
NoiseBuffer mbuf;
noise_buffer_init(mbuf);
noise_buffer_set_inout(mbuf, buffer.get(), encrypted_size, encrypted_size);
int err = noise_cipherstate_decrypt(decrypt_cipher, &mbuf);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("noise_cipherstate_decrypt failed");
noise_cipherstate_free(encrypt_cipher);
noise_cipherstate_free(decrypt_cipher);
return;
}
}
benchmark::DoNotOptimize(buffer[0]);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
noise_cipherstate_free(encrypt_cipher);
noise_cipherstate_free(decrypt_cipher);
}
// --- Decrypt benchmarks (matching read_packet path) ---
static void NoiseDecrypt_SmallMessage(benchmark::State &state) { noise_decrypt_bench(state, 14); }
BENCHMARK(NoiseDecrypt_SmallMessage);
static void NoiseDecrypt_MediumMessage(benchmark::State &state) { noise_decrypt_bench(state, 128); }
BENCHMARK(NoiseDecrypt_MediumMessage);
static void NoiseDecrypt_LargeMessage(benchmark::State &state) { noise_decrypt_bench(state, 1024); }
BENCHMARK(NoiseDecrypt_LargeMessage);
// --- Full Noise_NNpsk0 handshake benchmark ---
// Measures the complete handshake between initiator and responder:
// - Create handshake states for both sides
// - Set PSK and prologue
// - Exchange messages (initiator write -> responder read -> responder write -> initiator read)
// - Split to get cipher states
// This is dominated by Curve25519 DH operations (expensive on ESP8266).
// No inner iterations — each handshake is already expensive enough.
static void NoiseHandshake_Full(benchmark::State &state) {
// Matching ESPHome's protocol: Noise_NNpsk0_25519_ChaChaPoly_SHA256
NoiseProtocolId nid;
memset(&nid, 0, sizeof(nid));
nid.pattern_id = NOISE_PATTERN_NN;
nid.cipher_id = NOISE_CIPHER_CHACHAPOLY;
nid.dh_id = NOISE_DH_CURVE25519;
nid.prefix_id = NOISE_PREFIX_STANDARD;
nid.hybrid_id = NOISE_DH_NONE;
nid.hash_id = NOISE_HASH_SHA256;
nid.modifier_ids[0] = NOISE_MODIFIER_PSK0;
// Dummy PSK (32 bytes) and prologue matching production setup
static constexpr uint8_t PSK[32] = {0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB,
0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB, 0xAB};
static constexpr uint8_t PROLOGUE[] = "NoESPHome";
// Message buffer for handshake exchange (max handshake message ~96 bytes)
uint8_t msg_buf[128];
for (auto _ : state) {
NoiseHandshakeState *initiator = nullptr;
NoiseHandshakeState *responder = nullptr;
NoiseCipherState *init_send = nullptr, *init_recv = nullptr;
NoiseCipherState *resp_send = nullptr, *resp_recv = nullptr;
int err;
// Create both handshake states
err = noise_handshakestate_new_by_id(&initiator, &nid, NOISE_ROLE_INITIATOR);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Failed to create initiator");
return;
}
err = noise_handshakestate_new_by_id(&responder, &nid, NOISE_ROLE_RESPONDER);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Failed to create responder");
noise_handshakestate_free(initiator);
return;
}
// Set PSK and prologue on both sides
noise_handshakestate_set_pre_shared_key(initiator, PSK, sizeof(PSK));
noise_handshakestate_set_pre_shared_key(responder, PSK, sizeof(PSK));
noise_handshakestate_set_prologue(initiator, PROLOGUE, sizeof(PROLOGUE) - 1);
noise_handshakestate_set_prologue(responder, PROLOGUE, sizeof(PROLOGUE) - 1);
noise_handshakestate_start(initiator);
noise_handshakestate_start(responder);
// Message 1: Initiator -> Responder
NoiseBuffer write_buf, read_buf;
noise_buffer_set_output(write_buf, msg_buf, sizeof(msg_buf));
err = noise_handshakestate_write_message(initiator, &write_buf, nullptr);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Initiator write_message failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
return;
}
noise_buffer_set_input(read_buf, msg_buf, write_buf.size);
err = noise_handshakestate_read_message(responder, &read_buf, nullptr);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Responder read_message failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
return;
}
// Message 2: Responder -> Initiator
noise_buffer_set_output(write_buf, msg_buf, sizeof(msg_buf));
err = noise_handshakestate_write_message(responder, &write_buf, nullptr);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Responder write_message failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
return;
}
noise_buffer_set_input(read_buf, msg_buf, write_buf.size);
err = noise_handshakestate_read_message(initiator, &read_buf, nullptr);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Initiator read_message failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
return;
}
// Split to get cipher states
err = noise_handshakestate_split(initiator, &init_send, &init_recv);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Initiator split failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
return;
}
err = noise_handshakestate_split(responder, &resp_send, &resp_recv);
if (err != NOISE_ERROR_NONE) {
state.SkipWithError("Responder split failed");
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
noise_cipherstate_free(init_send);
noise_cipherstate_free(init_recv);
return;
}
benchmark::DoNotOptimize(init_send);
// Cleanup
noise_handshakestate_free(initiator);
noise_handshakestate_free(responder);
noise_cipherstate_free(init_send);
noise_cipherstate_free(init_recv);
noise_cipherstate_free(resp_send);
noise_cipherstate_free(resp_recv);
}
}
BENCHMARK(NoiseHandshake_Full);
} // namespace esphome::api::benchmarks
#endif // USE_API_NOISE
@@ -0,0 +1,108 @@
#include "esphome/core/defines.h"
#ifdef USE_API_PLAINTEXT
#include <benchmark/benchmark.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"
namespace esphome::api::benchmarks {
static constexpr int kInnerIterations = 2000;
// Helper to create a TCP loopback connection with an APIPlaintextFrameHelper
// on the write end. Returns the helper and the read-side fd.
static std::pair<std::unique_ptr<APIPlaintextFrameHelper>, int> create_plaintext_helper() {
auto [sock, read_fd] = create_tcp_loopback();
auto helper = std::make_unique<APIPlaintextFrameHelper>(std::move(sock));
helper->init();
return {std::move(helper), read_fd};
}
// --- Write a single SensorStateResponse through plaintext framing ---
// Measures the full write path: header construction, varint encoding,
// iovec assembly, and socket write.
static void PlaintextFrame_WriteSensorState(benchmark::State &state) {
auto [helper, read_fd] = create_plaintext_helper();
uint8_t padding = helper->frame_header_padding();
// Pre-init buffer to typical TCP MSS size to avoid benchmarking
// heap allocation — in real use the buffer is reused across writes.
APIBuffer buffer;
buffer.reserve(1460);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
buffer.clear();
SensorStateResponse msg;
msg.key = 0x12345678;
msg.state = 23.5f;
msg.missing_state = false;
uint32_t size = msg.calculate_size();
buffer.resize(padding + size);
ProtoWriteBuffer writer(&buffer, padding);
msg.encode(writer);
helper->write_protobuf_packet(SensorStateResponse::MESSAGE_TYPE, writer);
}
drain_socket(read_fd);
benchmark::DoNotOptimize(helper.get());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
::close(read_fd);
}
BENCHMARK(PlaintextFrame_WriteSensorState);
// --- Write a batch of 5 SensorStateResponses in one call ---
// Measures batched write: multiple messages assembled into one writev.
static void PlaintextFrame_WriteBatch5(benchmark::State &state) {
auto [helper, read_fd] = create_plaintext_helper();
uint8_t padding = helper->frame_header_padding();
uint8_t footer = helper->frame_footer_size();
// Pre-init buffer to typical TCP MSS size to avoid benchmarking
// heap allocation — in real use the buffer is reused across writes.
APIBuffer buffer;
buffer.reserve(1460);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
buffer.clear();
MessageInfo messages[5] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
for (int j = 0; j < 5; j++) {
uint16_t offset = buffer.size();
SensorStateResponse msg;
msg.key = static_cast<uint32_t>(j);
msg.state = 23.5f + static_cast<float>(j);
msg.missing_state = false;
uint32_t size = msg.calculate_size();
buffer.resize(offset + padding + size + footer);
ProtoWriteBuffer writer(&buffer, offset + padding);
msg.encode(writer);
messages[j] = MessageInfo(SensorStateResponse::MESSAGE_TYPE, offset, size);
}
helper->write_protobuf_messages(ProtoWriteBuffer(&buffer, 0), std::span<const MessageInfo>(messages, 5));
}
drain_socket(read_fd);
benchmark::DoNotOptimize(helper.get());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
::close(read_fd);
}
BENCHMARK(PlaintextFrame_WriteBatch5);
} // namespace esphome::api::benchmarks
#endif // USE_API_PLAINTEXT
@@ -0,0 +1,113 @@
#include <benchmark/benchmark.h>
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_buffer.h"
namespace esphome::api::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
// 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();
buffer.resize(size);
ProtoWriteBuffer writer(&buffer, 0);
msg.encode(writer);
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) {
HelloRequest source;
source.client_info = StringRef::from_lit("aioesphomeapi");
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) {
for (int i = 0; i < kInnerIterations; i++) {
HelloRequest msg;
escape(&msg);
msg.decode(data, size);
escape(&msg);
}
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Decode_HelloRequest);
// --- SwitchCommandRequest decode (simple command) ---
static void Decode_SwitchCommandRequest(benchmark::State &state) {
SwitchCommandRequest source;
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) {
for (int i = 0; i < kInnerIterations; i++) {
SwitchCommandRequest msg;
escape(&msg);
msg.decode(data, size);
escape(&msg);
}
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Decode_SwitchCommandRequest);
// --- LightCommandRequest decode (complex command with many fields) ---
static void Decode_LightCommandRequest(benchmark::State &state) {
LightCommandRequest source;
source.key = 0x11223344;
source.has_state = true;
source.state = true;
source.has_brightness = true;
source.brightness = 0.8f;
source.has_rgb = true;
source.red = 1.0f;
source.green = 0.5f;
source.blue = 0.2f;
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) {
for (int i = 0; i < kInnerIterations; i++) {
LightCommandRequest msg;
escape(&msg);
msg.decode(data, size);
escape(&msg);
}
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Decode_LightCommandRequest);
} // namespace esphome::api::benchmarks
@@ -0,0 +1,387 @@
#include <benchmark/benchmark.h>
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_buffer.h"
namespace esphome::api::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
// --- SensorStateResponse (highest frequency message) ---
static void Encode_SensorStateResponse(benchmark::State &state) {
APIBuffer buffer;
SensorStateResponse msg;
msg.key = 0x12345678;
msg.state = 23.5f;
msg.missing_state = false;
uint32_t size = msg.calculate_size();
buffer.resize(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_SensorStateResponse);
static void CalculateSize_SensorStateResponse(benchmark::State &state) {
SensorStateResponse msg;
msg.key = 0x12345678;
msg.state = 23.5f;
msg.missing_state = false;
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_SensorStateResponse);
// Steady state: buffer already allocated from previous iteration
static void CalcAndEncode_SensorStateResponse(benchmark::State &state) {
APIBuffer buffer;
SensorStateResponse msg;
msg.key = 0x12345678;
msg.state = 23.5f;
msg.missing_state = false;
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_SensorStateResponse);
// Cold path: fresh buffer each iteration (measures heap allocation cost).
// Inner loop still needed to amortize CodSpeed instrumentation overhead.
// Each inner iteration creates a fresh buffer, so this measures
// alloc+calc+encode per item.
static void CalcAndEncode_SensorStateResponse_Fresh(benchmark::State &state) {
SensorStateResponse msg;
msg.key = 0x12345678;
msg.state = 23.5f;
msg.missing_state = false;
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_SensorStateResponse_Fresh);
// --- BinarySensorStateResponse ---
static void Encode_BinarySensorStateResponse(benchmark::State &state) {
APIBuffer buffer;
BinarySensorStateResponse msg;
msg.key = 0xAABBCCDD;
msg.state = true;
msg.missing_state = false;
uint32_t size = msg.calculate_size();
buffer.resize(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_BinarySensorStateResponse);
// --- HelloResponse (string fields) ---
static void Encode_HelloResponse(benchmark::State &state) {
APIBuffer buffer;
HelloResponse msg;
msg.api_version_major = 1;
msg.api_version_minor = 10;
msg.server_info = StringRef::from_lit("esphome v2026.3.0");
msg.name = StringRef::from_lit("living-room-sensor");
uint32_t size = msg.calculate_size();
buffer.resize(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_HelloResponse);
// --- LightStateResponse (complex multi-field message) ---
static void Encode_LightStateResponse(benchmark::State &state) {
APIBuffer buffer;
LightStateResponse msg;
msg.key = 0x11223344;
msg.state = true;
msg.brightness = 0.8f;
msg.color_mode = enums::COLOR_MODE_RGB_WHITE;
msg.color_brightness = 1.0f;
msg.red = 1.0f;
msg.green = 0.5f;
msg.blue = 0.2f;
msg.white = 0.0f;
msg.color_temperature = 4000.0f;
msg.cold_white = 0.0f;
msg.warm_white = 0.0f;
msg.effect = StringRef::from_lit("rainbow");
uint32_t size = msg.calculate_size();
buffer.resize(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_LightStateResponse);
static void CalculateSize_LightStateResponse(benchmark::State &state) {
LightStateResponse msg;
msg.key = 0x11223344;
msg.state = true;
msg.brightness = 0.8f;
msg.color_mode = enums::COLOR_MODE_RGB_WHITE;
msg.color_brightness = 1.0f;
msg.red = 1.0f;
msg.green = 0.5f;
msg.blue = 0.2f;
msg.white = 0.0f;
msg.color_temperature = 4000.0f;
msg.cold_white = 0.0f;
msg.warm_white = 0.0f;
msg.effect = StringRef::from_lit("rainbow");
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_LightStateResponse);
// --- DeviceInfoResponse (nested submessages: 20 devices + 20 areas) ---
static DeviceInfoResponse make_device_info_response() {
DeviceInfoResponse msg;
msg.name = StringRef::from_lit("living-room-sensor");
msg.mac_address = StringRef::from_lit("AA:BB:CC:DD:EE:FF");
msg.esphome_version = StringRef::from_lit("2026.3.0");
msg.compilation_time = StringRef::from_lit("Mar 16 2026, 12:00:00");
msg.model = StringRef::from_lit("esp32-poe-iso");
msg.manufacturer = StringRef::from_lit("Olimex");
msg.friendly_name = StringRef::from_lit("Living Room Sensor");
#ifdef USE_DEVICES
for (uint32_t i = 0; i < ESPHOME_DEVICE_COUNT && i < 20; i++) {
msg.devices[i].device_id = i + 1;
msg.devices[i].name = StringRef::from_lit("device");
msg.devices[i].area_id = (i % 20) + 1;
}
#endif
#ifdef USE_AREAS
for (uint32_t i = 0; i < ESPHOME_AREA_COUNT && i < 20; i++) {
msg.areas[i].area_id = i + 1;
msg.areas[i].name = StringRef::from_lit("area");
}
#endif
return msg;
}
static void CalculateSize_DeviceInfoResponse(benchmark::State &state) {
auto msg = make_device_info_response();
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_DeviceInfoResponse);
static void Encode_DeviceInfoResponse(benchmark::State &state) {
auto msg = make_device_info_response();
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_DeviceInfoResponse);
// Steady state: buffer already allocated from previous iteration
static void CalcAndEncode_DeviceInfoResponse(benchmark::State &state) {
auto msg = make_device_info_response();
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_DeviceInfoResponse);
// Cold path: fresh buffer each iteration (measures heap allocation cost).
// Inner loop still needed to amortize CodSpeed instrumentation overhead.
// Each inner iteration creates a fresh buffer, so this measures
// alloc+calc+encode per item.
static void CalcAndEncode_DeviceInfoResponse_Fresh(benchmark::State &state) {
auto msg = make_device_info_response();
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_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,133 @@
#include <benchmark/benchmark.h>
#include "esphome/components/api/proto.h"
#include "esphome/components/api/api_buffer.h"
namespace esphome::api::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
// --- ProtoVarInt::parse() benchmarks ---
static void ProtoVarInt_Parse_SingleByte(benchmark::State &state) {
uint8_t buf[] = {0x42}; // value = 66
for (auto _ : state) {
ProtoVarIntResult result{};
for (int i = 0; i < kInnerIterations; i++) {
result = ProtoVarInt::parse(buf, sizeof(buf));
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ProtoVarInt_Parse_SingleByte);
static void ProtoVarInt_Parse_TwoByte(benchmark::State &state) {
uint8_t buf[] = {0x80, 0x01}; // value = 128
for (auto _ : state) {
ProtoVarIntResult result{};
for (int i = 0; i < kInnerIterations; i++) {
result = ProtoVarInt::parse(buf, sizeof(buf));
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ProtoVarInt_Parse_TwoByte);
static void ProtoVarInt_Parse_FiveByte(benchmark::State &state) {
uint8_t buf[] = {0xFF, 0xFF, 0xFF, 0xFF, 0x0F};
for (auto _ : state) {
ProtoVarIntResult result{};
for (int i = 0; i < kInnerIterations; i++) {
result = ProtoVarInt::parse(buf, sizeof(buf));
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ProtoVarInt_Parse_FiveByte);
// --- Varint encoding benchmarks ---
static void Encode_Varint_Small(benchmark::State &state) {
APIBuffer buffer;
buffer.resize(16);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ProtoWriteBuffer writer(&buffer, 0);
writer.encode_varint_raw(42);
}
benchmark::DoNotOptimize(buffer.data());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Encode_Varint_Small);
static void Encode_Varint_Large(benchmark::State &state) {
APIBuffer buffer;
buffer.resize(16);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ProtoWriteBuffer writer(&buffer, 0);
writer.encode_varint_raw(300);
}
benchmark::DoNotOptimize(buffer.data());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Encode_Varint_Large);
static void Encode_Varint_MaxUint32(benchmark::State &state) {
APIBuffer buffer;
buffer.resize(16);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ProtoWriteBuffer writer(&buffer, 0);
writer.encode_varint_raw(0xFFFFFFFF);
}
benchmark::DoNotOptimize(buffer.data());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Encode_Varint_MaxUint32);
// --- ProtoSize::varint() benchmarks ---
static void ProtoSize_Varint_Small(benchmark::State &state) {
// Use varying input to prevent constant folding.
// Values 0-127 all take 1 byte but the compiler can't prove that.
for (auto _ : state) {
uint32_t result = 0;
for (int i = 0; i < kInnerIterations; i++) {
result += ProtoSize::varint(static_cast<uint32_t>(i) & 0x7F);
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ProtoSize_Varint_Small);
static void ProtoSize_Varint_Large(benchmark::State &state) {
// Use varying input to prevent constant folding.
for (auto _ : state) {
uint32_t result = 0;
for (int i = 0; i < kInnerIterations; i++) {
result += ProtoSize::varint(0xFFFF0000 | static_cast<uint32_t>(i));
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ProtoSize_Varint_Large);
} // 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,115 @@
# Components needed for API protobuf benchmarks.
# Merged into the base config before validation so all
# dependencies get proper defaults.
#
# esphome: sub-keys are merged into the base config.
esphome:
areas:
- id: area_1
name: "Area 1"
- id: area_2
name: "Area 2"
- id: area_3
name: "Area 3"
- id: area_4
name: "Area 4"
- id: area_5
name: "Area 5"
- id: area_6
name: "Area 6"
- id: area_7
name: "Area 7"
- id: area_8
name: "Area 8"
- id: area_9
name: "Area 9"
- id: area_10
name: "Area 10"
- id: area_11
name: "Area 11"
- id: area_12
name: "Area 12"
- id: area_13
name: "Area 13"
- id: area_14
name: "Area 14"
- id: area_15
name: "Area 15"
- id: area_16
name: "Area 16"
- id: area_17
name: "Area 17"
- id: area_18
name: "Area 18"
- id: area_19
name: "Area 19"
- id: area_20
name: "Area 20"
devices:
- id: device_1
name: "Device 1"
area_id: area_1
- id: device_2
name: "Device 2"
area_id: area_2
- id: device_3
name: "Device 3"
area_id: area_3
- id: device_4
name: "Device 4"
area_id: area_4
- id: device_5
name: "Device 5"
area_id: area_5
- id: device_6
name: "Device 6"
area_id: area_6
- id: device_7
name: "Device 7"
area_id: area_7
- id: device_8
name: "Device 8"
area_id: area_8
- id: device_9
name: "Device 9"
area_id: area_9
- id: device_10
name: "Device 10"
area_id: area_10
- id: device_11
name: "Device 11"
area_id: area_11
- id: device_12
name: "Device 12"
area_id: area_12
- id: device_13
name: "Device 13"
area_id: area_13
- id: device_14
name: "Device 14"
area_id: area_14
- id: device_15
name: "Device 15"
area_id: area_15
- id: device_16
name: "Device 16"
area_id: area_16
- id: device_17
name: "Device 17"
area_id: area_17
- id: device_18
name: "Device 18"
area_id: area_18
- id: device_19
name: "Device 19"
area_id: area_19
- id: device_20
name: "Device 20"
area_id: area_20
api:
encryption:
sensor:
binary_sensor:
light:
switch:
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,61 @@
#include <benchmark/benchmark.h>
#include "esphome/components/binary_sensor/binary_sensor.h"
namespace esphome::binary_sensor::benchmarks {
static constexpr int kInnerIterations = 2000;
// Benchmark: publish_state with alternating values (forces state change every time)
static void BinarySensorPublish_Alternating(benchmark::State &state) {
BinarySensor sensor;
// First publish to establish initial state
sensor.publish_initial_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(i % 2 == 0);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(BinarySensorPublish_Alternating);
// Benchmark: publish_state with same value (tests dedup fast path)
static void BinarySensorPublish_NoChange(benchmark::State &state) {
BinarySensor sensor;
sensor.publish_initial_state(true);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(true);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(BinarySensorPublish_NoChange);
// Benchmark: publish_state with a callback registered
static void BinarySensorPublish_WithCallback(benchmark::State &state) {
BinarySensor sensor;
int callback_count = 0;
sensor.add_on_state_callback([&callback_count](bool) { callback_count++; });
sensor.publish_initial_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(i % 2 == 0);
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(BinarySensorPublish_WithCallback);
} // namespace esphome::binary_sensor::benchmarks
@@ -0,0 +1 @@
binary_sensor:
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,55 @@
#include <benchmark/benchmark.h>
#include "esphome/components/button/button.h"
namespace esphome::button::benchmarks {
static constexpr int kInnerIterations = 2000;
// Minimal Button for benchmarking — press_action() is a no-op.
class BenchButton : public Button {
public:
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
protected:
void press_action() override {}
};
// --- Button::press() ---
// Measures: ESP_LOGD + press_action() + callback dispatch.
static void ButtonPress(benchmark::State &state) {
BenchButton button;
button.configure("test_button");
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
button.press();
}
benchmark::DoNotOptimize(&button);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ButtonPress);
// --- Button::press() with callback ---
// Measures callback dispatch overhead.
static void ButtonPress_WithCallback(benchmark::State &state) {
BenchButton button;
button.configure("test_button");
uint64_t callback_count = 0;
button.add_on_press_callback([&callback_count]() { callback_count++; });
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
button.press();
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(ButtonPress_WithCallback);
} // namespace esphome::button::benchmarks
@@ -0,0 +1 @@
button:
@@ -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,7 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# core (esphome/core/config.py) must run its to_code during builds
# because it bootstraps the fundamental application infrastructure.
manifest.enable_codegen()
@@ -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,7 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# host must run its to_code during builds because it sets up
# the host platform target execution environment.
manifest.enable_codegen()
@@ -0,0 +1,7 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# json must run its to_code during benchmark builds because it
# adds the ArduinoJson library dependency needed by the API component.
manifest.enable_codegen()
@@ -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,7 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# logger must run its to_code during builds because it configures
# the logging subsystem used by ESP_LOG* macros.
manifest.enable_codegen()
+42
View File
@@ -0,0 +1,42 @@
#include <benchmark/benchmark.h>
#include "esphome/components/logger/logger.h"
/*
This special main.cpp provides the entry point for Google Benchmark.
It replaces the default ESPHome main with a benchmark runner.
*/
// Auto generated code by esphome
// ========== AUTO GENERATED INCLUDE BLOCK BEGIN ===========
// ========== AUTO GENERATED INCLUDE BLOCK END ===========
void original_setup() {
// Code-generated App initialization (pre_setup, area/device registration, etc.)
// ========== AUTO GENERATED CODE BEGIN ===========
// =========== AUTO GENERATED CODE END ============
}
void setup() {
// Run auto-generated initialization (App.pre_setup, area/device registration,
// looping_components_.init, etc.) so benchmarks that use App work correctly.
original_setup();
// Log functions call global_logger->log_vprintf_() without a null check,
// so we must set up a Logger before any test that triggers logging.
static esphome::logger::Logger test_logger(0);
test_logger.set_log_level(ESPHOME_LOG_LEVEL);
test_logger.pre_setup();
int argc = 1;
char arg0[] = "benchmark";
char *argv[] = {arg0, nullptr};
::benchmark::Initialize(&argc, argv);
::benchmark::RunSpecifiedBenchmarks();
::benchmark::Shutdown();
exit(0);
}
void loop() {}
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,121 @@
#include <benchmark/benchmark.h>
#include "esphome/components/number/number.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// Minimal Number for benchmarking — control() publishes the value back.
class BenchNumber : public number::Number {
public:
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
protected:
void control(float value) override { this->publish_state(value); }
};
// Helper to create a typical number entity for benchmarks.
static void setup_number(BenchNumber &number) {
number.configure("test_number");
number.traits.set_min_value(0.0f);
number.traits.set_max_value(100.0f);
number.traits.set_step(1.0f);
number.traits.set_mode(number::NUMBER_MODE_SLIDER);
}
// --- Number::publish_state() ---
// Measures the publish path: set_has_state, store value, callback dispatch.
static void NumberPublish_State(benchmark::State &state) {
BenchNumber number;
setup_number(number);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
number.publish_state(static_cast<float>(i % 100));
}
benchmark::DoNotOptimize(number.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(NumberPublish_State);
// --- Number::publish_state() with callback ---
// Measures callback dispatch overhead.
static void NumberPublish_WithCallback(benchmark::State &state) {
BenchNumber number;
setup_number(number);
uint64_t callback_count = 0;
number.add_on_state_callback([&callback_count](float) { callback_count++; });
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
number.publish_state(static_cast<float>(i % 100));
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(NumberPublish_WithCallback);
// --- NumberCall::perform() set value ---
// The most common number call — setting an absolute value.
// Exercises: validation against min/max, control() dispatch.
static void NumberCall_SetValue(benchmark::State &state) {
BenchNumber number;
setup_number(number);
number.publish_state(50.0f);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
float val = static_cast<float>(i % 100);
number.make_call().set_value(val).perform();
}
benchmark::DoNotOptimize(number.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(NumberCall_SetValue);
// --- NumberCall::perform() increment ---
// Exercises: state read, step arithmetic, max clamping.
static void NumberCall_Increment(benchmark::State &state) {
BenchNumber number;
setup_number(number);
number.publish_state(0.0f);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
number.make_call().number_increment(true).perform();
}
benchmark::DoNotOptimize(number.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(NumberCall_Increment);
// --- NumberCall::perform() decrement ---
// Exercises: state read, step arithmetic, min clamping.
static void NumberCall_Decrement(benchmark::State &state) {
BenchNumber number;
setup_number(number);
number.publish_state(100.0f);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
number.make_call().number_decrement(true).perform();
}
benchmark::DoNotOptimize(number.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(NumberCall_Decrement);
} // namespace esphome::benchmarks
@@ -0,0 +1 @@
number:
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,157 @@
#include <benchmark/benchmark.h>
#include "esphome/components/select/select.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// Minimal Select for benchmarking — control() publishes directly by index.
class BenchSelect : public select::Select {
public:
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
protected:
void control(size_t index) override { this->publish_state(index); }
};
// Helper to create a select with the given options.
static void setup_select(BenchSelect &select, const char *name, std::initializer_list<const char *> options) {
select.configure(name);
select.traits.set_options(options);
select.publish_state(size_t(0));
}
// --- Select::publish_state(size_t) ---
// The fast path: publish by index, no string lookup.
static void SelectPublish_ByIndex(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.publish_state(static_cast<size_t>(i % 4));
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectPublish_ByIndex);
// --- Select::publish_state(const char *) ---
// The string path: requires index_of() lookup via strncmp.
static void SelectPublish_ByString(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
const char *options[] = {"off", "still", "move", "still+move"};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.publish_state(options[i % 4]);
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectPublish_ByString);
// --- Select::publish_state() with callback ---
// Measures callback dispatch overhead on the index path.
static void SelectPublish_WithCallback(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
uint64_t callback_count = 0;
select.add_on_state_callback([&callback_count](size_t) { callback_count++; });
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.publish_state(static_cast<size_t>(i % 4));
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectPublish_WithCallback);
// --- SelectCall::perform() set by index ---
// The fast call path — no string matching needed.
static void SelectCall_SetByIndex(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.make_call().set_index(i % 4).perform();
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectCall_SetByIndex);
// --- SelectCall::perform() set by option string ---
// Exercises the string lookup path through index_of().
static void SelectCall_SetByOption(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
const char *options[] = {"off", "still", "move", "still+move"};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.make_call().set_option(options[i % 4]).perform();
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectCall_SetByOption);
// --- SelectCall::perform() next with cycling ---
// Exercises the navigation path through active_index_.
static void SelectCall_NextCycle(benchmark::State &state) {
BenchSelect select;
setup_select(select, "test_select", {"off", "still", "move", "still+move"});
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.make_call().select_next(true).perform();
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectCall_NextCycle);
// --- SelectCall with 10 options (string lookup) ---
// Worst-case string matching with more options.
static void SelectCall_SetByOption_10Options(benchmark::State &state) {
BenchSelect select;
setup_select(
select, "test_select",
{"off", "still", "move", "still+move", "custom1", "custom2", "custom3", "custom4", "custom5", "custom6"});
// Pick options spread across the list to exercise different search depths
const char *picks[] = {"off", "custom3", "custom6", "move"};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
select.make_call().set_option(picks[i % 4]).perform();
}
benchmark::DoNotOptimize(select.active_index());
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SelectCall_SetByOption_10Options);
} // namespace esphome::benchmarks
@@ -0,0 +1 @@
select:
@@ -0,0 +1,12 @@
import esphome.codegen as cg
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# Sensor filter benchmarks need USE_SENSOR_FILTER defined.
# We use a custom to_code instead of enable_codegen() to avoid
# pulling in the full sensor component setup.
async def to_code(config):
cg.add_define("USE_SENSOR_FILTER")
manifest.to_code = to_code
@@ -0,0 +1,78 @@
#include <benchmark/benchmark.h>
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/sensor/filter.h"
namespace esphome::sensor::benchmarks {
static constexpr int kInnerIterations = 2000;
// Benchmark: sensor publish through a SlidingWindowMovingAverageFilter (window=5, send_every=1)
static void SensorFilter_SlidingWindowAvg(benchmark::State &state) {
Sensor sensor;
// Create filter: window_size=5, send_every=1, send_first_at=1
auto *filter = new SlidingWindowMovingAverageFilter(5, 1, 1);
sensor.add_filter(filter);
float value = 0.0f;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(value);
value += 0.1f;
if (value > 1000.0f)
value = 0.0f;
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorFilter_SlidingWindowAvg);
// Benchmark: sensor publish through ExponentialMovingAverageFilter
static void SensorFilter_ExponentialMovingAvg(benchmark::State &state) {
Sensor sensor;
// alpha=0.1, send_every=1, send_first_at=1
auto *filter = new ExponentialMovingAverageFilter(0.1f, 1, 1);
sensor.add_filter(filter);
float value = 0.0f;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(value);
value += 0.1f;
if (value > 1000.0f)
value = 0.0f;
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorFilter_ExponentialMovingAvg);
// Benchmark: sensor publish through a chain of 3 filters (offset + multiply + sliding window)
static void SensorFilter_Chain3(benchmark::State &state) {
Sensor sensor;
sensor.add_filters({
new OffsetFilter(1.0f),
new MultiplyFilter(2.0f),
new SlidingWindowMovingAverageFilter(5, 1, 1),
});
float value = 0.0f;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(value);
value += 0.1f;
if (value > 1000.0f)
value = 0.0f;
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorFilter_Chain3);
} // namespace esphome::sensor::benchmarks
@@ -0,0 +1,79 @@
#include <benchmark/benchmark.h>
#include "esphome/components/sensor/sensor.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
// 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); }
};
// --- Sensor::publish_state() with no callbacks registered ---
// Measures baseline publish overhead: state assignment, logging,
// internal_send_state_to_frontend, ControllerRegistry notification.
static void SensorPublish_NoCallbacks(benchmark::State &state) {
TestSensor sensor;
sensor.configure("test_sensor");
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(static_cast<float>(i));
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorPublish_NoCallbacks);
// --- Sensor::publish_state() with one state callback ---
// Measures callback dispatch overhead through LazyCallbackManager.
static void SensorPublish_WithCallback(benchmark::State &state) {
TestSensor sensor;
sensor.configure("test_sensor");
float callback_value = 0.0f;
sensor.add_on_state_callback([&callback_value](float value) { callback_value = value; });
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(static_cast<float>(i));
}
benchmark::DoNotOptimize(callback_value);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorPublish_WithCallback);
// --- Sensor::publish_state() with the same value every time ---
// Steady-state pattern: sensor reports an unchanged reading.
// Sensor doesn't dedup today, so this exercises the same code path
// as changing values, but tracks the common real-world pattern
// separately for regression detection.
static void SensorPublish_SameValue(benchmark::State &state) {
TestSensor sensor;
sensor.configure("test_sensor");
// Warm up so has_state is already set
sensor.publish_state(23.5f);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(23.5f);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SensorPublish_SameValue);
} // namespace esphome::benchmarks
@@ -0,0 +1 @@
sensor:
@@ -0,0 +1,7 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# socket must run its to_code to define USE_SOCKET_IMPL_BSD_SOCKETS
# which is needed by the api frame helper benchmarks.
manifest.enable_codegen()
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,137 @@
#include <benchmark/benchmark.h>
#include "esphome/components/switch/switch.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
static constexpr int kInnerIterations = 2000;
// Minimal Switch for benchmarking — write_state() publishes directly.
class BenchSwitch : public switch_::Switch {
public:
void configure(const char *name) { this->configure_entity_(name, 0x12345678, 0); }
protected:
void write_state(bool state) override { this->publish_state(state); }
};
// --- Switch::publish_state() alternating ---
// Forces state change every call, exercising the full publish path.
static void SwitchPublish_Alternating(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
sw.publish_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.publish_state(i % 2 == 0);
}
benchmark::DoNotOptimize(sw.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchPublish_Alternating);
// --- Switch::publish_state() no change ---
// Tests the deduplication fast path in publish_dedup_.
static void SwitchPublish_NoChange(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
sw.publish_state(true);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.publish_state(true);
}
benchmark::DoNotOptimize(sw.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchPublish_NoChange);
// --- Switch::publish_state() with callback ---
// Measures callback dispatch overhead on state changes.
static void SwitchPublish_WithCallback(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
uint64_t callback_count = 0;
sw.add_on_state_callback([&callback_count](bool) { callback_count++; });
sw.publish_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.publish_state(i % 2 == 0);
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchPublish_WithCallback);
// --- Switch::turn_on() / turn_off() ---
// The front-end call path: turn_on → write_state → publish_state.
static void SwitchTurnOn(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
sw.publish_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.turn_on();
}
benchmark::DoNotOptimize(sw.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchTurnOn);
// --- Switch::toggle() alternating ---
// Exercises the toggle path which reads current state to determine target.
static void SwitchToggle(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
sw.publish_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.toggle();
}
benchmark::DoNotOptimize(sw.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchToggle);
// --- Switch::publish_state() inverted ---
// Verifies the inversion path doesn't add significant overhead.
static void SwitchPublish_Inverted(benchmark::State &state) {
BenchSwitch sw;
sw.configure("test_switch");
sw.set_restore_mode(switch_::SWITCH_ALWAYS_OFF);
sw.set_inverted(true);
sw.publish_state(false);
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sw.publish_state(i % 2 == 0);
}
benchmark::DoNotOptimize(sw.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(SwitchPublish_Inverted);
} // namespace esphome::benchmarks
@@ -0,0 +1 @@
switch:
@@ -0,0 +1,5 @@
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
@@ -0,0 +1,108 @@
#include <benchmark/benchmark.h>
#include "esphome/components/text_sensor/text_sensor.h"
namespace esphome::text_sensor::benchmarks {
static constexpr int kInnerIterations = 2000;
// --- publish_state(const char *) with short string, value changes each time ---
// Exercises: memcmp check (mismatch), string assign, callback dispatch.
static void TextSensorPublish_Short_Changing(benchmark::State &state) {
TextSensor sensor;
// Pre-populate with different short strings
const char *values[] = {"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(values[i % 4]);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(TextSensorPublish_Short_Changing);
// --- publish_state(const char *) with short string, same value (dedup path) ---
// Exercises: memcmp check (match), skips string assign.
static void TextSensorPublish_Short_NoChange(benchmark::State &state) {
TextSensor sensor;
sensor.publish_state("192.168.1.100");
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state("192.168.1.100");
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(TextSensorPublish_Short_NoChange);
// --- publish_state with longer string (firmware version, MAC address) ---
// Exercises: memcmp on longer strings, string assign with potential realloc.
static void TextSensorPublish_Long_Changing(benchmark::State &state) {
TextSensor sensor;
const char *values[] = {
"2025.12.0-dev (Jan 15 2025, 10:30:00)",
"2025.12.1-dev (Feb 20 2025, 14:45:00)",
"2025.12.2-dev (Mar 10 2025, 08:15:00)",
"2025.12.3-dev (Apr 5 2025, 16:00:00)",
};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(values[i % 4]);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(TextSensorPublish_Long_Changing);
// --- publish_state with callback ---
// Measures callback dispatch overhead for text sensors.
static void TextSensorPublish_WithCallback(benchmark::State &state) {
TextSensor sensor;
uint64_t callback_count = 0;
sensor.add_on_state_callback([&callback_count](const std::string &) { callback_count++; });
const char *values[] = {"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(values[i % 4]);
}
benchmark::DoNotOptimize(callback_count);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(TextSensorPublish_WithCallback);
// --- publish_state(const char *, size_t) direct ---
// The lowest-level overload, avoids strlen.
static void TextSensorPublish_WithLen(benchmark::State &state) {
TextSensor sensor;
static constexpr const char *values[] = {"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"};
static constexpr size_t lens[] = {11, 11, 11, 11};
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
sensor.publish_state(values[i % 4], lens[i % 4]);
}
benchmark::DoNotOptimize(sensor.state);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(TextSensorPublish_WithLen);
} // namespace esphome::text_sensor::benchmarks
@@ -0,0 +1 @@
text_sensor:
@@ -0,0 +1,9 @@
import esphome.codegen as cg
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code(config):
cg.add_build_flag("-DUSE_TIME_TIMEZONE")
manifest.to_code = to_code
@@ -0,0 +1,22 @@
#include <benchmark/benchmark.h>
#include "esphome/core/application.h"
namespace esphome::benchmarks {
// Benchmark Application::loop() with no registered components.
// App is initialized by original_setup() in main.cpp (code-generated
// pre_setup, area/device registration, looping_components_.init).
// This measures the baseline overhead of the main loop: scheduler,
// timing, before/after loop tasks, and yield_with_select_.
static void ApplicationLoop_Empty(benchmark::State &state) {
// Set loop interval to 0 so yield_with_select_ returns immediately
// instead of sleeping. This benchmarks the loop overhead, not the sleep.
App.set_loop_interval(0);
for (auto _ : state) {
App.loop();
}
}
BENCHMARK(ApplicationLoop_Empty);
} // namespace esphome::benchmarks
+41
View File
@@ -0,0 +1,41 @@
#include <benchmark/benchmark.h>
#include "esphome/core/helpers.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
// --- random_float() ---
// Ported from ol.yaml:148 "Random Float Benchmark"
static void RandomFloat(benchmark::State &state) {
for (auto _ : state) {
float result = 0.0f;
for (int i = 0; i < kInnerIterations; i++) {
result += random_float();
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(RandomFloat);
// --- random_uint32() ---
static void RandomUint32(benchmark::State &state) {
for (auto _ : state) {
uint32_t result = 0;
for (int i = 0; i < kInnerIterations; i++) {
result += random_uint32();
}
benchmark::DoNotOptimize(result);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(RandomUint32);
} // namespace esphome::benchmarks
+54
View File
@@ -0,0 +1,54 @@
#include <benchmark/benchmark.h>
#include "esphome/core/log.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
static constexpr int kInnerIterations = 2000;
static const char *const TAG = "bench";
// --- Log a message with no format specifiers (fastest path) ---
static void Logger_NoFormat(benchmark::State &state) {
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ESP_LOGW(TAG, "Something happened");
}
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Logger_NoFormat);
// --- Log a message with 3 uint32_t format specifiers ---
static void Logger_3Uint32(benchmark::State &state) {
uint32_t a = 12345, b = 67890, c = 99999;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ESP_LOGW(TAG, "Values: %" PRIu32 " %" PRIu32 " %" PRIu32, a, b, c);
}
benchmark::DoNotOptimize(a);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Logger_3Uint32);
// --- Log a message with 3 floats (common for sensor values) ---
static void Logger_3Float(benchmark::State &state) {
float temp = 23.456f, humidity = 67.89f, pressure = 1013.25f;
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
ESP_LOGW(TAG, "Sensor: %.2f %.1f %.2f", temp, humidity, pressure);
}
benchmark::DoNotOptimize(temp);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Logger_3Float);
} // namespace esphome::benchmarks
+233
View File
@@ -0,0 +1,233 @@
#include <benchmark/benchmark.h>
#include "esphome/core/scheduler.h"
#include "esphome/core/hal.h"
namespace esphome::benchmarks {
// Inner iteration count to amortize CodSpeed instrumentation overhead.
// Without this, the ~60ns per-iteration valgrind start/stop cost dominates
// sub-microsecond benchmarks.
// Must be divisible by all batch sizes used below (3, 10) to avoid
// pool imbalance at iteration boundaries that causes spurious malloc.
static constexpr int kInnerIterations = 2100;
// Warm the scheduler pool by registering and replacing items twice.
// The first batch allocates fresh items; the second batch cancels them and
// populates the recycling pool with the cancelled items from the first batch.
static void warm_pool(Scheduler &scheduler, Component *component, int batch_size, uint32_t delay) {
uint32_t now = millis();
for (int i = 0; i < batch_size; i++) {
scheduler.set_timeout(component, static_cast<uint32_t>(i), delay, []() {});
}
scheduler.call(++now);
for (int i = 0; i < batch_size; i++) {
scheduler.set_timeout(component, static_cast<uint32_t>(i), delay, []() {});
}
scheduler.call(++now);
}
// --- Scheduler fast path: no work to do ---
static void Scheduler_Call_NoWork(benchmark::State &state) {
Scheduler scheduler;
uint32_t now = millis();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
scheduler.call(now);
}
benchmark::DoNotOptimize(now);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_Call_NoWork);
// --- Scheduler with timers: call() when timers exist but aren't due ---
static void Scheduler_Call_TimersNotDue(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// Add some timeouts far in the future
for (int i = 0; i < 10; i++) {
scheduler.set_timeout(&dummy_component, static_cast<uint32_t>(i), 1000000, []() {});
}
scheduler.process_to_add();
uint32_t now = millis();
for (auto _ : state) {
for (int i = 0; i < kInnerIterations; i++) {
scheduler.call(now);
}
benchmark::DoNotOptimize(now);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_Call_TimersNotDue);
// --- Scheduler with 5 intervals firing every call ---
static void Scheduler_Call_5IntervalsFiring(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
int fire_count = 0;
// Benchmarks the heap-based scheduler dispatch with 5 callbacks firing.
// Uses monotonically increasing fake time so intervals reliably fire every call.
// USE_BENCHMARK ifdef in component.h disables WarnIfComponentBlockingGuard
// (fake now > real millis() would cause underflow in finish()).
// interval=0 would cause an infinite loop (reschedules at same now).
for (int i = 0; i < 5; i++) {
scheduler.set_interval(&dummy_component, static_cast<uint32_t>(i), 1, [&fire_count]() { fire_count++; });
}
scheduler.process_to_add();
uint32_t now = millis() + 100;
for (auto _ : state) {
scheduler.call(now);
now++;
benchmark::DoNotOptimize(fire_count);
}
}
BENCHMARK(Scheduler_Call_5IntervalsFiring);
// --- Scheduler: set_timeout registration ---
static void Scheduler_SetTimeout(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// Register 3 timeouts then call() — realistic worst case where multiple
// components schedule in the same loop iteration. Keeps item count within
// the recycling pool (MAX_POOL_SIZE=5) to avoid spurious malloc/free.
static constexpr int kBatchSize = 3;
static_assert(kInnerIterations % kBatchSize == 0, "kInnerIterations must be divisible by kBatchSize");
warm_pool(scheduler, &dummy_component, kBatchSize, 1000);
for (auto _ : state) {
uint32_t now = millis();
for (int i = 0; i < kInnerIterations; i++) {
scheduler.set_timeout(&dummy_component, static_cast<uint32_t>(i % kBatchSize), 1000, []() {});
if ((i + 1) % kBatchSize == 0) {
scheduler.call(++now);
}
}
scheduler.call(++now);
benchmark::DoNotOptimize(scheduler);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_SetTimeout);
// --- Scheduler: set_interval registration ---
static void Scheduler_SetInterval(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// Register 3 intervals then call() — realistic worst case where multiple
// components schedule in the same loop iteration. Keeps item count within
// the recycling pool (MAX_POOL_SIZE=5) to avoid spurious malloc/free.
static constexpr int kBatchSize = 3;
static_assert(kInnerIterations % kBatchSize == 0, "kInnerIterations must be divisible by kBatchSize");
warm_pool(scheduler, &dummy_component, kBatchSize, 1000);
for (auto _ : state) {
uint32_t now = millis();
for (int i = 0; i < kInnerIterations; i++) {
scheduler.set_interval(&dummy_component, static_cast<uint32_t>(i % kBatchSize), 1000, []() {});
if ((i + 1) % kBatchSize == 0) {
scheduler.call(++now);
}
}
scheduler.call(++now);
benchmark::DoNotOptimize(scheduler);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_SetInterval);
// --- Scheduler: defer registration (set_timeout with delay=0) ---
static void Scheduler_Defer(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// defer() is Component::defer which calls set_timeout(delay=0).
// Component::defer(func) passes nullptr as the name, which skips
// cancel_item_locked_ entirely — matching production behavior where
// defers are anonymous fire-and-forget callbacks.
static constexpr int kBatchSize = 3;
static_assert(kInnerIterations % kBatchSize == 0, "kInnerIterations must be divisible by kBatchSize");
warm_pool(scheduler, &dummy_component, kBatchSize, 0);
for (auto _ : state) {
uint32_t now = millis();
for (int i = 0; i < kInnerIterations; i++) {
scheduler.set_timeout(&dummy_component, static_cast<const char *>(nullptr), 0, []() {});
if ((i + 1) % kBatchSize == 0) {
scheduler.call(++now);
}
}
scheduler.call(++now);
benchmark::DoNotOptimize(scheduler);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_Defer);
// --- Scheduler: defer with same ID (cancel-and-replace pattern) ---
static void Scheduler_Defer_SameID(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// Measures defer with a fixed numeric ID — each call cancels the previous
// pending defer before adding the new one. This is the pattern used by
// components that defer work but want to coalesce rapid updates.
static constexpr int kBatchSize = 3;
static_assert(kInnerIterations % kBatchSize == 0, "kInnerIterations must be divisible by kBatchSize");
warm_pool(scheduler, &dummy_component, kBatchSize, 0);
for (auto _ : state) {
uint32_t now = millis();
for (int i = 0; i < kInnerIterations; i++) {
scheduler.set_timeout(&dummy_component, static_cast<uint32_t>(0), 0, []() {});
if ((i + 1) % kBatchSize == 0) {
scheduler.call(++now);
}
}
scheduler.call(++now);
benchmark::DoNotOptimize(scheduler);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_Defer_SameID);
// --- Scheduler: set_timeout with batch size exceeding pool (cliff test) ---
static void Scheduler_SetTimeout_ExceedPool(benchmark::State &state) {
Scheduler scheduler;
Component dummy_component;
// Register 10 timeouts then call() — exceeds MAX_POOL_SIZE=5 to measure
// the performance cliff when the recycling pool is exhausted and items
// must be malloc'd/freed.
static constexpr int kBatchSize = 10;
static_assert(kInnerIterations % kBatchSize == 0, "kInnerIterations must be divisible by kBatchSize");
warm_pool(scheduler, &dummy_component, kBatchSize, 1000);
for (auto _ : state) {
uint32_t now = millis();
for (int i = 0; i < kInnerIterations; i++) {
scheduler.set_timeout(&dummy_component, static_cast<uint32_t>(i % kBatchSize), 1000, []() {});
if ((i + 1) % kBatchSize == 0) {
scheduler.call(++now);
}
}
scheduler.call(++now);
benchmark::DoNotOptimize(scheduler);
}
state.SetItemsProcessed(state.iterations() * kInnerIterations);
}
BENCHMARK(Scheduler_SetTimeout_ExceedPool);
} // namespace esphome::benchmarks
@@ -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
@@ -1,5 +1,7 @@
"""Tests for the binary sensor component."""
from tests.component_tests.helpers import INTERNAL_BIT, extract_packed_value
def test_binary_sensor_is_setup(generate_main):
"""
@@ -13,7 +15,7 @@ def test_binary_sensor_is_setup(generate_main):
)
# Then
assert "new gpio::GPIOBinarySensor();" in main_cpp
assert "static gpio::GPIOBinarySensor *const" in main_cpp
assert "App.register_binary_sensor" in main_cpp
@@ -29,7 +31,7 @@ def test_binary_sensor_sets_mandatory_fields(generate_main):
)
# Then
assert 'bs_1->set_name("test bs1",' in main_cpp
assert 'bs_1->configure_entity_("test bs1",' in main_cpp
assert "bs_1->set_pin(" in main_cpp
@@ -44,9 +46,9 @@ def test_binary_sensor_config_value_internal_set(generate_main):
"tests/component_tests/binary_sensor/test_binary_sensor.yaml"
)
# Then
assert "bs_1->set_internal(true);" in main_cpp
assert "bs_2->set_internal(false);" in main_cpp
# Then: bs_1 has internal: true, bs_2 has internal: false
assert extract_packed_value(main_cpp, "bs_1") & INTERNAL_BIT != 0
assert extract_packed_value(main_cpp, "bs_2") & INTERNAL_BIT == 0
def test_binary_sensor_config_value_use_raw_set(generate_main):
+8 -5
View File
@@ -1,5 +1,7 @@
"""Tests for the button component"""
from tests.component_tests.helpers import INTERNAL_BIT, extract_packed_value
def test_button_is_setup(generate_main):
"""
@@ -11,7 +13,8 @@ def test_button_is_setup(generate_main):
main_cpp = generate_main("tests/component_tests/button/test_button.yaml")
# Then
assert "new wake_on_lan::WakeOnLanButton();" in main_cpp
assert "static wake_on_lan::WakeOnLanButton *const" in main_cpp
assert ") wake_on_lan::WakeOnLanButton();" in main_cpp
assert "App.register_button" in main_cpp
assert "App.register_component" in main_cpp
@@ -26,7 +29,7 @@ def test_button_sets_mandatory_fields(generate_main):
main_cpp = generate_main("tests/component_tests/button/test_button.yaml")
# Then
assert 'wol_1->set_name("wol_test_1",' in main_cpp
assert 'wol_1->configure_entity_("wol_test_1",' in main_cpp
assert "wol_2->set_macaddr(18, 52, 86, 120, 144, 171);" in main_cpp
@@ -39,6 +42,6 @@ def test_button_config_value_internal_set(generate_main):
# When
main_cpp = generate_main("tests/component_tests/button/test_button.yaml")
# Then
assert "wol_1->set_internal(true);" in main_cpp
assert "wol_2->set_internal(false);" in main_cpp
# Then: wol_1 has internal: true, wol_2 has internal: false
assert extract_packed_value(main_cpp, "wol_1") & INTERNAL_BIT != 0
assert extract_packed_value(main_cpp, "wol_2") & INTERNAL_BIT == 0
@@ -1,10 +1,14 @@
"""
Test schema.extend functionality in esphome.config_validation.
Test config_validation functionality in esphome.config_validation.
"""
from typing import Any
import pytest
from voluptuous import Invalid
import esphome.config_validation as cv
from esphome.core import CORE
def test_config_extend() -> None:
@@ -49,3 +53,37 @@ def test_config_extend() -> None:
assert validated["key2"] == "initial_value2"
assert validated["extra_1"] == "value1"
assert validated["extra_2"] == "value2"
def test_requires_component_passes_when_loaded() -> None:
"""Test requires_component passes when the required component is loaded."""
CORE.loaded_integrations.update({"wifi", "logger"})
validator = cv.requires_component("wifi")
result = validator("test_value")
assert result == "test_value"
def test_requires_component_fails_when_not_loaded() -> None:
"""Test requires_component raises Invalid when the required component is not loaded."""
CORE.loaded_integrations.add("logger")
validator = cv.requires_component("wifi")
with pytest.raises(Invalid) as exc_info:
validator("test_value")
assert "requires component wifi" in str(exc_info.value)
def test_conflicts_with_component_passes_when_not_loaded() -> None:
"""Test conflicts_with_component passes when the conflicting component is not loaded."""
CORE.loaded_integrations.update({"wifi", "logger"})
validator = cv.conflicts_with_component("esp32_hosted")
result = validator("test_value")
assert result == "test_value"
def test_conflicts_with_component_fails_when_loaded() -> None:
"""Test conflicts_with_component raises Invalid when the conflicting component is loaded."""
CORE.loaded_integrations.update({"wifi", "esp32_hosted"})
validator = cv.conflicts_with_component("esp32_hosted")
with pytest.raises(Invalid) as exc_info:
validator("test_value")
assert "not compatible with component esp32_hosted" in str(exc_info.value)
+1 -1
View File
@@ -134,7 +134,7 @@ def generate_main() -> Generator[Callable[[str | Path], str]]:
CORE.config_path = Path(path)
CORE.config = read_config({})
generate_cpp_contents(CORE.config)
return CORE.cpp_main_section
return CORE.cpp_global_section + CORE.cpp_main_section
yield generator
@@ -7,8 +7,12 @@ def test_deep_sleep_setup(generate_main):
"""
main_cpp = generate_main("tests/component_tests/deep_sleep/test_deep_sleep1.yaml")
assert "deepsleep = new deep_sleep::DeepSleepComponent();" in main_cpp
assert "App.register_component(deepsleep);" in main_cpp
assert (
"static deep_sleep::DeepSleepComponent *const deepsleep = reinterpret_cast<deep_sleep::DeepSleepComponent *>(deep_sleep__deepsleep__pstorage);"
in main_cpp
)
assert "new(deepsleep) deep_sleep::DeepSleepComponent();" in main_cpp
assert "App.register_component_(deepsleep);" in main_cpp
def test_deep_sleep_sleep_duration(generate_main):
@@ -0,0 +1,81 @@
"""Tests for display component metadata functions."""
from unittest.mock import patch
from esphome.components.display import (
DisplayMetaData,
add_metadata,
get_all_display_metadata,
get_display_metadata,
)
from esphome.cpp_generator import MockObj
def test_add_metadata_with_string_id():
"""Test adding metadata with a plain string ID."""
with patch("esphome.components.display.CORE.data", {}):
add_metadata("my_display", 320, 240, True)
meta = get_display_metadata("my_display")
assert meta == DisplayMetaData(
width=320, height=240, has_writer=True, has_hardware_rotation=False
)
def test_add_metadata_with_mockobj_id():
"""Test adding metadata with a MockObj ID (converted via str())."""
with patch("esphome.components.display.CORE.data", {}):
mock_id = MockObj("my_display_obj")
add_metadata(mock_id, 480, 320, False, has_hardware_rotation=True)
meta = get_display_metadata("my_display_obj")
assert meta == DisplayMetaData(
width=480, height=320, has_writer=False, has_hardware_rotation=True
)
def test_add_metadata_hardware_rotation_default():
"""Test that has_hardware_rotation defaults to False."""
with patch("esphome.components.display.CORE.data", {}):
add_metadata("disp", 128, 64, False)
meta = get_display_metadata("disp")
assert meta.has_hardware_rotation is False
def test_get_display_metadata_missing_returns_none():
"""Test that querying a non-existent ID returns None."""
with patch("esphome.components.display.CORE.data", {}):
data = get_display_metadata("no_such_display")
assert data.width == 0
assert data.height == 0
assert data.has_writer is False
assert data.has_hardware_rotation is False
def test_add_multiple_displays():
"""Test adding metadata for multiple displays."""
with patch("esphome.components.display.CORE.data", {}):
add_metadata("disp_a", 320, 240, True)
add_metadata("disp_b", 128, 64, False, has_hardware_rotation=True)
all_meta = get_all_display_metadata()
assert len(all_meta) == 2
assert all_meta["disp_a"] == DisplayMetaData(320, 240, True, False)
assert all_meta["disp_b"] == DisplayMetaData(128, 64, False, True)
def test_add_metadata_overwrites_existing():
"""Test that adding metadata for the same ID overwrites the previous entry."""
with patch("esphome.components.display.CORE.data", {}):
add_metadata("disp", 320, 240, True)
add_metadata("disp", 640, 480, False, has_hardware_rotation=True)
meta = get_display_metadata("disp")
assert meta == DisplayMetaData(640, 480, False, True)
def test_metadata_is_frozen():
"""Test that DisplayMetaData instances are immutable (frozen dataclass)."""
meta = DisplayMetaData(320, 240, True, False)
try:
meta.width = 640
assert False, "Expected FrozenInstanceError"
except AttributeError:
pass
@@ -289,3 +289,56 @@ def test_model_with_full_update_every(
"full_update_every": 10,
}
)
def test_busy_pin_input_mode_ssd1677(
set_core_config: SetCoreConfigCallable,
set_component_config: Callable[[str, Any], None],
) -> None:
"""Test that busy_pin has input mode and cs/dc/reset pins have output mode for ssd1677."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
# Configure SPI component which is required by epaper_spi
set_component_config("spi", {"id": "spi_bus", "clk_pin": 18, "mosi_pin": 19})
result = run_schema_validation(
{
"id": "test_display",
"model": "ssd1677",
"dc_pin": 21,
"busy_pin": 22,
"reset_pin": 23,
"cs_pin": 5,
"dimensions": {
"width": 200,
"height": 200,
},
}
)
# Verify that busy_pin has input mode set
assert CONF_BUSY_PIN in result
busy_pin_config = result[CONF_BUSY_PIN]
assert "mode" in busy_pin_config
assert busy_pin_config["mode"]["input"] is True
# Verify that cs_pin has output mode set
assert CONF_CS_PIN in result
cs_pin_config = result[CONF_CS_PIN]
assert "mode" in cs_pin_config
assert cs_pin_config["mode"]["output"] is True
# Verify that dc_pin has output mode set
assert CONF_DC_PIN in result
dc_pin_config = result[CONF_DC_PIN]
assert "mode" in dc_pin_config
assert dc_pin_config["mode"]["output"] is True
# Verify that reset_pin has output mode set
assert CONF_RESET_PIN in result
reset_pin_config = result[CONF_RESET_PIN]
assert "mode" in reset_pin_config
assert reset_pin_config["mode"]["output"] is True
@@ -0,0 +1,10 @@
esphome:
name: test
esp32:
variant: esp32s3
framework:
type: esp-idf
psram:
mode: octal
@@ -0,0 +1,11 @@
esphome:
name: test
esp32:
variant: esp32p4
framework:
type: esp-idf
advanced:
execute_from_psram: true
psram:
@@ -0,0 +1,12 @@
esphome:
name: test
esp32:
variant: esp32s3
framework:
type: esp-idf
advanced:
execute_from_psram: true
psram:
mode: octal
+53 -2
View File
@@ -2,13 +2,17 @@
Test ESP32 configuration
"""
from collections.abc import Callable
from pathlib import Path
from typing import Any
import pytest
from esphome.components.esp32 import VARIANTS
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
import esphome.config_validation as cv
from esphome.const import CONF_ESPHOME, PlatformFramework
from esphome.core import CORE
from tests.component_tests.types import SetCoreConfigCallable
@@ -70,7 +74,7 @@ def test_esp32_config(
"advanced": {"execute_from_psram": True},
},
},
r"'execute_from_psram' is only supported on ESP32S3 variant @ data\['framework'\]\['advanced'\]\['execute_from_psram'\]",
r"'execute_from_psram' is not available on this esp32 variant @ data\['framework'\]\['advanced'\]\['execute_from_psram'\]",
id="execute_from_psram_invalid_for_variant_config",
),
pytest.param(
@@ -82,7 +86,18 @@ def test_esp32_config(
},
},
r"'execute_from_psram' requires PSRAM to be configured @ data\['framework'\]\['advanced'\]\['execute_from_psram'\]",
id="execute_from_psram_requires_psram_config",
id="execute_from_psram_requires_psram_s3_config",
),
pytest.param(
{
"variant": "esp32p4",
"framework": {
"type": "esp-idf",
"advanced": {"execute_from_psram": True},
},
},
r"'execute_from_psram' requires PSRAM to be configured @ data\['framework'\]\['advanced'\]\['execute_from_psram'\]",
id="execute_from_psram_requires_psram_p4_config",
),
pytest.param(
{
@@ -108,3 +123,39 @@ def test_esp32_configuration_errors(
with pytest.raises(cv.Invalid, match=error_match):
FINAL_VALIDATE_SCHEMA(CONFIG_SCHEMA(config))
def test_execute_from_psram_s3_sdkconfig(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Test that execute_from_psram on ESP32-S3 sets the correct sdkconfig options."""
generate_main(component_config_path("execute_from_psram_s3.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert sdkconfig.get("CONFIG_SPIRAM_FETCH_INSTRUCTIONS") is True
assert sdkconfig.get("CONFIG_SPIRAM_RODATA") is True
assert "CONFIG_SPIRAM_XIP_FROM_PSRAM" not in sdkconfig
def test_execute_from_psram_p4_sdkconfig(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Test that execute_from_psram on ESP32-P4 sets the correct sdkconfig options."""
generate_main(component_config_path("execute_from_psram_p4.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert sdkconfig.get("CONFIG_SPIRAM_XIP_FROM_PSRAM") is True
assert "CONFIG_SPIRAM_FETCH_INSTRUCTIONS" not in sdkconfig
assert "CONFIG_SPIRAM_RODATA" not in sdkconfig
def test_execute_from_psram_disabled_sdkconfig(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Test that without execute_from_psram, no XIP sdkconfig options are set."""
generate_main(component_config_path("execute_from_psram_disabled.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert "CONFIG_SPIRAM_FETCH_INSTRUCTIONS" not in sdkconfig
assert "CONFIG_SPIRAM_RODATA" not in sdkconfig
assert "CONFIG_SPIRAM_XIP_FROM_PSRAM" not in sdkconfig
@@ -0,0 +1,2 @@
*.pcf -text
*.ttf -text
Binary file not shown.
+337
View File
@@ -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,16 @@
esphome:
name: test
esp32:
board: esp32dev
globals:
- id: my_global_int
type: int
initial_value: "42"
- id: my_global_float
type: float
initial_value: "1.5"
- id: my_global_bool
type: bool
initial_value: "true"
@@ -0,0 +1,27 @@
"""Tests for the globals component."""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
def test_globals_placement_new_with_template_args(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Test that globals uses placement new with template arguments preserved."""
main_cpp = generate_main(component_config_path("globals_test.yaml"))
# Globals uses Pvariable with Type.new(template_args, initial_value)
# which exercises the template_args preservation in placement new.
assert "static globals::GlobalsComponent<int> *const my_global_int" in main_cpp
assert "sizeof(globals::GlobalsComponent<int>)" in main_cpp
assert "new(my_global_int) globals::GlobalsComponent<int>" in main_cpp
# Verify initial value is passed as constructor arg
assert "42" in main_cpp
# Check other globals are also generated
assert "sizeof(globals::GlobalsComponent<float>)" in main_cpp
assert "sizeof(globals::GlobalsComponent<bool>)" in main_cpp
@@ -16,7 +16,8 @@ def test_gpio_binary_sensor_basic_setup(
"""
main_cpp = generate_main("tests/component_tests/gpio/test_gpio_binary_sensor.yaml")
assert "new gpio::GPIOBinarySensor();" in main_cpp
assert "static gpio::GPIOBinarySensor *const" in main_cpp
assert ") gpio::GPIOBinarySensor();" in main_cpp
assert "App.register_binary_sensor" in main_cpp
# set_use_interrupt(true) should NOT be generated (uses C++ default)
assert "bs_gpio->set_use_interrupt(true);" not in main_cpp
+19
View File
@@ -0,0 +1,19 @@
"""Shared helpers for component tests."""
from __future__ import annotations
import re
INTERNAL_BIT = 1 << 24
def extract_packed_value(main_cpp: str, var_name: str) -> int:
"""Extract the third (packed) argument from a configure_entity_ call."""
pattern = (
rf"{re.escape(var_name)}->configure_entity_\("
r'"(?:\\.|[^"\\])*"'
r",\s*\w+,\s*(\d+)\)"
)
match = re.search(pattern, main_cpp)
assert match, f"configure_entity_ call not found for {var_name}"
return int(match.group(1))
+9 -1
View File
@@ -242,7 +242,15 @@ def test_image_generation(
main_cpp = generate_main(component_config_path("image_test.yaml"))
assert "uint8_t_id[] PROGMEM = {0x24, 0x21, 0x24, 0x21" in main_cpp
assert (
"cat_img = new image::Image(uint8_t_id, 32, 24, image::IMAGE_TYPE_RGB565, image::TRANSPARENCY_OPAQUE);"
"alignas(image::Image) static unsigned char image__cat_img__pstorage[sizeof(image::Image)];"
in main_cpp
)
assert (
"static image::Image *const cat_img = reinterpret_cast<image::Image *>(image__cat_img__pstorage);"
in main_cpp
)
assert (
"new(cat_img) image::Image(uint8_t_id, 32, 24, image::IMAGE_TYPE_RGB565, image::TRANSPARENCY_OPAQUE);"
in main_cpp
)
@@ -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,54 @@
"""Tests for the logger component."""
import re
def test_logger_pre_setup_before_other_components(generate_main):
"""Logger::pre_setup() must be called before any other component is created.
Log functions call global_logger->log_vprintf_() without a null check,
so global_logger must be set before anything can log.
"""
main_cpp = generate_main("tests/component_tests/logger/test_logger.yaml")
# Find the logger's pre_setup() call specifically
logger_pre_setup = re.search(r"logger_logger->pre_setup\(\)", main_cpp)
if logger_pre_setup is None:
# Fall back to finding any logger-related pre_setup
logger_pre_setup = re.search(r"logger\w*->pre_setup\(\)", main_cpp)
assert logger_pre_setup is not None, (
"Logger pre_setup() not found in generated code"
)
# Find all "new " allocations (component creation)
new_allocations = list(re.finditer(r"\bnew [\w:]+", main_cpp))
# Find all "new(" allocations (component creation) and combine them
new_allocations.extend(re.finditer(r"\bnew\([^)]+\) [\w:]+", main_cpp))
# Sort allocations by position in the file
new_allocations.sort(key=lambda m: m.start())
assert len(new_allocations) > 0, "No component allocations found"
# Separate logger and non-logger allocations
logger_allocs = [a for a in new_allocations if "logger" in a.group().lower()]
non_logger_allocs = [
a
for a in new_allocations
if "logger" not in a.group().lower()
# Skip placement new for App
and "(&App)" not in main_cpp[max(0, a.start() - 5) : a.start()]
]
assert len(logger_allocs) > 0, (
f"Logger allocation not found in: {[a.group() for a in new_allocations]}"
)
assert len(non_logger_allocs) > 0, (
"No non-logger component allocations found — "
"add a component to test_logger.yaml so the ordering check is meaningful"
)
# All non-logger allocations must appear after logger pre_setup()
for alloc in non_logger_allocs:
assert alloc.start() > logger_pre_setup.start(), (
f"Component allocation '{alloc.group()}' at position {alloc.start()} "
f"appears before logger pre_setup() at position {logger_pre_setup.start()}"
)
@@ -0,0 +1,14 @@
---
esphome:
name: test
esp8266:
board: d1_mini_lite
logger:
level: DEBUG
# Need at least one non-logger component so the ordering test
# can verify that logger pre_setup() comes before other allocations.
preferences:
flash_write_interval: 1min
@@ -15,8 +15,30 @@ esp_ldo:
display:
- platform: mipi_dsi
id: p4_nano
model: WAVESHARE-P4-NANO-10.1
rotation: 90
- platform: mipi_dsi
id: p4_86
model: "WAVESHARE-P4-86-PANEL"
rotation: 180
- platform: mipi_dsi
model: custom
id: custom_id
dimensions:
width: 400
height: 1280
hsync_back_porch: 40
hsync_pulse_width: 30
hsync_front_porch: 40
vsync_back_porch: 20
vsync_pulse_width: 10
vsync_front_porch: 20
pclk_frequency: 48Mhz
lane_bit_rate: 1.2Gbps
rotation: 180
transform: disabled
init_sequence:
i2c:
sda: GPIO7
scl: GPIO8
@@ -119,9 +119,20 @@ def test_code_generation(
main_cpp = generate_main(component_fixture_path("mipi_dsi.yaml"))
assert (
"mipi_dsi_mipi_dsi_id = new mipi_dsi::MIPI_DSI(800, 1280, display::COLOR_BITNESS_565, 16);"
"alignas(mipi_dsi::MIPI_DSI) static unsigned char mipi_dsi__p4_nano__pstorage[sizeof(mipi_dsi::MIPI_DSI)];"
in main_cpp
)
assert (
"static mipi_dsi::MIPI_DSI *const p4_nano = reinterpret_cast<mipi_dsi::MIPI_DSI *>(mipi_dsi__p4_nano__pstorage);"
in main_cpp
)
assert (
"new(p4_nano) mipi_dsi::MIPI_DSI(800, 1280, display::COLOR_BITNESS_565, 16);"
in main_cpp
)
assert "set_init_sequence({224, 1, 0, 225, 1, 147, 226, 1," in main_cpp
assert "mipi_dsi_mipi_dsi_id->set_lane_bit_rate(1500);" in main_cpp
assert "p4_nano->set_lane_bit_rate(1500.0f);" in main_cpp
assert "p4_nano->set_rotation(display::DISPLAY_ROTATION_90_DEGREES);" in main_cpp
assert "p4_86->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);" not in main_cpp
assert "custom_id->set_rotation(display::DISPLAY_ROTATION_180_DEGREES);" in main_cpp
# assert "backlight_id = new light::LightState(mipi_dsi_dsibacklight_id);" in main_cpp
@@ -0,0 +1,200 @@
"""Tests for display metadata created by mipi_spi component."""
from collections.abc import Callable
from pathlib import Path
from esphome.components.display import (
DisplayMetaData,
get_all_display_metadata,
get_display_metadata,
)
from esphome.components.esp32 import (
KEY_BOARD,
KEY_VARIANT,
VARIANT_ESP32,
VARIANT_ESP32S3,
)
from esphome.components.mipi_spi.display import (
CONFIG_SCHEMA,
FINAL_VALIDATE_SCHEMA,
get_instance,
)
from esphome.const import PlatformFramework
from tests.component_tests.types import SetCoreConfigCallable
def validated_config(config):
"""Run schema + final validation and return the validated config."""
return FINAL_VALIDATE_SCHEMA(CONFIG_SCHEMA(config))
def test_metadata_native_quad_default_test_card(
set_core_config: SetCoreConfigCallable,
) -> None:
"""A quad-mode display with no explicit drawing gets a test card from final validation."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32-s3-devkitc-1", KEY_VARIANT: VARIANT_ESP32S3},
)
config = validated_config({"model": "JC3636W518"})
get_instance(config)
meta = get_display_metadata(str(config["id"]))
assert meta is not None
assert meta.width == 360
assert meta.height == 360
# final validation auto-enables show_test_card when no drawing methods are configured
assert meta.has_writer is True
assert meta.has_hardware_rotation is True
def test_metadata_single_mode_with_dc_pin(
set_core_config: SetCoreConfigCallable,
) -> None:
"""A single-mode display with no explicit drawing gets a test card from final validation."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
config = validated_config(
{
"model": "ST7735",
"dc_pin": 18,
}
)
get_instance(config)
meta = get_display_metadata(str(config["id"]))
assert meta is not None
assert meta.width == 128
assert meta.height == 160
assert meta.has_writer is True
assert meta.has_hardware_rotation is True
def test_metadata_custom_dimensions(
set_core_config: SetCoreConfigCallable,
) -> None:
"""A custom model picks up explicit dimensions."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
config = validated_config(
{
"model": "custom",
"dc_pin": 18,
"dimensions": {"width": 480, "height": 320},
"init_sequence": [[0xA0, 0x01]],
}
)
get_instance(config)
meta = get_display_metadata(str(config["id"]))
assert meta is not None
assert meta.width == 480
assert meta.height == 320
# final validation auto-enables show_test_card
assert meta.has_writer is True
assert meta.has_hardware_rotation is True
def test_metadata_with_test_card_has_writer(
set_core_config: SetCoreConfigCallable,
) -> None:
"""When show_test_card is enabled, has_writer should be True."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
config = validated_config(
{
"model": "custom",
"dc_pin": 18,
"dimensions": {"width": 240, "height": 240},
"init_sequence": [[0xA0, 0x01]],
"show_test_card": True,
}
)
get_instance(config)
meta = get_display_metadata(str(config["id"]))
assert meta is not None
assert meta.has_writer is True
def test_metadata_no_swap_xy_not_full_hardware_rotation(
set_core_config: SetCoreConfigCallable,
) -> None:
"""A model that disables swap_xy should report has_hardware_rotation=False."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32-s3-devkitc-1", KEY_VARIANT: VARIANT_ESP32S3},
)
# JC3248W535 has swap_xy=cv.UNDEFINED -> transforms={mirror_x, mirror_y} only
config = validated_config({"model": "JC3248W535"})
get_instance(config)
meta = get_display_metadata(str(config["id"]))
assert meta is not None
assert meta.has_hardware_rotation is False
def test_metadata_multiple_displays_independent(
set_core_config: SetCoreConfigCallable,
) -> None:
"""Multiple displays each get their own metadata entry."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
config_a = validated_config(
{
"id": "disp_a",
"model": "custom",
"dc_pin": 18,
"dimensions": {"width": 320, "height": 240},
"init_sequence": [[0xA0, 0x01]],
}
)
config_b = validated_config(
{
"id": "disp_b",
"model": "custom",
"dc_pin": 19,
"dimensions": {"width": 128, "height": 64},
"init_sequence": [[0xA0, 0x01]],
}
)
get_instance(config_a)
get_instance(config_b)
all_meta = get_all_display_metadata()
# final validation auto-enables show_test_card for both
assert all_meta["disp_a"] == DisplayMetaData(320, 240, True, True)
assert all_meta["disp_b"] == DisplayMetaData(128, 64, True, True)
def test_metadata_via_code_generation_native(
generate_main: Callable[[str | Path], str],
component_fixture_path: Callable[[str], Path],
) -> None:
"""Full code generation for native.yaml should produce correct metadata."""
generate_main(component_fixture_path("native.yaml"))
all_meta = get_all_display_metadata()
# native.yaml: model JC3636W518 -> 360x360, no writer, full hardware rotation
assert len(all_meta) == 1
meta = next(iter(all_meta.values()))
assert meta == DisplayMetaData(
width=360, height=360, has_writer=True, has_hardware_rotation=True
)
def test_metadata_via_code_generation_lvgl(
generate_main: Callable[[str | Path], str],
component_fixture_path: Callable[[str], Path],
) -> None:
"""Full code generation for lvgl.yaml should produce correct metadata."""
generate_main(component_fixture_path("lvgl.yaml"))
all_meta = get_all_display_metadata()
# lvgl.yaml: model ST7735 -> 128x160, no writer (lvgl draws directly), full hw rotation
assert len(all_meta) == 1
meta = next(iter(all_meta.values()))
assert meta == DisplayMetaData(
width=128, height=160, has_writer=False, has_hardware_rotation=True
)
+2 -7
View File
@@ -204,11 +204,6 @@ def test_transform_and_init_sequence_errors(
r"extra keys not allowed @ data\['brightness'\]",
id="brightness_not_supported",
),
pytest.param(
{"model": "T-DISPLAY-S3-PRO"},
"PSRAM is required for this display",
id="psram_required",
),
],
)
def test_esp32s3_specific_errors(
@@ -319,7 +314,7 @@ def test_native_generation(
main_cpp = generate_main(component_fixture_path("native.yaml"))
assert (
"mipi_spi::MipiSpiBuffer<uint16_t, mipi_spi::PIXEL_MODE_16, true, mipi_spi::PIXEL_MODE_16, mipi_spi::BUS_TYPE_QUAD, 360, 360, 0, 1, display::DISPLAY_ROTATION_0_DEGREES, 1, 1>()"
"mipi_spi::MipiSpiBuffer<uint16_t, mipi_spi::PIXEL_MODE_16, true, mipi_spi::PIXEL_MODE_16, mipi_spi::BUS_TYPE_QUAD, 360, 360, 0, 1, 0, true, 1, 1>()"
in main_cpp
)
assert "set_init_sequence({240, 1, 8, 242" in main_cpp
@@ -335,7 +330,7 @@ def test_lvgl_generation(
main_cpp = generate_main(component_fixture_path("lvgl.yaml"))
assert (
"mipi_spi::MipiSpi<uint16_t, mipi_spi::PIXEL_MODE_16, true, mipi_spi::PIXEL_MODE_16, mipi_spi::BUS_TYPE_SINGLE, 128, 160, 0, 0>();"
"mipi_spi::MipiSpi<uint16_t, mipi_spi::PIXEL_MODE_16, true, mipi_spi::PIXEL_MODE_16, mipi_spi::BUS_TYPE_SINGLE, 128, 160, 0, 0, 0, true>();"
in main_cpp
)
assert "set_init_sequence({1, 0, 10, 255, 177" in main_cpp
@@ -27,7 +27,7 @@ def test_web_server_ota_generated(generate_main: Callable[[str], str]) -> None:
assert "global_web_server_base" in main_cpp
# Check component is registered
assert "App.register_component(web_server_webserverotacomponent_id)" in main_cpp
assert "App.register_component_(web_server_webserverotacomponent_id)" in main_cpp
def test_web_server_ota_with_callbacks(generate_main: Callable[[str], str]) -> None:
+2 -2
View File
@@ -69,7 +69,7 @@ def test_packages_skip_update_false(
}
# Call with skip_update=False (default)
do_packages_pass(config, skip_update=False)
do_packages_pass(config, command_line_substitutions={}, skip_update=False)
# Verify clone_or_update was called with actual refresh value
mock_clone_or_update.assert_called_once()
@@ -104,7 +104,7 @@ def test_packages_default_no_skip(
}
# Call without skip_update parameter
do_packages_pass(config)
do_packages_pass(config, command_line_substitutions={})
# Verify clone_or_update was called with actual refresh value
mock_clone_or_update.assert_called_once()
+168 -12
View File
@@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patch
import pytest
from esphome.components.packages import CONFIG_SCHEMA, do_packages_pass, merge_packages
from esphome.components.substitutions import do_substitution_pass
import esphome.config as config_module
from esphome.config import resolve_extend_remove
from esphome.config_helpers import Extend, Remove
@@ -36,6 +37,7 @@ from esphome.const import (
)
from esphome.core import CORE
from esphome.util import OrderedDict
from esphome.yaml_util import add_context
# Test strings
TEST_DEVICE_NAME = "test_device_name"
@@ -69,8 +71,9 @@ def fixture_basic_esphome():
def packages_pass(config):
"""Wrapper around packages_pass that also resolves Extend and Remove."""
"""Passes the config through the packages processing steps."""
config = do_packages_pass(config)
config = do_substitution_pass(config)
config = merge_packages(config)
resolve_extend_remove(config)
return config
@@ -703,6 +706,85 @@ def test_remote_packages_with_files_list(
assert actual == expected
@patch("esphome.yaml_util.load_yaml")
@patch("pathlib.Path.is_file")
@patch("esphome.git.clone_or_update")
def test_remote_packages_with_files_list_and_substitutions(
mock_clone_or_update, mock_is_file, mock_load_yaml
) -> None:
"""
Ensures that packages are loaded as mixed list of dictionary and strings
"""
# Mock the response from git.clone_or_update
mock_revert = MagicMock()
mock_clone_or_update.return_value = (Path("/tmp/noexists"), mock_revert)
# Mock the response from pathlib.Path.is_file
mock_is_file.return_value = True
# Mock the response from esphome.yaml_util.load_yaml
mock_load_yaml.side_effect = [
OrderedDict(
{
CONF_SENSOR: [
{
CONF_PLATFORM: TEST_SENSOR_PLATFORM_1,
CONF_NAME: TEST_SENSOR_NAME_1,
}
]
}
),
OrderedDict(
{
CONF_SENSOR: [
{
CONF_PLATFORM: TEST_SENSOR_PLATFORM_1,
CONF_NAME: TEST_SENSOR_NAME_2,
}
]
}
),
]
# Define the input config
config = {
CONF_PACKAGES: {
"package1": add_context(
{
CONF_URL: r"${url}",
CONF_REF: r"${branch}",
CONF_FILES: [
{CONF_PATH: r"$file"},
"sensor2.yaml",
],
CONF_REFRESH: "1d",
},
{
"branch": "main",
"file": TEST_YAML_FILENAME,
"url": "https://github.com/esphome/non-existant-repo",
},
)
}
}
expected = {
CONF_SENSOR: [
{
CONF_PLATFORM: TEST_SENSOR_PLATFORM_1,
CONF_NAME: TEST_SENSOR_NAME_1,
},
{
CONF_PLATFORM: TEST_SENSOR_PLATFORM_1,
CONF_NAME: TEST_SENSOR_NAME_2,
},
]
}
actual = packages_pass(config)
assert actual == expected
@patch("esphome.yaml_util.load_yaml")
@patch("pathlib.Path.is_file")
@patch("esphome.git.clone_or_update")
@@ -904,7 +986,7 @@ def test_packages_merge_substitutions() -> None:
},
}
actual = do_packages_pass(config)
actual = do_packages_pass(config, command_line_substitutions={})
assert actual == expected
@@ -968,33 +1050,107 @@ def test_package_merge() -> None:
assert actual == expected
def test_packages_invalid_type_raises() -> None:
"""Packages that are not a dict or list raise cv.Invalid."""
config = {
CONF_PACKAGES: "not_a_dict_or_list",
}
with pytest.raises(
cv.Invalid, match="Packages must be a key to value mapping or list"
):
do_packages_pass(config)
@pytest.mark.parametrize(
"invalid_package",
[
6,
"some string",
["some string"],
None,
True,
{"some_component": 8},
{3: 2},
{"some_component": r"${unevaluated expression}"},
],
)
def test_package_merge_invalid(invalid_package) -> None:
"""
Tests that trying to merge an invalid package raises an error.
"""
def test_invalid_package_contents_rejected(invalid_package: object) -> None:
"""Invalid package contents are rejected by PACKAGE_SCHEMA during do_packages_pass."""
config = {
CONF_PACKAGES: {
"some_package": invalid_package,
},
}
with pytest.raises(cv.Invalid):
do_packages_pass(config)
@pytest.mark.xfail(
reason="Deprecated single-package fallback swallows these errors. "
"Remove xfail when single-package deprecation is removed (2026.7.0).",
strict=True,
)
@pytest.mark.parametrize(
"invalid_package",
[
None,
["some string"],
{"some_component": 8},
{3: 2},
],
)
def test_invalid_package_contents_masked_by_deprecation(
invalid_package: object,
) -> None:
"""These invalid packages are swallowed by the deprecated single-package fallback."""
config = {
CONF_PACKAGES: {
"some_package": invalid_package,
},
}
with pytest.raises(cv.Invalid):
do_packages_pass(config)
def test_merge_packages_invalid_nested_type_raises() -> None:
"""Invalid nested packages type during merge raises cv.Invalid."""
config = {
CONF_PACKAGES: {
"pkg": {
CONF_PACKAGES: "invalid",
},
},
}
with pytest.raises(
cv.Invalid, match="Packages must be a key to value mapping or list"
):
merge_packages(config)
@patch("esphome.yaml_util.load_yaml")
@patch("pathlib.Path.is_file")
@patch("esphome.git.clone_or_update")
def test_remote_packages_no_revert(
mock_clone_or_update, mock_is_file, mock_load_yaml
) -> None:
"""Remote packages with revert=None load without retry logic."""
mock_clone_or_update.return_value = (Path("/tmp/noexists"), None)
mock_is_file.return_value = True
mock_load_yaml.return_value = OrderedDict(
{CONF_SENSOR: [{CONF_PLATFORM: TEST_SENSOR_PLATFORM_1, CONF_NAME: "test"}]}
)
config = {
CONF_PACKAGES: {
"pkg": {
CONF_URL: "https://github.com/esphome/repo",
CONF_REF: "main",
CONF_FILES: [{CONF_PATH: "file.yaml"}],
CONF_REFRESH: "1d",
}
}
}
actual = packages_pass(config)
assert actual[CONF_SENSOR] == [
{CONF_PLATFORM: TEST_SENSOR_PLATFORM_1, CONF_NAME: "test"}
]
def test_raw_config_contains_merged_esphome_from_package(tmp_path) -> None:
"""Test that CORE.raw_config contains esphome section from merged package.
+5 -2
View File
@@ -1,5 +1,7 @@
"""Tests for the sensor component."""
from tests.component_tests.helpers import extract_packed_value
def test_sensor_device_class_set(generate_main):
"""
@@ -10,5 +12,6 @@ def test_sensor_device_class_set(generate_main):
# When
main_cpp = generate_main("tests/component_tests/sensor/test_sensor.yaml")
# Then
assert 's_1->set_device_class("voltage");' in main_cpp
# Then: device_class: voltage means packed value must be non-zero
packed = extract_packed_value(main_cpp, "s_1")
assert packed != 0
@@ -0,0 +1,8 @@
esphome:
name: test
esp32:
board: esp32dev
status_led:
pin: GPIO2
@@ -0,0 +1,23 @@
"""Tests for status_led."""
from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
def test_status_led_generation(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Test status_led generation."""
main_cpp = generate_main(component_config_path("status_led_test.yaml"))
assert (
"alignas(status_led::StatusLED) static unsigned char status_led__status_led_statusled_id__pstorage[sizeof(status_led::StatusLED)];"
in main_cpp
)
assert (
"static status_led::StatusLED *const status_led_statusled_id = reinterpret_cast<status_led::StatusLED *>(status_led__status_led_statusled_id__pstorage);"
in main_cpp
)
assert "new(status_led_statusled_id) status_led::StatusLED(" in main_cpp
+25 -7
View File
@@ -1,4 +1,6 @@
"""Tests for the binary sensor component."""
"""Tests for the text component."""
from tests.component_tests.helpers import INTERNAL_BIT, extract_packed_value
def test_text_is_setup(generate_main):
@@ -11,7 +13,8 @@ def test_text_is_setup(generate_main):
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
# Then
assert "new template_::TemplateText();" in main_cpp
assert "static template_::TemplateText *const" in main_cpp
assert ") template_::TemplateText();" in main_cpp
assert "App.register_text" in main_cpp
@@ -25,7 +28,7 @@ def test_text_sets_mandatory_fields(generate_main):
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
# Then
assert 'it_1->set_name("test 1 text",' in main_cpp
assert 'it_1->configure_entity_("test 1 text",' in main_cpp
def test_text_config_value_internal_set(generate_main):
@@ -37,9 +40,9 @@ def test_text_config_value_internal_set(generate_main):
# When
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
# Then
assert "it_2->set_internal(false);" in main_cpp
assert "it_3->set_internal(true);" in main_cpp
# Then: it_2 has internal: false, it_3 has internal: true
assert extract_packed_value(main_cpp, "it_2") & INTERNAL_BIT == 0
assert extract_packed_value(main_cpp, "it_3") & INTERNAL_BIT != 0
def test_text_config_value_mode_set(generate_main):
@@ -66,5 +69,20 @@ def test_text_config_lamda_is_set(generate_main):
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
# Then
assert "it_4->set_template([]() -> esphome::optional<std::string> {" in main_cpp
assert "it_4->set_template([]() -> std::optional<std::string> {" in main_cpp
assert 'return std::string{"Hello"};' in main_cpp
def test_esphome_optional_alias_works(generate_main):
"""
Test that esphome::optional alias compiles (backward compatibility)
"""
# Given
# When
main_cpp = generate_main("tests/component_tests/text/test_text.yaml")
# Then
# Codegen emits std::optional, but esphome::optional must also work
# via the using alias in esphome/core/optional.h
assert "std::optional<std::string>" in main_cpp
@@ -1,5 +1,7 @@
"""Tests for the text sensor component."""
from tests.component_tests.helpers import INTERNAL_BIT, extract_packed_value
def test_text_sensor_is_setup(generate_main):
"""
@@ -11,7 +13,8 @@ def test_text_sensor_is_setup(generate_main):
main_cpp = generate_main("tests/component_tests/text_sensor/test_text_sensor.yaml")
# Then
assert "new template_::TemplateTextSensor();" in main_cpp
assert "static template_::TemplateTextSensor *const" in main_cpp
assert ") template_::TemplateTextSensor();" in main_cpp
assert "App.register_text_sensor" in main_cpp
@@ -25,9 +28,9 @@ def test_text_sensor_sets_mandatory_fields(generate_main):
main_cpp = generate_main("tests/component_tests/text_sensor/test_text_sensor.yaml")
# Then
assert 'ts_1->set_name("Template Text Sensor 1",' in main_cpp
assert 'ts_2->set_name("Template Text Sensor 2",' in main_cpp
assert 'ts_3->set_name("Template Text Sensor 3",' in main_cpp
assert 'ts_1->configure_entity_("Template Text Sensor 1",' in main_cpp
assert 'ts_2->configure_entity_("Template Text Sensor 2",' in main_cpp
assert 'ts_3->configure_entity_("Template Text Sensor 3",' in main_cpp
def test_text_sensor_config_value_internal_set(generate_main):
@@ -39,9 +42,9 @@ def test_text_sensor_config_value_internal_set(generate_main):
# When
main_cpp = generate_main("tests/component_tests/text_sensor/test_text_sensor.yaml")
# Then
assert "ts_2->set_internal(true);" in main_cpp
assert "ts_3->set_internal(false);" in main_cpp
# Then: ts_2 has internal: true, ts_3 has internal: false
assert extract_packed_value(main_cpp, "ts_2") & INTERNAL_BIT != 0
assert extract_packed_value(main_cpp, "ts_3") & INTERNAL_BIT == 0
def test_text_sensor_device_class_set(generate_main):
@@ -53,6 +56,9 @@ def test_text_sensor_device_class_set(generate_main):
# When
main_cpp = generate_main("tests/component_tests/text_sensor/test_text_sensor.yaml")
# Then
assert 'ts_2->set_device_class("timestamp");' in main_cpp
assert 'ts_3->set_device_class("date");' in main_cpp
# Then: ts_2 has device_class: timestamp, ts_3 has device_class: date
# so their packed values must be non-zero
packed_ts_2 = extract_packed_value(main_cpp, "ts_2")
assert packed_ts_2 != 0
packed_ts_3 = extract_packed_value(main_cpp, "ts_3")
assert packed_ts_3 != 0
+65
View File
@@ -7,10 +7,75 @@
testing binaries that combine many components. By convention, this unique namespace is `esphome::component::testing`
(where "component" is the component under test), for example: `esphome::uart::testing`.
### Platform components
For components that expose to a platform component, create a folder under your component test folder with the platform component name, e.g. `binary_sensor` and
include the relevant `.cpp` and `.h` test files there.
### Override component code generation for testing
During C++ test builds, `to_code` is suppressed for every component by default — most components do not
need to generate configuration code for a unit test binary.
#### Manifest overrides
If your component needs to customise code generation behavior for testing — for example to re-enable
`to_code`, supply a lightweight stub, add a test-only dependency, or change any other manifest attribute —
create an `__init__.py` in your component's test directory and define `override_manifest`:
**Top-level component** (`tests/components/<component>/__init__.py`):
```python
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# Re-enable the component's own to_code (needed when the component must
# emit C++ setup code that the test binary depends on at link time).
manifest.enable_codegen()
```
Or supply a lightweight stub instead of the real `to_code`:
```python
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
async def to_code_testing(config):
# Only emit what the C++ tests actually need
pass
manifest.to_code = to_code_testing
manifest.dependencies = manifest.dependencies + ["some_test_only_dep"]
```
**Platform component** (`tests/components/<component>/<domain>/__init__.py`,
e.g. `tests/components/my_sensor/sensor/__init__.py`):
```python
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
manifest.enable_codegen()
```
`override_manifest` receives a `ComponentManifestOverride` that wraps the real manifest.
Attribute assignments store an override; reads fall back to the real manifest when no
override is present.
Key methods:
| Method | Effect |
|---|---|
| `manifest.enable_codegen()` | Remove the `to_code` suppression, re-enabling code generation |
| `manifest.restore()` | Clear **all** overrides, reverting every attribute to the original |
The function is called after `to_code` has already been set to `None`, so calling
`enable_codegen()` is a deliberate opt-in.
## Running component unit tests
(from the repository root)
```bash
./script/cpp_unit_test.py component1 component2 ...
```
@@ -0,0 +1,12 @@
sensor:
- id: my_sensor
platform: adc
pin: GPIO1
name: ADC Test sensor
update_interval: "1:01"
attenuation: 2.5db
unit_of_measurement: "°C"
icon: "mdi:water-percent"
accuracy_decimals: 5
setup_priority: -100
force_update: true

Some files were not shown because too many files have changed in this diff Show More