Skip to content

Commit

Permalink
Add reload service (#135, #97)
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed Jul 21, 2022
1 parent 1147505 commit ed0516e
Show file tree
Hide file tree
Showing 15 changed files with 160 additions and 33 deletions.
45 changes: 41 additions & 4 deletions custom_components/average/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,48 @@
#
# Copyright (c) 2019, Andrey "Limych" Khrolenok <[email protected]>
# Copyright (c) 2019-2022, Andrey "Limych" Khrolenok <[email protected]>
# Creative Commons BY-NC-SA 4.0 International Public License
# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/)
#

"""
The Average Temperature Sensor.
The Average Sensor.
For more details about this sensor, please refer to the documentation at
https://github.com/Limych/ha-average/
"""
from __future__ import annotations

import logging

import voluptuous as vol
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.reload import async_reload_integration_platforms
from homeassistant.helpers.typing import ConfigType

from .const import DOMAIN, PLATFORMS, STARTUP_MESSAGE

_LOGGER = logging.getLogger(__name__)


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the platforms."""
# Print startup message
_LOGGER.info(STARTUP_MESSAGE)

# await async_setup_reload_service(hass, DOMAIN, PLATFORMS)

component = EntityComponent(_LOGGER, DOMAIN, hass)

async def reload_service_handler(service: ServiceCall) -> None:
"""Reload all average sensors from config."""
print("+++++++++++++++++++++++++")
print(component)
# print(hass.data[DATA_INSTANCES]["sensor"].entities[0])

await async_reload_integration_platforms(hass, DOMAIN, PLATFORMS)

hass.services.async_register(
DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=vol.Schema({})
)

return True
6 changes: 6 additions & 0 deletions custom_components/average/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from typing import Final

# Base component constants
from homeassistant.const import Platform

NAME: Final = "Average Sensor"
DOMAIN: Final = "average"
VERSION: Final = "2.2.4-alpha"
Expand All @@ -23,6 +25,10 @@
-------------------------------------------------------------------
"""

PLATFORMS = [
Platform.SENSOR,
]

# Configuration and options
CONF_START: Final = "start"
CONF_END: Final = "end"
Expand Down
36 changes: 18 additions & 18 deletions custom_components/average/manifest.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
{
"domain": "average",
"name": "Average Sensor",
"version": "2.2.4-alpha",
"documentation": "https://github.com/Limych/ha-average",
"issue_tracker": "https://github.com/Limych/ha-average/issues",
"dependencies": [],
"after_dependencies": [
"history",
"recorder",
"weather"
],
"config_flow": false,
"codeowners": [
"@Limych"
],
"requirements": [],
"iot_class": "calculated"
}
"domain": "average",
"name": "Average Sensor",
"version": "2.2.4-alpha",
"documentation": "https://github.com/Limych/ha-average",
"issue_tracker": "https://github.com/Limych/ha-average/issues",
"dependencies": [],
"after_dependencies": [
"history",
"recorder",
"weather"
],
"config_flow": false,
"codeowners": [
"@Limych"
],
"requirements": [],
"iot_class": "calculated"
}
4 changes: 0 additions & 4 deletions custom_components/average/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
CONF_START,
DEFAULT_NAME,
DEFAULT_PRECISION,
STARTUP_MESSAGE,
UPDATE_MIN_TIME,
)

Expand Down Expand Up @@ -98,9 +97,6 @@ async def async_setup_platform(
hass: HomeAssistant, config, async_add_entities, discovery_info=None
):
"""Set up platform."""
# Print startup message
_LOGGER.info(STARTUP_MESSAGE)

start = config.get(CONF_START)
end = config.get(CONF_END)

Expand Down
3 changes: 3 additions & 0 deletions custom_components/average/services.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
reload:
name: Reload
description: Reload all average sensor entities
2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "Average Sensor",
"hacs": "1.6.0",
"homeassistant": "2022.6.0"
"homeassistant": "2022.7.0"
}
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
homeassistant>=2022.6.0
homeassistant>=2022.7.0
8 changes: 8 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
"""Tests for integration."""
import pathlib
import traceback


def get_fixture_path(filename: str) -> pathlib.Path:
"""Get path of fixture."""
start_path = traceback.extract_stack()[-1].filename
return pathlib.Path(start_path).parent.joinpath("fixtures", filename)
2 changes: 2 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#
# See here for more info: https://docs.pytest.org/en/latest/fixture.html (note that
# pytest includes fixtures OOB which you can use as defined on this page)
from __future__ import annotations

from unittest.mock import patch

import pytest
Expand Down
16 changes: 16 additions & 0 deletions tests/const.py
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
"""Constants for tests."""
from __future__ import annotations

from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_ENTITIES, CONF_NAME, CONF_UNIQUE_ID
from homeassistant.util import yaml

from tests import get_fixture_path

MOCK_CONFIG = yaml.load_yaml(str(get_fixture_path("configuration.yaml")))

_cfg = MOCK_CONFIG.get(SENSOR_DOMAIN)[0] # type: dict

TEST_UNIQUE_ID = _cfg.get(CONF_UNIQUE_ID)
TEST_NAME = _cfg.get(CONF_NAME)
TEST_ENTITY_IDS = _cfg.get(CONF_ENTITIES)
TEST_VALUES = [3, 11.16, -17, 4.29, -29, -16.8, 8, 5, -4.7, 5, -15]
6 changes: 6 additions & 0 deletions tests/fixtures/configuration.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
sensor:
- platform: average
entities:
- sensor.test_monitored
# unique_id: test_id
name: test_name
Empty file.
56 changes: 56 additions & 0 deletions tests/test__init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""The test for the average integration."""
# pylint: disable=redefined-outer-name
from __future__ import annotations

from unittest.mock import patch

from homeassistant import config as hass_config
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import SERVICE_RELOAD
from homeassistant.setup import async_setup_component

from custom_components.average.const import DOMAIN

from . import get_fixture_path
from .const import MOCK_CONFIG, TEST_NAME


async def test_reload(hass):
"""Verify we can reload."""
assert await async_setup_component(hass, SENSOR_DOMAIN, MOCK_CONFIG)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()

assert len(hass.states.async_all()) == 1

assert hass.states.get(f"{SENSOR_DOMAIN}.{TEST_NAME}")

yaml_path = get_fixture_path("configuration.yaml")

with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(DOMAIN, SERVICE_RELOAD, {}, blocking=True)
await hass.async_block_till_done()

assert hass.states.get(f"{SENSOR_DOMAIN}.{TEST_NAME}")


async def test_reload_and_remove_all(hass):
"""Verify we can reload and remove all."""
assert await async_setup_component(hass, SENSOR_DOMAIN, MOCK_CONFIG)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()

assert len(hass.states.async_all()) == 1

assert hass.states.get(f"{SENSOR_DOMAIN}.{TEST_NAME}")

yaml_path = get_fixture_path("configuration_empty.yaml")

with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(DOMAIN, SERVICE_RELOAD, {}, blocking=True)
await hass.async_block_till_done()

print(hass.states.get(f"{SENSOR_DOMAIN}.{TEST_NAME}"))
assert hass.states.get(f"{SENSOR_DOMAIN}.{TEST_NAME}") is None
2 changes: 1 addition & 1 deletion tests/test_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from homeassistant.components import recorder
from homeassistant.components.input_boolean import DOMAIN
from homeassistant.components.recorder.models import StateAttributes, States
from homeassistant.components.recorder.db_schema import StateAttributes, States
from homeassistant.components.recorder.util import session_scope
from homeassistant.const import ATTR_EDITABLE
from homeassistant.core import HomeAssistant, State
Expand Down
5 changes: 1 addition & 4 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@
check_period_keys,
)

TEST_UNIQUE_ID = "test_id"
TEST_NAME = "test_name"
TEST_ENTITY_IDS = ["sensor.test_monitored"]
TEST_VALUES = [3, 11.16, -17, 4.29, -29, -16.8, 8, 5, -4.7, 5, -15]
from .const import TEST_ENTITY_IDS, TEST_NAME, TEST_UNIQUE_ID


@pytest.fixture()
Expand Down

0 comments on commit ed0516e

Please sign in to comment.