2018-02-08 07:32:39 +00:00
|
|
|
"""The test for the sql sensor platform."""
|
|
|
|
import unittest
|
2019-10-20 08:10:27 +00:00
|
|
|
|
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
|
2019-10-20 08:10:27 +00:00
|
|
|
from homeassistant.setup import setup_component
|
2018-02-08 07:32:39 +00:00
|
|
|
|
|
|
|
from tests.common import get_test_home_assistant
|
|
|
|
|
|
|
|
|
|
|
|
class TestSQLSensor(unittest.TestCase):
|
|
|
|
"""Test the SQL sensor."""
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
"""Set up things to be run when tests are started."""
|
|
|
|
self.hass = get_test_home_assistant()
|
|
|
|
|
|
|
|
def teardown_method(self, method):
|
|
|
|
"""Stop everything that was started."""
|
|
|
|
self.hass.stop()
|
|
|
|
|
|
|
|
def test_query(self):
|
|
|
|
"""Test the SQL sensor."""
|
|
|
|
config = {
|
2019-07-31 19:25:30 +00:00
|
|
|
"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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
assert setup_component(self.hass, "sensor", config)
|
2018-02-08 07:32:39 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
state = self.hass.states.get("sensor.count_tables")
|
|
|
|
assert state.state == "5"
|
|
|
|
assert state.attributes["value"] == 5
|
2018-03-06 03:44:04 +00:00
|
|
|
|
|
|
|
def test_invalid_query(self):
|
|
|
|
"""Test the SQL sensor for invalid queries."""
|
|
|
|
with pytest.raises(vol.Invalid):
|
|
|
|
validate_sql_select("DROP TABLE *")
|
|
|
|
|
|
|
|
config = {
|
2019-07-31 19:25:30 +00:00
|
|
|
"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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
assert setup_component(self.hass, "sensor", config)
|
2018-03-06 03:44:04 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
state = self.hass.states.get("sensor.count_tables")
|
2018-10-24 10:10:05 +00:00
|
|
|
assert state.state == STATE_UNKNOWN
|