[binary_sensor] Fix reporting of 'unknown' (#12296)

Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
This commit is contained in:
Clyde Stubbs
2025-12-06 09:59:29 +11:00
committed by Jonathan Swoboda
parent 42811edeb4
commit fb7800a22f
7 changed files with 283 additions and 12 deletions

View File

@@ -7,7 +7,7 @@ This directory contains end-to-end integration tests for ESPHome, focusing on te
- `conftest.py` - Common fixtures and utilities
- `const.py` - Constants used throughout the integration tests
- `types.py` - Type definitions for fixtures and functions
- `state_utils.py` - State handling utilities (e.g., `InitialStateHelper`, `build_key_to_entity_mapping`)
- `state_utils.py` - State handling utilities (e.g., `InitialStateHelper`, `find_entity`, `require_entity`)
- `fixtures/` - YAML configuration files for tests
- `test_*.py` - Individual test files
@@ -53,6 +53,28 @@ The `InitialStateHelper` class solves a common problem in integration tests: whe
**Future work:**
Consider converting existing integration tests to use `InitialStateHelper` for more reliable state tracking and to eliminate race conditions related to initial state broadcasts.
#### Entity Lookup Helpers (`state_utils.py`)
Two helper functions simplify finding entities in test code:
**`find_entity(entities, object_id_substring, entity_type=None)`**
- Finds an entity by searching for a substring in its `object_id` (case-insensitive)
- Optionally filters by entity type (e.g., `BinarySensorInfo`)
- Returns `None` if not found
**`require_entity(entities, object_id_substring, entity_type=None, description=None)`**
- Same as `find_entity` but raises `AssertionError` if not found
- Use `description` parameter for clearer error messages
```python
from aioesphomeapi import BinarySensorInfo
from .state_utils import require_entity
# Find entities with clear error messages
binary_sensor = require_entity(entities, "test_sensor", BinarySensorInfo)
button = require_entity(entities, "set_true", description="Set True button")
```
### Writing Tests
The simplest way to write a test is to use the `run_compiled` and `api_client_connected` fixtures: