1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-11 14:29:58 +00:00
Files
.devcontainer
.github
.vscode
homeassistant
machine
pylint
rootfs
script
tests
auth
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
amberelectric
ambiclimate
ambient_station
analytics
android_ip_webcam
androidtv
androidtv_remote
anova
anthemav
aosmith
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprs
aranet
arcam_fmj
aseko_pool_live
assist_pipeline
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
baf
balboa
bayesian
binary_sensor
blackbird
blebox
blink
blue_current
bluemaestro
blueprint
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brottsplatskartan
brunt
bsblan
bthome
buienradar
button
caldav
calendar
camera
canary
cast
ccm15
cert_expiry
clicksend_tts
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comelit
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
counter
cover
cpuspeed
crownstone
daikin
datadog
date
datetime
debugpy
deconz
default_config
deluge
demo
denonavr
derivative
devialet
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
directv
discord
discovergy
dlink
dlna_dmr
dlna_dms
dnsip
doorbird
dormakaba_dkey
dremel_3d_printer
drop_connect
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
duotecno
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
ecoforest
econet
ecowitt
edl21
efergy
eight_sleep
electrasmart
electric_kiwi
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
energyzero
enocean
enphase_envoy
environment_canada
epson
escea
esphome
eufylife_ble
event
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
fastdotcom
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
fireservicerota
firmata
fitbit
fivem
fjaraskupan
flexit_bacnet
flic
flick_electric
flipr
flo
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
fully_kiosk
garages_amsterdam
gardena_bluetooth
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_assistant_sdk
google_domains
google_generative_ai_conversation
google_mail
google_pubsub
google_sheets
google_tasks
google_translate
google_travel_time
google_wifi
govee_ble
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hardkernel
hardware
harmony
hassio
hddtemp
hdmi_cec
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
holiday
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_green
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hydrawise
hyperion
ialarm
iaqualink
ibeacon
icloud
idasen_desk
ifttt
ign_sismologia
image
image_processing
image_upload
imap
improv_ble
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intellifire
intent
intent_script
ios
iotawatt
ipma
ipp
iqvia
islamic_prayer_times
iss
isy994
izone
jellyfin
jewish_calendar
juicenet
justnimbus
jvc_projector
kaleidescape
keenetic_ndms2
kegtron
keymitt_ble
kira
kitchen_sink
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lacrosse_view
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
led_ble
lg_soundbar
lidarr
life360
lifx
light
linear_garage_door
litejet
litterrobot
livisi
local_calendar
local_file
local_ip
local_todo
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
loqed
lovelace
luftdaten
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
marytts
matrix
matter
maxcube
mazda
meater
medcom_ble
media_extractor
media_player
media_source
melcloud
melissa
melnor
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
mopeka
motion_blinds
motioneye
motionmount
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mystrom
mythicbeastsdns
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
netgear_lte
network
nexia
nextbus
nextcloud
nextdns
nfandroidtv
nibe_heatpump
nightscout
nina
nmap_tracker
no_ip
nobo_hub
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
obihai
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openai_conversation
openalpr_cloud
openerz
openexchangerates
opengarage
openhardwaremonitor
openhome
opensky
opentherm_gw
openuv
openweathermap
opnsense
opower
oralb
osoenergy
otbr
ourgroceries
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
pegel_online
permobil
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
pjlink
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
private_ble_device
profiler
progettihwsw
prometheus
prosegur
proximity
prusalink
ps4
pure_energie
purpleair
push
pushbullet
pushover
pvoutput
pvpc_hourly_pricing
python_script
qbittorrent
qingping
qld_bushfire
qnap
qnap_qsw
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainbird
rainforest_eagle
rainmachine
random
rapt_ble
raspberry_pi
rdw
recollect_waste
recorder
recovery_mode
reddit
refoss
remember_the_milk
remote
renault
renson
reolink
repairs
rest
rest_command
rflink
rfxtrx
rhasspy
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roborock
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
samsungtv
scene
schedule
schlage
scrape
screenlogic
script
search
season
select
sense
sensibo
sensirion_ble
sensor
sensorpro
sensorpush
sentry
senz
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
siren
skybell
slack
sleepiq
slimproto
sma
smappee
smart_meter_texas
smartthings
smarttub
smhi
smtp
fixtures
__init__.py
test_notify.py
snapcast
snips
snmp
snooz
solaredge
solarlog
solax
soma
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlink
startca
statistics
statsd
steam_online
steamist
stookalert
stookwijzer
stream
streamlabswater
stt
subaru
suez_water
sun
sunweg
surepetcare
swiss_public_transport
switch
switch_as_x
switchbee
switchbot
switchbot_cloud
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tailwind
tami4
tankerkoenig
tasmota
tautulli
tcp
telegram
telegram_bot
tellduslive
temper
template
tesla_wall_connector
tessie
text
thermobeacon
thermopro
thread
threshold
tibber
tile
tilt_ble
time
time_date
timer
tod
todo
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
tplink_omada
traccar
trace
tractive
tradfri
trafikverket_camera
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
ukraine_alarm
unifi
unifiprotect
universal
upb
upcloud
update
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
v2c
vacuum
vallox
valve
velbus
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
vodafone_station
voicerss
voip
volumio
volvooncall
vulcan
vultr
wake_on_lan
wake_word
wallbox
waqi
water_heater
watttime
waze_travel_time
weather
weatherflow
weatherkit
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
withings
wiz
wled
wolflink
workday
worldclock
ws66i
wsdot
wyoming
xbox
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yardian
yeelight
yolink
youless
youtube
zamg
zeroconf
zerproc
zeversolar
zha
zodiac
zone
zwave_js
zwave_me
__init__.py
conftest.py
fixtures
hassfest
helpers
pylint
resources
scripts
snapshots
test_util
testing_config
util
__init__.py
common.py
conftest.py
ignore_uncaught_exceptions.py
patch_time.py
ruff.toml
syrupy.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_const.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
typing.py
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.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_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
core/tests/components/smtp/test_notify.py
Jan Bouwhuis d8a6d864c0 Raise on smtp notification if attachment is not allowed ()
* Raise smtp notification if attachment not allowed

* Pass url as placeholder

* Use variable in err message

* Add allow_list as placeholder
2023-12-04 11:48:29 +01:00

228 lines
7.0 KiB
Python

"""The tests for the notify smtp platform."""
from pathlib import Path
import re
from unittest.mock import patch
import pytest
from homeassistant import config as hass_config
import homeassistant.components.notify as notify
from homeassistant.components.smtp.const import DOMAIN
from homeassistant.components.smtp.notify import MailNotificationService
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.setup import async_setup_component
from tests.common import get_fixture_path
class MockSMTP(MailNotificationService):
"""Test SMTP object that doesn't need a working server."""
def _send_email(self, msg, recipients):
"""Just return msg string and recipients for testing."""
return msg.as_string(), recipients
async def test_reload_notify(hass: HomeAssistant) -> None:
"""Verify we can reload the notify service."""
with patch(
"homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid"
):
assert await async_setup_component(
hass,
notify.DOMAIN,
{
notify.DOMAIN: [
{
"name": DOMAIN,
"platform": DOMAIN,
"recipient": "test@example.com",
"sender": "test@example.com",
},
]
},
)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
yaml_path = get_fixture_path("configuration.yaml", "smtp")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path), patch(
"homeassistant.components.smtp.notify.MailNotificationService.connection_is_valid"
):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert not hass.services.has_service(notify.DOMAIN, DOMAIN)
assert hass.services.has_service(notify.DOMAIN, "smtp_reloaded")
@pytest.fixture
def message():
"""Return MockSMTP object with test data."""
mailer = MockSMTP(
"localhost",
25,
5,
"test@test.com",
1,
"testuser",
"testpass",
["recip1@example.com", "testrecip@test.com"],
"Home Assistant",
0,
True,
)
return mailer
HTML = """
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"></head>
<body>
<div>
<h1>Intruder alert at apartment!!</h1>
</div>
<div>
<img alt="tests/testing_config/notify/test.jpg" src="cid:tests/testing_config/notify/test.jpg"/>
</div>
</body>
</html>"""
EMAIL_DATA = [
(
"Test msg",
{"images": ["tests/testing_config/notify/test.jpg"]},
"Content-Type: multipart/mixed",
),
(
"Test msg",
{"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]},
"Content-Type: multipart/related",
),
(
"Test msg",
{"html": HTML, "images": ["tests/testing_config/notify/test_not_exists.jpg"]},
"Content-Type: multipart/related",
),
(
"Test msg",
{"html": HTML, "images": ["tests/testing_config/notify/test.pdf"]},
"Content-Type: multipart/related",
),
]
@pytest.mark.parametrize(
("message_data", "data", "content_type"),
EMAIL_DATA,
ids=[
"Tests when sending text message and images.",
"Tests when sending text message, HTML Template and images.",
"Tests when image does not exist at mentioned location.",
"Tests when image type cannot be detected or is of wrong type.",
],
)
def test_send_message(
hass: HomeAssistant, message_data, data, content_type, message
) -> None:
"""Verify if we can send messages of all types correctly."""
sample_email = "<mock@mock>"
message.hass = hass
hass.config.allowlist_external_dirs.add(Path("tests/testing_config").resolve())
with patch("email.utils.make_msgid", return_value=sample_email):
result, _ = message.send_message(message_data, data=data)
assert content_type in result
@pytest.mark.parametrize(
("message_data", "data", "content_type"),
[
(
"Test msg",
{"images": ["tests/testing_config/notify/test.jpg"]},
"Content-Type: multipart/mixed",
),
],
)
def test_sending_insecure_files_fails(
hass: HomeAssistant,
message_data,
data,
content_type,
message,
) -> None:
"""Verify if we cannot send messages with insecure attachments."""
sample_email = "<mock@mock>"
message.hass = hass
with patch("email.utils.make_msgid", return_value=sample_email), pytest.raises(
ServiceValidationError
) as exc:
result, _ = message.send_message(message_data, data=data)
assert content_type in result
assert exc.value.translation_key == "remote_path_not_allowed"
assert exc.value.translation_domain == DOMAIN
assert (
str(exc.value.translation_placeholders["file_path"])
== "tests/testing_config/notify"
)
assert exc.value.translation_placeholders["url"]
assert exc.value.translation_placeholders["file_name"] == "test.jpg"
def test_send_text_message(hass: HomeAssistant, message) -> None:
"""Verify if we can send simple text message."""
expected = (
'^Content-Type: text/plain; charset="us-ascii"\n'
"MIME-Version: 1.0\n"
"Content-Transfer-Encoding: 7bit\n"
"Subject: Home Assistant\n"
"To: recip1@example.com,testrecip@test.com\n"
"From: Home Assistant <test@test.com>\n"
"X-Mailer: Home Assistant\n"
"Date: [^\n]+\n"
"Message-Id: <[^@]+@[^>]+>\n"
"\n"
"Test msg$"
)
sample_email = "<mock@mock>"
message_data = "Test msg"
with patch("email.utils.make_msgid", return_value=sample_email):
result, _ = message.send_message(message_data)
assert re.search(expected, result)
@pytest.mark.parametrize(
"target",
[
None,
"target@example.com",
],
ids=[
"Verify we can send email to default recipient.",
"Verify email recipient can be overwritten by target arg.",
],
)
def test_send_target_message(target, hass: HomeAssistant, message) -> None:
"""Verify if we can send email to correct recipient."""
sample_email = "<mock@mock>"
message_data = "Test msg"
with patch("email.utils.make_msgid", return_value=sample_email):
if not target:
expected_recipient = ["recip1@example.com", "testrecip@test.com"]
else:
expected_recipient = target
_, recipient = message.send_message(message_data, target=target)
assert recipient == expected_recipient