hass-core/tests/components/sensor/test_sql.py
Diogo Gomes 5063464d5e Support for queries with no results (fix for #12856) (#12888)
* Addresses issue #12856

* error -> warning

* added edge case and test

* uff uff

* Added SELECT validation

* Improved tests
2018-03-05 19:44:04 -08:00

63 lines
1.9 KiB
Python

"""The test for the sql sensor platform."""
import unittest
import pytest
import voluptuous as vol
from homeassistant.components.sensor.sql import validate_sql_select
from homeassistant.setup import setup_component
from homeassistant.const import STATE_UNKNOWN
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 = {
'sensor': {
'platform': 'sql',
'db_url': 'sqlite://',
'queries': [{
'name': 'count_tables',
'query': 'SELECT count(*) value FROM sqlite_master;',
'column': 'value',
}]
}
}
assert setup_component(self.hass, 'sensor', config)
state = self.hass.states.get('sensor.count_tables')
self.assertEqual(state.state, '0')
def test_invalid_query(self):
"""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',
}]
}
}
assert setup_component(self.hass, 'sensor', config)
state = self.hass.states.get('sensor.count_tables')
self.assertEqual(state.state, STATE_UNKNOWN)