Pytest Home Assistant Custom Component
pytest-homeassistant-custom-component is an experimental pytest plugin designed to facilitate testing of Home Assistant custom components. It automatically extracts test plugins and provides fixtures tailored for Home Assistant's architecture. The current version is 0.13.322, with a frequent release cadence that closely tracks Home Assistant core versions.
Warnings
- breaking Compatibility with Home Assistant core versions is critical. The plugin is frequently updated to track HA core releases, and an older plugin version may not be compatible with a newer (or much older) Home Assistant core version due to internal API changes. Always align your `pytest-homeassistant-custom-component` version with the target HA core version you are testing against.
- gotcha Home Assistant core requires Python 3.12+ (as of recent versions), and this plugin specifies `requires_python >=3.14`. Ensure your test environment uses a compatible Python version that satisfies both the plugin and the Home Assistant core version you intend to test.
- gotcha Home Assistant is an asynchronous application. All test functions interacting with Home Assistant fixtures or APIs must be defined as `async def` and use `await` for asynchronous operations.
- gotcha To effectively test a custom component, you need to instruct the test environment to load it. The `enable_custom_integration` fixture is essential for making your custom component available to the `hass` instance during tests.
Install
-
pip install pytest-homeassistant-custom-component
Quickstart
import pytest
# Assuming you have a 'custom_components/my_integration/' directory
# with a basic __init__.py and possibly sensor.py, etc.
# To make the test runnable without a full custom integration,
# we'll just demonstrate the 'hass' fixture.
# For real tests, you'd enable your component like:
# await enable_custom_integration("my_integration")
async def test_basic_hass_fixture(hass):
"""Verify the hass fixture is available and functional."""
assert hass is not None
assert hass.loop is not None
assert hass.config is not None
# Example: Check that the event bus is active
assert hass.bus.listeners is not None
# In a real test, you'd interact with services, states, etc.
# For example:
# await hass.async_block_till_done()
# assert hass.states.get("sensor.my_test_sensor") is not None