Add pylint checker for manually enabled entities in snapshot tests (#192975)

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Joost Lekkerkerker
2026-11-18 19:01:00 +01:00
committed by GitHub
co-authored by Claude Martin Hjelmare
parent d8a54410b9
commit 0100d2540f
3 changed files with 341 additions and 0 deletions
+55
View File
@@ -125,6 +125,7 @@ Every check has a code following the
| `R7403` | [`home-assistant-tests-redundant-usefixtures`](#r7403-home-assistant-tests-redundant-usefixtures) | `@pytest.mark.usefixtures` redundant when `pytestmark` already applies it |
| `R7404` | [`home-assistant-tests-registry-fixtures`](#r7404-home-assistant-tests-registry-fixtures) | Use the registry fixture instead of calling `<registry>.async_get(hass)` directly in tests |
| `R7405` | [`home-assistant-tests-user-flow-no-data`](#r7405-home-assistant-tests-user-flow-no-data) | User config flow init in tests must not pass `data` |
| `R7406` | [`home-assistant-tests-snapshot-enable-entities`](#r7406-home-assistant-tests-snapshot-enable-entities) | Use the `entity_registry_enabled_by_default` fixture instead of enabling entities before `snapshot_platform` |
| `W7401` | [`home-assistant-deprecated-import`](#w7401-home-assistant-deprecated-import) | Import uses a deprecated path |
| `W7402` | [`home-assistant-async-callback-decorator`](#w7402-home-assistant-async-callback-decorator) | Coroutine should not be decorated with `@callback` |
| `W7403` | [`home-assistant-pytest-fixture-decorator`](#w7403-home-assistant-pytest-fixture-decorator) | Pytest fixture has invalid scope or autouse config |
@@ -1299,6 +1300,60 @@ flows without
`data` are not flagged. The checker is scoped to test modules.
## `home_assistant_tests_snapshot_enable_entities` checker
Detects snapshot tests that enable entities by hand. A test that calls
`snapshot_platform` should snapshot every entity, including the ones that
are disabled by default. The `entity_registry_enabled_by_default` fixture
enables them before the integration is set up, so there is no need to
update the registry and reload the config entry in the test.
### `R7406`: `home-assistant-tests-snapshot-enable-entities`
A `test_*` function calls `snapshot_platform` and also calls
`<registry>.async_update_entity(..., disabled_by=None)`:
```python
async def test_all_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
await setup_integration(hass, mock_config_entry)
for entry in er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
):
entity_registry.async_update_entity( # <-- flagged
entry.entity_id, disabled_by=None
)
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
```
Use the fixture instead:
```python
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
```
Calls in nested helpers defined inside the test are checked too. Tests
that enable an entity without calling `snapshot_platform` (for example,
to test what happens when a user enables it) are not flagged. The checker
is scoped to test modules.
## `home_assistant_test_determinism` checker
`if` and `match` statements inside test functions create non-deterministic
@@ -0,0 +1,100 @@
"""Checker for manually enabled entities in ``snapshot_platform`` tests.
Tests that snapshot a platform with ``snapshot_platform`` should snapshot
every entity, including the ones that are disabled by default. The
``entity_registry_enabled_by_default`` fixture enables all entities before
the integration is set up. Enabling them by hand in the test instead,
with ``entity_registry.async_update_entity(..., disabled_by=None)``
followed by a config entry reload, is more code, slower, and easily misses
entities.
This checker flags ``<registry>.async_update_entity(...)`` calls that pass
``disabled_by=None`` inside a ``test_*`` function that also calls
``snapshot_platform``.
"""
from astroid import nodes
from pylint.checkers import BaseChecker
from pylint.lint import PyLinter
from pylint_home_assistant.helpers.module_info import is_test_module
_SNAPSHOT_PLATFORM = "snapshot_platform"
_UPDATE_ENTITY = "async_update_entity"
def _call_name(node: nodes.Call) -> str | None:
"""Return the called function or method name, if it is a plain name."""
func = node.func
name: str | None = None
if isinstance(func, nodes.Name):
name = func.name
elif isinstance(func, nodes.Attribute):
name = func.attrname
return name
def _enables_entity(node: nodes.Call) -> bool:
"""Return True when *node* is ``*.async_update_entity(..., disabled_by=None)``."""
if not isinstance(node.func, nodes.Attribute):
return False
if node.func.attrname != _UPDATE_ENTITY:
return False
return any(
keyword.arg == "disabled_by"
and isinstance(keyword.value, nodes.Const)
and keyword.value.value is None
for keyword in node.keywords or ()
)
class SnapshotEnableEntitiesChecker(BaseChecker):
"""Checker that enforces the enabled-by-default fixture for snapshots."""
name = "home_assistant_tests_snapshot_enable_entities"
priority = -1
msgs = {
"R7406": (
"Use the 'entity_registry_enabled_by_default' fixture instead of "
"enabling entities manually before 'snapshot_platform'",
"home-assistant-tests-snapshot-enable-entities",
"Used when a test that calls ``snapshot_platform`` enables "
"entities by calling ``async_update_entity(..., "
"disabled_by=None)``. Add "
'``@pytest.mark.usefixtures("entity_registry_enabled_by_default")`` '
"to the test instead, so all entities are enabled before the "
"integration is set up.",
),
}
options = ()
_active: bool
def visit_module(self, node: nodes.Module) -> None:
"""Only check test modules."""
self._active = is_test_module(node.name)
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
"""Check a test function."""
if not self._active or not node.name.startswith("test_"):
return
# Nested functions are covered by the walk of their test function.
if not isinstance(node.parent, (nodes.Module, nodes.ClassDef)):
return
calls = list(node.nodes_of_class(nodes.Call))
if not any(_call_name(call) == _SNAPSHOT_PLATFORM for call in calls):
return
for call in calls:
if _enables_entity(call):
self.add_message(
"home-assistant-tests-snapshot-enable-entities", node=call
)
visit_asyncfunctiondef = visit_functiondef
def register(linter: PyLinter) -> None:
"""Register the checker."""
linter.register_checker(SnapshotEnableEntitiesChecker(linter))
@@ -0,0 +1,186 @@
"""Tests for the snapshot enable entities checker."""
import astroid
from astroid import nodes
from pylint.testutils import MessageTest, UnittestLinter
from pylint_home_assistant.checkers.tests.snapshot_enable_entities import (
SnapshotEnableEntitiesChecker,
)
import pytest
from tests.pylint import assert_adds_messages, assert_no_messages, walk_checker
MODULE_NAME = "tests.components.test_integration.test_sensor"
@pytest.fixture(name="snapshot_enable_entities_checker")
def snapshot_enable_entities_checker_fixture(
linter: UnittestLinter,
) -> SnapshotEnableEntitiesChecker:
"""Fixture to provide a snapshot enable entities checker."""
return SnapshotEnableEntitiesChecker(linter)
def _expected_messages(root_node: nodes.Module) -> list[MessageTest]:
"""Build the expected messages for every ``async_update_entity`` call."""
return [
MessageTest(
msg_id="home-assistant-tests-snapshot-enable-entities",
node=call,
line=call.lineno,
col_offset=call.col_offset,
end_line=call.end_lineno,
end_col_offset=call.end_col_offset,
)
for call in root_node.nodes_of_class(nodes.Call)
if isinstance(call.func, nodes.Attribute)
and call.func.attrname == "async_update_entity"
]
@pytest.mark.parametrize(
"code",
[
pytest.param(
"""
async def test_all_entities(hass, entity_registry, snapshot, entry) -> None:
await setup_integration(hass, entry)
for entity_entry in er.async_entries_for_config_entry(
entity_registry, entry.entry_id
):
entity_registry.async_update_entity(
entity_entry.entity_id, disabled_by=None
)
await hass.config_entries.async_reload(entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
id="loop_over_entries",
),
pytest.param(
"""
async def test_all_entities(hass, entity_registry, snapshot, entry) -> None:
await setup_integration(hass, entry)
entity_registry.async_update_entity("sensor.one", disabled_by=None)
entity_registry.async_update_entity("sensor.two", disabled_by=None)
await hass.config_entries.async_reload(entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
id="multiple_calls",
),
pytest.param(
"""
class TestSensor:
async def test_all_entities(
self, hass, entity_registry, snapshot, entry
) -> None:
entity_registry.async_update_entity("sensor.one", disabled_by=None)
await common.snapshot_platform(
hass, entity_registry, snapshot, entry.entry_id
)
""",
id="method_and_attribute_access",
),
pytest.param(
"""
def test_all_entities(hass, entity_registry, snapshot, entry) -> None:
def _enable() -> None:
entity_registry.async_update_entity("sensor.one", disabled_by=None)
_enable()
snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
id="nested_helper",
),
],
)
def test_manual_enable_flagged(
linter: UnittestLinter,
snapshot_enable_entities_checker: SnapshotEnableEntitiesChecker,
code: str,
) -> None:
"""Enabling entities by hand in a snapshot_platform test is flagged."""
root_node = astroid.parse(code, MODULE_NAME)
with assert_adds_messages(linter, *_expected_messages(root_node)):
walk_checker(linter, snapshot_enable_entities_checker, root_node)
@pytest.mark.parametrize(
("code", "module_name"),
[
pytest.param(
"""
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(hass, entity_registry, snapshot, entry) -> None:
await setup_integration(hass, entry)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
MODULE_NAME,
id="uses_fixture",
),
pytest.param(
"""
async def test_enable_entity(hass, entity_registry, entry) -> None:
await setup_integration(hass, entry)
entity_registry.async_update_entity("sensor.one", disabled_by=None)
await hass.config_entries.async_reload(entry.entry_id)
assert hass.states.get("sensor.one")
""",
MODULE_NAME,
id="no_snapshot_platform",
),
pytest.param(
"""
async def test_disable_entity(hass, entity_registry, snapshot, entry) -> None:
entity_registry.async_update_entity(
"sensor.one", disabled_by=er.RegistryEntryDisabler.USER
)
entity_registry.async_update_entity("sensor.two", name="Two")
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
MODULE_NAME,
id="other_updates",
),
pytest.param(
"""
async def test_enable(hass, entity_registry, entry) -> None:
entity_registry.async_update_entity("sensor.one", disabled_by=None)
async def test_snapshot(hass, entity_registry, snapshot, entry) -> None:
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
MODULE_NAME,
id="different_tests",
),
pytest.param(
"""
async def enable_and_snapshot(hass, entity_registry, snapshot, entry) -> None:
entity_registry.async_update_entity("sensor.one", disabled_by=None)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
MODULE_NAME,
id="not_a_test_function",
),
pytest.param(
"""
async def test_all_entities(hass, entity_registry, snapshot, entry) -> None:
entity_registry.async_update_entity("sensor.one", disabled_by=None)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
""",
"homeassistant.components.test_integration.sensor",
id="not_a_test_module",
),
],
)
def test_not_flagged(
linter: UnittestLinter,
snapshot_enable_entities_checker: SnapshotEnableEntitiesChecker,
code: str,
module_name: str,
) -> None:
"""Valid patterns are not flagged."""
root_node = astroid.parse(code, module_name)
with assert_no_messages(linter):
walk_checker(linter, snapshot_enable_entities_checker, root_node)