init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
"""Tests for the filesize component."""
from homeassistant.core import HomeAssistant
TEST_FILE_NAME = "mock_file_test_filesize.txt"
TEST_FILE_NAME2 = "mock_file_test_filesize2.txt"
async def async_create_file(hass: HomeAssistant, path: str) -> None:
"""Create a test file."""
await hass.async_add_executor_job(create_file, path)
def create_file(path: str) -> None:
"""Create the test file."""
with open(path, "w", encoding="utf-8") as test_file:
test_file.write("test")

View File

@@ -0,0 +1,46 @@
"""Fixtures for Filesize integration tests."""
from __future__ import annotations
from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch
import pytest
from homeassistant.components.filesize.const import DOMAIN, PLATFORMS
from homeassistant.const import CONF_FILE_PATH, Platform
from . import TEST_FILE_NAME
from tests.common import MockConfigEntry
@pytest.fixture(name="load_platforms")
async def patch_platform_constant() -> list[Platform]:
"""Return list of platforms to load."""
return PLATFORMS
@pytest.fixture
def mock_config_entry(
tmp_path: Path, load_platforms: list[Platform]
) -> MockConfigEntry:
"""Return the default mocked config entry."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
return MockConfigEntry(
title=TEST_FILE_NAME,
domain=DOMAIN,
entry_id="01JD5CTQMH9FKEFQKZJ8MMBQ3X",
data={CONF_FILE_PATH: test_file},
unique_id=test_file,
)
@pytest.fixture
def mock_setup_entry() -> Generator[None]:
"""Mock setting up a config entry."""
with patch(
"homeassistant.components.filesize.async_setup_entry", return_value=True
):
yield

View File

@@ -0,0 +1,197 @@
# serializer version: 1
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_created-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.mock_file_test_filesize_txt_created',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.TIMESTAMP: 'timestamp'>,
'original_icon': None,
'original_name': 'Created',
'platform': 'filesize',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'created',
'unique_id': '01JD5CTQMH9FKEFQKZJ8MMBQ3X-created',
'unit_of_measurement': None,
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_created-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'timestamp',
'friendly_name': 'mock_file_test_filesize.txt Created',
}),
'context': <ANY>,
'entity_id': 'sensor.mock_file_test_filesize_txt_created',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2024-11-20T18:19:04+00:00',
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_last_updated-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.mock_file_test_filesize_txt_last_updated',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.TIMESTAMP: 'timestamp'>,
'original_icon': None,
'original_name': 'Last updated',
'platform': 'filesize',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'last_updated',
'unique_id': '01JD5CTQMH9FKEFQKZJ8MMBQ3X-last_updated',
'unit_of_measurement': None,
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_last_updated-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'timestamp',
'friendly_name': 'mock_file_test_filesize.txt Last updated',
}),
'context': <ANY>,
'entity_id': 'sensor.mock_file_test_filesize_txt_last_updated',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2024-11-20T18:19:24+00:00',
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_size-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': None,
'entity_id': 'sensor.mock_file_test_filesize_txt_size',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.DATA_SIZE: 'data_size'>,
'original_icon': None,
'original_name': 'Size',
'platform': 'filesize',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'size',
'unique_id': '01JD5CTQMH9FKEFQKZJ8MMBQ3X',
'unit_of_measurement': <UnitOfInformation.MEGABYTES: 'MB'>,
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_size-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'data_size',
'friendly_name': 'mock_file_test_filesize.txt Size',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfInformation.MEGABYTES: 'MB'>,
}),
'context': <ANY>,
'entity_id': 'sensor.mock_file_test_filesize_txt_size',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '0.0',
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_size_in_bytes-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.mock_file_test_filesize_txt_size_in_bytes',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <SensorDeviceClass.DATA_SIZE: 'data_size'>,
'original_icon': None,
'original_name': 'Size in bytes',
'platform': 'filesize',
'previous_unique_id': None,
'supported_features': 0,
'translation_key': 'size_bytes',
'unique_id': '01JD5CTQMH9FKEFQKZJ8MMBQ3X-bytes',
'unit_of_measurement': <UnitOfInformation.BYTES: 'B'>,
})
# ---
# name: test_sensors[load_platforms0][sensor.mock_file_test_filesize_txt_size_in_bytes-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'data_size',
'friendly_name': 'mock_file_test_filesize.txt Size in bytes',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfInformation.BYTES: 'B'>,
}),
'context': <ANY>,
'entity_id': 'sensor.mock_file_test_filesize_txt_size_in_bytes',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '4',
})
# ---

View File

@@ -0,0 +1,226 @@
"""Tests for the Filesize config flow."""
from pathlib import Path
from unittest.mock import patch
import pytest
from homeassistant.components.filesize.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_FILE_PATH
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import TEST_FILE_NAME, TEST_FILE_NAME2, async_create_file
from tests.common import MockConfigEntry
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
async def test_full_user_flow(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test the full user configuration flow."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
await async_create_file(hass, test_file)
hass.config.allowlist_external_dirs = {tmp_path}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_FILE_PATH: test_file},
)
assert result2.get("type") is FlowResultType.CREATE_ENTRY
assert result2.get("title") == TEST_FILE_NAME
assert result2.get("data") == {CONF_FILE_PATH: test_file}
async def test_unique_path(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test we abort if already setup."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
await async_create_file(hass, test_file)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data={CONF_FILE_PATH: test_file}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
async def test_flow_fails_on_validation(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test config flow errors."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
hass.config.allowlist_external_dirs = {}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file,
},
)
assert result2["errors"] == {"base": "not_valid"}
await async_create_file(hass, test_file)
with patch(
"homeassistant.components.filesize.config_flow.pathlib.Path",
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file,
},
)
assert result2["errors"] == {"base": "not_allowed"}
hass.config.allowlist_external_dirs = {tmp_path}
with patch(
"homeassistant.components.filesize.config_flow.pathlib.Path",
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file,
},
)
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == TEST_FILE_NAME
assert result2["data"] == {
CONF_FILE_PATH: test_file,
}
async def test_reconfigure_flow(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test a reconfigure flow."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME2))
await async_create_file(hass, test_file)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_FILE_PATH: test_file},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reconfigure_successful"
assert mock_config_entry.data == {CONF_FILE_PATH: str(test_file)}
async def test_unique_id_already_exist_in_reconfigure_flow(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test a reconfigure flow fails when unique id already exist."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
test_file2 = str(tmp_path.joinpath(TEST_FILE_NAME2))
await async_create_file(hass, test_file)
await async_create_file(hass, test_file2)
hass.config.allowlist_external_dirs = {tmp_path}
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
mock_config_entry = MockConfigEntry(
title=TEST_FILE_NAME,
domain=DOMAIN,
data={CONF_FILE_PATH: test_file},
unique_id=test_file,
)
mock_config_entry2 = MockConfigEntry(
title=TEST_FILE_NAME2,
domain=DOMAIN,
data={CONF_FILE_PATH: test_file2},
unique_id=test_file2,
)
mock_config_entry.add_to_hass(hass)
mock_config_entry2.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_FILE_PATH: test_file2},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "already_configured"
async def test_reconfigure_flow_fails_on_validation(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test config flow errors in reconfigure."""
test_file2 = str(tmp_path.joinpath(TEST_FILE_NAME2))
hass.config.allowlist_external_dirs = {}
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file2,
},
)
assert result["errors"] == {"base": "not_valid"}
await async_create_file(hass, test_file2)
with patch(
"homeassistant.components.filesize.config_flow.pathlib.Path",
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file2,
},
)
assert result2["errors"] == {"base": "not_allowed"}
hass.config.allowlist_external_dirs = {tmp_path}
with patch(
"homeassistant.components.filesize.config_flow.pathlib.Path",
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_FILE_PATH: test_file2,
},
)
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reconfigure_successful"

View File

@@ -0,0 +1,69 @@
"""Tests for the Filesize integration."""
from pathlib import Path
from homeassistant.components.filesize.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_FILE_PATH
from homeassistant.core import HomeAssistant
from . import async_create_file
from tests.common import MockConfigEntry
async def test_load_unload_config_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test the Filesize configuration entry loading/unloading."""
testfile = str(tmp_path.joinpath("file.txt"))
await async_create_file(hass, testfile)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=testfile, data={CONF_FILE_PATH: testfile}
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_cannot_access_file(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test that an file not exist is caught."""
mock_config_entry.add_to_hass(hass)
testfile = str(tmp_path.joinpath("file_not_exist.txt"))
hass.config.allowlist_external_dirs = {tmp_path}
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=testfile, data={CONF_FILE_PATH: testfile}
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_not_valid_path_to_file(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test that an invalid path is caught."""
testfile = str(tmp_path.joinpath("file.txt"))
await async_create_file(hass, testfile)
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=testfile, data={CONF_FILE_PATH: testfile}
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY

View File

@@ -0,0 +1,124 @@
"""The tests for the filesize sensor."""
import os
from pathlib import Path
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.filesize.const import DOMAIN
from homeassistant.const import CONF_FILE_PATH, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.entity_component import async_update_entity
from . import TEST_FILE_NAME, async_create_file
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.parametrize(
"load_platforms",
[[Platform.SENSOR]],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
tmp_path: Path,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test that an invalid path is caught."""
testfile = str(tmp_path.joinpath("file.txt"))
await async_create_file(hass, testfile)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, data={CONF_FILE_PATH: testfile}
)
with (
patch(
"os.stat_result.st_mtime",
1732126764.780758,
),
patch(
"os.stat_result.st_ctime",
1732126744.780758,
),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_invalid_path(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, tmp_path: Path
) -> None:
"""Test that an invalid path is caught."""
test_file = str(tmp_path.joinpath(TEST_FILE_NAME))
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=test_file, data={CONF_FILE_PATH: test_file}
)
state = hass.states.get("sensor." + TEST_FILE_NAME)
assert not state
async def test_valid_path(
hass: HomeAssistant,
tmp_path: Path,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test for a valid path."""
testfile = str(tmp_path.joinpath("file.txt"))
await async_create_file(hass, testfile)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=testfile, data={CONF_FILE_PATH: testfile}
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.mock_file_test_filesize_txt_size")
assert state
assert state.state == "0.0"
device = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.entry_id)}
)
assert device.name == mock_config_entry.title
await hass.async_add_executor_job(os.remove, testfile)
async def test_state_unavailable(
hass: HomeAssistant, tmp_path: Path, mock_config_entry: MockConfigEntry
) -> None:
"""Verify we handle state unavailable."""
testfile = str(tmp_path.joinpath("file.txt"))
await async_create_file(hass, testfile)
hass.config.allowlist_external_dirs = {tmp_path}
mock_config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
mock_config_entry, unique_id=testfile, data={CONF_FILE_PATH: testfile}
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("sensor.mock_file_test_filesize_txt_size")
assert state
assert state.state == "0.0"
await hass.async_add_executor_job(os.remove, testfile)
await async_update_entity(hass, "sensor.mock_file_test_filesize_txt_size")
state = hass.states.get("sensor.mock_file_test_filesize_txt_size")
assert state.state == STATE_UNAVAILABLE