mirror of
https://github.com/home-assistant/core.git
synced 2025-08-22 03:40:02 +00:00
.devcontainer
.github
.vscode
docs
homeassistant
machine
pylint
rootfs
script
tests
auth
backports
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
agent_dvr
air_quality
airly
airnow
airthings
airtouch4
airvisual
alarm_control_panel
alarmdecoder
alert
alexa
almond
ambee
amberelectric
ambiclimate
ambient_station
analytics
androidtv
apache_kafka
api
api_streams
apns
apple_tv
apprise
aprs
arcam_fmj
arlo
aseko_pool_live
asuswrt
atag
august
aurora
aurora_abb_powerone
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
balboa
bayesian
binary_sensor
blackbird
blebox
blink
blueprint
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brunt
bsblan
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
climacell
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cpuspeed
crownstone
daikin
darksky
datadog
debugpy
deconz
default_config
demo
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
dialogflow
directv
discovery
dlna_dmr
doorbird
dsmr
dte_energy_bridge
duckdns
dunehd
dynalite
eafm
ecobee
econet
efergy
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enocean
enphase_envoy
environment_canada
epson
esphome
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fido
file
filesize
filter
fireservicerota
firmata
fjaraskupan
flic
flick_electric
flipr
flo
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
garages_amsterdam
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
geonetnz_volcano
gios
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_domains
google_pubsub
google_translate
google_travel_time
google_wifi
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hangouts
harmony
hassio
hddtemp
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
icloud
ifttt
ign_sismologia
image
image_processing
imap_email_content
influxdb
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intent
intent_script
ios
iotawatt
ipma
ipp
iqvia
islamic_prayer_times
isy994
izone
jellyfin
jewish_calendar
juicenet
keenetic_ndms2
kira
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lastfm
launch_library
lcn
light
litejet
litterrobot
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
lookin
lovelace
luftdaten
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
marytts
maxcube
mazda
media_player
media_source
melcloud
melissa
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
mhz19
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mobile_app
mochad
modbus
modem_callerid
modern_forms
mold_indicator
monoprice
moon
motion_blinds
motioneye
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mythicbeastsdns
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
network
nexia
nextbus
nfandroidtv
nightscout
nina
nmap_tracker
no_ip
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openalpr_cloud
openalpr_local
openerz
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
overkiz
ovo_energy
owntracks
ozw
p1_monitor
panasonic_viera
panel_custom
panel_iframe
persistent_notification
person
philips_js
pi_hole
picnic
pilight
__init__.py
test_init.py
test_sensor.py
ping
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
ps4
push
pushbullet
pvoutput
pvpc_hourly_pricing
python_script
qld_bushfire
qwikswitch
rachio
radarr
rainforest_eagle
rainmachine
random
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
rest
rest_command
rflink
rfxtrx
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
safe_mode
samsungtv
scene
screenlogic
script
search
season
select
sense
senseme
sensibo
sensor
sentry
seventeentrack
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplisafe
simulated
siren
slack
sleepiq
sma
smappee
smart_meter_texas
smarthab
smartthings
smarttub
smhi
smtp
snips
solaredge
solarlog
soma
somfy
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
startca
statistics
statsd
steamist
stookalert
stream
stt
subaru
sun
surepetcare
switch
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tasmota
tcp
telegram
tellduslive
template
tesla_wall_connector
threshold
tibber
tile
time_date
timer
tod
tolo
tomato
toon
totalconnect
tplink
traccar
trace
tractive
tradfri
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
unifi
unifi_direct
unifiprotect
universal
upb
upcloud
updater
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
velbus
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
voicerss
volumio
vultr
wake_on_lan
wallbox
water_heater
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
withings
wled
wolflink
workday
worldclock
wsdot
xbox
xiaomi
xiaomi_aqara
xiaomi_miio
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
youless
zeroconf
zerproc
zha
zodiac
zone
zwave
zwave_js
__init__.py
conftest.py
fixtures
hassfest
helpers
mock
resources
scripts
test_util
testing_config
util
__init__.py
bandit.yaml
common.py
conftest.py
ignore_uncaught_exceptions.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_core.py
test_data_entry_flow.py
test_exceptions.py
test_loader.py
test_main.py
test_requirements.py
test_runner.py
test_setup.py
test_test_fixtures.py
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
setup.py
tox.ini
402 lines
14 KiB
Python
402 lines
14 KiB
Python
"""The tests for the pilight component."""
|
|
from datetime import timedelta
|
|
import logging
|
|
import socket
|
|
from unittest.mock import patch
|
|
|
|
from voluptuous import MultipleInvalid
|
|
|
|
from homeassistant.components import pilight
|
|
from homeassistant.setup import async_setup_component
|
|
from homeassistant.util import dt as dt_util
|
|
|
|
from tests.common import assert_setup_component, async_fire_time_changed
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class PilightDaemonSim:
|
|
"""Class to fake the interface of the pilight python package.
|
|
|
|
Is used in an asyncio loop, thus the mock cannot be accessed to
|
|
determine if methods where called?!
|
|
This is solved here in a hackish way by printing errors
|
|
that can be checked using logging.error mocks.
|
|
"""
|
|
|
|
callback = None
|
|
called = None
|
|
|
|
test_message = {
|
|
"protocol": "kaku_switch",
|
|
"uuid": "1-2-3-4",
|
|
"message": {"id": 0, "unit": 0, "off": 1},
|
|
}
|
|
|
|
def __init__(self, host, port):
|
|
"""Init pilight client, ignore parameters."""
|
|
|
|
def send_code(self, call): # pylint: disable=no-self-use
|
|
"""Handle pilight.send service callback."""
|
|
_LOGGER.error("PilightDaemonSim payload: %s", call)
|
|
|
|
def start(self):
|
|
"""Handle homeassistant.start callback.
|
|
|
|
Also sends one test message after start up
|
|
"""
|
|
_LOGGER.error("PilightDaemonSim start")
|
|
# Fake one code receive after daemon started
|
|
if not self.called:
|
|
self.callback(self.test_message)
|
|
self.called = True
|
|
|
|
def stop(self): # pylint: disable=no-self-use
|
|
"""Handle homeassistant.stop callback."""
|
|
_LOGGER.error("PilightDaemonSim stop")
|
|
|
|
def set_callback(self, function):
|
|
"""Handle pilight.pilight_received event callback."""
|
|
self.callback = function
|
|
_LOGGER.error("PilightDaemonSim callback: %s", function)
|
|
|
|
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
async def test_connection_failed_error(mock_error, hass):
|
|
"""Try to connect at 127.0.0.1:5001 with socket error."""
|
|
with assert_setup_component(4), patch(
|
|
"pilight.pilight.Client", side_effect=socket.error
|
|
) as mock_client:
|
|
assert not await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {}}
|
|
)
|
|
mock_client.assert_called_once_with(
|
|
host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT
|
|
)
|
|
assert mock_error.call_count == 1
|
|
|
|
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
async def test_connection_timeout_error(mock_error, hass):
|
|
"""Try to connect at 127.0.0.1:5001 with socket timeout."""
|
|
with assert_setup_component(4), patch(
|
|
"pilight.pilight.Client", side_effect=socket.timeout
|
|
) as mock_client:
|
|
assert not await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {}}
|
|
)
|
|
mock_client.assert_called_once_with(
|
|
host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT
|
|
)
|
|
assert mock_error.call_count == 1
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
async def test_send_code_no_protocol(hass):
|
|
"""Try to send data without protocol information, should give error."""
|
|
with assert_setup_component(4):
|
|
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
|
|
|
|
# Call without protocol info, should raise an error
|
|
try:
|
|
await hass.services.async_call(
|
|
pilight.DOMAIN,
|
|
pilight.SERVICE_NAME,
|
|
service_data={"noprotocol": "test", "value": 42},
|
|
blocking=True,
|
|
)
|
|
await hass.async_block_till_done()
|
|
except MultipleInvalid as error:
|
|
assert "required key not provided @ data['protocol']" in str(error)
|
|
|
|
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
@patch("homeassistant.components.pilight._LOGGER", _LOGGER)
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
async def test_send_code(mock_pilight_error, hass):
|
|
"""Try to send proper data."""
|
|
with assert_setup_component(4):
|
|
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
|
|
|
|
# Call with protocol info, should not give error
|
|
service_data = {"protocol": "test", "value": 42}
|
|
await hass.services.async_call(
|
|
pilight.DOMAIN,
|
|
pilight.SERVICE_NAME,
|
|
service_data=service_data,
|
|
blocking=True,
|
|
)
|
|
await hass.async_block_till_done()
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
service_data["protocol"] = [service_data["protocol"]]
|
|
assert str(service_data) in str(error_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
async def test_send_code_fail(mock_pilight_error, hass):
|
|
"""Check IOError exception error message."""
|
|
with assert_setup_component(4), patch(
|
|
"pilight.pilight.Client.send_code", side_effect=IOError
|
|
):
|
|
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
|
|
|
|
# Call with protocol info, should not give error
|
|
service_data = {"protocol": "test", "value": 42}
|
|
await hass.services.async_call(
|
|
pilight.DOMAIN,
|
|
pilight.SERVICE_NAME,
|
|
service_data=service_data,
|
|
blocking=True,
|
|
)
|
|
await hass.async_block_till_done()
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
assert "Pilight send failed" in str(error_log_call)
|
|
|
|
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
@patch("homeassistant.components.pilight._LOGGER", _LOGGER)
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
async def test_send_code_delay(mock_pilight_error, hass):
|
|
"""Try to send proper data with delay afterwards."""
|
|
with assert_setup_component(4):
|
|
assert await async_setup_component(
|
|
hass,
|
|
pilight.DOMAIN,
|
|
{pilight.DOMAIN: {pilight.CONF_SEND_DELAY: 5.0}},
|
|
)
|
|
|
|
# Call with protocol info, should not give error
|
|
service_data1 = {"protocol": "test11", "value": 42}
|
|
service_data2 = {"protocol": "test22", "value": 42}
|
|
await hass.services.async_call(
|
|
pilight.DOMAIN,
|
|
pilight.SERVICE_NAME,
|
|
service_data=service_data1,
|
|
blocking=True,
|
|
)
|
|
await hass.services.async_call(
|
|
pilight.DOMAIN,
|
|
pilight.SERVICE_NAME,
|
|
service_data=service_data2,
|
|
blocking=True,
|
|
)
|
|
service_data1["protocol"] = [service_data1["protocol"]]
|
|
service_data2["protocol"] = [service_data2["protocol"]]
|
|
|
|
async_fire_time_changed(hass, dt_util.utcnow())
|
|
await hass.async_block_till_done()
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
assert str(service_data1) in str(error_log_call)
|
|
|
|
new_time = dt_util.utcnow() + timedelta(seconds=5)
|
|
async_fire_time_changed(hass, new_time)
|
|
await hass.async_block_till_done()
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
assert str(service_data2) in str(error_log_call)
|
|
|
|
|
|
@patch("homeassistant.components.pilight._LOGGER.error")
|
|
@patch("homeassistant.components.pilight._LOGGER", _LOGGER)
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
async def test_start_stop(mock_pilight_error, hass):
|
|
"""Check correct startup and stop of pilight daemon."""
|
|
with assert_setup_component(4):
|
|
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
|
|
|
|
# Test startup
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
|
|
error_log_call = mock_pilight_error.call_args_list[-2]
|
|
assert "PilightDaemonSim callback" in str(error_log_call)
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
assert "PilightDaemonSim start" in str(error_log_call)
|
|
|
|
# Test stop
|
|
with patch.object(hass.loop, "stop"):
|
|
await hass.async_stop()
|
|
error_log_call = mock_pilight_error.call_args_list[-1]
|
|
assert "PilightDaemonSim stop" in str(error_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.core._LOGGER.debug")
|
|
async def test_receive_code(mock_debug, hass):
|
|
"""Check if code receiving via pilight daemon works."""
|
|
with assert_setup_component(4):
|
|
assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
|
|
|
|
# Test startup
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
|
|
expected_message = dict(
|
|
{
|
|
"protocol": PilightDaemonSim.test_message["protocol"],
|
|
"uuid": PilightDaemonSim.test_message["uuid"],
|
|
},
|
|
**PilightDaemonSim.test_message["message"],
|
|
)
|
|
debug_log_call = mock_debug.call_args_list[-3]
|
|
|
|
# Check if all message parts are put on event bus
|
|
for key, value in expected_message.items():
|
|
assert str(key) in str(debug_log_call)
|
|
assert str(value) in str(debug_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.core._LOGGER.debug")
|
|
async def test_whitelist_exact_match(mock_debug, hass):
|
|
"""Check whitelist filter with matched data."""
|
|
with assert_setup_component(4):
|
|
whitelist = {
|
|
"protocol": [PilightDaemonSim.test_message["protocol"]],
|
|
"uuid": [PilightDaemonSim.test_message["uuid"]],
|
|
"id": [PilightDaemonSim.test_message["message"]["id"]],
|
|
"unit": [PilightDaemonSim.test_message["message"]["unit"]],
|
|
}
|
|
assert await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}}
|
|
)
|
|
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
|
|
expected_message = dict(
|
|
{
|
|
"protocol": PilightDaemonSim.test_message["protocol"],
|
|
"uuid": PilightDaemonSim.test_message["uuid"],
|
|
},
|
|
**PilightDaemonSim.test_message["message"],
|
|
)
|
|
debug_log_call = mock_debug.call_args_list[-3]
|
|
|
|
# Check if all message parts are put on event bus
|
|
for key, value in expected_message.items():
|
|
assert str(key) in str(debug_log_call)
|
|
assert str(value) in str(debug_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.core._LOGGER.debug")
|
|
async def test_whitelist_partial_match(mock_debug, hass):
|
|
"""Check whitelist filter with partially matched data, should work."""
|
|
with assert_setup_component(4):
|
|
whitelist = {
|
|
"protocol": [PilightDaemonSim.test_message["protocol"]],
|
|
"id": [PilightDaemonSim.test_message["message"]["id"]],
|
|
}
|
|
assert await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}}
|
|
)
|
|
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
|
|
expected_message = dict(
|
|
{
|
|
"protocol": PilightDaemonSim.test_message["protocol"],
|
|
"uuid": PilightDaemonSim.test_message["uuid"],
|
|
},
|
|
**PilightDaemonSim.test_message["message"],
|
|
)
|
|
debug_log_call = mock_debug.call_args_list[-3]
|
|
|
|
# Check if all message parts are put on event bus
|
|
for key, value in expected_message.items():
|
|
assert str(key) in str(debug_log_call)
|
|
assert str(value) in str(debug_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.core._LOGGER.debug")
|
|
async def test_whitelist_or_match(mock_debug, hass):
|
|
"""Check whitelist filter with several subsection, should work."""
|
|
with assert_setup_component(4):
|
|
whitelist = {
|
|
"protocol": [
|
|
PilightDaemonSim.test_message["protocol"],
|
|
"other_protocol",
|
|
],
|
|
"id": [PilightDaemonSim.test_message["message"]["id"]],
|
|
}
|
|
assert await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}}
|
|
)
|
|
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
|
|
expected_message = dict(
|
|
{
|
|
"protocol": PilightDaemonSim.test_message["protocol"],
|
|
"uuid": PilightDaemonSim.test_message["uuid"],
|
|
},
|
|
**PilightDaemonSim.test_message["message"],
|
|
)
|
|
debug_log_call = mock_debug.call_args_list[-3]
|
|
|
|
# Check if all message parts are put on event bus
|
|
for key, value in expected_message.items():
|
|
assert str(key) in str(debug_log_call)
|
|
assert str(value) in str(debug_log_call)
|
|
|
|
|
|
@patch("pilight.pilight.Client", PilightDaemonSim)
|
|
@patch("homeassistant.core._LOGGER.debug")
|
|
async def test_whitelist_no_match(mock_debug, hass):
|
|
"""Check whitelist filter with unmatched data, should not work."""
|
|
with assert_setup_component(4):
|
|
whitelist = {
|
|
"protocol": ["wrong_protocol"],
|
|
"id": [PilightDaemonSim.test_message["message"]["id"]],
|
|
}
|
|
assert await async_setup_component(
|
|
hass, pilight.DOMAIN, {pilight.DOMAIN: {"whitelist": whitelist}}
|
|
)
|
|
|
|
await hass.async_start()
|
|
await hass.async_block_till_done()
|
|
debug_log_call = mock_debug.call_args_list[-3]
|
|
|
|
assert "Event pilight_received" not in debug_log_call
|
|
|
|
|
|
async def test_call_rate_delay_throttle_enabled(hass):
|
|
"""Test that throttling actually work."""
|
|
runs = []
|
|
delay = 5.0
|
|
|
|
limit = pilight.CallRateDelayThrottle(hass, delay)
|
|
action = limit.limited(lambda x: runs.append(x))
|
|
|
|
for i in range(3):
|
|
await hass.async_add_executor_job(action, i)
|
|
|
|
await hass.async_block_till_done()
|
|
assert runs == [0]
|
|
|
|
exp = []
|
|
now = dt_util.utcnow()
|
|
for i in range(3):
|
|
exp.append(i)
|
|
shifted_time = now + (timedelta(seconds=delay + 0.1) * i)
|
|
async_fire_time_changed(hass, shifted_time)
|
|
await hass.async_block_till_done()
|
|
assert runs == exp
|
|
|
|
|
|
def test_call_rate_delay_throttle_disabled(hass):
|
|
"""Test that the limiter is a noop if no delay set."""
|
|
runs = []
|
|
|
|
limit = pilight.CallRateDelayThrottle(hass, 0.0)
|
|
action = limit.limited(lambda x: runs.append(x))
|
|
|
|
for i in range(3):
|
|
action(i)
|
|
|
|
assert runs == [0, 1, 2]
|