init home-assistant
This commit is contained in:
285
home-assistant/tests/components/sql/__init__.py
Normal file
285
home-assistant/tests/components/sql/__init__.py
Normal file
@@ -0,0 +1,285 @@
|
||||
"""Tests for the sql component."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.recorder import CONF_DB_URL
|
||||
from homeassistant.components.sensor import (
|
||||
CONF_STATE_CLASS,
|
||||
SensorDeviceClass,
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.components.sql.const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.const import (
|
||||
CONF_DEVICE_CLASS,
|
||||
CONF_ICON,
|
||||
CONF_NAME,
|
||||
CONF_UNIQUE_ID,
|
||||
CONF_UNIT_OF_MEASUREMENT,
|
||||
CONF_VALUE_TEMPLATE,
|
||||
UnitOfInformation,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.trigger_template_entity import (
|
||||
CONF_AVAILABILITY,
|
||||
CONF_PICTURE,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
ENTRY_CONFIG = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
CONF_DEVICE_CLASS: SensorDeviceClass.DATA_SIZE,
|
||||
CONF_STATE_CLASS: SensorStateClass.TOTAL,
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_WITH_VALUE_TEMPLATE = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
CONF_VALUE_TEMPLATE: "{{ value }}",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 FROM as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY_2 = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT5 FROM as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY_3 = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: ";;",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY_OPT = {
|
||||
CONF_QUERY: "SELECT 5 FROM as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY_2_OPT = {
|
||||
CONF_QUERY: "SELECT5 FROM as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_QUERY_3_OPT = {
|
||||
CONF_QUERY: ";;",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_QUERY_READ_ONLY_CTE = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "WITH test AS (SELECT 1 AS row_num, 10 AS state) SELECT state FROM test WHERE row_num = 1 LIMIT 1;",
|
||||
CONF_COLUMN_NAME: "state",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "UPDATE states SET state = 999999 WHERE state_id = 11125",
|
||||
CONF_COLUMN_NAME: "state",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "WITH test AS (SELECT state FROM states) UPDATE states SET states.state = test.state;",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_QUERY_READ_ONLY_CTE_OPT = {
|
||||
CONF_QUERY: "WITH test AS (SELECT 1 AS row_num, 10 AS state) SELECT state FROM test WHERE row_num = 1 LIMIT 1;",
|
||||
CONF_COLUMN_NAME: "state",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_OPT = {
|
||||
CONF_QUERY: "UPDATE 5 as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE_OPT = {
|
||||
CONF_QUERY: "WITH test AS (SELECT state FROM states) UPDATE states SET states.state = test.state;",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_MULTIPLE_QUERIES = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as state; UPDATE states SET state = 10;",
|
||||
CONF_COLUMN_NAME: "state",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_MULTIPLE_QUERIES_OPT = {
|
||||
CONF_QUERY: "SELECT 5 as state; UPDATE states SET state = 10;",
|
||||
CONF_COLUMN_NAME: "state",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
|
||||
ENTRY_CONFIG_INVALID_COLUMN_NAME = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_INVALID_COLUMN_NAME_OPT = {
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "size",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
ENTRY_CONFIG_NO_RESULTS = {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT kalle as value from no_table;",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
}
|
||||
|
||||
YAML_CONFIG = {
|
||||
"sql": {
|
||||
CONF_DB_URL: "sqlite://",
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIT_OF_MEASUREMENT: UnitOfInformation.MEBIBYTES,
|
||||
CONF_UNIQUE_ID: "unique_id_12345",
|
||||
CONF_VALUE_TEMPLATE: "{{ value }}",
|
||||
CONF_DEVICE_CLASS: SensorDeviceClass.DATA_SIZE,
|
||||
CONF_STATE_CLASS: SensorStateClass.MEASUREMENT,
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_FULL_TABLE_SCAN = {
|
||||
"sql": {
|
||||
CONF_NAME: "Get entity_id",
|
||||
CONF_QUERY: "SELECT entity_id from states",
|
||||
CONF_COLUMN_NAME: "entity_id",
|
||||
CONF_UNIQUE_ID: "entity_id_12345",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_NO_UNIQUE_ID = {
|
||||
"sql": {
|
||||
CONF_NAME: "Get entity_id",
|
||||
CONF_QUERY: "SELECT entity_id from states",
|
||||
CONF_COLUMN_NAME: "entity_id",
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_WITH_MULTIPLE_COLUMNS = {
|
||||
"sql": {
|
||||
CONF_NAME: "Get entity_id",
|
||||
CONF_QUERY: "SELECT entity_id,state_id from states",
|
||||
CONF_COLUMN_NAME: "entity_id",
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_WITH_VIEW_THAT_CONTAINS_ENTITY_ID = {
|
||||
"sql": {
|
||||
CONF_NAME: "Get entity_id",
|
||||
CONF_QUERY: "SELECT value from view_sensor_db_unique_entity_ids;",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
YAML_CONFIG_BINARY = {
|
||||
"sql": {
|
||||
CONF_DB_URL: "sqlite://",
|
||||
CONF_NAME: "Get Binary Value",
|
||||
CONF_QUERY: "SELECT cast(x'd34324324230392032' as blob) as value, cast(x'd343aa' as blob) as test_attr",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIQUE_ID: "unique_id_12345",
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_INVALID = {
|
||||
"sql": {
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB",
|
||||
CONF_UNIQUE_ID: "unique_id_12345",
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_NO_DB = {
|
||||
"sql": {
|
||||
CONF_NAME: "Get Value",
|
||||
CONF_QUERY: "SELECT 5 as value",
|
||||
CONF_COLUMN_NAME: "value",
|
||||
}
|
||||
}
|
||||
|
||||
YAML_CONFIG_ALL_TEMPLATES = {
|
||||
"sql": {
|
||||
CONF_DB_URL: "sqlite://",
|
||||
CONF_NAME: "Get values with template",
|
||||
CONF_QUERY: "SELECT 5 as output",
|
||||
CONF_COLUMN_NAME: "output",
|
||||
CONF_UNIT_OF_MEASUREMENT: "MiB/s",
|
||||
CONF_UNIQUE_ID: "unique_id_123456",
|
||||
CONF_VALUE_TEMPLATE: "{{ value }}",
|
||||
CONF_ICON: '{% if states("sensor.input1")=="on" %} mdi:on {% else %} mdi:off {% endif %}',
|
||||
CONF_PICTURE: '{% if states("sensor.input1")=="on" %} /local/picture1.jpg {% else %} /local/picture2.jpg {% endif %}',
|
||||
CONF_AVAILABILITY: '{{ states("sensor.input2")=="on" }}',
|
||||
CONF_DEVICE_CLASS: SensorDeviceClass.DATA_RATE,
|
||||
CONF_STATE_CLASS: SensorStateClass.MEASUREMENT,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async def init_integration(
|
||||
hass: HomeAssistant,
|
||||
config: dict[str, Any] | None = None,
|
||||
entry_id: str = "1",
|
||||
source: str = SOURCE_USER,
|
||||
) -> MockConfigEntry:
|
||||
"""Set up the SQL integration in Home Assistant."""
|
||||
if not config:
|
||||
config = ENTRY_CONFIG
|
||||
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
source=source,
|
||||
data={},
|
||||
options=config,
|
||||
entry_id=entry_id,
|
||||
)
|
||||
|
||||
config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return config_entry
|
||||
797
home-assistant/tests/components/sql/test_config_flow.py
Normal file
797
home-assistant/tests/components/sql/test_config_flow.py
Normal file
@@ -0,0 +1,797 @@
|
||||
"""Test the SQL config flow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.recorder import Recorder
|
||||
from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
|
||||
from homeassistant.components.sql.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from . import (
|
||||
ENTRY_CONFIG,
|
||||
ENTRY_CONFIG_INVALID_COLUMN_NAME,
|
||||
ENTRY_CONFIG_INVALID_COLUMN_NAME_OPT,
|
||||
ENTRY_CONFIG_INVALID_QUERY,
|
||||
ENTRY_CONFIG_INVALID_QUERY_2,
|
||||
ENTRY_CONFIG_INVALID_QUERY_2_OPT,
|
||||
ENTRY_CONFIG_INVALID_QUERY_3,
|
||||
ENTRY_CONFIG_INVALID_QUERY_3_OPT,
|
||||
ENTRY_CONFIG_INVALID_QUERY_OPT,
|
||||
ENTRY_CONFIG_MULTIPLE_QUERIES,
|
||||
ENTRY_CONFIG_MULTIPLE_QUERIES_OPT,
|
||||
ENTRY_CONFIG_NO_RESULTS,
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY,
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE,
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE_OPT,
|
||||
ENTRY_CONFIG_QUERY_NO_READ_ONLY_OPT,
|
||||
ENTRY_CONFIG_WITH_VALUE_TEMPLATE,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_form(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test we get the form."""
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
ENTRY_CONFIG,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "Get Value"
|
||||
assert result2["options"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_form_with_value_template(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test for with value template."""
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
ENTRY_CONFIG_WITH_VALUE_TEMPLATE,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "Get Value"
|
||||
assert result2["options"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"value_template": "{{ value }}",
|
||||
}
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_flow_fails_db_url(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test config flow fails incorrect db url."""
|
||||
result4 = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
assert result4["type"] is FlowResultType.FORM
|
||||
assert result4["step_id"] == config_entries.SOURCE_USER
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
side_effect=SQLAlchemyError("error_message"),
|
||||
):
|
||||
result4 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG,
|
||||
)
|
||||
|
||||
assert result4["errors"] == {"db_url": "db_url_invalid"}
|
||||
|
||||
|
||||
async def test_flow_fails_invalid_query(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test config flow fails incorrect db url."""
|
||||
result4 = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
assert result4["type"] is FlowResultType.FORM
|
||||
assert result4["step_id"] == config_entries.SOURCE_USER
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.FORM
|
||||
assert result5["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result6 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY_2,
|
||||
)
|
||||
|
||||
assert result6["type"] is FlowResultType.FORM
|
||||
assert result6["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result6 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY_3,
|
||||
)
|
||||
|
||||
assert result6["type"] is FlowResultType.FORM
|
||||
assert result6["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_QUERY_NO_READ_ONLY,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.FORM
|
||||
assert result5["errors"] == {
|
||||
"query": "query_no_read_only",
|
||||
}
|
||||
|
||||
result6 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE,
|
||||
)
|
||||
|
||||
assert result6["type"] is FlowResultType.FORM
|
||||
assert result6["errors"] == {
|
||||
"query": "query_no_read_only",
|
||||
}
|
||||
|
||||
result6 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_MULTIPLE_QUERIES,
|
||||
)
|
||||
|
||||
assert result6["type"] is FlowResultType.FORM
|
||||
assert result6["errors"] == {
|
||||
"query": "multiple_queries",
|
||||
}
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_NO_RESULTS,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.FORM
|
||||
assert result5["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result5["title"] == "Get Value"
|
||||
assert result5["options"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
}
|
||||
|
||||
|
||||
async def test_flow_fails_invalid_column_name(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test config flow fails invalid column name."""
|
||||
result4 = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
assert result4["type"] is FlowResultType.FORM
|
||||
assert result4["step_id"] == "user"
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_COLUMN_NAME,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.FORM
|
||||
assert result5["errors"] == {
|
||||
"column": "column_invalid",
|
||||
}
|
||||
|
||||
result5 = await hass.config_entries.flow.async_configure(
|
||||
result4["flow_id"],
|
||||
user_input=ENTRY_CONFIG,
|
||||
)
|
||||
|
||||
assert result5["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result5["title"] == "Get Value"
|
||||
assert result5["options"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test options config flow."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"db_url": "sqlite://",
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
"value_template": "{{ value }}",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
"value_template": "{{ value }}",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow_name_previously_removed(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test options config flow where the name was missing."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
title="Get Value Title",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value Title",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow_fails_db_url(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test options flow fails incorrect db url."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"db_url": "sqlite://",
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
side_effect=SQLAlchemyError("error_message"),
|
||||
):
|
||||
result2 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
|
||||
assert result2["errors"] == {"db_url": "db_url_invalid"}
|
||||
|
||||
|
||||
async def test_options_flow_fails_invalid_query(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test options flow fails incorrect query and template."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"db_url": "sqlite://",
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
result2 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY_OPT,
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY_2_OPT,
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_QUERY_3_OPT,
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {
|
||||
"query": "query_invalid",
|
||||
}
|
||||
|
||||
result2 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_QUERY_NO_READ_ONLY_OPT,
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {
|
||||
"query": "query_no_read_only",
|
||||
}
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_QUERY_NO_READ_ONLY_CTE_OPT,
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {
|
||||
"query": "query_no_read_only",
|
||||
}
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_MULTIPLE_QUERIES_OPT,
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.FORM
|
||||
assert result3["errors"] == {
|
||||
"query": "multiple_queries",
|
||||
}
|
||||
|
||||
result4 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
|
||||
assert result4["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result4["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow_fails_invalid_column_name(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test options flow fails invalid column name."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
result2 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=ENTRY_CONFIG_INVALID_COLUMN_NAME_OPT,
|
||||
)
|
||||
|
||||
assert result2["type"] is FlowResultType.FORM
|
||||
assert result2["errors"] == {
|
||||
"column": "column_invalid",
|
||||
}
|
||||
|
||||
result4 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
|
||||
assert result4["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result4["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
|
||||
async def test_options_flow_db_url_empty(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test options config flow with leaving db_url empty."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"db_url": "sqlite://",
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as size",
|
||||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
|
||||
async def test_full_flow_not_recorder_db(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Test full config flow with not using recorder db."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
db_path = tmp_path / "db.db"
|
||||
db_path_str = f"sqlite:///{db_path}"
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
"db_url": db_path_str,
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "Get Value"
|
||||
assert result2["options"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": db_path_str,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
}
|
||||
|
||||
entry = hass.config_entries.async_entries(DOMAIN)[0]
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"db_url": db_path_str,
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": db_path_str,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
# Need to test same again to mitigate issue with db_url removal
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"db_url": db_path_str,
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": db_path_str,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
}
|
||||
|
||||
assert entry.options == {
|
||||
"name": "Get Value",
|
||||
"db_url": db_path_str,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
}
|
||||
|
||||
|
||||
async def test_device_state_class(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test we get the form."""
|
||||
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={},
|
||||
options={
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
result2 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
}
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result3["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert "device_class" not in result3["data"]
|
||||
assert "state_class" not in result3["data"]
|
||||
assert result3["data"] == {
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
124
home-assistant/tests/components/sql/test_init.py
Normal file
124
home-assistant/tests/components/sql/test_init.py
Normal file
@@ -0,0 +1,124 @@
|
||||
"""Test for SQL component Init."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.recorder import Recorder
|
||||
from homeassistant.components.recorder.util import get_instance
|
||||
from homeassistant.components.sql import validate_sql_select
|
||||
from homeassistant.components.sql.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import YAML_CONFIG_INVALID, YAML_CONFIG_NO_DB, init_integration
|
||||
|
||||
|
||||
async def test_setup_entry(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test setup entry."""
|
||||
config_entry = await init_integration(hass)
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
async def test_unload_entry(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test unload an entry."""
|
||||
config_entry = await init_integration(hass)
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert await hass.config_entries.async_unload(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
|
||||
|
||||
async def test_setup_config(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test setup from yaml config."""
|
||||
with patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG_NO_DB)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_setup_invalid_config(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test setup from yaml with invalid config."""
|
||||
with patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
):
|
||||
assert not await async_setup_component(hass, DOMAIN, YAML_CONFIG_INVALID)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_invalid_query(hass: HomeAssistant) -> None:
|
||||
"""Test invalid query."""
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select("DROP TABLE *")
|
||||
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select("SELECT5 as value")
|
||||
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select(";;")
|
||||
|
||||
|
||||
async def test_query_no_read_only(hass: HomeAssistant) -> None:
|
||||
"""Test query no read only."""
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select("UPDATE states SET state = 999999 WHERE state_id = 11125")
|
||||
|
||||
|
||||
async def test_query_no_read_only_cte(hass: HomeAssistant) -> None:
|
||||
"""Test query no read only CTE."""
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select(
|
||||
"WITH test AS (SELECT state FROM states) UPDATE states SET states.state = test.state;"
|
||||
)
|
||||
|
||||
|
||||
async def test_multiple_queries(hass: HomeAssistant) -> None:
|
||||
"""Test multiple queries."""
|
||||
with pytest.raises(vol.Invalid):
|
||||
validate_sql_select("SELECT 5 as value; UPDATE states SET state = 10;")
|
||||
|
||||
|
||||
async def test_remove_configured_db_url_if_not_needed_when_not_needed(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test configured db_url is replaced with None if matching the recorder db."""
|
||||
recorder_db_url = get_instance(hass).db_url
|
||||
|
||||
config = {
|
||||
"db_url": recorder_db_url,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
|
||||
config_entry = await init_integration(hass, config)
|
||||
|
||||
assert config_entry.options.get("db_url") is None
|
||||
|
||||
|
||||
async def test_remove_configured_db_url_if_not_needed_when_needed(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test configured db_url is not replaced if it differs from the recorder db."""
|
||||
db_url = "mssql://"
|
||||
|
||||
config = {
|
||||
"db_url": db_url,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
|
||||
config_entry = await init_integration(hass, config)
|
||||
|
||||
assert config_entry.options.get("db_url") == db_url
|
||||
662
home-assistant/tests/components/sql/test_sensor.py
Normal file
662
home-assistant/tests/components/sql/test_sensor.py
Normal file
@@ -0,0 +1,662 @@
|
||||
"""The test for the sql sensor platform."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from homeassistant.components.recorder import Recorder
|
||||
from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
|
||||
from homeassistant.components.sql.const import CONF_QUERY, DOMAIN
|
||||
from homeassistant.components.sql.sensor import _generate_lambda_stmt
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.const import (
|
||||
CONF_ICON,
|
||||
CONF_UNIQUE_ID,
|
||||
STATE_UNAVAILABLE,
|
||||
STATE_UNKNOWN,
|
||||
UnitOfInformation,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import issue_registry as ir
|
||||
from homeassistant.helpers.entity_platform import async_get_platforms
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import (
|
||||
YAML_CONFIG,
|
||||
YAML_CONFIG_ALL_TEMPLATES,
|
||||
YAML_CONFIG_BINARY,
|
||||
YAML_CONFIG_FULL_TABLE_SCAN,
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_NO_UNIQUE_ID,
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_WITH_MULTIPLE_COLUMNS,
|
||||
YAML_CONFIG_WITH_VIEW_THAT_CONTAINS_ENTITY_ID,
|
||||
init_integration,
|
||||
)
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
async def test_query_basic(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test the SQL sensor."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query",
|
||||
"unique_id": "very_unique_id",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
|
||||
async def test_query_cte(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test the SQL sensor with CTE."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "WITH test AS (SELECT 1 AS row_num, 10 AS state) SELECT state FROM test WHERE row_num = 1 LIMIT 1;",
|
||||
"column": "state",
|
||||
"name": "Select value SQL query CTE",
|
||||
"unique_id": "very_unique_id",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query_cte")
|
||||
assert state.state == "10"
|
||||
assert state.attributes["state"] == 10
|
||||
|
||||
|
||||
async def test_query_value_template(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test the SQL sensor."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5.01 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
"value_template": "{{ value | int }}",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.count_tables")
|
||||
assert state.state == "5"
|
||||
|
||||
|
||||
async def test_query_value_template_invalid(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test the SQL sensor."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5.01 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
"value_template": "{{ value | dontwork }}",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.count_tables")
|
||||
assert state.state == "5.01"
|
||||
|
||||
|
||||
async def test_query_limit(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test the SQL sensor with a query containing 'LIMIT' in lowercase."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value limit 1",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
|
||||
async def test_query_no_value(
|
||||
recorder_mock: Recorder, hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test the SQL sensor with a query that returns no value."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value where 1=2",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.count_tables")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
text = "SELECT 5 as value where 1=2 LIMIT 1; returned no results"
|
||||
assert text in caplog.text
|
||||
|
||||
|
||||
async def test_query_on_disk_sqlite_no_result(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Test the SQL sensor with a query that returns no value."""
|
||||
db_path = tmp_path / "test.db"
|
||||
db_path_str = f"sqlite:///{db_path}"
|
||||
|
||||
def make_test_db():
|
||||
"""Create a test database."""
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.execute("CREATE TABLE users (value INTEGER)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
await hass.async_add_executor_job(make_test_db)
|
||||
|
||||
config = {
|
||||
"db_url": db_path_str,
|
||||
"query": "SELECT value from users",
|
||||
"column": "value",
|
||||
"name": "count_users",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.count_users")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
text = "SELECT value from users LIMIT 1; returned no results"
|
||||
assert text in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "expected_patterns", "not_expected_patterns"),
|
||||
[
|
||||
(
|
||||
"sqlite://homeassistant:hunter2@homeassistant.local",
|
||||
["sqlite://****:****@homeassistant.local"],
|
||||
["sqlite://homeassistant:hunter2@homeassistant.local"],
|
||||
),
|
||||
(
|
||||
"sqlite://homeassistant.local",
|
||||
["sqlite://homeassistant.local"],
|
||||
[],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_invalid_url_setup(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
url: str,
|
||||
expected_patterns: str,
|
||||
not_expected_patterns: str,
|
||||
) -> None:
|
||||
"""Test invalid db url with redacted credentials."""
|
||||
config = {
|
||||
"db_url": url,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
source=SOURCE_USER,
|
||||
data={},
|
||||
options=config,
|
||||
entry_id="1",
|
||||
)
|
||||
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.sensor.sqlalchemy.create_engine",
|
||||
side_effect=SQLAlchemyError(url),
|
||||
):
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
for pattern in not_expected_patterns:
|
||||
assert pattern not in caplog.text
|
||||
for pattern in expected_patterns:
|
||||
assert pattern in caplog.text
|
||||
|
||||
|
||||
async def test_invalid_url_on_update(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test invalid db url with redacted credentials on retry."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
|
||||
class MockSession:
|
||||
"""Mock session."""
|
||||
|
||||
def execute(self, query: Any) -> None:
|
||||
"""Execute the query."""
|
||||
raise SQLAlchemyError("sqlite://homeassistant:hunter2@homeassistant.local")
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.sensor.scoped_session",
|
||||
return_value=MockSession,
|
||||
):
|
||||
await init_integration(hass, config)
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + timedelta(minutes=1),
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert "sqlite://****:****@homeassistant.local" in caplog.text
|
||||
|
||||
|
||||
async def test_query_from_yaml(recorder_mock: Recorder, hass: HomeAssistant) -> None:
|
||||
"""Test the SQL sensor from yaml config."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.get_value")
|
||||
assert state.state == "5"
|
||||
|
||||
|
||||
async def test_templates_with_yaml(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test the SQL sensor from yaml config with templates."""
|
||||
|
||||
hass.states.async_set("sensor.input1", "on")
|
||||
hass.states.async_set("sensor.input2", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG_ALL_TEMPLATES)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.get_values_with_template")
|
||||
assert state.state == "5"
|
||||
assert state.attributes[CONF_ICON] == "mdi:on"
|
||||
assert state.attributes["entity_picture"] == "/local/picture1.jpg"
|
||||
|
||||
hass.states.async_set("sensor.input1", "off")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + timedelta(minutes=1),
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("sensor.get_values_with_template")
|
||||
assert state.state == "5"
|
||||
assert state.attributes[CONF_ICON] == "mdi:off"
|
||||
assert state.attributes["entity_picture"] == "/local/picture2.jpg"
|
||||
|
||||
hass.states.async_set("sensor.input2", "off")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + timedelta(minutes=2),
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("sensor.get_values_with_template")
|
||||
assert state.state == STATE_UNAVAILABLE
|
||||
|
||||
hass.states.async_set("sensor.input1", "on")
|
||||
hass.states.async_set("sensor.input2", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + timedelta(minutes=3),
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("sensor.get_values_with_template")
|
||||
assert state.state == "5"
|
||||
assert state.attributes[CONF_ICON] == "mdi:on"
|
||||
assert state.attributes["entity_picture"] == "/local/picture1.jpg"
|
||||
|
||||
|
||||
async def test_config_from_old_yaml(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test the SQL sensor from old yaml config does not create any entity."""
|
||||
config = {
|
||||
"sensor": {
|
||||
"platform": "sql",
|
||||
"db_url": "sqlite://",
|
||||
"queries": [
|
||||
{
|
||||
"name": "count_tables",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
assert await async_setup_component(hass, "sensor", config)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.count_tables")
|
||||
assert not state
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "expected_patterns", "not_expected_patterns"),
|
||||
[
|
||||
(
|
||||
"sqlite://homeassistant:hunter2@homeassistant.local",
|
||||
["sqlite://****:****@homeassistant.local"],
|
||||
["sqlite://homeassistant:hunter2@homeassistant.local"],
|
||||
),
|
||||
(
|
||||
"sqlite://homeassistant.local",
|
||||
["sqlite://homeassistant.local"],
|
||||
[],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_invalid_url_setup_from_yaml(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
url: str,
|
||||
expected_patterns: str,
|
||||
not_expected_patterns: str,
|
||||
) -> None:
|
||||
"""Test invalid db url with redacted credentials from yaml setup."""
|
||||
config = {
|
||||
"sql": {
|
||||
"db_url": url,
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "count_tables",
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.sensor.sqlalchemy.create_engine",
|
||||
side_effect=SQLAlchemyError(url),
|
||||
):
|
||||
assert await async_setup_component(hass, DOMAIN, config)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
for pattern in not_expected_patterns:
|
||||
assert pattern not in caplog.text
|
||||
for pattern in expected_patterns:
|
||||
assert pattern in caplog.text
|
||||
|
||||
|
||||
async def test_attributes_from_yaml_setup(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test attributes from yaml config."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.get_value")
|
||||
|
||||
assert state.state == "5"
|
||||
assert state.attributes["device_class"] == SensorDeviceClass.DATA_SIZE
|
||||
assert state.attributes["state_class"] == SensorStateClass.MEASUREMENT
|
||||
assert state.attributes["unit_of_measurement"] == UnitOfInformation.MEBIBYTES
|
||||
|
||||
|
||||
async def test_binary_data_from_yaml_setup(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test binary data from yaml config."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG_BINARY)
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("sensor.get_binary_value")
|
||||
assert state.state == "0xd34324324230392032"
|
||||
assert state.attributes["test_attr"] == "0xd343aa"
|
||||
|
||||
|
||||
async def test_issue_when_using_old_query(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
issue_registry: ir.IssueRegistry,
|
||||
) -> None:
|
||||
"""Test we create an issue for an old query that will do a full table scan."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG_FULL_TABLE_SCAN)
|
||||
await hass.async_block_till_done()
|
||||
assert "Query contains entity_id but does not reference states_meta" in caplog.text
|
||||
|
||||
assert not hass.states.async_all()
|
||||
|
||||
config = YAML_CONFIG_FULL_TABLE_SCAN["sql"]
|
||||
|
||||
unique_id = config[CONF_UNIQUE_ID]
|
||||
|
||||
issue = issue_registry.async_get_issue(
|
||||
DOMAIN, f"entity_id_query_does_full_table_scan_{unique_id}"
|
||||
)
|
||||
assert issue.translation_placeholders == {"query": config[CONF_QUERY]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"yaml_config",
|
||||
[
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_NO_UNIQUE_ID,
|
||||
YAML_CONFIG_FULL_TABLE_SCAN_WITH_MULTIPLE_COLUMNS,
|
||||
],
|
||||
)
|
||||
async def test_issue_when_using_old_query_without_unique_id(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
yaml_config: dict[str, Any],
|
||||
issue_registry: ir.IssueRegistry,
|
||||
) -> None:
|
||||
"""Test we create an issue for an old query that will do a full table scan."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, yaml_config)
|
||||
await hass.async_block_till_done()
|
||||
assert "Query contains entity_id but does not reference states_meta" in caplog.text
|
||||
|
||||
assert not hass.states.async_all()
|
||||
|
||||
config = yaml_config["sql"]
|
||||
query = config[CONF_QUERY]
|
||||
|
||||
issue = issue_registry.async_get_issue(
|
||||
DOMAIN, f"entity_id_query_does_full_table_scan_{query}"
|
||||
)
|
||||
assert issue.translation_placeholders == {"query": query}
|
||||
|
||||
|
||||
async def test_no_issue_when_view_has_the_text_entity_id_in_it(
|
||||
recorder_mock: Recorder, hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test we do not trigger the full table scan issue for a custom view."""
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.sensor.scoped_session",
|
||||
):
|
||||
await init_integration(
|
||||
hass, YAML_CONFIG_WITH_VIEW_THAT_CONTAINS_ENTITY_ID["sql"]
|
||||
)
|
||||
async_fire_time_changed(
|
||||
hass,
|
||||
dt_util.utcnow() + timedelta(minutes=1),
|
||||
)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert (
|
||||
"Query contains entity_id but does not reference states_meta" not in caplog.text
|
||||
)
|
||||
assert hass.states.get("sensor.get_entity_id") is not None
|
||||
|
||||
|
||||
async def test_multiple_sensors_using_same_db(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test multiple sensors using the same db."""
|
||||
config = {
|
||||
"db_url": "sqlite:///",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query",
|
||||
}
|
||||
config2 = {
|
||||
"db_url": "sqlite:///",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query 2",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
await init_integration(hass, config2, entry_id="2")
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query_2")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
with patch("sqlalchemy.engine.base.Engine.dispose"):
|
||||
await hass.async_stop()
|
||||
|
||||
|
||||
async def test_engine_is_disposed_at_stop(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test we dispose of the engine at stop."""
|
||||
config = {
|
||||
"db_url": "sqlite:///",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
with patch("sqlalchemy.engine.base.Engine.dispose") as mock_engine_dispose:
|
||||
await hass.async_stop()
|
||||
|
||||
assert mock_engine_dispose.call_count == 2
|
||||
|
||||
|
||||
async def test_attributes_from_entry_config(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test attributes from entry config."""
|
||||
|
||||
await init_integration(
|
||||
hass,
|
||||
config={
|
||||
"name": "Get Value - With",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
"device_class": SensorDeviceClass.DATA_SIZE,
|
||||
"state_class": SensorStateClass.TOTAL,
|
||||
},
|
||||
entry_id="8693d4782ced4fb1ecca4743f29ab8f1",
|
||||
)
|
||||
|
||||
state = hass.states.get("sensor.get_value_with")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
assert state.attributes["unit_of_measurement"] == "MiB"
|
||||
assert state.attributes["device_class"] == SensorDeviceClass.DATA_SIZE
|
||||
assert state.attributes["state_class"] == SensorStateClass.TOTAL
|
||||
|
||||
await init_integration(
|
||||
hass,
|
||||
config={
|
||||
"name": "Get Value - Without",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
entry_id="7aec7cd8045fba4778bb0621469e3cd9",
|
||||
)
|
||||
|
||||
state = hass.states.get("sensor.get_value_without")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
assert state.attributes["unit_of_measurement"] == "MiB"
|
||||
assert "device_class" not in state.attributes
|
||||
assert "state_class" not in state.attributes
|
||||
|
||||
|
||||
async def test_query_recover_from_rollback(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the SQL sensor."""
|
||||
config = {
|
||||
"db_url": "sqlite://",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"name": "Select value SQL query",
|
||||
"unique_id": "very_unique_id",
|
||||
}
|
||||
await init_integration(hass, config)
|
||||
platforms = async_get_platforms(hass, "sql")
|
||||
sql_entity = platforms[0].entities["sensor.select_value_sql_query"]
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes["value"] == 5
|
||||
|
||||
with patch.object(
|
||||
sql_entity,
|
||||
"_lambda_stmt",
|
||||
_generate_lambda_stmt("Faulty syntax create operational issue"),
|
||||
):
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert "sqlite3.OperationalError" in caplog.text
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes.get("value") is None
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
state = hass.states.get("sensor.select_value_sql_query")
|
||||
assert state.state == "5"
|
||||
assert state.attributes.get("value") == 5
|
||||
|
||||
|
||||
async def test_setup_without_recorder(hass: HomeAssistant) -> None:
|
||||
"""Test the SQL sensor without recorder."""
|
||||
|
||||
assert await async_setup_component(hass, DOMAIN, YAML_CONFIG)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("sensor.get_value")
|
||||
assert state.state == "5"
|
||||
24
home-assistant/tests/components/sql/test_util.py
Normal file
24
home-assistant/tests/components/sql/test_util.py
Normal file
@@ -0,0 +1,24 @@
|
||||
"""Test the sql utils."""
|
||||
|
||||
from homeassistant.components.recorder import Recorder, get_instance
|
||||
from homeassistant.components.sql.util import resolve_db_url
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def test_resolve_db_url_when_none_configured(
|
||||
recorder_mock: Recorder,
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test return recorder db_url if provided db_url is None."""
|
||||
db_url = None
|
||||
resolved_url = resolve_db_url(hass, db_url)
|
||||
|
||||
assert resolved_url == get_instance(hass).db_url
|
||||
|
||||
|
||||
async def test_resolve_db_url_when_configured(hass: HomeAssistant) -> None:
|
||||
"""Test return provided db_url if it's set."""
|
||||
db_url = "mssql://"
|
||||
resolved_url = resolve_db_url(hass, db_url)
|
||||
|
||||
assert resolved_url == db_url
|
||||
Reference in New Issue
Block a user