mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Install and load pytest-home-assistant as a standalone plugin (#187095)
This commit is contained in:
@@ -56,7 +56,7 @@ runs:
|
||||
RUNNER_OS: ${{ runner.os }}
|
||||
RUNNER_ARCH: ${{ runner.arch }}
|
||||
PYTHON_VERSION: ${{ steps.python.outputs.python-version }}
|
||||
HASH_FILES: ${{ hashFiles('requirements.txt', 'requirements_all.txt', 'requirements_test.txt', 'homeassistant/package_constraints.txt') }}
|
||||
HASH_FILES: ${{ hashFiles('requirements.txt', 'requirements_all.txt', 'requirements_test.txt', 'homeassistant/package_constraints.txt', 'packages/pytest-home-assistant/pyproject.toml') }}
|
||||
run: |
|
||||
partial_key="${RUNNER_OS}-${RUNNER_ARCH}-${PYTHON_VERSION}-uv-"
|
||||
echo "partial_key=${partial_key}" >> $GITHUB_OUTPUT
|
||||
@@ -102,7 +102,7 @@ runs:
|
||||
python --version
|
||||
uv pip install -r requirements.txt
|
||||
uv pip install -r requirements_all.txt -r requirements_test.txt
|
||||
uv pip install -e . --config-settings editable_mode=compat
|
||||
uv pip install -e . -e packages/pytest-home-assistant --config-settings editable_mode=compat
|
||||
- name: Prune uv cache
|
||||
if: inputs.save == 'true' && steps.cache-venv.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
|
||||
@@ -116,7 +116,7 @@ jobs:
|
||||
- name: Generate partial Python venv restore key
|
||||
id: generate_python_cache_key
|
||||
env:
|
||||
HASH_REQUIREMENTS_TEST: ${{ hashFiles('requirements_test.txt', 'requirements_test_pre_commit.txt') }}
|
||||
HASH_REQUIREMENTS_TEST: ${{ hashFiles('requirements_test.txt', 'requirements_test_pre_commit.txt', 'packages/pytest-home-assistant/pyproject.toml') }}
|
||||
HASH_REQUIREMENTS: ${{ hashFiles('requirements.txt') }}
|
||||
HASH_REQUIREMENTS_ALL: ${{ hashFiles('requirements_all.txt') }}
|
||||
HASH_PACKAGE_CONSTRAINTS: ${{ hashFiles('homeassistant/package_constraints.txt') }}
|
||||
@@ -832,6 +832,39 @@ jobs:
|
||||
python-version: ${{ needs.info.outputs.default_python }}
|
||||
- name: Build source distribution and wheel
|
||||
run: uv build packages/pytest-home-assistant --out-dir dist
|
||||
- name: Install wheel and matching Home Assistant in a clean environment
|
||||
run: |
|
||||
uv venv "${RUNNER_TEMP}/pytest-package-venv"
|
||||
uv pip install --python "${RUNNER_TEMP}/pytest-package-venv/bin/python" . dist/*.whl
|
||||
cp -R packages/pytest-home-assistant/tests/standalone "${RUNNER_TEMP}/pytest-package-tests"
|
||||
- name: Test installed package outside the checkout
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
"${RUNNER_TEMP}/pytest-package-venv/bin/pytest" \
|
||||
-c "${RUNNER_TEMP}/pytest-package-tests/pytest.ini" \
|
||||
"${RUNNER_TEMP}/pytest-package-tests/integration_tests/test_plugin.py"
|
||||
- name: Test optional helpers and fixtures
|
||||
run: |
|
||||
for wheel in dist/*.whl; do
|
||||
uv pip install --python "${RUNNER_TEMP}/pytest-package-venv/bin/python" \
|
||||
"${wheel}[bluetooth,infrared,radio-frequency]"
|
||||
done
|
||||
cd "${RUNNER_TEMP}"
|
||||
"${RUNNER_TEMP}/pytest-package-venv/bin/python" - <<'PY'
|
||||
import importlib
|
||||
|
||||
for module in (
|
||||
"pytest_homeassistant.plugins",
|
||||
"pytest_homeassistant.components.bluetooth",
|
||||
"pytest_homeassistant.components.infrared.common",
|
||||
"pytest_homeassistant.components.radio_frequency.common",
|
||||
):
|
||||
importlib.import_module(module)
|
||||
PY
|
||||
|
||||
"${RUNNER_TEMP}/pytest-package-venv/bin/pytest" \
|
||||
-c "${RUNNER_TEMP}/pytest-package-tests/pytest.ini" \
|
||||
"${RUNNER_TEMP}/pytest-package-tests/integration_tests/test_optional.py"
|
||||
|
||||
prepare-pytest-full:
|
||||
name: Split tests for full run
|
||||
|
||||
Vendored
+1
-1
@@ -148,7 +148,7 @@
|
||||
{
|
||||
"label": "Install all (test & production) Requirements",
|
||||
"type": "shell",
|
||||
"command": "uv pip install -r requirements_all.txt -r requirements_test.txt",
|
||||
"command": "uv pip install -e . -e packages/pytest-home-assistant -r requirements_all.txt -r requirements_test.txt --config-settings editable_mode=compat",
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
|
||||
@@ -58,6 +58,15 @@ RUN --mount=type=bind,source=requirements.txt,target=requirements.txt \
|
||||
--mount=type=bind,source=requirements_test_pre_commit.txt,target=requirements_test_pre_commit.txt \
|
||||
uv pip install -r requirements.txt -r requirements_test.txt
|
||||
|
||||
# Bootstrap installs Core and points the editable package at the workspace.
|
||||
COPY --chown=vscode:vscode packages/pytest-home-assistant/pyproject.toml \
|
||||
packages/pytest-home-assistant/README.md \
|
||||
packages/pytest-home-assistant/LICENSE.md /home/vscode/pytest-home-assistant/
|
||||
COPY --chown=vscode:vscode packages/pytest-home-assistant/pytest_homeassistant \
|
||||
/home/vscode/pytest-home-assistant/pytest_homeassistant
|
||||
RUN uv pip install --no-deps -e /home/vscode/pytest-home-assistant \
|
||||
--config-settings editable_mode=compat
|
||||
|
||||
# Claude Code native install
|
||||
RUN curl -fsSL https://claude.ai/install.sh | bash
|
||||
|
||||
|
||||
@@ -22,7 +22,10 @@ async def hass() -> AsyncGenerator[HomeAssistant]:
|
||||
synchronously from within the running loop.
|
||||
"""
|
||||
async with async_test_home_assistant() as hass:
|
||||
yield hass
|
||||
try:
|
||||
yield hass
|
||||
finally:
|
||||
await hass.async_stop(force=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -1,27 +1,77 @@
|
||||
# pytest-home-assistant
|
||||
|
||||
Pytest fixtures and helpers for testing Home Assistant integrations. This package
|
||||
contains the shared testing tools used by Home Assistant Core, with the goal of
|
||||
making those same tools available to third-party integration authors.
|
||||
Pytest fixtures and helpers for testing Home Assistant integrations. Create a
|
||||
Home Assistant instance, mock configuration entries and external services,
|
||||
simulate events, and check integration behavior.
|
||||
|
||||
Use these tools to create a Home Assistant instance for a test, mock configuration
|
||||
entries and external services, simulate events, and check integration behavior.
|
||||
The Python import namespace is `pytest_homeassistant`.
|
||||
## Installation and compatibility
|
||||
|
||||
## Current status
|
||||
Install the package into your custom integration's virtual environment:
|
||||
|
||||
**This package is not yet ready for external consumption.** It is being extracted
|
||||
from Home Assistant Core and currently requires a Core development checkout. It
|
||||
can be built as a wheel and source distribution, but standalone use and publishing
|
||||
are not yet supported.
|
||||
```shell
|
||||
uv pip install pytest-home-assistant
|
||||
```
|
||||
|
||||
Runtime dependencies and automatic pytest plugin registration are not yet
|
||||
declared. Some helpers also depend on Core's test data, configuration, and
|
||||
historical recorder migration schemas. Installing the wheel alone does not
|
||||
provide a working test environment for a custom integration.
|
||||
The package installs the matching Home Assistant version. Upgrade them together.
|
||||
The plugin loads automatically. Do not install it together with
|
||||
`pytest-homeassistant-custom-component`, which supplies overlapping fixtures.
|
||||
|
||||
The helpers evolve alongside Core. For now, use them with the Core checkout they
|
||||
come from; compatibility across Home Assistant versions is not guaranteed.
|
||||
Bluetooth, infrared, and radio-frequency helpers have optional dependencies:
|
||||
install the corresponding `bluetooth`, `infrared`, or `radio-frequency` extra
|
||||
when using those helpers. Integration-specific libraries must also be installed
|
||||
by the consuming project. SQLite recorder tests work with the base installation;
|
||||
MySQL/PostgreSQL tests additionally need their database driver and
|
||||
`sqlalchemy-utils`.
|
||||
|
||||
## Writing tests
|
||||
|
||||
Add this pytest configuration to your project's `pyproject.toml`:
|
||||
|
||||
```toml
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
asyncio_default_fixture_loop_scope = "function"
|
||||
# Let Home Assistant install its httpx alias before respx is imported.
|
||||
addopts = "-p no:respx"
|
||||
pythonpath = ["."]
|
||||
testpaths = ["tests"]
|
||||
```
|
||||
|
||||
The package's HTTP mocks still use respx directly; only its separate pytest
|
||||
plugin is disabled. The `hass` fixture enables custom integrations by default.
|
||||
|
||||
Tests request fixtures such as `hass` by name and import helpers from
|
||||
`pytest_homeassistant`. For example, `tests/test_config_entry.py` can create a
|
||||
configuration entry without setting up the integration:
|
||||
|
||||
```python
|
||||
from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_config_entry(hass: HomeAssistant) -> None:
|
||||
entry = MockConfigEntry(domain="my_integration", data={"host": "example.local"})
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
assert hass.config_entries.async_get_entry(entry.entry_id) is entry
|
||||
```
|
||||
|
||||
Run your tests with `pytest`.
|
||||
|
||||
## Test data and configuration
|
||||
|
||||
Load test data with helpers such as `load_fixture` and `load_json_object_fixture`
|
||||
from `pytest_homeassistant.common`. They read `tests/fixtures` by default. When
|
||||
given an integration name, they use `tests/components/<domain>/fixtures` if that
|
||||
integration's test directory exists, otherwise `tests/fixtures`. Set `ha_test_root`
|
||||
to use another test directory. Paths are relative to pytest's project root.
|
||||
Snapshots are stored next to the consuming test in `snapshots/`.
|
||||
|
||||
The `hass` fixture uses the shared `tests/testing_config` path by default, without
|
||||
creating or copying a directory. Set `ha_test_config_dir` relative to the project
|
||||
root to use another path. For tests that need an isolated writable directory,
|
||||
override `hass_config_dir` to return `hass_tmp_config_dir`. That fixture copies the
|
||||
shared configuration if it exists, or provides an empty temporary directory.
|
||||
|
||||
## What's included
|
||||
|
||||
@@ -40,46 +90,14 @@ come from; compatibility across Home Assistant versions is not guaranteed.
|
||||
| `pytest_homeassistant.syrupy` | Snapshot extensions for Home Assistant objects. |
|
||||
| `pytest_homeassistant.typing` | Type aliases for shared test fixtures. |
|
||||
|
||||
The package also includes the JSON, time, and recorder patches used by Core's test
|
||||
environment, plus support for detecting uncaught exceptions.
|
||||
## Migrating from pytest-homeassistant-custom-component
|
||||
|
||||
## Using helpers in Core tests
|
||||
|
||||
Set up a Core development checkout with `script/setup`, then run tests from the
|
||||
repository root. Core configures the package's import path and loads its shared
|
||||
fixtures and hooks through `tests/conftest.py`.
|
||||
|
||||
For example, a test can create a configuration entry without setting up the
|
||||
integration:
|
||||
|
||||
```python
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_config_entry(hass: HomeAssistant) -> None:
|
||||
entry = MockConfigEntry(domain="my_integration", data={"host": "example.local"})
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
assert hass.config_entries.async_get_entry(entry.entry_id) is entry
|
||||
```
|
||||
|
||||
Existing imports such as `from tests.common import MockConfigEntry` continue to
|
||||
work: the original Core test modules re-export the same helpers. Core initializes
|
||||
the test data path in `tests/__init__.py`, so fixture loaders still read from the
|
||||
Core test tree.
|
||||
|
||||
## Building
|
||||
|
||||
Build both distributions from the Core repository root:
|
||||
|
||||
```shell
|
||||
uv build packages/pytest-home-assistant
|
||||
```
|
||||
|
||||
Core's CI builds the package to check that it remains buildable. Publishing and
|
||||
standalone installation support will be added separately.
|
||||
Replace the old package dependency with `pytest-home-assistant` and change imports
|
||||
of `pytest_homeassistant_custom_component` to `pytest_homeassistant`. Existing
|
||||
`hass`, `enable_custom_integrations`, registry, HTTP, recorder, and snapshot
|
||||
fixtures keep their names.
|
||||
The wrapper fixture requesting `enable_custom_integrations` can be removed;
|
||||
custom integrations are enabled by default.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ dependencies = [
|
||||
"syrupy==6.1.1",
|
||||
]
|
||||
|
||||
[project.entry-points.pytest11]
|
||||
pytest_homeassistant = "pytest_homeassistant.bootstrap"
|
||||
|
||||
[project.optional-dependencies]
|
||||
bluetooth = [
|
||||
"aiousbwatcher==1.1.2",
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
import pytest
|
||||
|
||||
# Install Home Assistant's httpx and voluptuous aliases before test dependencies.
|
||||
import homeassistant # noqa: F401
|
||||
|
||||
# Preserve assertion introspection when helpers are imported through compatibility modules.
|
||||
pytest.register_assert_rewrite(
|
||||
"pytest_homeassistant.common",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Load Home Assistant's fixtures after third-party pytest plugins."""
|
||||
|
||||
import pytest
|
||||
|
||||
from . import _paths
|
||||
|
||||
|
||||
def pytest_load_initial_conftests(early_config: pytest.Config) -> None:
|
||||
"""Register fixture overrides before importing the consuming test suite."""
|
||||
early_config.pluginmanager.import_plugin("pytest_homeassistant.plugins")
|
||||
_paths.configure(early_config)
|
||||
@@ -2069,6 +2069,7 @@ def mock_recorder_before_hass() -> None:
|
||||
"""
|
||||
|
||||
|
||||
# Radio frequency test fixtures
|
||||
@pytest.fixture(name="init_radio_frequency")
|
||||
async def init_radio_frequency_fixture(hass: HomeAssistant) -> None:
|
||||
"""Set up the Radio Frequency integration for testing."""
|
||||
@@ -2087,6 +2088,7 @@ async def mock_rf_entity_fixture(
|
||||
return await mock_rf_entity_fixture_helper(hass)
|
||||
|
||||
|
||||
# Infrared test fixtures
|
||||
@pytest.fixture(name="init_infrared")
|
||||
async def init_infrared_fixture(hass: HomeAssistant) -> None:
|
||||
"""Set up the Infrared integration for testing."""
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Custom integrations for standalone package tests."""
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"""A custom integration used to test the installed pytest package."""
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up the sample integration."""
|
||||
hass.states.async_set("sensor.pytest_sample", entry.data["state"])
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload the sample integration."""
|
||||
hass.states.async_remove("sensor.pytest_sample")
|
||||
return True
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"""Configuration flow for the standalone test integration."""
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
|
||||
|
||||
class SampleConfigFlow(ConfigFlow, domain="pytest_sample"):
|
||||
"""Create a sample config entry."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, str] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Set up the sample integration."""
|
||||
return self.async_create_entry(title="Sample", data={"state": "ready"})
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"domain": "pytest_sample",
|
||||
"name": "Pytest sample",
|
||||
"codeowners": [],
|
||||
"config_flow": true,
|
||||
"documentation": "https://contributors.home-assistant.io/",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Tests for the installed Home Assistant pytest package."""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Load fixtures while collecting a consuming project's conftest."""
|
||||
|
||||
from pytest_homeassistant.common import load_json_object_fixture
|
||||
|
||||
assert load_json_object_fixture("sample.json") == {"state": "ready"}
|
||||
@@ -0,0 +1 @@
|
||||
{ "state": "ready" }
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# serializer version: 1
|
||||
# name: test_registry_snapshot
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.sample',
|
||||
'has_entity_name': False,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': None,
|
||||
'platform': 'pytest_sample',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': 'sample',
|
||||
'supported_features': 0,
|
||||
'translation_key': None,
|
||||
'unique_id': 'sample',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Test fixtures with optional dependencies."""
|
||||
|
||||
from infrared_protocols.commands.nec import NECCommand
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import bluetooth, infrared, radio_frequency
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
from pytest_homeassistant.components.bluetooth import (
|
||||
HCI0_SOURCE_ADDRESS,
|
||||
HCI1_SOURCE_ADDRESS,
|
||||
NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS,
|
||||
)
|
||||
from pytest_homeassistant.components.infrared.common import (
|
||||
MockInfraredEmitterEntity,
|
||||
MockInfraredReceiverEntity,
|
||||
)
|
||||
from pytest_homeassistant.components.radio_frequency.common import (
|
||||
MockRadioFrequencyCommand,
|
||||
MockRadioFrequencyEntity,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def bluetooth_manager(hass: HomeAssistant) -> None:
|
||||
"""Set up the Bluetooth manager."""
|
||||
assert await async_setup_component(hass, bluetooth.DOMAIN, {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures(
|
||||
"bluetooth_manager",
|
||||
"register_hci0_scanner",
|
||||
"register_hci1_scanner",
|
||||
"register_non_connectable_scanner",
|
||||
)
|
||||
async def test_bluetooth_scanners(hass: HomeAssistant) -> None:
|
||||
"""Test registration of connectable and non-connectable scanners."""
|
||||
scanners = {
|
||||
scanner.source: scanner for scanner in bluetooth.async_current_scanners(hass)
|
||||
}
|
||||
assert scanners[HCI0_SOURCE_ADDRESS].connectable
|
||||
assert scanners[HCI1_SOURCE_ADDRESS].connectable
|
||||
assert not scanners[NON_CONNECTABLE_REMOTE_SOURCE_ADDRESS].connectable
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("enable_bluetooth", "macos_adapter")
|
||||
async def test_bluetooth_macos_adapter(hass: HomeAssistant) -> None:
|
||||
"""Test reloading Bluetooth with a mocked macOS adapter."""
|
||||
entry = hass.config_entries.async_entries(bluetooth.DOMAIN)[0]
|
||||
assert await hass.config_entries.async_reload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_infrared")
|
||||
async def test_infrared_setup(hass: HomeAssistant) -> None:
|
||||
"""Test infrared setup without entities."""
|
||||
assert infrared.DOMAIN in hass.config.components
|
||||
assert infrared.async_get_emitters(hass) == []
|
||||
assert infrared.async_get_receivers(hass) == []
|
||||
|
||||
|
||||
async def test_infrared_entities(
|
||||
hass: HomeAssistant,
|
||||
mock_infrared_emitter_entity: MockInfraredEmitterEntity,
|
||||
mock_infrared_receiver_entity: MockInfraredReceiverEntity,
|
||||
) -> None:
|
||||
"""Test infrared entity discovery and command delivery."""
|
||||
assert infrared.async_get_emitters(hass) == [mock_infrared_emitter_entity.entity_id]
|
||||
assert infrared.async_get_receivers(hass) == [
|
||||
mock_infrared_receiver_entity.entity_id
|
||||
]
|
||||
command = NECCommand(address=0x04FB, command=0xF7, modulation=38000)
|
||||
await infrared.async_send_command(
|
||||
hass, mock_infrared_emitter_entity.entity_id, command
|
||||
)
|
||||
assert mock_infrared_emitter_entity.send_command_calls == [command]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_radio_frequency")
|
||||
async def test_radio_frequency_setup(hass: HomeAssistant) -> None:
|
||||
"""Test radio frequency setup without entities."""
|
||||
assert radio_frequency.DOMAIN in hass.config.components
|
||||
assert not hass.data[radio_frequency.DATA_COMPONENT].entities
|
||||
|
||||
|
||||
async def test_radio_frequency_entity(
|
||||
hass: HomeAssistant, mock_rf_entity: MockRadioFrequencyEntity
|
||||
) -> None:
|
||||
"""Test radio frequency entity discovery and command delivery."""
|
||||
command = MockRadioFrequencyCommand()
|
||||
assert radio_frequency.async_get_transmitters(
|
||||
hass, command.frequency, command.modulation
|
||||
) == [mock_rf_entity.entity_id]
|
||||
await radio_frequency.async_send_command(hass, mock_rf_entity.entity_id, command)
|
||||
assert len(mock_rf_entity.send_command_calls) == 1
|
||||
assert mock_rf_entity.send_command_calls[0].command is command
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Exercise the installed package without a Home Assistant source checkout."""
|
||||
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant import loader
|
||||
from homeassistant.components.recorder import Recorder
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers.http import HomeAssistantView
|
||||
from homeassistant.setup import async_setup_component
|
||||
from pytest_homeassistant import _paths
|
||||
from pytest_homeassistant.common import (
|
||||
MockConfigEntry,
|
||||
async_load_json_object_fixture,
|
||||
load_json_object_fixture,
|
||||
)
|
||||
from pytest_homeassistant.components.recorder.common import (
|
||||
async_wait_recording_done,
|
||||
get_schema_module_path,
|
||||
)
|
||||
from pytest_homeassistant.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def test_custom_integration(hass: HomeAssistant) -> None:
|
||||
"""Discover and run a custom integration using the standard fixtures."""
|
||||
entry = MockConfigEntry(
|
||||
domain="pytest_sample",
|
||||
data=await async_load_json_object_fixture(hass, "sample.json", "pytest_sample"),
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
assert hass.states.get("sensor.pytest_sample").state == "ready"
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
assert hass.states.get("sensor.pytest_sample") is None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("recorder_mock", "enable_custom_integrations")
|
||||
async def test_enable_custom_integrations(hass: HomeAssistant) -> None:
|
||||
"""Test custom integration opt-in compatibility."""
|
||||
integration = await loader.async_get_integration(hass, "pytest_sample")
|
||||
assert not integration.is_built_in
|
||||
|
||||
|
||||
@pytest.mark.parametrize("custom_integrations_enabled", [False])
|
||||
async def test_disable_custom_integrations(hass: HomeAssistant) -> None:
|
||||
"""Test disabling custom integrations."""
|
||||
with pytest.raises(loader.IntegrationNotFound):
|
||||
await loader.async_get_integration(hass, "pytest_sample")
|
||||
|
||||
|
||||
def test_fixture_loader() -> None:
|
||||
"""Load a project's fixtures without Core's tests/__init__.py."""
|
||||
assert load_json_object_fixture("sample.json") == {"state": "ready"}
|
||||
|
||||
|
||||
def test_shared_configuration(
|
||||
hass: HomeAssistant, pytestconfig: pytest.Config, request: pytest.FixtureRequest
|
||||
) -> None:
|
||||
"""Default configuration uses a shared path without creating a directory."""
|
||||
config_dir = pytestconfig.rootpath / "integration_tests" / "testing_config"
|
||||
assert Path(hass.config.config_dir) == config_dir
|
||||
assert not config_dir.exists()
|
||||
assert "tmp_path" not in request.fixturenames
|
||||
|
||||
|
||||
def test_temporary_configuration(hass_tmp_config_dir: str, tmp_path: Path) -> None:
|
||||
"""Tests can opt into writable configuration outside the installed package."""
|
||||
assert Path(hass_tmp_config_dir) == tmp_path
|
||||
(Path(hass_tmp_config_dir) / "configuration.yaml").write_text("default_config:\n")
|
||||
|
||||
|
||||
def test_temporary_configuration_copy(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest
|
||||
) -> None:
|
||||
"""Opting into a temporary directory copies a configured source."""
|
||||
config_dir = tmp_path / "source"
|
||||
config_dir.mkdir()
|
||||
(config_dir / "configuration.yaml").write_text("default_config:\n")
|
||||
monkeypatch.setattr(_paths, "CONFIG_DIR", config_dir)
|
||||
|
||||
destination = Path(request.getfixturevalue("hass_tmp_config_dir"))
|
||||
assert destination == tmp_path
|
||||
assert (destination / "configuration.yaml").read_text() == "default_config:\n"
|
||||
|
||||
|
||||
def test_registry_snapshot(
|
||||
entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion
|
||||
) -> None:
|
||||
"""Use registry fixtures and store snapshots alongside the consuming tests."""
|
||||
entity = entity_registry.async_get_or_create(
|
||||
"sensor", "pytest_sample", "sample", suggested_object_id="sample"
|
||||
)
|
||||
assert entity == snapshot
|
||||
|
||||
|
||||
async def test_http_client(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Initialize an HTTP client using only the package's declared dependencies."""
|
||||
assert await async_setup_component(hass, "api", {})
|
||||
client = await hass_client()
|
||||
response = await client.get("/api/")
|
||||
assert response.status == 200
|
||||
assert await response.json() == {"message": "API running."}
|
||||
|
||||
class LateView(HomeAssistantView):
|
||||
"""A view registered after the test server starts."""
|
||||
|
||||
requires_auth = False
|
||||
url = "/api/pytest_sample"
|
||||
name = "api:pytest_sample"
|
||||
|
||||
async def get(self, request: web.Request) -> web.Response:
|
||||
"""Return a test response."""
|
||||
return self.json({"state": "ready"})
|
||||
|
||||
hass.http.register_view(LateView())
|
||||
response = await client.get("/api/pytest_sample")
|
||||
assert response.status == 200
|
||||
assert await response.json() == {"state": "ready"}
|
||||
|
||||
|
||||
async def test_recorder(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Run recorder fixtures with only declared package dependencies."""
|
||||
hass.states.async_set("sensor.pytest_sample", "ready")
|
||||
await async_wait_recording_done(hass)
|
||||
assert recorder_mock.is_alive()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"schema",
|
||||
[
|
||||
"0",
|
||||
"9",
|
||||
"16",
|
||||
"18",
|
||||
"22",
|
||||
"23",
|
||||
"23_with_newer_columns",
|
||||
"25",
|
||||
"28",
|
||||
"30",
|
||||
"32",
|
||||
"43",
|
||||
"48",
|
||||
"50",
|
||||
"51",
|
||||
],
|
||||
)
|
||||
def test_historical_recorder_schema(schema: str) -> None:
|
||||
"""Historical schema helpers must not import Core's test tree."""
|
||||
module = import_module(get_schema_module_path(schema))
|
||||
assert module.Base.metadata.tables
|
||||
@@ -0,0 +1,7 @@
|
||||
[pytest]
|
||||
addopts = -p no:respx
|
||||
asyncio_mode = auto
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
pythonpath = .
|
||||
ha_test_root = integration_tests
|
||||
testpaths = integration_tests
|
||||
+2
-3
@@ -117,8 +117,7 @@ init-hook = """\
|
||||
from pylint.config import find_default_config_files; \
|
||||
|
||||
sys.path.extend([ \
|
||||
str(Path(next(find_default_config_files())).parent.joinpath('packages/pylint-home-assistant')), \
|
||||
str(Path(next(find_default_config_files())).parent.joinpath('packages/pytest-home-assistant'))\
|
||||
str(Path(next(find_default_config_files())).parent.joinpath('packages/pylint-home-assistant'))\
|
||||
]) \
|
||||
"""
|
||||
load-plugins = [
|
||||
@@ -446,7 +445,7 @@ max-line-length-suggestions = 72
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
ha_test_config_dir = "tests/testing_config"
|
||||
pythonpath = ["packages/pylint-home-assistant", "packages/pytest-home-assistant"]
|
||||
pythonpath = ["packages/pylint-home-assistant"]
|
||||
# The respx plugin imports httpx before tests/__init__.py can alias it to
|
||||
# httpx2 (see homeassistant/__init__.py). Tests use respx directly instead.
|
||||
addopts = "-p no:respx"
|
||||
|
||||
@@ -13,6 +13,7 @@ fi
|
||||
echo "Installing development dependencies..."
|
||||
uv pip install \
|
||||
-e . \
|
||||
-e packages/pytest-home-assistant \
|
||||
-r requirements_all.txt \
|
||||
-r requirements_test.txt \
|
||||
colorlog \
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
"""Tests for the bluetooth component."""
|
||||
|
||||
# ruff: noqa: PLC0414
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import patch
|
||||
|
||||
from dbus_fast.aio import message_bus
|
||||
import habluetooth.util as habluetooth_utils
|
||||
import pytest
|
||||
from pytest_homeassistant.plugins import (
|
||||
macos_adapter as macos_adapter,
|
||||
register_hci0_scanner as register_hci0_scanner,
|
||||
register_hci1_scanner as register_hci1_scanner,
|
||||
register_non_connectable_scanner as register_non_connectable_scanner,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="disable_dbus_socket", autouse=True, scope="package")
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
"""Fixtures for component testing."""
|
||||
|
||||
# ruff: noqa: PLC0414
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncGenerator, Callable, Coroutine, Generator, Mapping
|
||||
from functools import lru_cache
|
||||
@@ -56,13 +54,6 @@ from aiohasupervisor.store import StoreClient
|
||||
from aiohasupervisor.supervisor import SupervisorManagementClient
|
||||
import probatio
|
||||
import pytest
|
||||
from pytest_homeassistant.plugins import (
|
||||
init_infrared_fixture as init_infrared_fixture,
|
||||
init_radio_frequency_fixture as init_radio_frequency_fixture,
|
||||
mock_infrared_emitter_entity_fixture as mock_infrared_emitter_entity_fixture,
|
||||
mock_infrared_receiver_entity_fixture as mock_infrared_receiver_entity_fixture,
|
||||
mock_rf_entity_fixture as mock_rf_entity_fixture,
|
||||
)
|
||||
|
||||
from homeassistant import components, loader
|
||||
from homeassistant.components import repairs
|
||||
|
||||
@@ -75,137 +75,54 @@ from pytest_homeassistant.plugins import (
|
||||
_real_dhcp_service_info_init as _real_dhcp_service_info_init,
|
||||
_real_getaddrinfo as _real_getaddrinfo,
|
||||
_TranslationsCacheData as _TranslationsCacheData,
|
||||
aioclient_mock as aioclient_mock,
|
||||
aiohttp_client as aiohttp_client,
|
||||
aiohttp_client_cls as aiohttp_client_cls,
|
||||
ar as ar,
|
||||
area_registry as area_registry,
|
||||
async_dispatcher_send as async_dispatcher_send,
|
||||
async_fire_mqtt_message as async_fire_mqtt_message,
|
||||
async_setup_component as async_setup_component,
|
||||
async_setup_recorder_instance as async_setup_recorder_instance,
|
||||
async_test_home_assistant as async_test_home_assistant,
|
||||
async_test_recorder as async_test_recorder,
|
||||
asynccontextmanager as asynccontextmanager,
|
||||
asyncio as asyncio,
|
||||
bcrypt as bcrypt,
|
||||
bcrypt_cost as bcrypt_cost,
|
||||
bleak_manager as bleak_manager,
|
||||
block_async_io as block_async_io,
|
||||
block_shared_serial as block_shared_serial,
|
||||
caplog_fixture as caplog_fixture,
|
||||
cast as cast,
|
||||
category_registry as category_registry,
|
||||
check_real as check_real,
|
||||
client as client,
|
||||
components as components,
|
||||
config_entry_oauth2_flow as config_entry_oauth2_flow,
|
||||
configure_event_loop as configure_event_loop,
|
||||
configure_session_event_loop as configure_session_event_loop,
|
||||
contextmanager as contextmanager,
|
||||
copytree as copytree,
|
||||
cr as cr,
|
||||
create_eager_task as create_eager_task,
|
||||
current_request as current_request,
|
||||
current_request_with_host as current_request_with_host,
|
||||
deprecation as deprecation,
|
||||
device_registry as device_registry,
|
||||
disable_block_async_io as disable_block_async_io,
|
||||
disable_block_shared_serial as disable_block_shared_serial,
|
||||
disable_http_server as disable_http_server,
|
||||
disable_mock_zeroconf_resolver as disable_mock_zeroconf_resolver,
|
||||
disable_translations_once as disable_translations_once,
|
||||
dr as dr,
|
||||
dt as dt,
|
||||
dt_util as dt_util,
|
||||
enable_custom_integrations as enable_custom_integrations,
|
||||
enable_event_loop_debug as enable_event_loop_debug,
|
||||
enable_migrate_entity_ids as enable_migrate_entity_ids,
|
||||
enable_migrate_event_context_ids as enable_migrate_event_context_ids,
|
||||
enable_migrate_event_ids as enable_migrate_event_ids,
|
||||
enable_migrate_event_type_ids as enable_migrate_event_type_ids,
|
||||
enable_migrate_state_context_ids as enable_migrate_state_context_ids,
|
||||
enable_missing_statistics as enable_missing_statistics,
|
||||
enable_nightly_purge as enable_nightly_purge,
|
||||
enable_schema_validation as enable_schema_validation,
|
||||
enable_statistics as enable_statistics,
|
||||
entity_registry as entity_registry,
|
||||
er as er,
|
||||
evict_faked_translations as evict_faked_translations,
|
||||
execnet as execnet,
|
||||
expected_lingering_tasks as expected_lingering_tasks,
|
||||
expected_lingering_timers as expected_lingering_timers,
|
||||
extract_stack_to_frame as extract_stack_to_frame,
|
||||
fail_on_log_exception as fail_on_log_exception,
|
||||
floor_registry as floor_registry,
|
||||
fr as fr,
|
||||
frame as frame,
|
||||
freezegun as freezegun,
|
||||
functools as functools,
|
||||
garbage_collection as garbage_collection,
|
||||
gc as gc,
|
||||
get_scheduled_timer_handles as get_scheduled_timer_handles,
|
||||
get_test_config_dir as get_test_config_dir,
|
||||
ha as ha,
|
||||
hass as hass,
|
||||
hass_access_token as hass_access_token,
|
||||
hass_admin_credential as hass_admin_credential,
|
||||
hass_admin_user as hass_admin_user,
|
||||
hass_client as hass_client,
|
||||
hass_client_no_auth as hass_client_no_auth,
|
||||
hass_config as hass_config,
|
||||
hass_config_dir as hass_config_dir,
|
||||
hass_config_yaml as hass_config_yaml,
|
||||
hass_config_yaml_files as hass_config_yaml_files,
|
||||
hass_fixture_setup as hass_fixture_setup,
|
||||
hass_owner_user as hass_owner_user,
|
||||
hass_read_only_access_token as hass_read_only_access_token,
|
||||
hass_read_only_user as hass_read_only_user,
|
||||
hass_storage as hass_storage,
|
||||
hass_supervisor_access_token as hass_supervisor_access_token,
|
||||
hass_supervisor_user as hass_supervisor_user,
|
||||
hass_tmp_config_dir as hass_tmp_config_dir,
|
||||
hass_ws_client as hass_ws_client,
|
||||
hassio_env as hassio_env,
|
||||
hassio_stubs as hassio_stubs,
|
||||
homeassistant as homeassistant,
|
||||
integration_frame_path as integration_frame_path,
|
||||
ipaddress as ipaddress,
|
||||
ir as ir,
|
||||
issue_registry as issue_registry,
|
||||
itertools as itertools,
|
||||
json_loads as json_loads,
|
||||
label_registry as label_registry,
|
||||
load_registries as load_registries,
|
||||
loader as loader,
|
||||
local_auth as local_auth,
|
||||
location_util as location_util,
|
||||
logging as logging,
|
||||
long_repr_strings as long_repr_strings,
|
||||
lr as lr,
|
||||
make_mocked_request as make_mocked_request,
|
||||
mock_aiohttp_client as mock_aiohttp_client,
|
||||
mock_async_zeroconf as mock_async_zeroconf,
|
||||
mock_bleak_scanner_start as mock_bleak_scanner_start,
|
||||
mock_bluetooth as mock_bluetooth,
|
||||
mock_bluetooth_adapters as mock_bluetooth_adapters,
|
||||
mock_device_tracker_conf as mock_device_tracker_conf,
|
||||
mock_enable_bluetooth as mock_enable_bluetooth,
|
||||
mock_get_source_ip as mock_get_source_ip,
|
||||
mock_hass_config as mock_hass_config,
|
||||
mock_hass_config_yaml as mock_hass_config_yaml,
|
||||
mock_integration_frame as mock_integration_frame,
|
||||
mock_network as mock_network,
|
||||
mock_recorder_before_hass as mock_recorder_before_hass,
|
||||
mock_storage as mock_storage,
|
||||
mock_zeroconf as mock_zeroconf,
|
||||
mock_zeroconf_resolver as mock_zeroconf_resolver,
|
||||
mqtt_client_mock as mqtt_client_mock,
|
||||
mqtt_config_entry_data as mqtt_config_entry_data,
|
||||
mqtt_config_entry_options as mqtt_config_entry_options,
|
||||
mqtt_config_subentries_data as mqtt_config_subentries_data,
|
||||
mqtt_mock as mqtt_mock,
|
||||
mqtt_mock_entry as mqtt_mock_entry,
|
||||
multidict as multidict,
|
||||
os as os,
|
||||
patch as patch,
|
||||
@@ -214,41 +131,24 @@ from pytest_homeassistant.plugins import (
|
||||
patch_time as patch_time,
|
||||
patch_yaml_files as patch_yaml_files,
|
||||
pathlib as pathlib,
|
||||
persistent_database as persistent_database,
|
||||
pytest as pytest,
|
||||
pytest_addoption as pytest_addoption,
|
||||
pytest_asyncio as pytest_asyncio,
|
||||
pytest_configure as pytest_configure,
|
||||
pytest_runtest_setup as pytest_runtest_setup,
|
||||
pytest_socket as pytest_socket,
|
||||
pytest_xdist_setupnodes as pytest_xdist_setupnodes,
|
||||
recorder_config as recorder_config,
|
||||
recorder_db_url as recorder_db_url,
|
||||
recorder_helper as recorder_helper,
|
||||
recorder_mock as recorder_mock,
|
||||
reprlib as reprlib,
|
||||
requests_mock as requests_mock,
|
||||
requests_mock_fixture as requests_mock_fixture,
|
||||
reset_globals as reset_globals,
|
||||
respx as respx,
|
||||
rmtree as rmtree,
|
||||
runner as runner,
|
||||
service_calls as service_calls,
|
||||
skip_stop_scripts as skip_stop_scripts,
|
||||
snapshot as snapshot,
|
||||
socket as socket,
|
||||
sqlite3 as sqlite3,
|
||||
ssl as ssl,
|
||||
stop_hass as stop_hass,
|
||||
suppress as suppress,
|
||||
sys as sys,
|
||||
thread_session as thread_session,
|
||||
threading as threading,
|
||||
time as time,
|
||||
translation_helper as translation_helper,
|
||||
translations_once as translations_once,
|
||||
verify_cleanup as verify_cleanup,
|
||||
wait_for_stop_scripts_after_shutdown as wait_for_stop_scripts_after_shutdown,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from aiohttp import web
|
||||
import pytest
|
||||
from pytest_homeassistant import _paths
|
||||
from pytest_homeassistant.common import get_fixture_path
|
||||
from pytest_homeassistant.plugins import evict_faked_translations
|
||||
import pytest_socket
|
||||
|
||||
from homeassistant import loader
|
||||
@@ -19,7 +20,7 @@ from homeassistant.helpers.http import HomeAssistantView
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .common import MockModule, mock_integration
|
||||
from .conftest import HASocketBlockedError, evict_faked_translations
|
||||
from .conftest import HASocketBlockedError
|
||||
from .typing import ClientSessionGenerator
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user