Workday cleanup (#90267)

* clean binary sensor

* fix const

* clean sensor

* Fix tests

* Clean up

---------

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
G Johansson 2023-03-27 23:11:49 +02:00 committed by GitHub
parent 182af87f97
commit cb6d384dba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 332 additions and 354 deletions

View File

@ -92,44 +92,38 @@ def setup_platform(
sensor_name: str = config[CONF_NAME] sensor_name: str = config[CONF_NAME]
workdays: list[str] = config[CONF_WORKDAYS] workdays: list[str] = config[CONF_WORKDAYS]
year: int = (get_date(dt.now()) + timedelta(days=days_offset)).year year: int = (dt.now() + timedelta(days=days_offset)).year
obj_holidays: HolidayBase = getattr(holidays, country)(years=year) obj_holidays: HolidayBase = getattr(holidays, country)(years=year)
if province: if province:
if ( try:
hasattr(obj_holidays, "subdivisions")
and province in obj_holidays.subdivisions
):
obj_holidays = getattr(holidays, country)(subdiv=province, years=year) obj_holidays = getattr(holidays, country)(subdiv=province, years=year)
else: except NotImplementedError:
LOGGER.error("There is no subdivision %s in country %s", province, country) LOGGER.error("There is no subdivision %s in country %s", province, country)
return return
# Add custom holidays # Add custom holidays
try: try:
obj_holidays.append(add_holidays) obj_holidays.append(add_holidays)
except TypeError: except ValueError as error:
LOGGER.debug("No custom holidays or invalid holidays") LOGGER.error("Could not add custom holidays: %s", error)
# Remove holidays # Remove holidays
try: for remove_holiday in remove_holidays:
for remove_holiday in remove_holidays: try:
try: # is this formatted as a date?
# is this formatted as a date? if dt.parse_date(remove_holiday):
if dt.parse_date(remove_holiday): # remove holiday by date
# remove holiday by date removed = obj_holidays.pop(remove_holiday)
removed = obj_holidays.pop(remove_holiday) LOGGER.debug("Removed %s", remove_holiday)
LOGGER.debug("Removed %s", remove_holiday) else:
else: # remove holiday by name
# remove holiday by name LOGGER.debug("Treating '%s' as named holiday", remove_holiday)
LOGGER.debug("Treating '%s' as named holiday", remove_holiday) removed = obj_holidays.pop_named(remove_holiday)
removed = obj_holidays.pop_named(remove_holiday) for holiday in removed:
for holiday in removed: LOGGER.debug("Removed %s by name '%s'", holiday, remove_holiday)
LOGGER.debug("Removed %s by name '%s'", holiday, remove_holiday) except KeyError as unmatched:
except KeyError as unmatched: LOGGER.warning("No holiday found matching %s", unmatched)
LOGGER.warning("No holiday found matching %s", unmatched)
except TypeError:
LOGGER.debug("No holidays to remove or invalid holidays")
LOGGER.debug("Found the following holidays for your configuration:") LOGGER.debug("Found the following holidays for your configuration:")
for holiday_date, name in sorted(obj_holidays.items()): for holiday_date, name in sorted(obj_holidays.items()):
@ -143,19 +137,6 @@ def setup_platform(
) )
def day_to_string(day: int) -> str | None:
"""Convert day index 0 - 7 to string."""
try:
return ALLOWED_DAYS[day]
except IndexError:
return None
def get_date(input_date: date) -> date:
"""Return date. Needed for testing."""
return input_date
class IsWorkdaySensor(BinarySensorEntity): class IsWorkdaySensor(BinarySensorEntity):
"""Implementation of a Workday sensor.""" """Implementation of a Workday sensor."""
@ -203,12 +184,9 @@ class IsWorkdaySensor(BinarySensorEntity):
self._attr_is_on = False self._attr_is_on = False
# Get ISO day of the week (1 = Monday, 7 = Sunday) # Get ISO day of the week (1 = Monday, 7 = Sunday)
adjusted_date = get_date(dt.now()) + timedelta(days=self._days_offset) adjusted_date = dt.now() + timedelta(days=self._days_offset)
day = adjusted_date.isoweekday() - 1 day = adjusted_date.isoweekday() - 1
day_of_week = day_to_string(day) day_of_week = ALLOWED_DAYS[day]
if day_of_week is None:
return
if self.is_include(day_of_week, adjusted_date): if self.is_include(day_of_week, adjusted_date):
self._attr_is_on = True self._attr_is_on = True

View File

@ -5,7 +5,7 @@ import logging
from homeassistant.const import WEEKDAYS from homeassistant.const import WEEKDAYS
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__package__)
ALLOWED_DAYS = WEEKDAYS + ["holiday"] ALLOWED_DAYS = WEEKDAYS + ["holiday"]

View File

@ -1 +1,159 @@
"""Tests the Home Assistant workday binary sensor.""" """Tests the Home Assistant workday binary sensor."""
from __future__ import annotations
from typing import Any
from homeassistant.components.workday.const import (
DEFAULT_EXCLUDES,
DEFAULT_NAME,
DEFAULT_OFFSET,
DEFAULT_WORKDAYS,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def init_integration(
hass: HomeAssistant,
config: dict[str, Any],
) -> None:
"""Set up the Workday integration in Home Assistant."""
await async_setup_component(
hass, "binary_sensor", {"binary_sensor": {"platform": "workday", **config}}
)
await hass.async_block_till_done()
TEST_CONFIG_WITH_PROVINCE = {
"name": DEFAULT_NAME,
"country": "DE",
"province": "BW",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_INCORRECT_PROVINCE = {
"name": DEFAULT_NAME,
"country": "DE",
"province": "ZZ",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_NO_PROVINCE = {
"name": DEFAULT_NAME,
"country": "DE",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_WITH_STATE = {
"name": DEFAULT_NAME,
"country": "US",
"province": "CA",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_NO_STATE = {
"name": DEFAULT_NAME,
"country": "US",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_INCLUDE_HOLIDAY = {
"name": DEFAULT_NAME,
"country": "DE",
"province": "BW",
"excludes": ["sat", "sun"],
"days_offset": DEFAULT_OFFSET,
"workdays": ["holiday"],
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_EXAMPLE_1 = {
"name": DEFAULT_NAME,
"country": "US",
"excludes": ["sat", "sun"],
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_EXAMPLE_2 = {
"name": DEFAULT_NAME,
"country": "DE",
"province": "BW",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": ["mon", "wed", "fri"],
"add_holidays": ["2020-02-24"],
"remove_holidays": [],
}
TEST_CONFIG_REMOVE_HOLIDAY = {
"name": DEFAULT_NAME,
"country": "US",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": ["2020-12-25", "2020-11-26"],
}
TEST_CONFIG_REMOVE_NAMED = {
"name": DEFAULT_NAME,
"country": "US",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": ["Not a Holiday", "Christmas", "Thanksgiving"],
}
TEST_CONFIG_TOMORROW = {
"name": DEFAULT_NAME,
"country": "DE",
"excludes": DEFAULT_EXCLUDES,
"days_offset": 1,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_DAY_AFTER_TOMORROW = {
"name": DEFAULT_NAME,
"country": "DE",
"excludes": DEFAULT_EXCLUDES,
"days_offset": 2,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_YESTERDAY = {
"name": DEFAULT_NAME,
"country": "DE",
"excludes": DEFAULT_EXCLUDES,
"days_offset": -1,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": [],
"remove_holidays": [],
}
TEST_CONFIG_INCORRECT_ADD_REMOVE = {
"name": DEFAULT_NAME,
"country": "DE",
"province": "BW",
"excludes": DEFAULT_EXCLUDES,
"days_offset": DEFAULT_OFFSET,
"workdays": DEFAULT_WORKDAYS,
"add_holidays": ["2023-12-32"],
"remove_holidays": ["2023-12-32"],
}

View File

@ -1,350 +1,192 @@
"""Tests the Home Assistant workday binary sensor.""" """Tests the Home Assistant workday binary sensor."""
from datetime import date from datetime import datetime
from unittest.mock import patch from typing import Any
from freezegun.api import FrozenDateTimeFactory
import pytest import pytest
import voluptuous as vol import voluptuous as vol
import homeassistant.components.workday.binary_sensor as binary_sensor from homeassistant.components.workday import binary_sensor
from homeassistant.setup import setup_component from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import UTC
from tests.common import assert_setup_component, get_test_home_assistant from . import (
TEST_CONFIG_DAY_AFTER_TOMORROW,
FUNCTION_PATH = "homeassistant.components.workday.binary_sensor.get_date" TEST_CONFIG_EXAMPLE_1,
TEST_CONFIG_EXAMPLE_2,
TEST_CONFIG_INCLUDE_HOLIDAY,
TEST_CONFIG_INCORRECT_ADD_REMOVE,
TEST_CONFIG_INCORRECT_PROVINCE,
TEST_CONFIG_NO_PROVINCE,
TEST_CONFIG_NO_STATE,
TEST_CONFIG_REMOVE_HOLIDAY,
TEST_CONFIG_REMOVE_NAMED,
TEST_CONFIG_TOMORROW,
TEST_CONFIG_WITH_PROVINCE,
TEST_CONFIG_WITH_STATE,
TEST_CONFIG_YESTERDAY,
init_integration,
)
class TestWorkdaySetup: async def test_valid_country_yaml() -> None:
"""Test class for workday sensor.""" """Test valid country from yaml."""
# Invalid UTF-8, must not contain U+D800 to U+DFFF
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("\ud800")
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("\udfff")
# Country MUST NOT be empty
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("")
# Country must be supported by holidays
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("HomeAssistantLand")
def setup_method(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
# Set valid default config for test @pytest.mark.parametrize(
self.config_province = { ("config", "expected_state"),
"binary_sensor": {"platform": "workday", "country": "DE", "province": "BW"} [
} (TEST_CONFIG_WITH_PROVINCE, "off"),
(TEST_CONFIG_NO_PROVINCE, "off"),
(TEST_CONFIG_WITH_STATE, "on"),
(TEST_CONFIG_NO_STATE, "on"),
(TEST_CONFIG_EXAMPLE_1, "on"),
(TEST_CONFIG_EXAMPLE_2, "off"),
(TEST_CONFIG_TOMORROW, "off"),
(TEST_CONFIG_DAY_AFTER_TOMORROW, "off"),
(TEST_CONFIG_YESTERDAY, "on"),
],
)
async def test_setup(
hass: HomeAssistant,
config: dict[str, Any],
expected_state: str,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test setup from various configs."""
freezer.move_to(datetime(2022, 4, 15, 12, tzinfo=UTC)) # Monday
await init_integration(hass, config)
self.config_noprovince = { state = hass.states.get("binary_sensor.workday_sensor")
"binary_sensor": {"platform": "workday", "country": "DE"} assert state.state == expected_state
} assert state.attributes == {
"friendly_name": "Workday Sensor",
"workdays": config["workdays"],
"excludes": config["excludes"],
"days_offset": config["days_offset"],
}
self.config_invalidprovince = {
async def test_setup_with_invalid_province_from_yaml(hass: HomeAssistant) -> None:
"""Test setup invalid province with import."""
await async_setup_component(
hass,
"binary_sensor",
{
"binary_sensor": { "binary_sensor": {
"platform": "workday", "platform": "workday",
"country": "DE", "country": "DE",
"province": "invalid", "province": "invalid",
} }
} },
)
await hass.async_block_till_done()
self.config_state = { state = hass.states.get("binary_sensor.workday_sensor")
"binary_sensor": {"platform": "workday", "country": "US", "province": "CA"} assert state is None
}
self.config_nostate = {
"binary_sensor": {"platform": "workday", "country": "US"}
}
self.config_includeholiday = { async def test_setup_with_working_holiday(
"binary_sensor": { hass: HomeAssistant,
"platform": "workday", freezer: FrozenDateTimeFactory,
"country": "DE", ) -> None:
"province": "BW", """Test setup from various configs."""
"workdays": ["holiday"], freezer.move_to(datetime(2017, 1, 6, 12, tzinfo=UTC)) # Friday
"excludes": ["sat", "sun"], await init_integration(hass, TEST_CONFIG_INCLUDE_HOLIDAY)
}
}
self.config_example1 = { state = hass.states.get("binary_sensor.workday_sensor")
"binary_sensor": { assert state.state == "on"
"platform": "workday",
"country": "US",
"workdays": ["mon", "tue", "wed", "thu", "fri"],
"excludes": ["sat", "sun"],
}
}
self.config_example2 = {
"binary_sensor": {
"platform": "workday",
"country": "DE",
"province": "BW",
"workdays": ["mon", "wed", "fri"],
"excludes": ["sat", "sun", "holiday"],
"add_holidays": ["2020-02-24"],
}
}
self.config_remove_holidays = { async def test_setup_add_holiday(
"binary_sensor": { hass: HomeAssistant,
"platform": "workday", freezer: FrozenDateTimeFactory,
"country": "US", ) -> None:
"workdays": ["mon", "tue", "wed", "thu", "fri"], """Test setup from various configs."""
"excludes": ["sat", "sun", "holiday"], freezer.move_to(datetime(2020, 2, 24, 12, tzinfo=UTC)) # Monday
"remove_holidays": ["2020-12-25", "2020-11-26"], await init_integration(hass, TEST_CONFIG_EXAMPLE_2)
}
}
self.config_remove_named_holidays = { state = hass.states.get("binary_sensor.workday_sensor")
"binary_sensor": { assert state.state == "off"
"platform": "workday",
"country": "US",
"workdays": ["mon", "tue", "wed", "thu", "fri"],
"excludes": ["sat", "sun", "holiday"],
"remove_holidays": ["Not a Holiday", "Christmas", "Thanksgiving"],
}
}
self.config_tomorrow = {
"binary_sensor": {"platform": "workday", "country": "DE", "days_offset": 1}
}
self.config_day_after_tomorrow = { async def test_setup_remove_holiday(
"binary_sensor": {"platform": "workday", "country": "DE", "days_offset": 2} hass: HomeAssistant,
} freezer: FrozenDateTimeFactory,
) -> None:
"""Test setup from various configs."""
freezer.move_to(datetime(2020, 12, 25, 12, tzinfo=UTC)) # Friday
await init_integration(hass, TEST_CONFIG_REMOVE_HOLIDAY)
self.config_yesterday = { state = hass.states.get("binary_sensor.workday_sensor")
"binary_sensor": {"platform": "workday", "country": "DE", "days_offset": -1} assert state.state == "on"
}
def teardown_method(self):
"""Stop everything that was started."""
self.hass.stop()
def test_valid_country(self): async def test_setup_remove_holiday_named(
"""Test topic name/filter validation.""" hass: HomeAssistant,
# Invalid UTF-8, must not contain U+D800 to U+DFFF freezer: FrozenDateTimeFactory,
with pytest.raises(vol.Invalid): ) -> None:
binary_sensor.valid_country("\ud800") """Test setup from various configs."""
with pytest.raises(vol.Invalid): freezer.move_to(datetime(2020, 12, 25, 12, tzinfo=UTC)) # Friday
binary_sensor.valid_country("\udfff") await init_integration(hass, TEST_CONFIG_REMOVE_NAMED)
# Country MUST NOT be empty
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("")
# Country must be supported by holidays
with pytest.raises(vol.Invalid):
binary_sensor.valid_country("HomeAssistantLand")
# Valid country code validation must not raise an exception state = hass.states.get("binary_sensor.workday_sensor")
for country in ("IM", "LI", "US"): assert state.state == "on"
assert binary_sensor.valid_country(country) == country
def test_setup_component_province(self):
"""Set up workday component."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_province)
self.hass.block_till_done()
entity = self.hass.states.get("binary_sensor.workday_sensor") async def test_setup_day_after_tomorrow(
assert entity is not None hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test setup from various configs."""
freezer.move_to(datetime(2022, 5, 27, 12, tzinfo=UTC)) # Friday
await init_integration(hass, TEST_CONFIG_DAY_AFTER_TOMORROW)
# Freeze time to a workday - Mar 15th, 2017 state = hass.states.get("binary_sensor.workday_sensor")
@patch(FUNCTION_PATH, return_value=date(2017, 3, 15)) assert state.state == "off"
def test_workday_province(self, mock_date):
"""Test if workdays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_province)
self.hass.block_till_done()
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor") async def test_setup_faulty_province(
assert entity.state == "on" hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test setup with faulty province."""
freezer.move_to(datetime(2017, 1, 6, 12, tzinfo=UTC)) # Friday
await init_integration(hass, TEST_CONFIG_INCORRECT_PROVINCE)
# Freeze time to a weekend - Mar 12th, 2017 state = hass.states.get("binary_sensor.workday_sensor")
@patch(FUNCTION_PATH, return_value=date(2017, 3, 12)) assert state is None
def test_weekend_province(self, mock_date):
"""Test if weekends are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_province)
self.hass.block_till_done()
self.hass.start() assert "There is no subdivision" in caplog.text
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "off"
# Freeze time to a public holiday in province BW - Jan 6th, 2017 async def test_setup_incorrect_add_remove(
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6)) hass: HomeAssistant,
def test_public_holiday_province(self, mock_date): freezer: FrozenDateTimeFactory,
"""Test if public holidays are reported correctly.""" caplog: pytest.LogCaptureFixture,
with assert_setup_component(1, "binary_sensor"): ) -> None:
setup_component(self.hass, "binary_sensor", self.config_province) """Test setup with incorrect add/remove custom holiday."""
self.hass.block_till_done() freezer.move_to(datetime(2017, 1, 6, 12, tzinfo=UTC)) # Friday
await init_integration(hass, TEST_CONFIG_INCORRECT_ADD_REMOVE)
self.hass.start() hass.states.get("binary_sensor.workday_sensor")
entity = self.hass.states.get("binary_sensor.workday_sensor") assert (
assert entity.state == "off" "Could not add custom holidays: Cannot parse date from string '2023-12-32'"
in caplog.text
def test_setup_component_noprovince(self): )
"""Set up workday component.""" assert "No holiday found matching '2023-12-32'" in caplog.text
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_noprovince)
self.hass.block_till_done()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity is not None
# Freeze time to a public holiday in province BW - Jan 6th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
def test_public_holiday_noprovince(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_noprovince)
self.hass.block_till_done()
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to a public holiday in state CA - Mar 31st, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
def test_public_holiday_state(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_state)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "off"
# Freeze time to a public holiday in state CA - Mar 31st, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
def test_public_holiday_nostate(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_nostate)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
def test_setup_component_invalidprovince(self):
"""Set up workday component."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_invalidprovince)
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity is None
# Freeze time to a public holiday in province BW - Jan 6th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
def test_public_holiday_includeholiday(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_includeholiday)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_tomorrow(self, mock_date):
"""Test if tomorrow are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_tomorrow)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "off"
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_day_after_tomorrow(self, mock_date):
"""Test if the day after tomorrow are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_day_after_tomorrow)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to a saturday to test offset - Aug 5th, 2017
@patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
def test_yesterday(self, mock_date):
"""Test if yesterday are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_yesterday)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to a Presidents day to test Holiday on a Work day - Jan 20th, 2020
# Presidents day Feb 17th 2020 is mon.
@patch(FUNCTION_PATH, return_value=date(2020, 2, 17))
def test_config_example1_holiday(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_example1)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to test tue - Feb 18th, 2020
@patch(FUNCTION_PATH, return_value=date(2020, 2, 18))
def test_config_example2_tue(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_example2)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "off"
# Freeze time to test mon, but added as holiday - Feb 24th, 2020
@patch(FUNCTION_PATH, return_value=date(2020, 2, 24))
def test_config_example2_add_holiday(self, mock_date):
"""Test if public holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_example2)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "off"
def test_day_to_string(self):
"""Test if day_to_string is behaving correctly."""
assert binary_sensor.day_to_string(0) == "mon"
assert binary_sensor.day_to_string(1) == "tue"
assert binary_sensor.day_to_string(7) == "holiday"
assert binary_sensor.day_to_string(8) is None
# Freeze time to test Fri, but remove holiday - December 25, 2020
@patch(FUNCTION_PATH, return_value=date(2020, 12, 25))
def test_config_remove_holidays_xmas(self, mock_date):
"""Test if removed holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(self.hass, "binary_sensor", self.config_remove_holidays)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"
# Freeze time to test Fri, but remove holiday by name - Christmas
@patch(FUNCTION_PATH, return_value=date(2020, 12, 25))
def test_config_remove_named_holidays_xmas(self, mock_date):
"""Test if removed by name holidays are reported correctly."""
with assert_setup_component(1, "binary_sensor"):
setup_component(
self.hass, "binary_sensor", self.config_remove_named_holidays
)
self.hass.start()
entity = self.hass.states.get("binary_sensor.workday_sensor")
assert entity.state == "on"