mirror of
https://github.com/home-assistant/core.git
synced 2025-08-12 06:50:00 +00:00
.devcontainer
.github
.vscode
docs
homeassistant
script
tests
auth
components
adguard
air_quality
alarm_control_panel
alert
alexa
ambiclimate
ambient_station
androidtv
api
api_streams
apns
aprs
arcam_fmj
arlo
asuswrt
aurora
auth
automatic
automation
awair
aws
axis
bayesian
binary_sensor
blackbird
bom
broadlink
buienradar
caldav
calendar
camera
canary
cast
cert_expiry
climate
cloud
coinmarketcap
command_line
config
configurator
conversation
counter
cover
daikin
darksky
datadog
deconz
default_config
demo
device_automation
device_sun_light_trigger
device_tracker
dialogflow
directv
discovery
dsmr
dte_energy_bridge
duckdns
dyson
ecobee
ee_brightbox
efergy
emulated_hue
emulated_roku
esphome
everlights
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fido
file
filesize
filter
flux
folder
folder_watcher
foobot
freedns
fritzbox
frontend
generic
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
google
google_assistant
google_domains
google_pubsub
google_translate
google_wifi
gpslogger
graphite
group
hangouts
hassio
hddtemp
heos
here_travel_time
history
history_graph
history_stats
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
honeywell
html5
http
huawei_lte
hue
hydroquebec
iaqualink
ifttt
ign_sismologia
image_processing
imap_email_content
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
integration
intent_script
ios
ipma
iqvia
islamic_prayer_times
izone
jewish_calendar
kira
light
linky
litejet
local_file
locative
lock
logbook
logentries
logger
logi_circle
london_air
lovelace
luftdaten
mailbox
mailgun
manual
manual_mqtt
marytts
media_player
melissa
meraki
met
mfi
mhz19
microsoft_face
microsoft_face_detect
microsoft_face_identify
min_max
minio
mobile_app
mochad
modbus
mold_indicator
monoprice
moon
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mythicbeastsdns
namecheapdns
ness_alarm
nest
nextbus
no_ip
notify
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nws
nx584
onboarding
openalpr_cloud
openalpr_local
openhardwaremonitor
openuv
owntracks
panel_custom
panel_iframe
persistent_notification
person
pi_hole
pilight
plant
plex
point
prometheus
proximity
ps4
ptvsd
push
pushbullet
python_script
qld_bushfire
qwikswitch
radarr
rainmachine
random
recorder
reddit
remember_the_milk
remote
rest
rest_command
rflink
rfxtrx
ring
rmvtransport
rss_feed_template
samsungtv
scene
script
season
sensor
seventeentrack
shell_command
shopping_list
sigfox
simplisafe
simulated
sleepiq
sma
smartthings
smhi
smtp
snips
solaredge
somfy
sonarr
sonos
soundtouch
spaceapi
spc
splunk
sql
ssdp
startca
statistics
statsd
stream
sun
__init__.py
test_init.py
switch
switcher_kis
system_health
system_log
tcp
teksavvy
tellduslive
template
threshold
time_date
timer
tod
tomato
toon
tplink
traccar
tradfri
transport_nsw
trend
tts
twentemilieu
twilio
uk_transport
unifi
unifi_direct
universal
updater
upnp
uptime
usgs_earthquakes_feed
utility_meter
uvc
vacuum
velbus
verisure
version
vesync
voicerss
vultr
wake_on_lan
water_heater
weather
webhook
weblink
webostv
websocket_api
withings
workday
worldclock
wsdot
wunderground
wwlln
xiaomi
xiaomi_miio
yamaha
yandex_transport
yandextts
yessssms
yr
yweather
zeroconf
zha
zone
zwave
__init__.py
conftest.py
fixtures
helpers
mock
resources
scripts
test_util
testing_config
util
__init__.py
common.py
conftest.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_core.py
test_data_entry_flow.py
test_loader.py
test_main.py
test_requirements.py
test_setup.py
.codecov.yml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.pre-commit-config.yaml
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
azure-pipelines-ci.yml
azure-pipelines-release.yml
azure-pipelines-translation.yml
azure-pipelines-wheels.yml
mypyrc
pylintrc
pyproject.toml
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini
193 lines
5.7 KiB
Python
193 lines
5.7 KiB
Python
"""The tests for the Sun component."""
|
|
from datetime import datetime, timedelta
|
|
from unittest.mock import patch
|
|
|
|
from pytest import mark
|
|
|
|
import homeassistant.components.sun as sun
|
|
import homeassistant.core as ha
|
|
import homeassistant.util.dt as dt_util
|
|
from homeassistant.const import EVENT_STATE_CHANGED
|
|
from homeassistant.setup import async_setup_component
|
|
|
|
|
|
async def test_setting_rising(hass):
|
|
"""Test retrieving sun setting and rising."""
|
|
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
|
|
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=utc_now):
|
|
await async_setup_component(
|
|
hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}
|
|
)
|
|
|
|
await hass.async_block_till_done()
|
|
state = hass.states.get(sun.ENTITY_ID)
|
|
|
|
from astral import Astral
|
|
|
|
astral = Astral()
|
|
utc_today = utc_now.date()
|
|
|
|
latitude = hass.config.latitude
|
|
longitude = hass.config.longitude
|
|
|
|
mod = -1
|
|
while True:
|
|
next_dawn = astral.dawn_utc(
|
|
utc_today + timedelta(days=mod), latitude, longitude
|
|
)
|
|
if next_dawn > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
mod = -1
|
|
while True:
|
|
next_dusk = astral.dusk_utc(
|
|
utc_today + timedelta(days=mod), latitude, longitude
|
|
)
|
|
if next_dusk > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
mod = -1
|
|
while True:
|
|
next_midnight = astral.solar_midnight_utc(
|
|
utc_today + timedelta(days=mod), longitude
|
|
)
|
|
if next_midnight > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
mod = -1
|
|
while True:
|
|
next_noon = astral.solar_noon_utc(utc_today + timedelta(days=mod), longitude)
|
|
if next_noon > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
mod = -1
|
|
while True:
|
|
next_rising = astral.sunrise_utc(
|
|
utc_today + timedelta(days=mod), latitude, longitude
|
|
)
|
|
if next_rising > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
mod = -1
|
|
while True:
|
|
next_setting = astral.sunset_utc(
|
|
utc_today + timedelta(days=mod), latitude, longitude
|
|
)
|
|
if next_setting > utc_now:
|
|
break
|
|
mod += 1
|
|
|
|
assert next_dawn == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_DAWN]
|
|
)
|
|
assert next_dusk == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_DUSK]
|
|
)
|
|
assert next_midnight == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_MIDNIGHT]
|
|
)
|
|
assert next_noon == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_NOON]
|
|
)
|
|
assert next_rising == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_RISING]
|
|
)
|
|
assert next_setting == dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_SETTING]
|
|
)
|
|
|
|
|
|
async def test_state_change(hass):
|
|
"""Test if the state changes at next setting/rising."""
|
|
now = datetime(2016, 6, 1, 8, 0, 0, tzinfo=dt_util.UTC)
|
|
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
|
|
await async_setup_component(
|
|
hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}
|
|
)
|
|
|
|
await hass.async_block_till_done()
|
|
|
|
test_time = dt_util.parse_datetime(
|
|
hass.states.get(sun.ENTITY_ID).attributes[sun.STATE_ATTR_NEXT_RISING]
|
|
)
|
|
assert test_time is not None
|
|
|
|
assert sun.STATE_BELOW_HORIZON == hass.states.get(sun.ENTITY_ID).state
|
|
|
|
hass.bus.async_fire(
|
|
ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: test_time + timedelta(seconds=5)}
|
|
)
|
|
|
|
await hass.async_block_till_done()
|
|
|
|
assert sun.STATE_ABOVE_HORIZON == hass.states.get(sun.ENTITY_ID).state
|
|
|
|
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
|
|
await hass.config.async_update(longitude=hass.config.longitude + 90)
|
|
await hass.async_block_till_done()
|
|
|
|
assert sun.STATE_ABOVE_HORIZON == hass.states.get(sun.ENTITY_ID).state
|
|
|
|
|
|
async def test_norway_in_june(hass):
|
|
"""Test location in Norway where the sun doesn't set in summer."""
|
|
hass.config.latitude = 69.6
|
|
hass.config.longitude = 18.8
|
|
|
|
june = datetime(2016, 6, 1, tzinfo=dt_util.UTC)
|
|
|
|
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=june):
|
|
assert await async_setup_component(
|
|
hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}
|
|
)
|
|
|
|
state = hass.states.get(sun.ENTITY_ID)
|
|
assert state is not None
|
|
|
|
assert dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_RISING]
|
|
) == datetime(2016, 7, 25, 23, 23, 39, tzinfo=dt_util.UTC)
|
|
assert dt_util.parse_datetime(
|
|
state.attributes[sun.STATE_ATTR_NEXT_SETTING]
|
|
) == datetime(2016, 7, 26, 22, 19, 1, tzinfo=dt_util.UTC)
|
|
|
|
assert state.state == sun.STATE_ABOVE_HORIZON
|
|
|
|
|
|
@mark.skip
|
|
async def test_state_change_count(hass):
|
|
"""Count the number of state change events in a location."""
|
|
# Skipped because it's a bit slow. Has been validated with
|
|
# multiple lattitudes and dates
|
|
hass.config.latitude = 10
|
|
hass.config.longitude = 0
|
|
|
|
now = datetime(2016, 6, 1, tzinfo=dt_util.UTC)
|
|
|
|
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
|
|
assert await async_setup_component(
|
|
hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}
|
|
)
|
|
|
|
events = []
|
|
|
|
@ha.callback
|
|
def state_change_listener(event):
|
|
if event.data.get("entity_id") == "sun.sun":
|
|
events.append(event)
|
|
|
|
hass.bus.async_listen(EVENT_STATE_CHANGED, state_change_listener)
|
|
await hass.async_block_till_done()
|
|
|
|
for _ in range(24 * 60 * 60):
|
|
now += timedelta(seconds=1)
|
|
hass.bus.async_fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now})
|
|
await hass.async_block_till_done()
|
|
|
|
assert len(events) < 721
|