2018-02-08 07:32:39 +00:00
|
|
|
"""The test for the sql sensor platform."""
|
2018-03-06 03:44:04 +00:00
|
|
|
import pytest
|
|
|
|
import voluptuous as vol
|
2018-02-08 07:32:39 +00:00
|
|
|
|
2019-03-19 06:07:39 +00:00
|
|
|
from homeassistant.components.sql.sensor import validate_sql_select
|
2018-03-06 03:44:04 +00:00
|
|
|
from homeassistant.const import STATE_UNKNOWN
|
2020-10-03 01:42:50 +00:00
|
|
|
from homeassistant.setup import async_setup_component
|
2018-02-08 07:32:39 +00:00
|
|
|
|
|
|
|
|
2020-10-03 01:42:50 +00:00
|
|
|
async def test_query(hass):
|
2018-02-08 07:32:39 +00:00
|
|
|
"""Test the SQL sensor."""
|
2020-10-03 01:42:50 +00:00
|
|
|
config = {
|
|
|
|
"sensor": {
|
|
|
|
"platform": "sql",
|
|
|
|
"db_url": "sqlite://",
|
|
|
|
"queries": [
|
|
|
|
{
|
|
|
|
"name": "count_tables",
|
|
|
|
"query": "SELECT 5 as value",
|
|
|
|
"column": "value",
|
|
|
|
}
|
|
|
|
],
|
2018-02-08 07:32:39 +00:00
|
|
|
}
|
2020-10-03 01:42:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
assert await async_setup_component(hass, "sensor", config)
|
|
|
|
await hass.async_block_till_done()
|
|
|
|
|
|
|
|
state = hass.states.get("sensor.count_tables")
|
|
|
|
assert state.state == "5"
|
|
|
|
assert state.attributes["value"] == 5
|
|
|
|
|
|
|
|
|
|
|
|
async def test_invalid_query(hass):
|
|
|
|
"""Test the SQL sensor for invalid queries."""
|
|
|
|
with pytest.raises(vol.Invalid):
|
|
|
|
validate_sql_select("DROP TABLE *")
|
|
|
|
|
|
|
|
config = {
|
|
|
|
"sensor": {
|
|
|
|
"platform": "sql",
|
|
|
|
"db_url": "sqlite://",
|
|
|
|
"queries": [
|
|
|
|
{
|
|
|
|
"name": "count_tables",
|
|
|
|
"query": "SELECT * value FROM sqlite_master;",
|
|
|
|
"column": "value",
|
|
|
|
}
|
|
|
|
],
|
2018-03-06 03:44:04 +00:00
|
|
|
}
|
2020-10-03 01:42:50 +00:00
|
|
|
}
|
2018-03-06 03:44:04 +00:00
|
|
|
|
2020-10-03 01:42:50 +00:00
|
|
|
assert await async_setup_component(hass, "sensor", config)
|
|
|
|
await hass.async_block_till_done()
|
2018-03-06 03:44:04 +00:00
|
|
|
|
2020-10-03 01:42:50 +00:00
|
|
|
state = hass.states.get("sensor.count_tables")
|
|
|
|
assert state.state == STATE_UNKNOWN
|