input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
"""Config flow for Rollease Acmeda Automate Pulse Hub.""" import asyncio from typing import Dict, Optional import aiopulse import async_timeout import voluptuous as vol from homeassistant import config_entries from .const import DOMAIN # pylint: disable=unused-import class AcmedaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Acmeda config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize the config flow.""" self.discovered_hubs: Optional[Dict[str, aiopulse.Hub]] = None async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if ( user_input is not None and self.discovered_hubs is not None and user_input["id"] in self.discovered_hubs ): return await self.async_create(self.discovered_hubs[user_input["id"]]) # Already configured hosts already_configured = { entry.unique_id for entry in self._async_current_entries() } hubs = [] try: with async_timeout.timeout(5): async for hub in aiopulse.Hub.discover(): if hub.id not in already_configured: hubs.append(hub) except asyncio.TimeoutError: pass if len(hubs) == 0: return self.async_abort(reason="no_devices_found") if len(hubs) == 1: return await self.async_create(hubs[0]) self.discovered_hubs = {hub.id: hub for hub in hubs} return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required("id"): vol.In( {hub.id: f"{hub.id} {hub.host}" for hub in hubs} ) } ), ) async def async_create(self, hub): """Create the Acmeda Hub entry.""" await self.async_set_unique_id(hub.id, raise_on_progress=False) return self.async_create_entry(title=hub.id, data={"host": hub.host})
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/acmeda/config_flow.py
"""A sensor platform that give you information about the next space launch.""" from datetime import timedelta import logging from typing import Optional from pylaunches import PyLaunches, PyLaunchesException import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from .const import ( ATTR_AGENCY, ATTR_AGENCY_COUNTRY_CODE, ATTR_LAUNCH_TIME, ATTR_STREAM, ATTRIBUTION, DEFAULT_NAME, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(hours=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Create the launch sensor.""" name = config[CONF_NAME] session = async_get_clientsession(hass) launches = PyLaunches(session) async_add_entities([LaunchLibrarySensor(launches, name)], True) class LaunchLibrarySensor(Entity): """Representation of a launch_library Sensor.""" def __init__(self, launches: PyLaunches, name: str) -> None: """Initialize the sensor.""" self.launches = launches self.next_launch = None self._name = name async def async_update(self) -> None: """Get the latest data.""" try: launches = await self.launches.upcoming_launches() except PyLaunchesException as exception: _LOGGER.error("Error getting data, %s", exception) else: if launches: self.next_launch = launches[0] @property def name(self) -> str: """Return the name of the sensor.""" return self._name @property def state(self) -> Optional[str]: """Return the state of the sensor.""" if self.next_launch: return self.next_launch.name return None @property def icon(self) -> str: """Return the icon of the sensor.""" return "mdi:rocket" @property def device_state_attributes(self) -> Optional[dict]: """Return attributes for the sensor.""" if self.next_launch: return { ATTR_LAUNCH_TIME: self.next_launch.net, ATTR_AGENCY: self.next_launch.launch_service_provider.name, ATTR_AGENCY_COUNTRY_CODE: self.next_launch.pad.location.country_code, ATTR_STREAM: self.next_launch.webcast_live, ATTR_ATTRIBUTION: ATTRIBUTION, } return None
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/launch_library/sensor.py
"""Reproduce an Timer state.""" import asyncio import logging from typing import Any, Dict, Iterable, Optional from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import Context, State from homeassistant.helpers.typing import HomeAssistantType from . import ( ATTR_DURATION, DOMAIN, SERVICE_CANCEL, SERVICE_PAUSE, SERVICE_START, STATUS_ACTIVE, STATUS_IDLE, STATUS_PAUSED, ) _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATUS_IDLE, STATUS_ACTIVE, STATUS_PAUSED} async def _async_reproduce_state( hass: HomeAssistantType, state: State, *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state and cur_state.attributes.get( ATTR_DURATION ) == state.attributes.get(ATTR_DURATION): return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state == STATUS_ACTIVE: service = SERVICE_START if ATTR_DURATION in state.attributes: service_data[ATTR_DURATION] = state.attributes[ATTR_DURATION] elif state.state == STATUS_PAUSED: service = SERVICE_PAUSE elif state.state == STATUS_IDLE: service = SERVICE_CANCEL await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce Timer states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/timer/reproduce_state.py
"""Support for Neato sensors.""" from datetime import timedelta import logging from pybotvac.exceptions import NeatoRobotException from homeassistant.components.sensor import DEVICE_CLASS_BATTERY from homeassistant.const import PERCENTAGE from homeassistant.helpers.entity import Entity from .const import NEATO_DOMAIN, NEATO_LOGIN, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=SCAN_INTERVAL_MINUTES) BATTERY = "Battery" async def async_setup_entry(hass, entry, async_add_entities): """Set up the Neato sensor using config entry.""" dev = [] neato = hass.data.get(NEATO_LOGIN) for robot in hass.data[NEATO_ROBOTS]: dev.append(NeatoSensor(neato, robot)) if not dev: return _LOGGER.debug("Adding robots for sensors %s", dev) async_add_entities(dev, True) class NeatoSensor(Entity): """Neato sensor.""" def __init__(self, neato, robot): """Initialize Neato sensor.""" self.robot = robot self._available = False self._robot_name = f"{self.robot.name} {BATTERY}" self._robot_serial = self.robot.serial self._state = None def update(self): """Update Neato Sensor.""" try: self._state = self.robot.state except NeatoRobotException as ex: if self._available: _LOGGER.error( "Neato sensor connection error for '%s': %s", self.entity_id, ex ) self._state = None self._available = False return self._available = True _LOGGER.debug("self._state=%s", self._state) @property def name(self): """Return the name of this sensor.""" return self._robot_name @property def unique_id(self): """Return unique ID.""" return self._robot_serial @property def device_class(self): """Return the device class.""" return DEVICE_CLASS_BATTERY @property def available(self): """Return availability.""" return self._available @property def state(self): """Return the state.""" return self._state["details"]["charge"] @property def unit_of_measurement(self): """Return unit of measurement.""" return PERCENTAGE @property def device_info(self): """Device info for neato robot.""" return {"identifiers": {(NEATO_DOMAIN, self._robot_serial)}}
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/neato/sensor.py
"""Support for Synology DSM binary sensors.""" from typing import Dict from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DISKS from homeassistant.helpers.typing import HomeAssistantType from . import SynologyDSMDeviceEntity, SynologyDSMDispatcherEntity from .const import ( DOMAIN, SECURITY_BINARY_SENSORS, STORAGE_DISK_BINARY_SENSORS, SYNO_API, UPGRADE_BINARY_SENSORS, ) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Synology NAS binary sensor.""" api = hass.data[DOMAIN][entry.unique_id][SYNO_API] entities = [ SynoDSMSecurityBinarySensor( api, sensor_type, SECURITY_BINARY_SENSORS[sensor_type] ) for sensor_type in SECURITY_BINARY_SENSORS ] entities += [ SynoDSMUpgradeBinarySensor( api, sensor_type, UPGRADE_BINARY_SENSORS[sensor_type] ) for sensor_type in UPGRADE_BINARY_SENSORS ] # Handle all disks if api.storage.disks_ids: for disk in entry.data.get(CONF_DISKS, api.storage.disks_ids): entities += [ SynoDSMStorageBinarySensor( api, sensor_type, STORAGE_DISK_BINARY_SENSORS[sensor_type], disk ) for sensor_type in STORAGE_DISK_BINARY_SENSORS ] async_add_entities(entities) class SynoDSMSecurityBinarySensor(SynologyDSMDispatcherEntity, BinarySensorEntity): """Representation a Synology Security binary sensor.""" @property def is_on(self) -> bool: """Return the state.""" return getattr(self._api.security, self.entity_type) != "safe" @property def available(self) -> bool: """Return True if entity is available.""" return bool(self._api.security) @property def device_state_attributes(self) -> Dict[str, str]: """Return security checks details.""" return self._api.security.status_by_check class SynoDSMStorageBinarySensor(SynologyDSMDeviceEntity, BinarySensorEntity): """Representation a Synology Storage binary sensor.""" @property def is_on(self) -> bool: """Return the state.""" return getattr(self._api.storage, self.entity_type)(self._device_id) class SynoDSMUpgradeBinarySensor(SynologyDSMDispatcherEntity, BinarySensorEntity): """Representation a Synology Upgrade binary sensor.""" @property def is_on(self) -> bool: """Return the state.""" return getattr(self._api.upgrade, self.entity_type) @property def available(self) -> bool: """Return True if entity is available.""" return bool(self._api.upgrade)
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/synology_dsm/binary_sensor.py
"""Support for Powerview scenes from a Powerview hub.""" from typing import Any from aiopvapi.resources.scene import Scene as PvScene import voluptuous as vol from homeassistant.components.scene import Scene from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import CONF_HOST, CONF_PLATFORM import homeassistant.helpers.config_validation as cv from .const import ( COORDINATOR, DEVICE_INFO, DOMAIN, HUB_ADDRESS, PV_API, PV_ROOM_DATA, PV_SCENE_DATA, ROOM_NAME_UNICODE, STATE_ATTRIBUTE_ROOM_NAME, ) from .entity import HDEntity PLATFORM_SCHEMA = vol.Schema( {vol.Required(CONF_PLATFORM): DOMAIN, vol.Required(HUB_ADDRESS): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Import platform from yaml.""" hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_HOST: config[HUB_ADDRESS]}, ) ) async def async_setup_entry(hass, entry, async_add_entities): """Set up powerview scene entries.""" pv_data = hass.data[DOMAIN][entry.entry_id] room_data = pv_data[PV_ROOM_DATA] scene_data = pv_data[PV_SCENE_DATA] pv_request = pv_data[PV_API] coordinator = pv_data[COORDINATOR] device_info = pv_data[DEVICE_INFO] pvscenes = ( PowerViewScene( PvScene(raw_scene, pv_request), room_data, coordinator, device_info ) for scene_id, raw_scene in scene_data.items() ) async_add_entities(pvscenes) class PowerViewScene(HDEntity, Scene): """Representation of a Powerview scene.""" def __init__(self, scene, room_data, coordinator, device_info): """Initialize the scene.""" super().__init__(coordinator, device_info, scene.id) self._scene = scene self._room_name = room_data.get(scene.room_id, {}).get(ROOM_NAME_UNICODE, "") @property def name(self): """Return the name of the scene.""" return self._scene.name @property def device_state_attributes(self): """Return the state attributes.""" return {STATE_ATTRIBUTE_ROOM_NAME: self._room_name} @property def icon(self): """Icon to use in the frontend.""" return "mdi:blinds" async def async_activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" await self._scene.activate()
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/hunterdouglas_powerview/scene.py
"""The Global Disaster Alert and Coordination System (GDACS) integration.""" import asyncio from datetime import timedelta import logging from aio_georss_gdacs import GdacsFeedManager import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS, CONF_SCAN_INTERVAL, CONF_UNIT_SYSTEM_IMPERIAL, LENGTH_MILES, ) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_track_time_interval from homeassistant.util.unit_system import METRIC_SYSTEM from .const import ( CONF_CATEGORIES, DEFAULT_RADIUS, DEFAULT_SCAN_INTERVAL, DOMAIN, FEED, PLATFORMS, VALID_CATEGORIES, ) _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude, vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude, vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float), vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL ): cv.time_period, vol.Optional(CONF_CATEGORIES, default=[]): vol.All( cv.ensure_list, [vol.In(VALID_CATEGORIES)] ), } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the GDACS component.""" if DOMAIN not in config: return True conf = config[DOMAIN] latitude = conf.get(CONF_LATITUDE, hass.config.latitude) longitude = conf.get(CONF_LONGITUDE, hass.config.longitude) scan_interval = conf[CONF_SCAN_INTERVAL] categories = conf[CONF_CATEGORIES] hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_LATITUDE: latitude, CONF_LONGITUDE: longitude, CONF_RADIUS: conf[CONF_RADIUS], CONF_SCAN_INTERVAL: scan_interval, CONF_CATEGORIES: categories, }, ) ) return True async def async_setup_entry(hass, config_entry): """Set up the GDACS component as config entry.""" hass.data.setdefault(DOMAIN, {}) feeds = hass.data[DOMAIN].setdefault(FEED, {}) radius = config_entry.data[CONF_RADIUS] if hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL: radius = METRIC_SYSTEM.length(radius, LENGTH_MILES) # Create feed entity manager for all platforms. manager = GdacsFeedEntityManager(hass, config_entry, radius) feeds[config_entry.entry_id] = manager _LOGGER.debug("Feed entity manager added for %s", config_entry.entry_id) await manager.async_init() return True async def async_unload_entry(hass, config_entry): """Unload an GDACS component config entry.""" manager = hass.data[DOMAIN][FEED].pop(config_entry.entry_id) await manager.async_stop() await asyncio.wait( [ hass.config_entries.async_forward_entry_unload(config_entry, domain) for domain in PLATFORMS ] ) return True class GdacsFeedEntityManager: """Feed Entity Manager for GDACS feed.""" def __init__(self, hass, config_entry, radius_in_km): """Initialize the Feed Entity Manager.""" self._hass = hass self._config_entry = config_entry coordinates = ( config_entry.data[CONF_LATITUDE], config_entry.data[CONF_LONGITUDE], ) categories = config_entry.data[CONF_CATEGORIES] websession = aiohttp_client.async_get_clientsession(hass) self._feed_manager = GdacsFeedManager( websession, self._generate_entity, self._update_entity, self._remove_entity, coordinates, filter_radius=radius_in_km, filter_categories=categories, status_async_callback=self._status_update, ) self._config_entry_id = config_entry.entry_id self._scan_interval = timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL]) self._track_time_remove_callback = None self._status_info = None self.listeners = [] async def async_init(self): """Schedule initial and regular updates based on configured time interval.""" for domain in PLATFORMS: self._hass.async_create_task( self._hass.config_entries.async_forward_entry_setup( self._config_entry, domain ) ) async def update(event_time): """Update.""" await self.async_update() # Trigger updates at regular intervals. self._track_time_remove_callback = async_track_time_interval( self._hass, update, self._scan_interval ) _LOGGER.debug("Feed entity manager initialized") async def async_update(self): """Refresh data.""" await self._feed_manager.update() _LOGGER.debug("Feed entity manager updated") async def async_stop(self): """Stop this feed entity manager from refreshing.""" for unsub_dispatcher in self.listeners: unsub_dispatcher() self.listeners = [] if self._track_time_remove_callback: self._track_time_remove_callback() _LOGGER.debug("Feed entity manager stopped") @callback def async_event_new_entity(self): """Return manager specific event to signal new entity.""" return f"gdacs_new_geolocation_{self._config_entry_id}" def get_entry(self, external_id): """Get feed entry by external id.""" return self._feed_manager.feed_entries.get(external_id) def status_info(self): """Return latest status update info received.""" return self._status_info async def _generate_entity(self, external_id): """Generate new entity.""" async_dispatcher_send( self._hass, self.async_event_new_entity(), self, self._config_entry.unique_id, external_id, ) async def _update_entity(self, external_id): """Update entity.""" async_dispatcher_send(self._hass, f"gdacs_update_{external_id}") async def _remove_entity(self, external_id): """Remove entity.""" async_dispatcher_send(self._hass, f"gdacs_delete_{external_id}") async def _status_update(self, status_info): """Propagate status update.""" _LOGGER.debug("Status update received: %s", status_info) self._status_info = status_info async_dispatcher_send(self._hass, f"gdacs_status_{self._config_entry_id}")
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/gdacs/__init__.py
"""Support for Nexia / Trane XL Thermostats.""" from homeassistant.components.binary_sensor import BinarySensorEntity from .const import DOMAIN, NEXIA_DEVICE, UPDATE_COORDINATOR from .entity import NexiaThermostatEntity async def async_setup_entry(hass, config_entry, async_add_entities): """Set up sensors for a Nexia device.""" nexia_data = hass.data[DOMAIN][config_entry.entry_id] nexia_home = nexia_data[NEXIA_DEVICE] coordinator = nexia_data[UPDATE_COORDINATOR] entities = [] for thermostat_id in nexia_home.get_thermostat_ids(): thermostat = nexia_home.get_thermostat_by_id(thermostat_id) entities.append( NexiaBinarySensor( coordinator, thermostat, "is_blower_active", "Blower Active" ) ) if thermostat.has_emergency_heat(): entities.append( NexiaBinarySensor( coordinator, thermostat, "is_emergency_heat_active", "Emergency Heat Active", ) ) async_add_entities(entities, True) class NexiaBinarySensor(NexiaThermostatEntity, BinarySensorEntity): """Provices Nexia BinarySensor support.""" def __init__(self, coordinator, thermostat, sensor_call, sensor_name): """Initialize the nexia sensor.""" super().__init__( coordinator, thermostat, name=f"{thermostat.get_name()} {sensor_name}", unique_id=f"{thermostat.thermostat_id}_{sensor_call}", ) self._call = sensor_call self._state = None @property def is_on(self): """Return the status of the sensor.""" return getattr(self._thermostat, self._call)()
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/nexia/binary_sensor.py
"""Support for Twilio.""" from twilio.rest import Client from twilio.twiml import TwiML import voluptuous as vol from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from .const import DOMAIN CONF_ACCOUNT_SID = "account_sid" CONF_AUTH_TOKEN = "auth_token" DATA_TWILIO = DOMAIN RECEIVED_DATA = f"{DOMAIN}_data_received" CONFIG_SCHEMA = vol.Schema( { vol.Optional(DOMAIN): vol.Schema( { vol.Required(CONF_ACCOUNT_SID): cv.string, vol.Required(CONF_AUTH_TOKEN): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the Twilio component.""" if DOMAIN not in config: return True conf = config[DOMAIN] hass.data[DATA_TWILIO] = Client( conf.get(CONF_ACCOUNT_SID), conf.get(CONF_AUTH_TOKEN) ) return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Twilio for inbound messages and calls.""" data = dict(await request.post()) data["webhook_id"] = webhook_id hass.bus.async_fire(RECEIVED_DATA, dict(data)) return TwiML().to_xml() async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "Twilio", entry.data[CONF_WEBHOOK_ID], handle_webhook ) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) return True async_remove_entry = config_entry_flow.webhook_async_remove_entry
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/twilio/__init__.py
"""Support for Lupusec Security System switches.""" from datetime import timedelta import lupupy.constants as CONST from homeassistant.components.switch import SwitchEntity from . import DOMAIN as LUPUSEC_DOMAIN, LupusecDevice SCAN_INTERVAL = timedelta(seconds=2) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Lupusec switch devices.""" if discovery_info is None: return data = hass.data[LUPUSEC_DOMAIN] devices = [] for device in data.lupusec.get_devices(generic_type=CONST.TYPE_SWITCH): devices.append(LupusecSwitch(data, device)) add_entities(devices) class LupusecSwitch(LupusecDevice, SwitchEntity): """Representation of a Lupusec switch.""" def turn_on(self, **kwargs): """Turn on the device.""" self._device.switch_on() def turn_off(self, **kwargs): """Turn off the device.""" self._device.switch_off() @property def is_on(self): """Return true if device is on.""" return self._device.is_on
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/lupusec/switch.py
"""Reproduce an input boolean state.""" import asyncio import logging from typing import Any, Dict, Iterable, Optional from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import Context, State from homeassistant.helpers.typing import HomeAssistantType from . import DOMAIN _LOGGER = logging.getLogger(__name__) async def _async_reproduce_states( hass: HomeAssistantType, state: State, *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce input boolean states.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in (STATE_ON, STATE_OFF): _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return if cur_state.state == state.state: return service = SERVICE_TURN_ON if state.state == STATE_ON else SERVICE_TURN_OFF await hass.services.async_call( DOMAIN, service, {ATTR_ENTITY_ID: state.entity_id}, context=context, blocking=True, ) async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce component states.""" await asyncio.gather( *( _async_reproduce_states( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/input_boolean/reproduce_state.py
"""The ATAG Integration.""" from datetime import timedelta import logging import async_timeout from pyatag import AtagException, AtagOne from homeassistant.components.climate import DOMAIN as CLIMATE from homeassistant.components.sensor import DOMAIN as SENSOR from homeassistant.components.water_heater import DOMAIN as WATER_HEATER from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, asyncio from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) _LOGGER = logging.getLogger(__name__) DOMAIN = "atag" PLATFORMS = [CLIMATE, WATER_HEATER, SENSOR] async def async_setup(hass: HomeAssistant, config): """Set up the Atag component.""" return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Atag integration from a config entry.""" session = async_get_clientsession(hass) coordinator = AtagDataUpdateCoordinator(hass, session, entry) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = coordinator if entry.unique_id is None: hass.config_entries.async_update_entry(entry, unique_id=coordinator.atag.id) for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) return True class AtagDataUpdateCoordinator(DataUpdateCoordinator): """Define an object to hold Atag data.""" def __init__(self, hass, session, entry): """Initialize.""" self.atag = AtagOne(session=session, **entry.data) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30) ) async def _async_update_data(self): """Update data via library.""" with async_timeout.timeout(20): try: if not await self.atag.update(): raise UpdateFailed("No data received") except AtagException as error: raise UpdateFailed(error) from error return self.atag.report async def async_unload_entry(hass, entry): """Unload Atag config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok class AtagEntity(CoordinatorEntity): """Defines a base Atag entity.""" def __init__(self, coordinator: AtagDataUpdateCoordinator, atag_id: str) -> None: """Initialize the Atag entity.""" super().__init__(coordinator) self._id = atag_id self._name = DOMAIN.title() @property def device_info(self) -> dict: """Return info for device registry.""" device = self.coordinator.atag.id version = self.coordinator.atag.apiversion return { "identifiers": {(DOMAIN, device)}, "name": "Atag Thermostat", "model": "Atag One", "sw_version": version, "manufacturer": "Atag", } @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def unique_id(self): """Return a unique ID to use for this entity.""" return f"{self.coordinator.atag.id}-{self._id}"
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/atag/__init__.py
"""The Dune HD component.""" import asyncio from pdunehd import DuneHDPlayer from homeassistant.const import CONF_HOST from .const import DOMAIN PLATFORMS = ["media_player"] async def async_setup(hass, config): """Set up the Dune HD component.""" return True async def async_setup_entry(hass, config_entry): """Set up a config entry.""" host = config_entry.data[CONF_HOST] player = DuneHDPlayer(host) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][config_entry.entry_id] = player for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, component) ) return True async def async_unload_entry(hass, config_entry): """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(config_entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(config_entry.entry_id) return unload_ok
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/dunehd/__init__.py
"""Provides device trigger for lights.""" from typing import List import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation import toggle_entity from homeassistant.const import CONF_DOMAIN from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_SCHEMA = toggle_entity.TRIGGER_SCHEMA.extend( {vol.Required(CONF_DOMAIN): DOMAIN} ) async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Listen for state changes based on configuration.""" return await toggle_entity.async_attach_trigger( hass, config, action, automation_info ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers.""" return await toggle_entity.async_get_triggers(hass, device_id, DOMAIN) async def async_get_trigger_capabilities(hass: HomeAssistant, config: dict) -> dict: """List trigger capabilities.""" return await toggle_entity.async_get_trigger_capabilities(hass, config)
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/light/device_trigger.py
"""Support for switch controlled using a telnet connection.""" from datetime import timedelta import logging import telnetlib import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_NAME, CONF_PORT, CONF_RESOURCE, CONF_SWITCHES, CONF_TIMEOUT, CONF_VALUE_TEMPLATE, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_PORT = 23 DEFAULT_TIMEOUT = 0.2 SWITCH_SCHEMA = vol.Schema( { vol.Required(CONF_COMMAND_OFF): cv.string, vol.Required(CONF_COMMAND_ON): cv.string, vol.Required(CONF_RESOURCE): cv.string, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_COMMAND_STATE): cv.string, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.Coerce(float), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)} ) SCAN_INTERVAL = timedelta(seconds=10) def setup_platform(hass, config, add_entities, discovery_info=None): """Find and return switches controlled by telnet commands.""" devices = config.get(CONF_SWITCHES, {}) switches = [] for object_id, device_config in devices.items(): value_template = device_config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass switches.append( TelnetSwitch( hass, object_id, device_config.get(CONF_RESOURCE), device_config.get(CONF_PORT), device_config.get(CONF_NAME, object_id), device_config.get(CONF_COMMAND_ON), device_config.get(CONF_COMMAND_OFF), device_config.get(CONF_COMMAND_STATE), value_template, device_config.get(CONF_TIMEOUT), ) ) if not switches: _LOGGER.error("No switches added") return add_entities(switches) class TelnetSwitch(SwitchEntity): """Representation of a switch that can be toggled using telnet commands.""" def __init__( self, hass, object_id, resource, port, friendly_name, command_on, command_off, command_state, value_template, timeout, ): """Initialize the switch.""" self._hass = hass self.entity_id = ENTITY_ID_FORMAT.format(object_id) self._resource = resource self._port = port self._name = friendly_name self._state = False self._command_on = command_on self._command_off = command_off self._command_state = command_state self._value_template = value_template self._timeout = timeout def _telnet_command(self, command): try: telnet = telnetlib.Telnet(self._resource, self._port) telnet.write(command.encode("ASCII") + b"\r") response = telnet.read_until(b"\r", timeout=self._timeout) _LOGGER.debug("telnet response: %s", response.decode("ASCII").strip()) return response.decode("ASCII").strip() except OSError as error: _LOGGER.error( 'Command "%s" failed with exception: %s', command, repr(error) ) return None @property def name(self): """Return the name of the switch.""" return self._name @property def should_poll(self): """Only poll if we have state command.""" return self._command_state is not None @property def is_on(self): """Return true if device is on.""" return self._state @property def assumed_state(self): """Return true if no state command is defined, false otherwise.""" return self._command_state is None def update(self): """Update device state.""" response = self._telnet_command(self._command_state) if response: rendered = self._value_template.render_with_possible_json_value(response) self._state = rendered == "True" else: _LOGGER.warning("Empty response for command: %s", self._command_state) def turn_on(self, **kwargs): """Turn the device on.""" self._telnet_command(self._command_on) if self.assumed_state: self._state = True def turn_off(self, **kwargs): """Turn the device off.""" self._telnet_command(self._command_off) if self.assumed_state: self._state = False
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/telnet/switch.py
"""Support for Google Nest SDM Cameras.""" import datetime import logging from typing import Optional from google_nest_sdm.camera_traits import ( CameraEventImageTrait, CameraImageTrait, CameraLiveStreamTrait, ) from google_nest_sdm.device import Device from google_nest_sdm.exceptions import GoogleNestException from haffmpeg.tools import IMAGE_JPEG from homeassistant.components.camera import SUPPORT_STREAM, Camera from homeassistant.components.ffmpeg import async_get_image from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util.dt import utcnow from .const import DATA_SUBSCRIBER, DOMAIN from .device_info import DeviceInfo _LOGGER = logging.getLogger(__name__) # Used to schedule an alarm to refresh the stream before expiration STREAM_EXPIRATION_BUFFER = datetime.timedelta(seconds=30) async def async_setup_sdm_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the cameras.""" subscriber = hass.data[DOMAIN][DATA_SUBSCRIBER] try: device_manager = await subscriber.async_get_device_manager() except GoogleNestException as err: raise PlatformNotReady from err # Fetch initial data so we have data when entities subscribe. entities = [] for device in device_manager.devices.values(): if ( CameraImageTrait.NAME in device.traits or CameraLiveStreamTrait.NAME in device.traits ): entities.append(NestCamera(device)) async_add_entities(entities) class NestCamera(Camera): """Devices that support cameras.""" def __init__(self, device: Device): """Initialize the camera.""" super().__init__() self._device = device self._device_info = DeviceInfo(device) self._stream = None self._stream_refresh_unsub = None # Cache of most recent event image self._event_id = None self._event_image_bytes = None self._event_image_cleanup_unsub = None @property def should_poll(self) -> bool: """Disable polling since entities have state pushed via pubsub.""" return False @property def unique_id(self) -> Optional[str]: """Return a unique ID.""" # The API "name" field is a unique device identifier. return f"{self._device.name}-camera" @property def name(self): """Return the name of the camera.""" return self._device_info.device_name @property def device_info(self): """Return device specific attributes.""" return self._device_info.device_info @property def brand(self): """Return the camera brand.""" return self._device_info.device_brand @property def model(self): """Return the camera model.""" return self._device_info.device_model @property def supported_features(self): """Flag supported features.""" supported_features = 0 if CameraLiveStreamTrait.NAME in self._device.traits: supported_features |= SUPPORT_STREAM return supported_features async def stream_source(self): """Return the source of the stream.""" if CameraLiveStreamTrait.NAME not in self._device.traits: return None trait = self._device.traits[CameraLiveStreamTrait.NAME] if not self._stream: _LOGGER.debug("Fetching stream url") self._stream = await trait.generate_rtsp_stream() self._schedule_stream_refresh() if self._stream.expires_at < utcnow(): _LOGGER.warning("Stream already expired") return self._stream.rtsp_stream_url def _schedule_stream_refresh(self): """Schedules an alarm to refresh the stream url before expiration.""" _LOGGER.debug("New stream url expires at %s", self._stream.expires_at) refresh_time = self._stream.expires_at - STREAM_EXPIRATION_BUFFER # Schedule an alarm to extend the stream if self._stream_refresh_unsub is not None: self._stream_refresh_unsub() self._stream_refresh_unsub = async_track_point_in_utc_time( self.hass, self._handle_stream_refresh, refresh_time, ) async def _handle_stream_refresh(self, now): """Alarm that fires to check if the stream should be refreshed.""" if not self._stream: return _LOGGER.debug("Extending stream url") try: self._stream = await self._stream.extend_rtsp_stream() except GoogleNestException as err: _LOGGER.debug("Failed to extend stream: %s", err) # Next attempt to catch a url will get a new one self._stream = None return # Update the stream worker with the latest valid url if self.stream: self.stream.update_source(self._stream.rtsp_stream_url) self._schedule_stream_refresh() async def async_will_remove_from_hass(self): """Invalidates the RTSP token when unloaded.""" if self._stream: _LOGGER.debug("Invalidating stream") await self._stream.stop_rtsp_stream() if self._stream_refresh_unsub: self._stream_refresh_unsub() self._event_id = None self._event_image_bytes = None if self._event_image_cleanup_unsub is not None: self._event_image_cleanup_unsub() async def async_added_to_hass(self): """Run when entity is added to register update signal handler.""" self.async_on_remove( self._device.add_update_listener(self.async_write_ha_state) ) async def async_camera_image(self): """Return bytes of camera image.""" # Returns the snapshot of the last event for ~30 seconds after the event active_event_image = await self._async_active_event_image() if active_event_image: return active_event_image # Fetch still image from the live stream stream_url = await self.stream_source() if not stream_url: return None return await async_get_image(self.hass, stream_url, output_format=IMAGE_JPEG) async def _async_active_event_image(self): """Return image from any active events happening.""" if CameraEventImageTrait.NAME not in self._device.traits: return None trait = self._device.active_event_trait if not trait: return None # Reuse image bytes if they have already been fetched event = trait.last_event if self._event_id is not None and self._event_id == event.event_id: return self._event_image_bytes _LOGGER.debug("Generating event image URL for event_id %s", event.event_id) image_bytes = await self._async_fetch_active_event_image(trait) if image_bytes is None: return None self._event_id = event.event_id self._event_image_bytes = image_bytes self._schedule_event_image_cleanup(event.expires_at) return image_bytes async def _async_fetch_active_event_image(self, trait): """Return image bytes for an active event.""" try: event_image = await trait.generate_active_event_image() except GoogleNestException as err: _LOGGER.debug("Unable to generate event image URL: %s", err) return None if not event_image: return None try: return await event_image.contents() except GoogleNestException as err: _LOGGER.debug("Unable to fetch event image: %s", err) return None def _schedule_event_image_cleanup(self, point_in_time): """Schedules an alarm to remove the image bytes from memory, honoring expiration.""" if self._event_image_cleanup_unsub is not None: self._event_image_cleanup_unsub() self._event_image_cleanup_unsub = async_track_point_in_utc_time( self.hass, self._handle_event_image_cleanup, point_in_time, ) def _handle_event_image_cleanup(self, now): """Clear images cached from events and scheduled callback.""" self._event_id = None self._event_image_bytes = None self._event_image_cleanup_unsub = None
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/nest/camera_sdm.py
"""Support for testing internet speed via Speedtest.net.""" from datetime import timedelta import logging import speedtest import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_STARTED, ) from homeassistant.core import CoreState, callback from homeassistant.exceptions import ConfigEntryNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( CONF_MANUAL, CONF_SERVER_ID, DEFAULT_SCAN_INTERVAL, DEFAULT_SERVER, DOMAIN, SENSOR_TYPES, SPEED_TEST_SERVICE, ) _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_SERVER_ID): cv.positive_int, vol.Optional( CONF_SCAN_INTERVAL, default=timedelta(minutes=DEFAULT_SCAN_INTERVAL) ): cv.positive_time_period, vol.Optional(CONF_MANUAL, default=False): cv.boolean, vol.Optional( CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES) ): vol.All(cv.ensure_list, [vol.In(list(SENSOR_TYPES))]), } ) }, extra=vol.ALLOW_EXTRA, ) def server_id_valid(server_id): """Check if server_id is valid.""" try: api = speedtest.Speedtest() api.get_servers([int(server_id)]) except (speedtest.ConfigRetrievalError, speedtest.NoMatchedServers): return False return True async def async_setup(hass, config): """Import integration from config.""" if DOMAIN in config: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN] ) ) return True async def async_setup_entry(hass, config_entry): """Set up the Speedtest.net component.""" coordinator = SpeedTestDataCoordinator(hass, config_entry) await coordinator.async_setup() async def _enable_scheduled_speedtests(*_): """Activate the data update coordinator.""" coordinator.update_interval = timedelta( minutes=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) ) await coordinator.async_refresh() if not config_entry.options[CONF_MANUAL]: if hass.state == CoreState.running: await _enable_scheduled_speedtests() if not coordinator.last_update_success: raise ConfigEntryNotReady else: # Running a speed test during startup can prevent # integrations from being able to setup because it # can saturate the network interface. hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STARTED, _enable_scheduled_speedtests ) hass.data[DOMAIN] = coordinator hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, "sensor") ) return True async def async_unload_entry(hass, config_entry): """Unload SpeedTest Entry from config_entry.""" hass.services.async_remove(DOMAIN, SPEED_TEST_SERVICE) hass.data[DOMAIN].async_unload() await hass.config_entries.async_forward_entry_unload(config_entry, "sensor") hass.data.pop(DOMAIN) return True class SpeedTestDataCoordinator(DataUpdateCoordinator): """Get the latest data from speedtest.net.""" def __init__(self, hass, config_entry): """Initialize the data object.""" self.hass = hass self.config_entry = config_entry self.api = None self.servers = {} self._unsub_update_listener = None super().__init__( self.hass, _LOGGER, name=DOMAIN, update_method=self.async_update, ) def update_servers(self): """Update list of test servers.""" try: server_list = self.api.get_servers() except speedtest.ConfigRetrievalError: _LOGGER.debug("Error retrieving server list") return self.servers[DEFAULT_SERVER] = {} for server in sorted( server_list.values(), key=lambda server: server[0]["country"] + server[0]["sponsor"], ): self.servers[ f"{server[0]['country']} - {server[0]['sponsor']} - {server[0]['name']}" ] = server[0] def update_data(self): """Get the latest data from speedtest.net.""" self.update_servers() self.api.closest.clear() if self.config_entry.options.get(CONF_SERVER_ID): server_id = self.config_entry.options.get(CONF_SERVER_ID) self.api.get_servers(servers=[server_id]) self.api.get_best_server() _LOGGER.debug( "Executing speedtest.net speed test with server_id: %s", self.api.best["id"] ) self.api.download() self.api.upload() return self.api.results.dict() async def async_update(self, *_): """Update Speedtest data.""" try: return await self.hass.async_add_executor_job(self.update_data) except (speedtest.ConfigRetrievalError, speedtest.NoMatchedServers) as err: raise UpdateFailed from err async def async_set_options(self): """Set options for entry.""" if not self.config_entry.options: data = {**self.config_entry.data} options = { CONF_SCAN_INTERVAL: data.pop(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL), CONF_MANUAL: data.pop(CONF_MANUAL, False), CONF_SERVER_ID: str(data.pop(CONF_SERVER_ID, "")), } self.hass.config_entries.async_update_entry( self.config_entry, data=data, options=options ) async def async_setup(self): """Set up SpeedTest.""" try: self.api = await self.hass.async_add_executor_job(speedtest.Speedtest) except speedtest.ConfigRetrievalError as err: raise ConfigEntryNotReady from err async def request_update(call): """Request update.""" await self.async_request_refresh() await self.async_set_options() await self.hass.async_add_executor_job(self.update_servers) self.hass.services.async_register(DOMAIN, SPEED_TEST_SERVICE, request_update) self._unsub_update_listener = self.config_entry.add_update_listener( options_updated_listener ) @callback def async_unload(self): """Unload the coordinator.""" if not self._unsub_update_listener: return self._unsub_update_listener() self._unsub_update_listener = None async def options_updated_listener(hass, entry): """Handle options update.""" if entry.options[CONF_MANUAL]: hass.data[DOMAIN].update_interval = None return hass.data[DOMAIN].update_interval = timedelta( minutes=entry.options[CONF_SCAN_INTERVAL] ) await hass.data[DOMAIN].async_request_refresh()
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/components/speedtestdotnet/__init__.py
""" Module with location helpers. detect_location_info and elevation are mocked by default during tests. """ import asyncio import collections import math from typing import Any, Dict, Optional, Tuple import aiohttp ELEVATION_URL = "https://api.open-elevation.com/api/v1/lookup" IP_API = "http://ip-api.com/json" IPAPI = "https://ipapi.co/json/" # Constants from https://github.com/maurycyp/vincenty # Earth ellipsoid according to WGS 84 # Axis a of the ellipsoid (Radius of the earth in meters) AXIS_A = 6378137 # Flattening f = (a-b) / a FLATTENING = 1 / 298.257223563 # Axis b of the ellipsoid in meters. AXIS_B = 6356752.314245 MILES_PER_KILOMETER = 0.621371 MAX_ITERATIONS = 200 CONVERGENCE_THRESHOLD = 1e-12 LocationInfo = collections.namedtuple( "LocationInfo", [ "ip", "country_code", "country_name", "region_code", "region_name", "city", "zip_code", "time_zone", "latitude", "longitude", "use_metric", ], ) async def async_detect_location_info( session: aiohttp.ClientSession, ) -> Optional[LocationInfo]: """Detect location information.""" data = await _get_ipapi(session) if data is None: data = await _get_ip_api(session) if data is None: return None data["use_metric"] = data["country_code"] not in ("US", "MM", "LR") return LocationInfo(**data) def distance( lat1: Optional[float], lon1: Optional[float], lat2: float, lon2: float ) -> Optional[float]: """Calculate the distance in meters between two points. Async friendly. """ if lat1 is None or lon1 is None: return None result = vincenty((lat1, lon1), (lat2, lon2)) if result is None: return None return result * 1000 # Author: https://github.com/maurycyp # Source: https://github.com/maurycyp/vincenty # License: https://github.com/maurycyp/vincenty/blob/master/LICENSE def vincenty( point1: Tuple[float, float], point2: Tuple[float, float], miles: bool = False ) -> Optional[float]: """ Vincenty formula (inverse method) to calculate the distance. Result in kilometers or miles between two points on the surface of a spheroid. Async friendly. """ # short-circuit coincident points if point1[0] == point2[0] and point1[1] == point2[1]: return 0.0 # pylint: disable=invalid-name U1 = math.atan((1 - FLATTENING) * math.tan(math.radians(point1[0]))) U2 = math.atan((1 - FLATTENING) * math.tan(math.radians(point2[0]))) L = math.radians(point2[1] - point1[1]) Lambda = L sinU1 = math.sin(U1) cosU1 = math.cos(U1) sinU2 = math.sin(U2) cosU2 = math.cos(U2) for _ in range(MAX_ITERATIONS): sinLambda = math.sin(Lambda) cosLambda = math.cos(Lambda) sinSigma = math.sqrt( (cosU2 * sinLambda) ** 2 + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) ** 2 ) if sinSigma == 0.0: return 0.0 # coincident points cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda sigma = math.atan2(sinSigma, cosSigma) sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma cosSqAlpha = 1 - sinAlpha ** 2 try: cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha except ZeroDivisionError: cos2SigmaM = 0 C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) LambdaPrev = Lambda Lambda = L + (1 - C) * FLATTENING * sinAlpha * ( sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2)) ) if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD: break # successful convergence else: return None # failure to converge uSq = cosSqAlpha * (AXIS_A ** 2 - AXIS_B ** 2) / (AXIS_B ** 2) A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) deltaSigma = ( B * sinSigma * ( cos2SigmaM + B / 4 * ( cosSigma * (-1 + 2 * cos2SigmaM ** 2) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma ** 2) * (-3 + 4 * cos2SigmaM ** 2) ) ) ) s = AXIS_B * A * (sigma - deltaSigma) s /= 1000 # Conversion of meters to kilometers if miles: s *= MILES_PER_KILOMETER # kilometers to miles return round(s, 6) async def _get_ipapi(session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]: """Query ipapi.co for location data.""" try: resp = await session.get(IPAPI, timeout=5) except (aiohttp.ClientError, asyncio.TimeoutError): return None try: raw_info = await resp.json() except (aiohttp.ClientError, ValueError): return None # ipapi allows 30k free requests/month. Some users exhaust those. if raw_info.get("latitude") == "Sign up to access": return None return { "ip": raw_info.get("ip"), "country_code": raw_info.get("country"), "country_name": raw_info.get("country_name"), "region_code": raw_info.get("region_code"), "region_name": raw_info.get("region"), "city": raw_info.get("city"), "zip_code": raw_info.get("postal"), "time_zone": raw_info.get("timezone"), "latitude": raw_info.get("latitude"), "longitude": raw_info.get("longitude"), } async def _get_ip_api(session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]: """Query ip-api.com for location data.""" try: resp = await session.get(IP_API, timeout=5) except (aiohttp.ClientError, asyncio.TimeoutError): return None try: raw_info = await resp.json() except (aiohttp.ClientError, ValueError): return None return { "ip": raw_info.get("query"), "country_code": raw_info.get("countryCode"), "country_name": raw_info.get("country"), "region_code": raw_info.get("region"), "region_name": raw_info.get("regionName"), "city": raw_info.get("city"), "zip_code": raw_info.get("zip"), "time_zone": raw_info.get("timezone"), "latitude": raw_info.get("lat"), "longitude": raw_info.get("lon"), }
"""The tests for the notify smtp platform.""" from os 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 import DOMAIN from homeassistant.components.smtp.notify import MailNotificationService from homeassistant.const import SERVICE_RELOAD from homeassistant.setup import async_setup_component class MockSMTP(MailNotificationService): """Test SMTP object that doesn't need a working server.""" def _send_email(self, msg): """Just return string for testing.""" return msg.as_string() async def test_reload_notify(hass): """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 = path.join( _get_fixtures_base_path(), "fixtures", "smtp/configuration.yaml", ) 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") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__))) @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, ) yield 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/related", ), ( "Test msg", {"html": HTML, "images": ["tests/testing_config/notify/test.jpg"]}, "Content-Type: multipart/related", ), ( "Test msg", {"html": HTML, "images": ["test.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(message_data, data, content_type, hass, message): """Verify if we can send messages of all types correctly.""" sample_email = "<mock@mock>" with patch("email.utils.make_msgid", return_value=sample_email): result = message.send_message(message_data, data=data) assert content_type in result def test_send_text_message(hass, message): """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)
turbokongen/home-assistant
tests/components/smtp/test_notify.py
homeassistant/util/location.py
"""Reproduce an Remote state.""" from __future__ import annotations import asyncio from collections.abc import Iterable import logging from typing import Any from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import Context, HomeAssistant, State from . import DOMAIN _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATE_ON, STATE_OFF} async def _async_reproduce_state( hass: HomeAssistant, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state: return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state == STATE_ON: service = SERVICE_TURN_ON elif state.state == STATE_OFF: service = SERVICE_TURN_OFF await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistant, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Remote states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/remote/reproduce_state.py
"""Demo platform that has a couple of fake sensors.""" from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity from homeassistant.const import ( ATTR_BATTERY_LEVEL, CONCENTRATION_PARTS_PER_MILLION, DEVICE_CLASS_CO, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from . import DOMAIN async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo sensors.""" async_add_entities( [ DemoSensor( "sensor_1", "Outside Temperature", 15.6, DEVICE_CLASS_TEMPERATURE, STATE_CLASS_MEASUREMENT, TEMP_CELSIUS, 12, ), DemoSensor( "sensor_2", "Outside Humidity", 54, DEVICE_CLASS_HUMIDITY, STATE_CLASS_MEASUREMENT, PERCENTAGE, None, ), DemoSensor( "sensor_3", "Carbon monoxide", 54, DEVICE_CLASS_CO, STATE_CLASS_MEASUREMENT, CONCENTRATION_PARTS_PER_MILLION, None, ), DemoSensor( "sensor_4", "Carbon dioxide", 54, DEVICE_CLASS_CO2, STATE_CLASS_MEASUREMENT, CONCENTRATION_PARTS_PER_MILLION, 14, ), ] ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" await async_setup_platform(hass, {}, async_add_entities) class DemoSensor(SensorEntity): """Representation of a Demo sensor.""" def __init__( self, unique_id, name, state, device_class, state_class, unit_of_measurement, battery, ): """Initialize the sensor.""" self._battery = battery self._device_class = device_class self._name = name self._state = state self._state_class = state_class self._unique_id = unique_id self._unit_of_measurement = unit_of_measurement @property def device_info(self): """Return device info.""" return { "identifiers": { # Serial numbers are unique identifiers within a specific domain (DOMAIN, self.unique_id) }, "name": self.name, } @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def should_poll(self): """No polling needed for a demo sensor.""" return False @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def state_class(self): """Return the state class of the sensor.""" return self._state_class @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit_of_measurement @property def extra_state_attributes(self): """Return the state attributes.""" if self._battery: return {ATTR_BATTERY_LEVEL: self._battery}
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/demo/sensor.py
"""BleBox switch implementation.""" from homeassistant.components.switch import SwitchEntity from . import BleBoxEntity, create_blebox_entities from .const import BLEBOX_TO_HASS_DEVICE_CLASSES async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a BleBox switch entity.""" create_blebox_entities( hass, config_entry, async_add_entities, BleBoxSwitchEntity, "switches" ) class BleBoxSwitchEntity(BleBoxEntity, SwitchEntity): """Representation of a BleBox switch feature.""" @property def device_class(self): """Return the device class.""" return BLEBOX_TO_HASS_DEVICE_CLASSES[self._feature.device_class] @property def is_on(self): """Return whether switch is on.""" return self._feature.is_on async def async_turn_on(self, **kwargs): """Turn on the switch.""" await self._feature.async_turn_on() async def async_turn_off(self, **kwargs): """Turn off the switch.""" await self._feature.async_turn_off()
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/blebox/switch.py
"""Support for the Hive binary sensors.""" from datetime import timedelta from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_SMOKE, DEVICE_CLASS_SOUND, BinarySensorEntity, ) from . import HiveEntity from .const import ATTR_MODE, DOMAIN DEVICETYPE = { "contactsensor": DEVICE_CLASS_OPENING, "motionsensor": DEVICE_CLASS_MOTION, "Connectivity": DEVICE_CLASS_CONNECTIVITY, "SMOKE_CO": DEVICE_CLASS_SMOKE, "DOG_BARK": DEVICE_CLASS_SOUND, "GLASS_BREAK": DEVICE_CLASS_SOUND, } PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("binary_sensor") entities = [] if devices: for dev in devices: entities.append(HiveBinarySensorEntity(hive, dev)) async_add_entities(entities, True) class HiveBinarySensorEntity(HiveEntity, BinarySensorEntity): """Representation of a Hive binary sensor.""" @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self.device["device_id"])}, "name": self.device["device_name"], "model": self.device["deviceData"]["model"], "manufacturer": self.device["deviceData"]["manufacturer"], "sw_version": self.device["deviceData"]["version"], "via_device": (DOMAIN, self.device["parentDevice"]), } @property def device_class(self): """Return the class of this sensor.""" return DEVICETYPE.get(self.device["hiveType"]) @property def name(self): """Return the name of the binary sensor.""" return self.device["haName"] @property def available(self): """Return if the device is available.""" if self.device["hiveType"] != "Connectivity": return self.device["deviceData"]["online"] return True @property def extra_state_attributes(self): """Show Device Attributes.""" return { ATTR_MODE: self.attributes.get(ATTR_MODE), } @property def is_on(self): """Return true if the binary sensor is on.""" return self.device["status"]["state"] async def async_update(self): """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.sensor.getSensor(self.device) self.attributes = self.device.get("attributes", {})
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/hive/binary_sensor.py
"""Helper to test significant Binary Sensor state changes.""" from __future__ import annotations from typing import Any from homeassistant.core import HomeAssistant, callback @callback def async_check_significant_change( hass: HomeAssistant, old_state: str, old_attrs: dict, new_state: str, new_attrs: dict, **kwargs: Any, ) -> bool | None: """Test if state significantly changed.""" if old_state != new_state: return True return False
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/binary_sensor/significant_change.py
"""KIRA interface to receive UDP packets from an IR-IP bridge.""" import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import CONF_DEVICE, CONF_NAME, STATE_UNKNOWN from . import CONF_SENSOR, DOMAIN _LOGGER = logging.getLogger(__name__) ICON = "mdi:remote" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Kira sensor.""" if discovery_info is not None: name = discovery_info.get(CONF_NAME) device = discovery_info.get(CONF_DEVICE) kira = hass.data[DOMAIN][CONF_SENSOR][name] add_entities([KiraReceiver(device, kira)]) class KiraReceiver(SensorEntity): """Implementation of a Kira Receiver.""" def __init__(self, name, kira): """Initialize the sensor.""" self._name = name self._state = None self._device = STATE_UNKNOWN kira.registerCallback(self._update_callback) def _update_callback(self, code): code_name, device = code _LOGGER.debug("Kira Code: %s", code_name) self._state = code_name self._device = device self.schedule_update_ha_state() @property def name(self): """Return the name of the receiver.""" return self._name @property def icon(self): """Return icon.""" return ICON @property def state(self): """Return the state of the receiver.""" return self._state @property def extra_state_attributes(self): """Return the state attributes of the device.""" return {CONF_DEVICE: self._device} @property def should_poll(self) -> bool: """Entity should not be polled.""" return False @property def force_update(self) -> bool: """Kira should force updates. Repeated states have meaning.""" return True
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/kira/sensor.py
"""Support for Axis switches.""" from axis.event_stream import CLASS_OUTPUT from homeassistant.components.switch import SwitchEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .axis_base import AxisEventBase from .const import DOMAIN as AXIS_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a Axis switch.""" device = hass.data[AXIS_DOMAIN][config_entry.unique_id] @callback def async_add_switch(event_id): """Add switch from Axis device.""" event = device.api.event[event_id] if event.CLASS == CLASS_OUTPUT: async_add_entities([AxisSwitch(event, device)]) config_entry.async_on_unload( async_dispatcher_connect(hass, device.signal_new_event, async_add_switch) ) class AxisSwitch(AxisEventBase, SwitchEntity): """Representation of a Axis switch.""" @property def is_on(self): """Return true if event is active.""" return self.event.is_tripped async def async_turn_on(self, **kwargs): """Turn on switch.""" await self.device.api.vapix.ports[self.event.id].close() async def async_turn_off(self, **kwargs): """Turn off switch.""" await self.device.api.vapix.ports[self.event.id].open() @property def name(self): """Return the name of the event.""" if self.event.id and self.device.api.vapix.ports[self.event.id].name: return ( f"{self.device.name} {self.device.api.vapix.ports[self.event.id].name}" ) return super().name
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/axis/switch.py
"""Support for the EZcontrol XS1 gateway.""" import asyncio import logging import voluptuous as vol import xs1_api_client from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, ) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) DOMAIN = "xs1" ACTUATORS = "actuators" SENSORS = "sensors" # define configuration parameters CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=80): cv.string, vol.Optional(CONF_SSL, default=False): cv.boolean, vol.Optional(CONF_USERNAME): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) PLATFORMS = ["climate", "sensor", "switch"] # Lock used to limit the amount of concurrent update requests # as the XS1 Gateway can only handle a very # small amount of concurrent requests UPDATE_LOCK = asyncio.Lock() def setup(hass, config): """Set up XS1 integration.""" _LOGGER.debug("Initializing XS1") host = config[DOMAIN][CONF_HOST] port = config[DOMAIN][CONF_PORT] ssl = config[DOMAIN][CONF_SSL] user = config[DOMAIN].get(CONF_USERNAME) password = config[DOMAIN].get(CONF_PASSWORD) # initialize XS1 API try: xs1 = xs1_api_client.XS1( host=host, port=port, ssl=ssl, user=user, password=password ) except ConnectionError as error: _LOGGER.error( "Failed to create XS1 API client because of a connection error: %s", error, ) return False _LOGGER.debug("Establishing connection to XS1 gateway and retrieving data") hass.data[DOMAIN] = {} actuators = xs1.get_all_actuators(enabled=True) sensors = xs1.get_all_sensors(enabled=True) hass.data[DOMAIN][ACTUATORS] = actuators hass.data[DOMAIN][SENSORS] = sensors _LOGGER.debug("Loading platforms for XS1 integration") # Load platforms for supported devices for platform in PLATFORMS: discovery.load_platform(hass, platform, DOMAIN, {}, config) return True class XS1DeviceEntity(Entity): """Representation of a base XS1 device.""" def __init__(self, device): """Initialize the XS1 device.""" self.device = device async def async_update(self): """Retrieve latest device state.""" async with UPDATE_LOCK: await self.hass.async_add_executor_job(self.device.update)
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/xs1/__init__.py
"""Config flow for SiteSage Emonitor integration.""" import logging from aioemonitor import Emonitor import aiohttp import voluptuous as vol from homeassistant import config_entries, core from homeassistant.components.dhcp import IP_ADDRESS, MAC_ADDRESS from homeassistant.const import CONF_HOST, CONF_NAME from homeassistant.helpers import aiohttp_client from homeassistant.helpers.device_registry import format_mac from . import name_short_mac from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def fetch_mac_and_title(hass: core.HomeAssistant, host): """Validate the user input allows us to connect.""" session = aiohttp_client.async_get_clientsession(hass) emonitor = Emonitor(host, session) status = await emonitor.async_get_status() mac_address = status.network.mac_address return {"title": name_short_mac(mac_address[-6:]), "mac_address": mac_address} class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for SiteSage Emonitor.""" VERSION = 1 def __init__(self): """Initialize Emonitor ConfigFlow.""" self.discovered_ip = None self.discovered_info = None async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: info = await fetch_mac_and_title(self.hass, user_input[CONF_HOST]) except aiohttp.ClientError: errors[CONF_HOST] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id( format_mac(info["mac_address"]), raise_on_progress=False ) self._abort_if_unique_id_configured() return self.async_create_entry(title=info["title"], data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required("host", default=self.discovered_ip): str} ), errors=errors, ) async def async_step_dhcp(self, discovery_info): """Handle dhcp discovery.""" self.discovered_ip = discovery_info[IP_ADDRESS] await self.async_set_unique_id(format_mac(discovery_info[MAC_ADDRESS])) self._abort_if_unique_id_configured(updates={CONF_HOST: self.discovered_ip}) name = name_short_mac(short_mac(discovery_info[MAC_ADDRESS])) self.context["title_placeholders"] = {"name": name} try: self.discovered_info = await fetch_mac_and_title( self.hass, self.discovered_ip ) except Exception as ex: # pylint: disable=broad-except _LOGGER.debug( "Unable to fetch status, falling back to manual entry", exc_info=ex ) return await self.async_step_user() return await self.async_step_confirm() async def async_step_confirm(self, user_input=None): """Attempt to confim.""" if user_input is not None: return self.async_create_entry( title=self.discovered_info["title"], data={CONF_HOST: self.discovered_ip}, ) self._set_confirm_only() self.context["title_placeholders"] = {"name": self.discovered_info["title"]} return self.async_show_form( step_id="confirm", description_placeholders={ CONF_HOST: self.discovered_ip, CONF_NAME: self.discovered_info["title"], }, ) def short_mac(mac): """Short version of the mac.""" return "".join(mac.split(":")[3:]).upper()
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/emonitor/config_flow.py
"""Support for LED lights.""" from __future__ import annotations from functools import partial from typing import Any import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_registry import ( async_get_registry as async_get_entity_registry, ) import homeassistant.util.color as color_util from . import WLEDDataUpdateCoordinator, WLEDEntity, wled_exception_handler from .const import ( ATTR_COLOR_PRIMARY, ATTR_INTENSITY, ATTR_ON, ATTR_PALETTE, ATTR_PLAYLIST, ATTR_PRESET, ATTR_REVERSE, ATTR_SEGMENT_ID, ATTR_SPEED, DOMAIN, SERVICE_EFFECT, SERVICE_PRESET, ) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up WLED light based on a config entry.""" coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_EFFECT, { vol.Optional(ATTR_EFFECT): vol.Any(cv.positive_int, cv.string), vol.Optional(ATTR_INTENSITY): vol.All( vol.Coerce(int), vol.Range(min=0, max=255) ), vol.Optional(ATTR_PALETTE): vol.Any(cv.positive_int, cv.string), vol.Optional(ATTR_REVERSE): cv.boolean, vol.Optional(ATTR_SPEED): vol.All( vol.Coerce(int), vol.Range(min=0, max=255) ), }, "async_effect", ) platform.async_register_entity_service( SERVICE_PRESET, { vol.Required(ATTR_PRESET): vol.All( vol.Coerce(int), vol.Range(min=-1, max=65535) ), }, "async_preset", ) update_segments = partial( async_update_segments, entry, coordinator, {}, async_add_entities ) coordinator.async_add_listener(update_segments) update_segments() class WLEDMasterLight(WLEDEntity, LightEntity): """Defines a WLED master light.""" _attr_supported_features = SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION _attr_icon = "mdi:led-strip-variant" def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None: """Initialize WLED master light.""" super().__init__(coordinator=coordinator) self._attr_name = f"{coordinator.data.info.name} Master" self._attr_unique_id = coordinator.data.info.mac_address @property def brightness(self) -> int | None: """Return the brightness of this light between 1..255.""" return self.coordinator.data.state.brightness @property def is_on(self) -> bool: """Return the state of the light.""" return bool(self.coordinator.data.state.on) @wled_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" data: dict[str, bool | int] = {ATTR_ON: False} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) await self.coordinator.wled.master(**data) @wled_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" data: dict[str, bool | int] = {ATTR_ON: True} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) if ATTR_BRIGHTNESS in kwargs: data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS] await self.coordinator.wled.master(**data) async def async_effect( self, effect: int | str | None = None, intensity: int | None = None, palette: int | str | None = None, reverse: bool | None = None, speed: int | None = None, ) -> None: """Set the effect of a WLED light.""" # Master light does not have an effect setting. @wled_exception_handler async def async_preset( self, preset: int, ) -> None: """Set a WLED light to a saved preset.""" data = {ATTR_PRESET: preset} await self.coordinator.wled.preset(**data) class WLEDSegmentLight(WLEDEntity, LightEntity): """Defines a WLED light based on a segment.""" _attr_icon = "mdi:led-strip-variant" def __init__(self, coordinator: WLEDDataUpdateCoordinator, segment: int) -> None: """Initialize WLED segment light.""" super().__init__(coordinator=coordinator) self._rgbw = coordinator.data.info.leds.rgbw self._segment = segment # If this is the one and only segment, use a simpler name self._attr_name = f"{coordinator.data.info.name} Segment {segment}" if len(coordinator.data.state.segments) == 1: self._attr_name = coordinator.data.info.name self._attr_unique_id = ( f"{self.coordinator.data.info.mac_address}_{self._segment}" ) @property def available(self) -> bool: """Return True if entity is available.""" try: self.coordinator.data.state.segments[self._segment] except IndexError: return False return super().available @property def extra_state_attributes(self) -> dict[str, Any] | None: """Return the state attributes of the entity.""" playlist = self.coordinator.data.state.playlist if playlist == -1: playlist = None preset = self.coordinator.data.state.preset if preset == -1: preset = None segment = self.coordinator.data.state.segments[self._segment] return { ATTR_INTENSITY: segment.intensity, ATTR_PALETTE: segment.palette.name, ATTR_PLAYLIST: playlist, ATTR_PRESET: preset, ATTR_REVERSE: segment.reverse, ATTR_SPEED: segment.speed, } @property def hs_color(self) -> tuple[float, float]: """Return the hue and saturation color value [float, float].""" color = self.coordinator.data.state.segments[self._segment].color_primary return color_util.color_RGB_to_hs(*color[:3]) @property def effect(self) -> str | None: """Return the current effect of the light.""" return self.coordinator.data.state.segments[self._segment].effect.name @property def brightness(self) -> int | None: """Return the brightness of this light between 1..255.""" state = self.coordinator.data.state # If this is the one and only segment, calculate brightness based # on the master and segment brightness if len(state.segments) == 1: return int( (state.segments[self._segment].brightness * state.brightness) / 255 ) return state.segments[self._segment].brightness @property def white_value(self) -> int | None: """Return the white value of this light between 0..255.""" color = self.coordinator.data.state.segments[self._segment].color_primary return color[-1] if self._rgbw else None @property def supported_features(self) -> int: """Flag supported features.""" flags = ( SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | SUPPORT_TRANSITION ) if self._rgbw: flags |= SUPPORT_WHITE_VALUE return flags @property def effect_list(self) -> list[str]: """Return the list of supported effects.""" return [effect.name for effect in self.coordinator.data.effects] @property def is_on(self) -> bool: """Return the state of the light.""" state = self.coordinator.data.state # If there is a single segment, take master into account if len(state.segments) == 1 and not state.on: return False return bool(state.segments[self._segment].on) @wled_exception_handler async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" data: dict[str, bool | int] = {ATTR_ON: False} if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) # If there is a single segment, control via the master if len(self.coordinator.data.state.segments) == 1: await self.coordinator.wled.master(**data) return data[ATTR_SEGMENT_ID] = self._segment await self.coordinator.wled.segment(**data) @wled_exception_handler async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" data: dict[str, Any] = { ATTR_ON: True, ATTR_SEGMENT_ID: self._segment, } if ATTR_COLOR_TEMP in kwargs: mireds = color_util.color_temperature_kelvin_to_mired( kwargs[ATTR_COLOR_TEMP] ) data[ATTR_COLOR_PRIMARY] = tuple( map(int, color_util.color_temperature_to_rgb(mireds)) ) if ATTR_HS_COLOR in kwargs: hue, sat = kwargs[ATTR_HS_COLOR] data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100) if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10) if ATTR_BRIGHTNESS in kwargs: data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS] if ATTR_EFFECT in kwargs: data[ATTR_EFFECT] = kwargs[ATTR_EFFECT] # Support for RGBW strips, adds white value if self._rgbw and any( x in (ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_WHITE_VALUE) for x in kwargs ): # WLED cannot just accept a white value, it needs the color. # We use the last know color in case just the white value changes. if all(x not in (ATTR_COLOR_TEMP, ATTR_HS_COLOR) for x in kwargs): hue, sat = self.hs_color data[ATTR_COLOR_PRIMARY] = color_util.color_hsv_to_RGB(hue, sat, 100) # On a RGBW strip, when the color is pure white, disable the RGB LEDs in # WLED by setting RGB to 0,0,0 if data[ATTR_COLOR_PRIMARY] == (255, 255, 255): data[ATTR_COLOR_PRIMARY] = (0, 0, 0) # Add requested or last known white value if ATTR_WHITE_VALUE in kwargs: data[ATTR_COLOR_PRIMARY] += (kwargs[ATTR_WHITE_VALUE],) else: data[ATTR_COLOR_PRIMARY] += (self.white_value,) # When only 1 segment is present, switch along the master, and use # the master for power/brightness control. if len(self.coordinator.data.state.segments) == 1: master_data = {ATTR_ON: True} if ATTR_BRIGHTNESS in data: master_data[ATTR_BRIGHTNESS] = data[ATTR_BRIGHTNESS] data[ATTR_BRIGHTNESS] = 255 if ATTR_TRANSITION in data: master_data[ATTR_TRANSITION] = data[ATTR_TRANSITION] del data[ATTR_TRANSITION] await self.coordinator.wled.segment(**data) await self.coordinator.wled.master(**master_data) return await self.coordinator.wled.segment(**data) @wled_exception_handler async def async_effect( self, effect: int | str | None = None, intensity: int | None = None, palette: int | str | None = None, reverse: bool | None = None, speed: int | None = None, ) -> None: """Set the effect of a WLED light.""" data: dict[str, bool | int | str | None] = {ATTR_SEGMENT_ID: self._segment} if effect is not None: data[ATTR_EFFECT] = effect if intensity is not None: data[ATTR_INTENSITY] = intensity if palette is not None: data[ATTR_PALETTE] = palette if reverse is not None: data[ATTR_REVERSE] = reverse if speed is not None: data[ATTR_SPEED] = speed await self.coordinator.wled.segment(**data) @wled_exception_handler async def async_preset( self, preset: int, ) -> None: """Set a WLED light to a saved preset.""" data = {ATTR_PRESET: preset} await self.coordinator.wled.preset(**data) @callback def async_update_segments( entry: ConfigEntry, coordinator: WLEDDataUpdateCoordinator, current: dict[int, WLEDSegmentLight | WLEDMasterLight], async_add_entities, ) -> None: """Update segments.""" segment_ids = {light.segment_id for light in coordinator.data.state.segments} current_ids = set(current) # Discard master (if present) current_ids.discard(-1) # Process new segments, add them to Home Assistant new_entities = [] for segment_id in segment_ids - current_ids: current[segment_id] = WLEDSegmentLight(coordinator, segment_id) new_entities.append(current[segment_id]) # More than 1 segment now? Add master controls if len(current_ids) < 2 and len(segment_ids) > 1: current[-1] = WLEDMasterLight(coordinator) new_entities.append(current[-1]) if new_entities: async_add_entities(new_entities) # Process deleted segments, remove them from Home Assistant for segment_id in current_ids - segment_ids: coordinator.hass.async_create_task( async_remove_entity(segment_id, coordinator, current) ) # Remove master if there is only 1 segment left if len(current_ids) > 1 and len(segment_ids) < 2: coordinator.hass.async_create_task( async_remove_entity(-1, coordinator, current) ) async def async_remove_entity( index: int, coordinator: WLEDDataUpdateCoordinator, current: dict[int, WLEDSegmentLight | WLEDMasterLight], ) -> None: """Remove WLED segment light from Home Assistant.""" entity = current[index] await entity.async_remove(force_remove=True) registry = await async_get_entity_registry(coordinator.hass) if entity.entity_id in registry.entities: registry.async_remove(entity.entity_id) del current[index]
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/wled/light.py
"""Constants used by multiple MQTT modules.""" from homeassistant.const import CONF_PAYLOAD ATTR_DISCOVERY_HASH = "discovery_hash" ATTR_DISCOVERY_PAYLOAD = "discovery_payload" ATTR_DISCOVERY_TOPIC = "discovery_topic" ATTR_PAYLOAD = "payload" ATTR_QOS = "qos" ATTR_RETAIN = "retain" ATTR_TOPIC = "topic" CONF_BROKER = "broker" CONF_BIRTH_MESSAGE = "birth_message" CONF_QOS = ATTR_QOS CONF_RETAIN = ATTR_RETAIN CONF_STATE_TOPIC = "state_topic" CONF_WILL_MESSAGE = "will_message" DATA_MQTT_CONFIG = "mqtt_config" DEFAULT_PREFIX = "homeassistant" DEFAULT_BIRTH_WILL_TOPIC = DEFAULT_PREFIX + "/status" DEFAULT_DISCOVERY = True DEFAULT_QOS = 0 DEFAULT_PAYLOAD_AVAILABLE = "online" DEFAULT_PAYLOAD_NOT_AVAILABLE = "offline" DEFAULT_RETAIN = False DEFAULT_BIRTH = { ATTR_TOPIC: DEFAULT_BIRTH_WILL_TOPIC, CONF_PAYLOAD: DEFAULT_PAYLOAD_AVAILABLE, ATTR_QOS: DEFAULT_QOS, ATTR_RETAIN: DEFAULT_RETAIN, } DEFAULT_WILL = { ATTR_TOPIC: DEFAULT_BIRTH_WILL_TOPIC, CONF_PAYLOAD: DEFAULT_PAYLOAD_NOT_AVAILABLE, ATTR_QOS: DEFAULT_QOS, ATTR_RETAIN: DEFAULT_RETAIN, } DOMAIN = "mqtt" MQTT_CONNECTED = "mqtt_connected" MQTT_DISCONNECTED = "mqtt_disconnected" PROTOCOL_311 = "3.1.1"
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/mqtt/const.py
"""Config flow for Picnic integration.""" from __future__ import annotations import logging from python_picnic_api import PicnicAPI from python_picnic_api.session import PicnicAuthError import requests import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import CONF_ACCESS_TOKEN, CONF_PASSWORD, CONF_USERNAME from .const import CONF_COUNTRY_CODE, COUNTRY_CODES, DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_COUNTRY_CODE, default=COUNTRY_CODES[0]): vol.In( COUNTRY_CODES ), } ) class PicnicHub: """Hub class to test user authentication.""" @staticmethod def authenticate(username, password, country_code) -> tuple[str, dict]: """Test if we can authenticate with the Picnic API.""" picnic = PicnicAPI(username, password, country_code) return picnic.session.auth_token, picnic.get_user() async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. """ hub = PicnicHub() try: auth_token, user_data = await hass.async_add_executor_job( hub.authenticate, data[CONF_USERNAME], data[CONF_PASSWORD], data[CONF_COUNTRY_CODE], ) except requests.exceptions.ConnectionError as error: raise CannotConnect from error except PicnicAuthError as error: raise InvalidAuth from error # Return the validation result address = ( f'{user_data["address"]["street"]} {user_data["address"]["house_number"]}' + f'{user_data["address"]["house_number_ext"]}' ) return auth_token, { "title": address, "unique_id": user_data["user_id"], } class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Picnic.""" VERSION = 1 async def async_step_user(self, user_input=None): """Handle the initial step.""" if user_input is None: return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA ) errors = {} try: auth_token, info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Set the unique id and abort if it already exists await self.async_set_unique_id(info["unique_id"]) self._abort_if_unique_id_configured() return self.async_create_entry( title=info["title"], data={ CONF_ACCESS_TOKEN: auth_token, CONF_COUNTRY_CODE: user_input[CONF_COUNTRY_CODE], }, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth."""
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/picnic/config_flow.py
"""Support for Met Éireann weather service.""" import logging from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME, WeatherEntity, ) from homeassistant.const import ( CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, LENGTH_INCHES, LENGTH_METERS, LENGTH_MILES, LENGTH_MILLIMETERS, PRESSURE_HPA, PRESSURE_INHG, TEMP_CELSIUS, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util import dt as dt_util from homeassistant.util.distance import convert as convert_distance from homeassistant.util.pressure import convert as convert_pressure from .const import ATTRIBUTION, CONDITION_MAP, DEFAULT_NAME, DOMAIN, FORECAST_MAP _LOGGER = logging.getLogger(__name__) def format_condition(condition: str): """Map the conditions provided by the weather API to those supported by the frontend.""" if condition is not None: for key, value in CONDITION_MAP.items(): if condition in value: return key return condition async def async_setup_entry(hass, config_entry, async_add_entities): """Add a weather entity from a config_entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] async_add_entities( [ MetEireannWeather( coordinator, config_entry.data, hass.config.units.is_metric, False ), MetEireannWeather( coordinator, config_entry.data, hass.config.units.is_metric, True ), ] ) class MetEireannWeather(CoordinatorEntity, WeatherEntity): """Implementation of a Met Éireann weather condition.""" def __init__(self, coordinator, config, is_metric, hourly): """Initialise the platform with a data instance and site.""" super().__init__(coordinator) self._config = config self._is_metric = is_metric self._hourly = hourly @property def unique_id(self): """Return unique ID.""" name_appendix = "" if self._hourly: name_appendix = "-hourly" return f"{self._config[CONF_LATITUDE]}-{self._config[CONF_LONGITUDE]}{name_appendix}" @property def name(self): """Return the name of the sensor.""" name = self._config.get(CONF_NAME) name_appendix = "" if self._hourly: name_appendix = " Hourly" if name is not None: return f"{name}{name_appendix}" return f"{DEFAULT_NAME}{name_appendix}" @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return not self._hourly @property def condition(self): """Return the current condition.""" return format_condition( self.coordinator.data.current_weather_data.get("condition") ) @property def temperature(self): """Return the temperature.""" return self.coordinator.data.current_weather_data.get("temperature") @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def pressure(self): """Return the pressure.""" pressure_hpa = self.coordinator.data.current_weather_data.get("pressure") if self._is_metric or pressure_hpa is None: return pressure_hpa return round(convert_pressure(pressure_hpa, PRESSURE_HPA, PRESSURE_INHG), 2) @property def humidity(self): """Return the humidity.""" return self.coordinator.data.current_weather_data.get("humidity") @property def wind_speed(self): """Return the wind speed.""" speed_m_s = self.coordinator.data.current_weather_data.get("wind_speed") if self._is_metric or speed_m_s is None: return speed_m_s speed_mi_s = convert_distance(speed_m_s, LENGTH_METERS, LENGTH_MILES) speed_mi_h = speed_mi_s / 3600.0 return int(round(speed_mi_h)) @property def wind_bearing(self): """Return the wind direction.""" return self.coordinator.data.current_weather_data.get("wind_bearing") @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def forecast(self): """Return the forecast array.""" if self._hourly: me_forecast = self.coordinator.data.hourly_forecast else: me_forecast = self.coordinator.data.daily_forecast required_keys = {ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME} ha_forecast = [] for item in me_forecast: if not set(item).issuperset(required_keys): continue ha_item = { k: item[v] for k, v in FORECAST_MAP.items() if item.get(v) is not None } if not self._is_metric and ATTR_FORECAST_PRECIPITATION in ha_item: precip_inches = convert_distance( ha_item[ATTR_FORECAST_PRECIPITATION], LENGTH_MILLIMETERS, LENGTH_INCHES, ) ha_item[ATTR_FORECAST_PRECIPITATION] = round(precip_inches, 2) if ha_item.get(ATTR_FORECAST_CONDITION): ha_item[ATTR_FORECAST_CONDITION] = format_condition( ha_item[ATTR_FORECAST_CONDITION] ) # Convert timestamp to UTC if ha_item.get(ATTR_FORECAST_TIME): ha_item[ATTR_FORECAST_TIME] = dt_util.as_utc( ha_item.get(ATTR_FORECAST_TIME) ).isoformat() ha_forecast.append(ha_item) return ha_forecast @property def device_info(self): """Device info.""" return { "identifiers": {(DOMAIN,)}, "manufacturer": "Met Éireann", "model": "Forecast", "default_name": "Forecast", "entry_type": "service", }
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/met_eireann/weather.py
"""Adapter to wrap the rachiopy api for home assistant.""" from homeassistant.helpers import device_registry from homeassistant.helpers.entity import Entity from .const import DEFAULT_NAME, DOMAIN class RachioDevice(Entity): """Base class for rachio devices.""" def __init__(self, controller): """Initialize a Rachio device.""" super().__init__() self._controller = controller @property def should_poll(self) -> bool: """Declare that this entity pushes its state to HA.""" return False @property def device_info(self): """Return the device_info of the device.""" return { "identifiers": { ( DOMAIN, self._controller.serial_number, ) }, "connections": { ( device_registry.CONNECTION_NETWORK_MAC, self._controller.mac_address, ) }, "name": self._controller.name, "model": self._controller.model, "manufacturer": DEFAULT_NAME, }
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/rachio/entity.py
"""Validation utility functions for ecobee services.""" from datetime import datetime import voluptuous as vol def ecobee_date(date_string): """Validate a date_string as valid for the ecobee API.""" try: datetime.strptime(date_string, "%Y-%m-%d") except ValueError as err: raise vol.Invalid("Date does not match ecobee date format YYYY-MM-DD") from err return date_string def ecobee_time(time_string): """Validate a time_string as valid for the ecobee API.""" try: datetime.strptime(time_string, "%H:%M:%S") except ValueError as err: raise vol.Invalid( "Time does not match ecobee 24-hour time format HH:MM:SS" ) from err return time_string
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/ecobee/util.py
"""Generic Z-Wave Entity Class.""" from __future__ import annotations import logging from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.model.value import Value as ZwaveValue, get_value_id from homeassistant.config_entries import ConfigEntry from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from .const import DOMAIN from .discovery import ZwaveDiscoveryInfo from .helpers import get_device_id, get_unique_id LOGGER = logging.getLogger(__name__) EVENT_VALUE_UPDATED = "value updated" class ZWaveBaseEntity(Entity): """Generic Entity Class for a Z-Wave Device.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo ) -> None: """Initialize a generic Z-Wave device entity.""" self.config_entry = config_entry self.client = client self.info = info # entities requiring additional values, can add extra ids to this list self.watched_value_ids = {self.info.primary_value.value_id} if self.info.additional_value_ids_to_watch: self.watched_value_ids = self.watched_value_ids.union( self.info.additional_value_ids_to_watch ) # Entity class attributes self._attr_name = self.generate_name() self._attr_unique_id = get_unique_id( self.client.driver.controller.home_id, self.info.primary_value.value_id ) self._attr_assumed_state = self.info.assumed_state # device is precreated in main handler self._attr_device_info = { "identifiers": {get_device_id(self.client, self.info.node)}, } @callback def on_value_update(self) -> None: """Call when one of the watched values change. To be overridden by platforms needing this event. """ async def async_poll_value(self, refresh_all_values: bool) -> None: """Poll a value.""" if not refresh_all_values: self.hass.async_create_task( self.info.node.async_poll_value(self.info.primary_value) ) LOGGER.info( ( "Refreshing primary value %s for %s, " "state update may be delayed for devices on battery" ), self.info.primary_value, self.entity_id, ) return for value_id in self.watched_value_ids: self.hass.async_create_task(self.info.node.async_poll_value(value_id)) LOGGER.info( ( "Refreshing values %s for %s, state update may be delayed for " "devices on battery" ), ", ".join(self.watched_value_ids), self.entity_id, ) async def async_added_to_hass(self) -> None: """Call when entity is added.""" # Add value_changed callbacks. self.async_on_remove( self.info.node.on(EVENT_VALUE_UPDATED, self._value_changed) ) self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self.unique_id}_poll_value", self.async_poll_value, ) ) def generate_name( self, include_value_name: bool = False, alternate_value_name: str | None = None, additional_info: list[str] | None = None, name_suffix: str | None = None, ) -> str: """Generate entity name.""" if additional_info is None: additional_info = [] name: str = ( self.info.node.name or self.info.node.device_config.description or f"Node {self.info.node.node_id}" ) if name_suffix: name = f"{name} {name_suffix}" if include_value_name: value_name = ( alternate_value_name or self.info.primary_value.metadata.label or self.info.primary_value.property_key_name or self.info.primary_value.property_name ) name = f"{name}: {value_name}" for item in additional_info: if item: name += f" - {item}" # append endpoint if > 1 if self.info.primary_value.endpoint > 1: name += f" ({self.info.primary_value.endpoint})" return name @property def available(self) -> bool: """Return entity availability.""" return self.client.connected and bool(self.info.node.ready) @callback def _value_changed(self, event_data: dict) -> None: """Call when (one of) our watched values changes. Should not be overridden by subclasses. """ value_id = event_data["value"].value_id if value_id not in self.watched_value_ids: return value = self.info.node.values[value_id] LOGGER.debug( "[%s] Value %s/%s changed to: %s", self.entity_id, value.property_, value.property_key_name, value.value, ) self.on_value_update() self.async_write_ha_state() @callback def get_zwave_value( self, value_property: str | int, command_class: int | None = None, endpoint: int | None = None, value_property_key: int | None = None, add_to_watched_value_ids: bool = True, check_all_endpoints: bool = False, ) -> ZwaveValue | None: """Return specific ZwaveValue on this ZwaveNode.""" # use commandclass and endpoint from primary value if omitted return_value = None if command_class is None: command_class = self.info.primary_value.command_class if endpoint is None: endpoint = self.info.primary_value.endpoint # lookup value by value_id value_id = get_value_id( self.info.node, command_class, value_property, endpoint=endpoint, property_key=value_property_key, ) return_value = self.info.node.values.get(value_id) # If we haven't found a value and check_all_endpoints is True, we should # return the first value we can find on any other endpoint if return_value is None and check_all_endpoints: for endpoint_ in self.info.node.endpoints: if endpoint_.index != self.info.primary_value.endpoint: value_id = get_value_id( self.info.node, command_class, value_property, endpoint=endpoint_.index, property_key=value_property_key, ) return_value = self.info.node.values.get(value_id) if return_value: break # add to watched_ids list so we will be triggered when the value updates if ( return_value and return_value.value_id not in self.watched_value_ids and add_to_watched_value_ids ): self.watched_value_ids.add(return_value.value_id) return return_value @property def should_poll(self) -> bool: """No polling needed.""" return False
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/zwave_js/entity.py
"""Interface implementation for cloud client.""" from __future__ import annotations import asyncio import logging from pathlib import Path from typing import Any import aiohttp from hass_nabucasa.client import CloudClient as Interface from homeassistant.components.alexa import ( errors as alexa_errors, smart_home as alexa_sh, ) from homeassistant.components.google_assistant import const as gc, smart_home as ga from homeassistant.const import HTTP_OK from homeassistant.core import Context, HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_call_later from homeassistant.util.aiohttp import MockRequest from . import alexa_config, google_config, utils from .const import DISPATCHER_REMOTE_UPDATE, DOMAIN from .prefs import CloudPreferences class CloudClient(Interface): """Interface class for Home Assistant Cloud.""" def __init__( self, hass: HomeAssistant, prefs: CloudPreferences, websession: aiohttp.ClientSession, alexa_user_config: dict[str, Any], google_user_config: dict[str, Any], ) -> None: """Initialize client interface to Cloud.""" self._hass = hass self._prefs = prefs self._websession = websession self.google_user_config = google_user_config self.alexa_user_config = alexa_user_config self._alexa_config = None self._google_config = None @property def base_path(self) -> Path: """Return path to base dir.""" return Path(self._hass.config.config_dir) @property def prefs(self) -> CloudPreferences: """Return Cloud preferences.""" return self._prefs @property def loop(self) -> asyncio.BaseEventLoop: """Return client loop.""" return self._hass.loop @property def websession(self) -> aiohttp.ClientSession: """Return client session for aiohttp.""" return self._websession @property def aiohttp_runner(self) -> aiohttp.web.AppRunner: """Return client webinterface aiohttp application.""" return self._hass.http.runner @property def cloudhooks(self) -> dict[str, dict[str, str]]: """Return list of cloudhooks.""" return self._prefs.cloudhooks @property def remote_autostart(self) -> bool: """Return true if we want start a remote connection.""" return self._prefs.remote_enabled async def get_alexa_config(self) -> alexa_config.AlexaConfig: """Return Alexa config.""" if self._alexa_config is None: assert self.cloud is not None cloud_user = await self._prefs.get_cloud_user() self._alexa_config = alexa_config.AlexaConfig( self._hass, self.alexa_user_config, cloud_user, self._prefs, self.cloud ) await self._alexa_config.async_initialize() return self._alexa_config async def get_google_config(self) -> google_config.CloudGoogleConfig: """Return Google config.""" if not self._google_config: assert self.cloud is not None cloud_user = await self._prefs.get_cloud_user() self._google_config = google_config.CloudGoogleConfig( self._hass, self.google_user_config, cloud_user, self._prefs, self.cloud ) await self._google_config.async_initialize() return self._google_config async def logged_in(self) -> None: """When user logs in.""" is_new_user = await self.prefs.async_set_username(self.cloud.username) async def enable_alexa(_): """Enable Alexa.""" aconf = await self.get_alexa_config() try: await aconf.async_enable_proactive_mode() except aiohttp.ClientError as err: # If no internet available yet if self._hass.is_running: logging.getLogger(__package__).warning( "Unable to activate Alexa Report State: %s. Retrying in 30 seconds", err, ) async_call_later(self._hass, 30, enable_alexa) except alexa_errors.NoTokenAvailable: pass async def enable_google(_): """Enable Google.""" gconf = await self.get_google_config() gconf.async_enable_local_sdk() if gconf.should_report_state: gconf.async_enable_report_state() if is_new_user: await gconf.async_sync_entities(gconf.agent_user_id) tasks = [] if self._prefs.alexa_enabled and self._prefs.alexa_report_state: tasks.append(enable_alexa) if self._prefs.google_enabled: tasks.append(enable_google) if tasks: await asyncio.gather(*[task(None) for task in tasks]) async def cleanups(self) -> None: """Cleanup some stuff after logout.""" await self.prefs.async_set_username(None) self._google_config = None @callback def user_message(self, identifier: str, title: str, message: str) -> None: """Create a message for user to UI.""" self._hass.components.persistent_notification.async_create( message, title, identifier ) @callback def dispatcher_message(self, identifier: str, data: Any = None) -> None: """Match cloud notification to dispatcher.""" if identifier.startswith("remote_"): async_dispatcher_send(self._hass, DISPATCHER_REMOTE_UPDATE, data) async def async_alexa_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud alexa message to client.""" cloud_user = await self._prefs.get_cloud_user() aconfig = await self.get_alexa_config() return await alexa_sh.async_handle_message( self._hass, aconfig, payload, context=Context(user_id=cloud_user), enabled=self._prefs.alexa_enabled, ) async def async_google_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud google message to client.""" if not self._prefs.google_enabled: return ga.turned_off_response(payload) gconf = await self.get_google_config() return await ga.async_handle_message( self._hass, gconf, gconf.cloud_user, payload, gc.SOURCE_CLOUD ) async def async_webhook_message(self, payload: dict[Any, Any]) -> dict[Any, Any]: """Process cloud webhook message to client.""" cloudhook_id = payload["cloudhook_id"] found = None for cloudhook in self._prefs.cloudhooks.values(): if cloudhook["cloudhook_id"] == cloudhook_id: found = cloudhook break if found is None: return {"status": HTTP_OK} request = MockRequest( content=payload["body"].encode("utf-8"), headers=payload["headers"], method=payload["method"], query_string=payload["query"], mock_source=DOMAIN, ) response = await self._hass.components.webhook.async_handle_webhook( found["webhook_id"], request ) response_dict = utils.aiohttp_serialize_response(response) body = response_dict.get("body") return { "body": body, "status": response_dict["status"], "headers": {"Content-Type": response.content_type}, } async def async_cloudhooks_update(self, data: dict[str, dict[str, str]]) -> None: """Update local list of cloudhooks.""" await self._prefs.async_update(cloudhooks=data)
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/cloud/client.py
"""Config flow for ezviz.""" import logging from pyezviz.client import EzvizClient, HTTPError, InvalidURL, PyEzvizError from pyezviz.test_cam_rtsp import AuthTestResultFailed, InvalidHost, TestRTSPAuth import voluptuous as vol from homeassistant.config_entries import ConfigFlow, OptionsFlow from homeassistant.const import ( CONF_CUSTOMIZE, CONF_IP_ADDRESS, CONF_PASSWORD, CONF_TIMEOUT, CONF_TYPE, CONF_URL, CONF_USERNAME, ) from homeassistant.core import callback from .const import ( ATTR_SERIAL, ATTR_TYPE_CAMERA, ATTR_TYPE_CLOUD, CONF_FFMPEG_ARGUMENTS, DEFAULT_CAMERA_USERNAME, DEFAULT_FFMPEG_ARGUMENTS, DEFAULT_TIMEOUT, DOMAIN, EU_URL, RUSSIA_URL, ) _LOGGER = logging.getLogger(__name__) def _get_ezviz_client_instance(data): """Initialize a new instance of EzvizClientApi.""" ezviz_client = EzvizClient( data[CONF_USERNAME], data[CONF_PASSWORD], data.get(CONF_URL, EU_URL), data.get(CONF_TIMEOUT, DEFAULT_TIMEOUT), ) ezviz_client.login() return ezviz_client def _test_camera_rtsp_creds(data): """Try DESCRIBE on RTSP camera with credentials.""" test_rtsp = TestRTSPAuth( data[CONF_IP_ADDRESS], data[CONF_USERNAME], data[CONF_PASSWORD] ) test_rtsp.main() class EzvizConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Ezviz.""" VERSION = 1 async def _validate_and_create_auth(self, data): """Try to login to ezviz cloud account and create entry if successful.""" await self.async_set_unique_id(data[CONF_USERNAME]) self._abort_if_unique_id_configured() # Verify cloud credentials by attempting a login request. try: await self.hass.async_add_executor_job(_get_ezviz_client_instance, data) except InvalidURL as err: raise InvalidURL from err except HTTPError as err: raise InvalidHost from err except PyEzvizError as err: raise PyEzvizError from err auth_data = { CONF_USERNAME: data[CONF_USERNAME], CONF_PASSWORD: data[CONF_PASSWORD], CONF_URL: data.get(CONF_URL, EU_URL), CONF_TYPE: ATTR_TYPE_CLOUD, } return self.async_create_entry(title=data[CONF_USERNAME], data=auth_data) async def _validate_and_create_camera_rtsp(self, data): """Try DESCRIBE on RTSP camera with credentials.""" # Get Ezviz cloud credentials from config entry ezviz_client_creds = { CONF_USERNAME: None, CONF_PASSWORD: None, CONF_URL: None, } for item in self._async_current_entries(): if item.data.get(CONF_TYPE) == ATTR_TYPE_CLOUD: ezviz_client_creds = { CONF_USERNAME: item.data.get(CONF_USERNAME), CONF_PASSWORD: item.data.get(CONF_PASSWORD), CONF_URL: item.data.get(CONF_URL), } # Abort flow if user removed cloud account before adding camera. if ezviz_client_creds[CONF_USERNAME] is None: return self.async_abort(reason="ezviz_cloud_account_missing") # We need to wake hibernating cameras. # First create EZVIZ API instance. try: ezviz_client = await self.hass.async_add_executor_job( _get_ezviz_client_instance, ezviz_client_creds ) except InvalidURL as err: raise InvalidURL from err except HTTPError as err: raise InvalidHost from err except PyEzvizError as err: raise PyEzvizError from err # Secondly try to wake hybernating camera. try: await self.hass.async_add_executor_job( ezviz_client.get_detection_sensibility, data[ATTR_SERIAL] ) except HTTPError as err: raise InvalidHost from err # Thirdly attempts an authenticated RTSP DESCRIBE request. try: await self.hass.async_add_executor_job(_test_camera_rtsp_creds, data) except InvalidHost as err: raise InvalidHost from err except AuthTestResultFailed as err: raise AuthTestResultFailed from err return self.async_create_entry( title=data[ATTR_SERIAL], data={ CONF_USERNAME: data[CONF_USERNAME], CONF_PASSWORD: data[CONF_PASSWORD], CONF_TYPE: ATTR_TYPE_CAMERA, }, ) @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return EzvizOptionsFlowHandler(config_entry) async def async_step_user(self, user_input=None): """Handle a flow initiated by the user.""" # Check if ezviz cloud account is present in entry config, # abort if already configured. for item in self._async_current_entries(): if item.data.get(CONF_TYPE) == ATTR_TYPE_CLOUD: return self.async_abort(reason="already_configured_account") errors = {} if user_input is not None: if user_input[CONF_URL] == CONF_CUSTOMIZE: self.context["data"] = { CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], } return await self.async_step_user_custom_url() if CONF_TIMEOUT not in user_input: user_input[CONF_TIMEOUT] = DEFAULT_TIMEOUT try: return await self._validate_and_create_auth(user_input) except InvalidURL: errors["base"] = "invalid_host" except InvalidHost: errors["base"] = "cannot_connect" except PyEzvizError: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") data_schema = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_URL, default=EU_URL): vol.In( [EU_URL, RUSSIA_URL, CONF_CUSTOMIZE] ), } ) return self.async_show_form( step_id="user", data_schema=data_schema, errors=errors ) async def async_step_user_custom_url(self, user_input=None): """Handle a flow initiated by the user for custom region url.""" errors = {} if user_input is not None: user_input[CONF_USERNAME] = self.context["data"][CONF_USERNAME] user_input[CONF_PASSWORD] = self.context["data"][CONF_PASSWORD] if CONF_TIMEOUT not in user_input: user_input[CONF_TIMEOUT] = DEFAULT_TIMEOUT try: return await self._validate_and_create_auth(user_input) except InvalidURL: errors["base"] = "invalid_host" except InvalidHost: errors["base"] = "cannot_connect" except PyEzvizError: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") data_schema_custom_url = vol.Schema( { vol.Required(CONF_URL, default=EU_URL): str, } ) return self.async_show_form( step_id="user_custom_url", data_schema=data_schema_custom_url, errors=errors ) async def async_step_discovery(self, discovery_info): """Handle a flow for discovered camera without rtsp config entry.""" await self.async_set_unique_id(discovery_info[ATTR_SERIAL]) self._abort_if_unique_id_configured() self.context["title_placeholders"] = {"serial": self.unique_id} self.context["data"] = {CONF_IP_ADDRESS: discovery_info[CONF_IP_ADDRESS]} return await self.async_step_confirm() async def async_step_confirm(self, user_input=None): """Confirm and create entry from discovery step.""" errors = {} if user_input is not None: user_input[ATTR_SERIAL] = self.unique_id user_input[CONF_IP_ADDRESS] = self.context["data"][CONF_IP_ADDRESS] try: return await self._validate_and_create_camera_rtsp(user_input) except (InvalidHost, InvalidURL): errors["base"] = "invalid_host" except (PyEzvizError, AuthTestResultFailed): errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") discovered_camera_schema = vol.Schema( { vol.Required(CONF_USERNAME, default=DEFAULT_CAMERA_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ) return self.async_show_form( step_id="confirm", data_schema=discovered_camera_schema, errors=errors, description_placeholders={ "serial": self.unique_id, CONF_IP_ADDRESS: self.context["data"][CONF_IP_ADDRESS], }, ) async def async_step_import(self, import_config): """Handle config import from yaml.""" _LOGGER.debug("import config: %s", import_config) # Check importing camera. if ATTR_SERIAL in import_config: return await self.async_step_import_camera(import_config) # Validate and setup of main ezviz cloud account. try: return await self._validate_and_create_auth(import_config) except InvalidURL: _LOGGER.error("Error importing Ezviz platform config: invalid host") return self.async_abort(reason="invalid_host") except InvalidHost: _LOGGER.error("Error importing Ezviz platform config: cannot connect") return self.async_abort(reason="cannot_connect") except (AuthTestResultFailed, PyEzvizError): _LOGGER.error("Error importing Ezviz platform config: invalid auth") return self.async_abort(reason="invalid_auth") except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error importing ezviz platform config: unexpected exception" ) return self.async_abort(reason="unknown") async def async_step_import_camera(self, data): """Create RTSP auth entry per camera in config.""" await self.async_set_unique_id(data[ATTR_SERIAL]) self._abort_if_unique_id_configured() _LOGGER.debug("Create camera with: %s", data) cam_serial = data.pop(ATTR_SERIAL) data[CONF_TYPE] = ATTR_TYPE_CAMERA return self.async_create_entry(title=cam_serial, data=data) class EzvizOptionsFlowHandler(OptionsFlow): """Handle Ezviz client options.""" def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage Ezviz options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = { vol.Optional( CONF_TIMEOUT, default=self.config_entry.options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT), ): int, vol.Optional( CONF_FFMPEG_ARGUMENTS, default=self.config_entry.options.get( CONF_FFMPEG_ARGUMENTS, DEFAULT_FFMPEG_ARGUMENTS ), ): str, } return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/ezviz/config_flow.py
"""Config flow for Universal Devices ISY994 integration.""" import logging from urllib.parse import urlparse from aiohttp import CookieJar import async_timeout from pyisy import ISYConnectionError, ISYInvalidAuthError, ISYResponseParseError from pyisy.configuration import Configuration from pyisy.connection import Connection import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.components import ssdp from homeassistant.components.dhcp import HOSTNAME, IP_ADDRESS, MAC_ADDRESS from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from homeassistant.helpers import aiohttp_client from .const import ( CONF_IGNORE_STRING, CONF_RESTORE_LIGHT_STATE, CONF_SENSOR_STRING, CONF_TLS_VER, CONF_VAR_SENSOR_STRING, DEFAULT_IGNORE_STRING, DEFAULT_RESTORE_LIGHT_STATE, DEFAULT_SENSOR_STRING, DEFAULT_TLS_VERSION, DEFAULT_VAR_SENSOR_STRING, DOMAIN, ISY_URL_POSTFIX, UDN_UUID_PREFIX, ) _LOGGER = logging.getLogger(__name__) def _data_schema(schema_input): """Generate schema with defaults.""" return vol.Schema( { vol.Required(CONF_HOST, default=schema_input.get(CONF_HOST, "")): str, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Optional(CONF_TLS_VER, default=DEFAULT_TLS_VERSION): vol.In([1.1, 1.2]), }, extra=vol.ALLOW_EXTRA, ) async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ user = data[CONF_USERNAME] password = data[CONF_PASSWORD] host = urlparse(data[CONF_HOST]) tls_version = data.get(CONF_TLS_VER) if host.scheme == "http": https = False port = host.port or 80 session = aiohttp_client.async_create_clientsession( hass, verify_ssl=None, cookie_jar=CookieJar(unsafe=True) ) elif host.scheme == "https": https = True port = host.port or 443 session = aiohttp_client.async_get_clientsession(hass) else: _LOGGER.error("The isy994 host value in configuration is invalid") raise InvalidHost # Connect to ISY controller. isy_conn = Connection( host.hostname, port, user, password, use_https=https, tls_ver=tls_version, webroot=host.path, websession=session, ) try: with async_timeout.timeout(30): isy_conf_xml = await isy_conn.test_connection() except ISYInvalidAuthError as error: raise InvalidAuth from error except ISYConnectionError as error: raise CannotConnect from error try: isy_conf = Configuration(xml=isy_conf_xml) except ISYResponseParseError as error: raise CannotConnect from error if not isy_conf or "name" not in isy_conf or not isy_conf["name"]: raise CannotConnect # Return info that you want to store in the config entry. return {"title": f"{isy_conf['name']} ({host.hostname})", "uuid": isy_conf["uuid"]} class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Universal Devices ISY994.""" VERSION = 1 def __init__(self) -> None: """Initialize the isy994 config flow.""" self.discovered_conf = {} @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return OptionsFlowHandler(config_entry) async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} info = None if user_input is not None: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidHost: errors["base"] = "invalid_host" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: await self.async_set_unique_id(info["uuid"], raise_on_progress=False) self._abort_if_unique_id_configured() return self.async_create_entry(title=info["title"], data=user_input) return self.async_show_form( step_id="user", data_schema=_data_schema(self.discovered_conf), errors=errors, ) async def async_step_import(self, user_input): """Handle import.""" return await self.async_step_user(user_input) async def async_step_dhcp(self, discovery_info): """Handle a discovered isy994 via dhcp.""" friendly_name = discovery_info[HOSTNAME] url = f"http://{discovery_info[IP_ADDRESS]}" mac = discovery_info[MAC_ADDRESS] isy_mac = ( f"{mac[0:2]}:{mac[2:4]}:{mac[4:6]}:{mac[6:8]}:{mac[8:10]}:{mac[10:12]}" ) await self.async_set_unique_id(isy_mac) self._abort_if_unique_id_configured() self.discovered_conf = { CONF_NAME: friendly_name, CONF_HOST: url, } self.context["title_placeholders"] = self.discovered_conf return await self.async_step_user() async def async_step_ssdp(self, discovery_info): """Handle a discovered isy994.""" friendly_name = discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME] url = discovery_info[ssdp.ATTR_SSDP_LOCATION] mac = discovery_info[ssdp.ATTR_UPNP_UDN] if mac.startswith(UDN_UUID_PREFIX): mac = mac[len(UDN_UUID_PREFIX) :] if url.endswith(ISY_URL_POSTFIX): url = url[: -len(ISY_URL_POSTFIX)] await self.async_set_unique_id(mac) self._abort_if_unique_id_configured() self.discovered_conf = { CONF_NAME: friendly_name, CONF_HOST: url, } self.context["title_placeholders"] = self.discovered_conf return await self.async_step_user() class OptionsFlowHandler(config_entries.OptionsFlow): """Handle a option flow for isy994.""" def __init__(self, config_entry: config_entries.ConfigEntry) -> None: """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Handle options flow.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = self.config_entry.options restore_light_state = options.get( CONF_RESTORE_LIGHT_STATE, DEFAULT_RESTORE_LIGHT_STATE ) ignore_string = options.get(CONF_IGNORE_STRING, DEFAULT_IGNORE_STRING) sensor_string = options.get(CONF_SENSOR_STRING, DEFAULT_SENSOR_STRING) var_sensor_string = options.get( CONF_VAR_SENSOR_STRING, DEFAULT_VAR_SENSOR_STRING ) options_schema = vol.Schema( { vol.Optional(CONF_IGNORE_STRING, default=ignore_string): str, vol.Optional(CONF_SENSOR_STRING, default=sensor_string): str, vol.Optional(CONF_VAR_SENSOR_STRING, default=var_sensor_string): str, vol.Required( CONF_RESTORE_LIGHT_STATE, default=restore_light_state ): bool, } ) return self.async_show_form(step_id="init", data_schema=options_schema) class InvalidHost(exceptions.HomeAssistantError): """Error to indicate the host value is invalid.""" class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth."""
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/isy994/config_flow.py
"""Config flow for Coronavirus integration.""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.data_entry_flow import FlowResult from . import get_coordinator from .const import DOMAIN, OPTION_WORLDWIDE class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Coronavirus.""" VERSION = 1 _options = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if self._options is None: coordinator = await get_coordinator(self.hass) if not coordinator.last_update_success or coordinator.data is None: return self.async_abort(reason="cannot_connect") self._options = {OPTION_WORLDWIDE: "Worldwide"} for case in sorted( coordinator.data.values(), key=lambda case: case.country ): self._options[case.country] = case.country if user_input is not None: await self.async_set_unique_id(user_input["country"]) self._abort_if_unique_id_configured() return self.async_create_entry( title=self._options[user_input["country"]], data=user_input ) return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required("country"): vol.In(self._options)}), errors=errors, )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/coronavirus/config_flow.py
"""Support for controlling Global Cache gc100.""" import gc100 import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP import homeassistant.helpers.config_validation as cv CONF_PORTS = "ports" DEFAULT_PORT = 4998 DOMAIN = "gc100" DATA_GC100 = "gc100" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, base_config): """Set up the gc100 component.""" config = base_config[DOMAIN] host = config[CONF_HOST] port = config[CONF_PORT] gc_device = gc100.GC100SocketClient(host, port) def cleanup_gc100(event): """Stuff to do before stopping.""" gc_device.quit() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gc100) hass.data[DATA_GC100] = GC100Device(hass, gc_device) return True class GC100Device: """The GC100 component.""" def __init__(self, hass, gc_device): """Init a gc100 device.""" self.hass = hass self.gc_device = gc_device def read_sensor(self, port_addr, callback): """Read a value from a digital input.""" self.gc_device.read_sensor(port_addr, callback) def write_switch(self, port_addr, state, callback): """Write a value to a relay.""" self.gc_device.write_switch(port_addr, state, callback) def subscribe(self, port_addr, callback): """Add detection for RISING and FALLING events.""" self.gc_device.subscribe_notify(port_addr, callback)
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/gc100/__init__.py
"""Support for Aqualink temperature sensors.""" from __future__ import annotations from homeassistant.components.sensor import DOMAIN, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from . import AqualinkEntity from .const import DOMAIN as AQUALINK_DOMAIN PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up discovered sensors.""" devs = [] for dev in hass.data[AQUALINK_DOMAIN][DOMAIN]: devs.append(HassAqualinkSensor(dev)) async_add_entities(devs, True) class HassAqualinkSensor(AqualinkEntity, SensorEntity): """Representation of a sensor.""" @property def name(self) -> str: """Return the name of the sensor.""" return self.dev.label @property def unit_of_measurement(self) -> str | None: """Return the measurement unit for the sensor.""" if self.dev.name.endswith("_temp"): if self.dev.system.temp_unit == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS return None @property def state(self) -> str | None: """Return the state of the sensor.""" if self.dev.state == "": return None try: state = int(self.dev.state) except ValueError: state = float(self.dev.state) return state @property def device_class(self) -> str | None: """Return the class of the sensor.""" if self.dev.name.endswith("_temp"): return DEVICE_CLASS_TEMPERATURE return None
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/iaqualink/sensor.py
"""Constants for the syncthing integration.""" from datetime import timedelta DOMAIN = "syncthing" DEFAULT_VERIFY_SSL = True DEFAULT_URL = "http://127.0.0.1:8384" RECONNECT_INTERVAL = timedelta(seconds=10) SCAN_INTERVAL = timedelta(seconds=120) FOLDER_SUMMARY_RECEIVED = "syncthing_folder_summary_received" FOLDER_PAUSED_RECEIVED = "syncthing_folder_paused_received" SERVER_UNAVAILABLE = "syncthing_server_unavailable" SERVER_AVAILABLE = "syncthing_server_available" STATE_CHANGED_RECEIVED = "syncthing_state_changed_received" EVENTS = { "FolderSummary": FOLDER_SUMMARY_RECEIVED, "StateChanged": STATE_CHANGED_RECEIVED, "FolderPaused": FOLDER_PAUSED_RECEIVED, } FOLDER_SENSOR_ICONS = { "paused": "mdi:folder-clock", "scanning": "mdi:folder-search", "syncing": "mdi:folder-sync", "idle": "mdi:folder", } FOLDER_SENSOR_ALERT_ICON = "mdi:folder-alert" FOLDER_SENSOR_DEFAULT_ICON = "mdi:folder"
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/syncthing/const.py
"""Support for powering relays in a DoorBird video doorbell.""" import datetime from homeassistant.components.switch import SwitchEntity from homeassistant.core import callback from homeassistant.helpers.event import async_track_point_in_utc_time import homeassistant.util.dt as dt_util from .const import DOMAIN, DOOR_STATION, DOOR_STATION_INFO from .entity import DoorBirdEntity IR_RELAY = "__ir_light__" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the DoorBird switch platform.""" entities = [] config_entry_id = config_entry.entry_id data = hass.data[DOMAIN][config_entry_id] doorstation = data[DOOR_STATION] doorstation_info = data[DOOR_STATION_INFO] relays = doorstation_info["RELAYS"] relays.append(IR_RELAY) for relay in relays: switch = DoorBirdSwitch(doorstation, doorstation_info, relay) entities.append(switch) async_add_entities(entities) class DoorBirdSwitch(DoorBirdEntity, SwitchEntity): """A relay in a DoorBird device.""" def __init__(self, doorstation, doorstation_info, relay): """Initialize a relay in a DoorBird device.""" super().__init__(doorstation, doorstation_info) self._doorstation = doorstation self._relay = relay self._state = False if relay == IR_RELAY: self._time = datetime.timedelta(minutes=5) else: self._time = datetime.timedelta(seconds=5) self._unique_id = f"{self._mac_addr}_{self._relay}" self._reset_sub = None @property def unique_id(self): """Switch unique id.""" return self._unique_id @property def name(self): """Return the name of the switch.""" if self._relay == IR_RELAY: return f"{self._doorstation.name} IR" return f"{self._doorstation.name} Relay {self._relay}" @property def icon(self): """Return the icon to display.""" return "mdi:lightbulb" if self._relay == IR_RELAY else "mdi:dip-switch" @property def should_poll(self): """No need to poll.""" return False @property def is_on(self): """Get the assumed state of the relay.""" return self._state async def async_turn_on(self, **kwargs): """Power the relay.""" if self._reset_sub is not None: self._reset_sub() self._reset_sub = None self._reset_sub = async_track_point_in_utc_time( self.hass, self._async_turn_off, dt_util.utcnow() + self._time ) await self.hass.async_add_executor_job(self._turn_on) self.async_write_ha_state() def _turn_on(self): """Power the relay.""" if self._relay == IR_RELAY: self._state = self._doorstation.device.turn_light_on() else: self._state = self._doorstation.device.energize_relay(self._relay) async def async_turn_off(self, **kwargs): """Turn off the relays is not needed. They are time-based.""" raise NotImplementedError("DoorBird relays cannot be manually turned off.") @callback def _async_turn_off(self, *_): """Wait for the correct amount of assumed time to pass.""" self._state = False self._reset_sub = None self.async_write_ha_state()
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/doorbird/switch.py
"""Common code for GogoGate2 component.""" from __future__ import annotations from collections.abc import Awaitable from datetime import timedelta import logging from typing import Callable, NamedTuple from ismartgate import AbstractGateApi, GogoGate2Api, ISmartGateApi from ismartgate.common import AbstractDoor, get_door_by_id from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_DEVICE, CONF_IP_ADDRESS, CONF_PASSWORD, CONF_USERNAME, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.httpx_client import get_async_client from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import DATA_UPDATE_COORDINATOR, DEVICE_TYPE_ISMARTGATE, DOMAIN, MANUFACTURER _LOGGER = logging.getLogger(__name__) class StateData(NamedTuple): """State data for a cover entity.""" config_unique_id: str unique_id: str | None door: AbstractDoor | None class DeviceDataUpdateCoordinator(DataUpdateCoordinator): """Manages polling for state changes from the device.""" def __init__( self, hass: HomeAssistant, logger: logging.Logger, api: AbstractGateApi, *, name: str, update_interval: timedelta, update_method: Callable[[], Awaitable] | None = None, request_refresh_debouncer: Debouncer | None = None, ) -> None: """Initialize the data update coordinator.""" DataUpdateCoordinator.__init__( self, hass, logger, name=name, update_interval=update_interval, update_method=update_method, request_refresh_debouncer=request_refresh_debouncer, ) self.api = api class GoGoGate2Entity(CoordinatorEntity): """Base class for gogogate2 entities.""" def __init__( self, config_entry: ConfigEntry, data_update_coordinator: DeviceDataUpdateCoordinator, door: AbstractDoor, unique_id: str, ) -> None: """Initialize gogogate2 base entity.""" super().__init__(data_update_coordinator) self._config_entry = config_entry self._door = door self._unique_id = unique_id @property def unique_id(self) -> str | None: """Return a unique ID.""" return self._unique_id def _get_door(self) -> AbstractDoor: door = get_door_by_id(self._door.door_id, self.coordinator.data) self._door = door or self._door return self._door @property def device_info(self): """Device info for the controller.""" data = self.coordinator.data return { "identifiers": {(DOMAIN, self._config_entry.unique_id)}, "name": self._config_entry.title, "manufacturer": MANUFACTURER, "model": data.model, "sw_version": data.firmwareversion, } def get_data_update_coordinator( hass: HomeAssistant, config_entry: ConfigEntry ) -> DeviceDataUpdateCoordinator: """Get an update coordinator.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN].setdefault(config_entry.entry_id, {}) config_entry_data = hass.data[DOMAIN][config_entry.entry_id] if DATA_UPDATE_COORDINATOR not in config_entry_data: api = get_api(hass, config_entry.data) async def async_update_data(): try: return await api.async_info() except Exception as exception: raise UpdateFailed( f"Error communicating with API: {exception}" ) from exception config_entry_data[DATA_UPDATE_COORDINATOR] = DeviceDataUpdateCoordinator( hass, _LOGGER, api, # Name of the data. For logging purposes. name="gogogate2", update_method=async_update_data, # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(seconds=5), ) return config_entry_data[DATA_UPDATE_COORDINATOR] def cover_unique_id(config_entry: ConfigEntry, door: AbstractDoor) -> str: """Generate a cover entity unique id.""" return f"{config_entry.unique_id}_{door.door_id}" def sensor_unique_id( config_entry: ConfigEntry, door: AbstractDoor, sensor_type: str ) -> str: """Generate a cover entity unique id.""" return f"{config_entry.unique_id}_{door.door_id}_{sensor_type}" def get_api(hass: HomeAssistant, config_data: dict) -> AbstractGateApi: """Get an api object for config data.""" gate_class = GogoGate2Api if config_data[CONF_DEVICE] == DEVICE_TYPE_ISMARTGATE: gate_class = ISmartGateApi return gate_class( config_data[CONF_IP_ADDRESS], config_data[CONF_USERNAME], config_data[CONF_PASSWORD], httpx_async_client=get_async_client(hass), )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/gogogate2/common.py
"""Utilities to help with aiohttp.""" from __future__ import annotations import io import json from typing import Any from urllib.parse import parse_qsl from multidict import CIMultiDict, MultiDict from homeassistant.const import HTTP_OK class MockStreamReader: """Small mock to imitate stream reader.""" def __init__(self, content: bytes) -> None: """Initialize mock stream reader.""" self._content = io.BytesIO(content) async def read(self, byte_count: int = -1) -> bytes: """Read bytes.""" if byte_count == -1: return self._content.read() return self._content.read(byte_count) class MockRequest: """Mock an aiohttp request.""" mock_source: str | None = None def __init__( self, content: bytes, mock_source: str, method: str = "GET", status: int = HTTP_OK, headers: dict[str, str] | None = None, query_string: str | None = None, url: str = "", ) -> None: """Initialize a request.""" self.method = method self.url = url self.status = status self.headers: CIMultiDict[str] = CIMultiDict(headers or {}) self.query_string = query_string or "" self._content = content self.mock_source = mock_source @property def query(self) -> MultiDict[str]: """Return a dictionary with the query variables.""" return MultiDict(parse_qsl(self.query_string, keep_blank_values=True)) @property def _text(self) -> str: """Return the body as text.""" return self._content.decode("utf-8") @property def content(self) -> MockStreamReader: """Return the body as text.""" return MockStreamReader(self._content) async def json(self) -> Any: """Return the body as JSON.""" return json.loads(self._text) async def post(self) -> MultiDict[str]: """Return POST parameters.""" return MultiDict(parse_qsl(self._text, keep_blank_values=True)) async def text(self) -> str: """Return the body as text.""" return self._text
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/util/aiohttp.py
"""Binary sensor platform integration for Numato USB GPIO expanders.""" from functools import partial import logging from numato_gpio import NumatoGpioError from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.const import DEVICE_DEFAULT_NAME from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send from . import ( CONF_BINARY_SENSORS, CONF_DEVICES, CONF_ID, CONF_INVERT_LOGIC, CONF_PORTS, DATA_API, DOMAIN, ) _LOGGER = logging.getLogger(__name__) NUMATO_SIGNAL = "numato_signal_{}_{}" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the configured Numato USB GPIO binary sensor ports.""" if discovery_info is None: return def read_gpio(device_id, port, level): """Send signal to entity to have it update state.""" dispatcher_send(hass, NUMATO_SIGNAL.format(device_id, port), level) api = hass.data[DOMAIN][DATA_API] binary_sensors = [] devices = hass.data[DOMAIN][CONF_DEVICES] for device in [d for d in devices if CONF_BINARY_SENSORS in d]: device_id = device[CONF_ID] platform = device[CONF_BINARY_SENSORS] invert_logic = platform[CONF_INVERT_LOGIC] ports = platform[CONF_PORTS] for port, port_name in ports.items(): try: api.setup_input(device_id, port) api.edge_detect(device_id, port, partial(read_gpio, device_id)) except NumatoGpioError as err: _LOGGER.error( "Failed to initialize binary sensor '%s' on Numato device %s port %s: %s", port_name, device_id, port, err, ) continue binary_sensors.append( NumatoGpioBinarySensor( port_name, device_id, port, invert_logic, api, ) ) add_entities(binary_sensors, True) class NumatoGpioBinarySensor(BinarySensorEntity): """Represents a binary sensor (input) port of a Numato GPIO expander.""" def __init__(self, name, device_id, port, invert_logic, api): """Initialize the Numato GPIO based binary sensor object.""" self._name = name or DEVICE_DEFAULT_NAME self._device_id = device_id self._port = port self._invert_logic = invert_logic self._state = None self._api = api async def async_added_to_hass(self): """Connect state update callback.""" self.async_on_remove( async_dispatcher_connect( self.hass, NUMATO_SIGNAL.format(self._device_id, self._port), self._async_update_state, ) ) @callback def _async_update_state(self, level): """Update entity state.""" self._state = level self.async_write_ha_state() @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return the state of the entity.""" return self._state != self._invert_logic def update(self): """Update the GPIO state.""" try: self._state = self._api.read_input(self._device_id, self._port) except NumatoGpioError as err: self._state = None _LOGGER.error( "Failed to update Numato device %s port %s: %s", self._device_id, self._port, err, )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/numato/binary_sensor.py
"""Middleware to handle forwarded data by a reverse proxy.""" from __future__ import annotations from collections.abc import Awaitable, Callable from ipaddress import ip_address import logging from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO from aiohttp.web import Application, HTTPBadRequest, Request, StreamResponse, middleware from homeassistant.core import callback _LOGGER = logging.getLogger(__name__) @callback def async_setup_forwarded( app: Application, use_x_forwarded_for: bool | None, trusted_proxies: list[str] ) -> None: """Create forwarded middleware for the app. Process IP addresses, proto and host information in the forwarded for headers. `X-Forwarded-For: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178` We go through the list from the right side, and skip all entries that are in our trusted proxies list. The first non-trusted IP is used as the client IP. If all items in the X-Forwarded-For are trusted, including the most left item (client), the most left item is used. In the latter case, the client connection originated from an IP that is also listed as a trusted proxy IP or network. `X-Forwarded-Proto: <client>, <proxy1>, <proxy2>` e.g., `X-Forwarded-Proto: https, http, http` OR `X-Forwarded-Proto: https` (one entry, even with multiple proxies) The X-Forwarded-Proto is determined based on the corresponding entry of the X-Forwarded-For header that is used/chosen as the client IP. However, some proxies, for example, Kubernetes NGINX ingress, only retain one element in the X-Forwarded-Proto header. In that case, we'll just use what we have. `X-Forwarded-Host: <host>` e.g., `X-Forwarded-Host: example.com` If the previous headers are processed successfully, and the X-Forwarded-Host is present, it will be used. Additionally: - If no X-Forwarded-For header is found, the processing of all headers is skipped. - Log a warning when untrusted connected peer provides X-Forwarded-For headers. - If multiple instances of X-Forwarded-For, X-Forwarded-Proto or X-Forwarded-Host are found, an HTTP 400 status code is thrown. - If malformed or invalid (IP) data in X-Forwarded-For header is found, an HTTP 400 status code is thrown. - The connected client peer on the socket of the incoming connection, must be trusted for any processing to take place. - If the number of elements in X-Forwarded-Proto does not equal 1 or is equal to the number of elements in X-Forwarded-For, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Host is provided, an HTTP 400 status code is thrown. - If an empty X-Forwarded-Proto is provided, or an empty element in the list, an HTTP 400 status code is thrown. """ @middleware async def forwarded_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Process forwarded data by a reverse proxy.""" overrides: dict[str, str] = {} # Handle X-Forwarded-For forwarded_for_headers: list[str] = request.headers.getall(X_FORWARDED_FOR, []) if not forwarded_for_headers: # No forwarding headers, continue as normal return await handler(request) # Get connected IP if ( request.transport is None or request.transport.get_extra_info("peername") is None ): # Connected IP isn't retrieveable from the request transport, continue return await handler(request) connected_ip = ip_address(request.transport.get_extra_info("peername")[0]) # We have X-Forwarded-For, but config does not agree if not use_x_forwarded_for: _LOGGER.warning( "A request from a reverse proxy was received from %s, but your " "HTTP integration is not set-up for reverse proxies; " "This request will be blocked in Home Assistant 2021.7 unless " "you configure your HTTP integration to allow this header", connected_ip, ) # Block this request in the future, for now we pass. return await handler(request) # Ensure the IP of the connected peer is trusted if not any(connected_ip in trusted_proxy for trusted_proxy in trusted_proxies): _LOGGER.warning( "Received X-Forwarded-For header from untrusted proxy %s, headers not processed; " "This request will be blocked in Home Assistant 2021.7 unless you configure " "your HTTP integration to allow this proxy to reverse your Home Assistant instance", connected_ip, ) # Not trusted, Block this request in the future, continue as normal return await handler(request) # Multiple X-Forwarded-For headers if len(forwarded_for_headers) > 1: _LOGGER.error( "Too many headers for X-Forwarded-For: %s", forwarded_for_headers ) raise HTTPBadRequest # Process X-Forwarded-For from the right side (by reversing the list) forwarded_for_split = list(reversed(forwarded_for_headers[0].split(","))) try: forwarded_for = [ip_address(addr.strip()) for addr in forwarded_for_split] except ValueError as err: _LOGGER.error( "Invalid IP address in X-Forwarded-For: %s", forwarded_for_headers[0] ) raise HTTPBadRequest from err # Find the last trusted index in the X-Forwarded-For list forwarded_for_index = 0 for forwarded_ip in forwarded_for: if any(forwarded_ip in trusted_proxy for trusted_proxy in trusted_proxies): forwarded_for_index += 1 continue overrides["remote"] = str(forwarded_ip) break else: # If all the IP addresses are from trusted networks, take the left-most. forwarded_for_index = -1 overrides["remote"] = str(forwarded_for[-1]) # Handle X-Forwarded-Proto forwarded_proto_headers: list[str] = request.headers.getall( X_FORWARDED_PROTO, [] ) if forwarded_proto_headers: if len(forwarded_proto_headers) > 1: _LOGGER.error( "Too many headers for X-Forward-Proto: %s", forwarded_proto_headers ) raise HTTPBadRequest forwarded_proto_split = list( reversed(forwarded_proto_headers[0].split(",")) ) forwarded_proto = [proto.strip() for proto in forwarded_proto_split] # Catch empty values if "" in forwarded_proto: _LOGGER.error( "Empty item received in X-Forward-Proto header: %s", forwarded_proto_headers[0], ) raise HTTPBadRequest # The X-Forwarded-Proto contains either one element, or the equals number # of elements as X-Forwarded-For if len(forwarded_proto) not in (1, len(forwarded_for)): _LOGGER.error( "Incorrect number of elements in X-Forward-Proto. Expected 1 or %d, got %d: %s", len(forwarded_for), len(forwarded_proto), forwarded_proto_headers[0], ) raise HTTPBadRequest # Ideally this should take the scheme corresponding to the entry # in X-Forwarded-For that was chosen, but some proxies only retain # one element. In that case, use what we have. overrides["scheme"] = forwarded_proto[-1] if len(forwarded_proto) != 1: overrides["scheme"] = forwarded_proto[forwarded_for_index] # Handle X-Forwarded-Host forwarded_host_headers: list[str] = request.headers.getall(X_FORWARDED_HOST, []) if forwarded_host_headers: # Multiple X-Forwarded-Host headers if len(forwarded_host_headers) > 1: _LOGGER.error( "Too many headers for X-Forwarded-Host: %s", forwarded_host_headers ) raise HTTPBadRequest forwarded_host = forwarded_host_headers[0].strip() if not forwarded_host: _LOGGER.error("Empty value received in X-Forward-Host header") raise HTTPBadRequest overrides["host"] = forwarded_host # Done, create a new request based on gathered data. request = request.clone(**overrides) # type: ignore[arg-type] return await handler(request) app.middlewares.append(forwarded_middleware)
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/http/forwarded.py
"""Support for LCN binary sensors.""" import pypck from homeassistant.components.binary_sensor import ( DOMAIN as DOMAIN_BINARY_SENSOR, BinarySensorEntity, ) from homeassistant.const import CONF_ADDRESS, CONF_DOMAIN, CONF_ENTITIES, CONF_SOURCE from . import LcnEntity from .const import BINSENSOR_PORTS, CONF_DOMAIN_DATA, SETPOINTS from .helpers import get_device_connection def create_lcn_binary_sensor_entity(hass, entity_config, config_entry): """Set up an entity for this domain.""" device_connection = get_device_connection( hass, tuple(entity_config[CONF_ADDRESS]), config_entry ) if entity_config[CONF_DOMAIN_DATA][CONF_SOURCE] in SETPOINTS: return LcnRegulatorLockSensor( entity_config, config_entry.entry_id, device_connection ) if entity_config[CONF_DOMAIN_DATA][CONF_SOURCE] in BINSENSOR_PORTS: return LcnBinarySensor(entity_config, config_entry.entry_id, device_connection) # in KEY return LcnLockKeysSensor(entity_config, config_entry.entry_id, device_connection) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up LCN switch entities from a config entry.""" entities = [] for entity_config in config_entry.data[CONF_ENTITIES]: if entity_config[CONF_DOMAIN] == DOMAIN_BINARY_SENSOR: entities.append( create_lcn_binary_sensor_entity(hass, entity_config, config_entry) ) async_add_entities(entities) class LcnRegulatorLockSensor(LcnEntity, BinarySensorEntity): """Representation of a LCN binary sensor for regulator locks.""" def __init__(self, config, entry_id, device_connection): """Initialize the LCN binary sensor.""" super().__init__(config, entry_id, device_connection) self.setpoint_variable = pypck.lcn_defs.Var[ config[CONF_DOMAIN_DATA][CONF_SOURCE] ] self._value = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() if not self.device_connection.is_group: await self.device_connection.activate_status_request_handler( self.setpoint_variable ) async def async_will_remove_from_hass(self): """Run when entity will be removed from hass.""" await super().async_will_remove_from_hass() if not self.device_connection.is_group: await self.device_connection.cancel_status_request_handler( self.setpoint_variable ) @property def is_on(self): """Return true if the binary sensor is on.""" return self._value def input_received(self, input_obj): """Set sensor value when LCN input object (command) is received.""" if ( not isinstance(input_obj, pypck.inputs.ModStatusVar) or input_obj.get_var() != self.setpoint_variable ): return self._value = input_obj.get_value().is_locked_regulator() self.async_write_ha_state() class LcnBinarySensor(LcnEntity, BinarySensorEntity): """Representation of a LCN binary sensor for binary sensor ports.""" def __init__(self, config, entry_id, device_connection): """Initialize the LCN binary sensor.""" super().__init__(config, entry_id, device_connection) self.bin_sensor_port = pypck.lcn_defs.BinSensorPort[ config[CONF_DOMAIN_DATA][CONF_SOURCE] ] self._value = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() if not self.device_connection.is_group: await self.device_connection.activate_status_request_handler( self.bin_sensor_port ) async def async_will_remove_from_hass(self): """Run when entity will be removed from hass.""" await super().async_will_remove_from_hass() if not self.device_connection.is_group: await self.device_connection.cancel_status_request_handler( self.bin_sensor_port ) @property def is_on(self): """Return true if the binary sensor is on.""" return self._value def input_received(self, input_obj): """Set sensor value when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusBinSensors): return self._value = input_obj.get_state(self.bin_sensor_port.value) self.async_write_ha_state() class LcnLockKeysSensor(LcnEntity, BinarySensorEntity): """Representation of a LCN sensor for key locks.""" def __init__(self, config, entry_id, device_connection): """Initialize the LCN sensor.""" super().__init__(config, entry_id, device_connection) self.source = pypck.lcn_defs.Key[config[CONF_DOMAIN_DATA][CONF_SOURCE]] self._value = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() if not self.device_connection.is_group: await self.device_connection.activate_status_request_handler(self.source) async def async_will_remove_from_hass(self): """Run when entity will be removed from hass.""" await super().async_will_remove_from_hass() if not self.device_connection.is_group: await self.device_connection.cancel_status_request_handler(self.source) @property def is_on(self): """Return true if the binary sensor is on.""" return self._value def input_received(self, input_obj): """Set sensor value when LCN input object (command) is received.""" if ( not isinstance(input_obj, pypck.inputs.ModStatusKeyLocks) or self.source not in pypck.lcn_defs.Key ): return table_id = ord(self.source.name[0]) - 65 key_id = int(self.source.name[1]) - 1 self._value = input_obj.get_state(table_id, key_id) self.async_write_ha_state()
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/lcn/binary_sensor.py
"""Hue sensor entities.""" from aiohue.sensors import ( TYPE_ZLL_LIGHTLEVEL, TYPE_ZLL_ROTARY, TYPE_ZLL_SWITCH, TYPE_ZLL_TEMPERATURE, ) from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity from homeassistant.const import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_ILLUMINANCE, DEVICE_CLASS_TEMPERATURE, LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS, ) from .const import DOMAIN as HUE_DOMAIN from .sensor_base import SENSOR_CONFIG_MAP, GenericHueSensor, GenericZLLSensor LIGHT_LEVEL_NAME_FORMAT = "{} light level" REMOTE_NAME_FORMAT = "{} battery level" TEMPERATURE_NAME_FORMAT = "{} temperature" async def async_setup_entry(hass, config_entry, async_add_entities): """Defer sensor setup to the shared sensor module.""" bridge = hass.data[HUE_DOMAIN][config_entry.entry_id] if not bridge.sensor_manager: return await bridge.sensor_manager.async_register_component("sensor", async_add_entities) class GenericHueGaugeSensorEntity(GenericZLLSensor, SensorEntity): """Parent class for all 'gauge' Hue device sensors.""" class HueLightLevel(GenericHueGaugeSensorEntity): """The light level sensor entity for a Hue motion sensor device.""" _attr_device_class = DEVICE_CLASS_ILLUMINANCE _attr_unit_of_measurement = LIGHT_LUX @property def state(self): """Return the state of the device.""" if self.sensor.lightlevel is None: return None # https://developers.meethue.com/develop/hue-api/supported-devices/#clip_zll_lightlevel # Light level in 10000 log10 (lux) +1 measured by sensor. Logarithm # scale used because the human eye adjusts to light levels and small # changes at low lux levels are more noticeable than at high lux # levels. return round(float(10 ** ((self.sensor.lightlevel - 1) / 10000)), 2) @property def extra_state_attributes(self): """Return the device state attributes.""" attributes = super().extra_state_attributes attributes.update( { "lightlevel": self.sensor.lightlevel, "daylight": self.sensor.daylight, "dark": self.sensor.dark, "threshold_dark": self.sensor.tholddark, "threshold_offset": self.sensor.tholdoffset, } ) return attributes class HueTemperature(GenericHueGaugeSensorEntity): """The temperature sensor entity for a Hue motion sensor device.""" _attr_device_class = DEVICE_CLASS_TEMPERATURE _attr_state_class = STATE_CLASS_MEASUREMENT _attr_unit_of_measurement = TEMP_CELSIUS @property def state(self): """Return the state of the device.""" if self.sensor.temperature is None: return None return self.sensor.temperature / 100 class HueBattery(GenericHueSensor, SensorEntity): """Battery class for when a batt-powered device is only represented as an event.""" _attr_device_class = DEVICE_CLASS_BATTERY _attr_state_class = STATE_CLASS_MEASUREMENT _attr_unit_of_measurement = PERCENTAGE @property def unique_id(self): """Return a unique identifier for this device.""" return f"{self.sensor.uniqueid}-battery" @property def state(self): """Return the state of the battery.""" return self.sensor.battery SENSOR_CONFIG_MAP.update( { TYPE_ZLL_LIGHTLEVEL: { "platform": "sensor", "name_format": LIGHT_LEVEL_NAME_FORMAT, "class": HueLightLevel, }, TYPE_ZLL_TEMPERATURE: { "platform": "sensor", "name_format": TEMPERATURE_NAME_FORMAT, "class": HueTemperature, }, TYPE_ZLL_SWITCH: { "platform": "sensor", "name_format": REMOTE_NAME_FORMAT, "class": HueBattery, }, TYPE_ZLL_ROTARY: { "platform": "sensor", "name_format": REMOTE_NAME_FORMAT, "class": HueBattery, }, } )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/hue/sensor.py
"""Support for Nightscout sensors.""" from __future__ import annotations from asyncio import TimeoutError as AsyncIOTimeoutError from datetime import timedelta import logging from aiohttp import ClientError from py_nightscout import Api as NightscoutAPI from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_DATE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import ATTR_DELTA, ATTR_DEVICE, ATTR_DIRECTION, DOMAIN SCAN_INTERVAL = timedelta(minutes=1) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Blood Glucose" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Glucose Sensor.""" api = hass.data[DOMAIN][entry.entry_id] async_add_entities([NightscoutSensor(api, "Blood Sugar", entry.unique_id)], True) class NightscoutSensor(SensorEntity): """Implementation of a Nightscout sensor.""" def __init__(self, api: NightscoutAPI, name, unique_id): """Initialize the Nightscout sensor.""" self.api = api self._unique_id = unique_id self._name = name self._state = None self._attributes = None self._unit_of_measurement = "mg/dL" self._icon = "mdi:cloud-question" self._available = False @property def unique_id(self): """Return the unique ID of the sensor.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement @property def available(self): """Return if the sensor data are available.""" return self._available @property def state(self): """Return the state of the device.""" return self._state @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon async def async_update(self): """Fetch the latest data from Nightscout REST API and update the state.""" try: values = await self.api.get_sgvs() except (ClientError, AsyncIOTimeoutError, OSError) as error: _LOGGER.error("Error fetching data. Failed with %s", error) self._available = False return self._available = True self._attributes = {} self._state = None if values: value = values[0] self._attributes = { ATTR_DEVICE: value.device, ATTR_DATE: value.date, ATTR_DELTA: value.delta, ATTR_DIRECTION: value.direction, } self._state = value.sgv self._icon = self._parse_icon() else: self._available = False _LOGGER.warning("Empty reply found when expecting JSON data") def _parse_icon(self) -> str: """Update the icon based on the direction attribute.""" switcher = { "Flat": "mdi:arrow-right", "SingleDown": "mdi:arrow-down", "FortyFiveDown": "mdi:arrow-bottom-right", "DoubleDown": "mdi:chevron-triple-down", "SingleUp": "mdi:arrow-up", "FortyFiveUp": "mdi:arrow-top-right", "DoubleUp": "mdi:chevron-triple-up", } return switcher.get(self._attributes[ATTR_DIRECTION], "mdi:cloud-question") @property def extra_state_attributes(self): """Return the state attributes.""" return self._attributes
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/nightscout/sensor.py
"""Config flow for Garmin Connect integration.""" import logging from garminconnect_aio import ( Garmin, GarminConnectAuthenticationError, GarminConnectConnectionError, GarminConnectTooManyRequestsError, ) import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_ID, CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) class GarminConnectConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Garmin Connect.""" VERSION = 1 async def _show_setup_form(self, errors=None): """Show the setup form to the user.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str} ), errors=errors or {}, ) async def async_step_user(self, user_input=None): """Handle the initial step.""" if user_input is None: return await self._show_setup_form() websession = async_get_clientsession(self.hass) garmin_client = Garmin( websession, user_input[CONF_USERNAME], user_input[CONF_PASSWORD] ) errors = {} try: username = await garmin_client.login() except GarminConnectConnectionError: errors["base"] = "cannot_connect" return await self._show_setup_form(errors) except GarminConnectAuthenticationError: errors["base"] = "invalid_auth" return await self._show_setup_form(errors) except GarminConnectTooManyRequestsError: errors["base"] = "too_many_requests" return await self._show_setup_form(errors) except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" return await self._show_setup_form(errors) await self.async_set_unique_id(username) self._abort_if_unique_id_configured() return self.async_create_entry( title=username, data={ CONF_ID: username, CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], }, )
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/garmin_connect/config_flow.py
"""Config flow for the Velbus platform.""" import velbus import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME, CONF_PORT from homeassistant.core import HomeAssistant, callback from homeassistant.util import slugify from .const import DOMAIN @callback def velbus_entries(hass: HomeAssistant): """Return connections for Velbus domain.""" return { (entry.data[CONF_PORT]) for entry in hass.config_entries.async_entries(DOMAIN) } class VelbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VERSION = 1 def __init__(self) -> None: """Initialize the velbus config flow.""" self._errors = {} def _create_device(self, name: str, prt: str): """Create an entry async.""" return self.async_create_entry(title=name, data={CONF_PORT: prt}) def _test_connection(self, prt): """Try to connect to the velbus with the port specified.""" try: controller = velbus.Controller(prt) except Exception: # pylint: disable=broad-except self._errors[CONF_PORT] = "cannot_connect" return False controller.stop() return True def _prt_in_configuration_exists(self, prt: str) -> bool: """Return True if port exists in configuration.""" if prt in velbus_entries(self.hass): return True return False async def async_step_user(self, user_input=None): """Step when user initializes a integration.""" self._errors = {} if user_input is not None: name = slugify(user_input[CONF_NAME]) prt = user_input[CONF_PORT] if not self._prt_in_configuration_exists(prt): if self._test_connection(prt): return self._create_device(name, prt) else: self._errors[CONF_PORT] = "already_configured" else: user_input = {} user_input[CONF_NAME] = "" user_input[CONF_PORT] = "" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_NAME, default=user_input[CONF_NAME]): str, vol.Required(CONF_PORT, default=user_input[CONF_PORT]): str, } ), errors=self._errors, ) async def async_step_import(self, user_input=None): """Import a config entry.""" user_input[CONF_NAME] = "Velbus Import" prt = user_input[CONF_PORT] if self._prt_in_configuration_exists(prt): # if the velbus import is already in the config # we should not proceed the import return self.async_abort(reason="already_configured") return await self.async_step_user(user_input)
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/velbus/config_flow.py
"""ATAG water heater component.""" from homeassistant.components.water_heater import ( ATTR_TEMPERATURE, STATE_ECO, STATE_PERFORMANCE, WaterHeaterEntity, ) from homeassistant.const import STATE_OFF, TEMP_CELSIUS from . import DOMAIN, WATER_HEATER, AtagEntity SUPPORT_FLAGS_HEATER = 0 OPERATION_LIST = [STATE_OFF, STATE_ECO, STATE_PERFORMANCE] async def async_setup_entry(hass, config_entry, async_add_entities): """Initialize DHW device from config entry.""" coordinator = hass.data[DOMAIN][config_entry.entry_id] async_add_entities([AtagWaterHeater(coordinator, WATER_HEATER)]) class AtagWaterHeater(AtagEntity, WaterHeaterEntity): """Representation of an ATAG water heater.""" @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS_HEATER @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def current_temperature(self): """Return the current temperature.""" return self.coordinator.data.dhw.temperature @property def current_operation(self): """Return current operation.""" operation = self.coordinator.data.dhw.current_operation return operation if operation in self.operation_list else STATE_OFF @property def operation_list(self): """List of available operation modes.""" return OPERATION_LIST async def async_set_temperature(self, **kwargs): """Set new target temperature.""" if await self.coordinator.data.dhw.set_temp(kwargs.get(ATTR_TEMPERATURE)): self.async_write_ha_state() @property def target_temperature(self): """Return the setpoint if water demand, otherwise return base temp (comfort level).""" return self.coordinator.data.dhw.target_temperature @property def max_temp(self): """Return the maximum temperature.""" return self.coordinator.data.dhw.max_temp @property def min_temp(self): """Return the minimum temperature.""" return self.coordinator.data.dhw.min_temp
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/atag/water_heater.py
"""KIRA interface to receive UDP packets from an IR-IP bridge.""" import logging import os import pykira import voluptuous as vol from voluptuous.error import Error as VoluptuousError import yaml from homeassistant.const import ( CONF_CODE, CONF_DEVICE, CONF_HOST, CONF_NAME, CONF_PORT, CONF_REPEAT, CONF_SENSORS, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN, ) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv DOMAIN = "kira" _LOGGER = logging.getLogger(__name__) DEFAULT_HOST = "0.0.0.0" DEFAULT_PORT = 65432 CONF_REMOTES = "remotes" CONF_SENSOR = "sensor" CONF_REMOTE = "remote" CODES_YAML = f"{DOMAIN}_codes.yaml" CODE_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Required(CONF_CODE): cv.string, vol.Optional(CONF_TYPE): cv.string, vol.Optional(CONF_DEVICE): cv.string, vol.Optional(CONF_REPEAT): cv.positive_int, } ) SENSOR_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DOMAIN): vol.Exclusive(cv.string, "sensors"), vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) REMOTE_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DOMAIN): vol.Exclusive(cv.string, "remotes"), vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_SENSORS): [SENSOR_SCHEMA], vol.Optional(CONF_REMOTES): [REMOTE_SCHEMA], } ) }, extra=vol.ALLOW_EXTRA, ) def load_codes(path): """Load KIRA codes from specified file.""" codes = [] if os.path.exists(path): with open(path) as code_file: data = yaml.safe_load(code_file) or [] for code in data: try: codes.append(CODE_SCHEMA(code)) except VoluptuousError as exception: # keep going _LOGGER.warning("KIRA code invalid data: %s", exception) else: with open(path, "w") as code_file: code_file.write("") return codes def setup(hass, config): """Set up the KIRA component.""" sensors = config.get(DOMAIN, {}).get(CONF_SENSORS, []) remotes = config.get(DOMAIN, {}).get(CONF_REMOTES, []) # If no sensors or remotes were specified, add a sensor if not (sensors or remotes): sensors.append({}) codes = load_codes(hass.config.path(CODES_YAML)) hass.data[DOMAIN] = {CONF_SENSOR: {}, CONF_REMOTE: {}} def load_module(platform, idx, module_conf): """Set up the KIRA module and load platform.""" # note: module_name is not the HA device name. it's just a unique name # to ensure the component and platform can share information module_name = ("%s_%d" % (DOMAIN, idx)) if idx else DOMAIN device_name = module_conf.get(CONF_NAME, DOMAIN) port = module_conf.get(CONF_PORT, DEFAULT_PORT) host = module_conf.get(CONF_HOST, DEFAULT_HOST) if platform == CONF_SENSOR: module = pykira.KiraReceiver(host, port) module.start() else: module = pykira.KiraModule(host, port) hass.data[DOMAIN][platform][module_name] = module for code in codes: code_tuple = (code.get(CONF_NAME), code.get(CONF_DEVICE, STATE_UNKNOWN)) module.registerCode(code_tuple, code.get(CONF_CODE)) discovery.load_platform( hass, platform, DOMAIN, {"name": module_name, "device": device_name}, config ) for idx, module_conf in enumerate(sensors): load_module(CONF_SENSOR, idx, module_conf) for idx, module_conf in enumerate(remotes): load_module(CONF_REMOTE, idx, module_conf) def _stop_kira(_event): """Stop the KIRA receiver.""" for receiver in hass.data[DOMAIN][CONF_SENSOR].values(): receiver.stop() _LOGGER.info("Terminated receivers") hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_kira) return True
"""Tests for the TP-Link component.""" from __future__ import annotations from typing import Any from unittest.mock import MagicMock, patch from pyHS100 import SmartBulb, SmartDevice, SmartDeviceException, SmartPlug import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import tplink from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_SWITCH, ) from homeassistant.const import CONF_HOST from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, mock_coro async def test_creating_entry_tries_discover(hass): """Test setting up does discovery.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value={"host": 1234}, ): result = await hass.config_entries.flow.async_init( tplink.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_configuring_tplink_causes_discovery(hass): """Test that specifying empty config does discovery.""" with patch("homeassistant.components.tplink.common.Discover.discover") as discover: discover.return_value = {"host": 1234} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 @pytest.mark.parametrize( "name,cls,platform", [ ("pyHS100.SmartPlug", SmartPlug, "switch"), ("pyHS100.SmartBulb", SmartBulb, "light"), ], ) @pytest.mark.parametrize("count", [1, 2, 3]) async def test_configuring_device_types(hass, name, cls, platform, count): """Test that light or switch platform list is filled correctly.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=True, ): discovery_data = { f"123.123.123.{c}": cls("123.123.123.123") for c in range(count) } discover.return_value = discovery_data await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][platform]) == count class UnknownSmartDevice(SmartDevice): """Dummy class for testing.""" @property def has_emeter(self) -> bool: """Do nothing.""" def turn_off(self) -> None: """Do nothing.""" def turn_on(self) -> None: """Do nothing.""" @property def is_on(self) -> bool: """Do nothing.""" @property def state_information(self) -> dict[str, Any]: """Do nothing.""" async def test_configuring_devices_from_multiple_sources(hass): """Test static and discover devices are not duplicated.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup" ): discover_device_fail = SmartPlug("123.123.123.123") discover_device_fail.get_sysinfo = MagicMock(side_effect=SmartDeviceException()) discover.return_value = { "123.123.123.1": SmartBulb("123.123.123.1"), "123.123.123.2": SmartPlug("123.123.123.2"), "123.123.123.3": SmartBulb("123.123.123.3"), "123.123.123.4": SmartPlug("123.123.123.4"), "123.123.123.123": discover_device_fail, "123.123.123.124": UnknownSmartDevice("123.123.123.124"), } await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_LIGHT: [{CONF_HOST: "123.123.123.1"}], CONF_SWITCH: [{CONF_HOST: "123.123.123.2"}], CONF_DIMMER: [{CONF_HOST: "123.123.123.22"}], } }, ) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3 assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2 async def test_is_dimmable(hass): """Test that is_dimmable switches are correctly added as lights.""" with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as setup, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", True ): dimmable_switch = SmartPlug("123.123.123.123") discover.return_value = {"host": dimmable_switch} await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}}) await hass.async_block_till_done() assert len(discover.mock_calls) == 1 assert len(setup.mock_calls) == 1 assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1 assert not hass.data[tplink.DOMAIN][CONF_SWITCH] async def test_configuring_discovery_disabled(hass): """Test that discover does not get called when disabled.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup, patch( "homeassistant.components.tplink.common.Discover.discover", return_value=[] ) as discover: await async_setup_component( hass, tplink.DOMAIN, {tplink.DOMAIN: {tplink.CONF_DISCOVERY: False}} ) await hass.async_block_till_done() assert discover.call_count == 0 assert mock_setup.call_count == 1 async def test_platforms_are_initialized(hass): """Test that platforms are initialized per configuration array.""" config = { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], CONF_SWITCH: [{CONF_HOST: "321.321.321.321"}], } } with patch( "homeassistant.components.tplink.common.Discover.discover" ) as discover, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( "homeassistant.components.tplink.light.async_setup_entry", return_value=mock_coro(True), ) as light_setup, patch( "homeassistant.components.tplink.switch.async_setup_entry", return_value=mock_coro(True), ) as switch_setup, patch( "homeassistant.components.tplink.common.SmartPlug.is_dimmable", False ): # patching is_dimmable is necessray to avoid misdetection as light. await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert discover.call_count == 0 assert light_setup.call_count == 1 assert switch_setup.call_count == 1 async def test_no_config_creates_no_entry(hass): """Test for when there is no tplink in config.""" with patch( "homeassistant.components.tplink.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: await async_setup_component(hass, tplink.DOMAIN, {}) await hass.async_block_till_done() assert mock_setup.call_count == 0 @pytest.mark.parametrize("platform", ["switch", "light"]) async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as light_setup: config = { tplink.DOMAIN: { platform: [{CONF_HOST: "123.123.123.123"}], CONF_DISCOVERY: False, } } assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(light_setup.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]
kennedyshead/home-assistant
tests/components/tplink/test_init.py
homeassistant/components/kira/__init__.py
from __future__ import absolute_import from .squash import squash
import pytest import numpy as np import sys if sys.version_info > (3, 0): from io import StringIO else: from StringIO import StringIO from keras_contrib import callbacks from keras.models import Sequential, Model from keras.layers import Input, Dense, Conv2D, Flatten, Activation from keras import backend as K n_out = 11 # with 1 neuron dead, 1/11 is just below the threshold of 10% with verbose = False def check_print(do_train, expected_warnings, nr_dead=None, perc_dead=None): """ Receive stdout to check if correct warning message is delivered :param nr_dead: int :param perc_dead: float, 10% should be written as 0.1 """ saved_stdout = sys.stdout out = StringIO() out.flush() sys.stdout = out # overwrite current stdout do_train() # get prints, can be something like: "Layer # dense (#0) has 2 dead neurons (20.00%)!" stdoutput = out.getvalue().strip() str_to_count = "dead neurons" count = stdoutput.count(str_to_count) sys.stdout = saved_stdout # restore stdout out.close() assert expected_warnings == count if expected_warnings and (nr_dead is not None): str_to_check = 'has {} dead'.format(nr_dead) assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check, stdoutput) if expected_warnings and (perc_dead is not None): str_to_check = 'neurons ({:.2%})!'.format(perc_dead) assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check, stdoutput) def test_DeadDeadReluDetector(): n_samples = 9 input_shape = (n_samples, 3, 4) # 4 input features shape_out = (n_samples, 3, n_out) # 11 output features shape_weights = (4, n_out) # ignore batch size input_shape_dense = tuple(input_shape[1:]) def do_test(weights, expected_warnings, verbose, nr_dead=None, perc_dead=None): def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense, use_bias=False, weights=[weights], name='dense')) model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) # weights that correspond to all neurons dead weights_all_dead = np.zeros(shape_weights) weights_1_dead[:, 0] = 0 weights_2_dead[:, 0:2] = 0 do_test(weights_1_dead, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_1_dead, verbose=False, expected_warnings=0) do_test(weights_2_dead, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_all_dead, verbose=True, expected_warnings=1, # nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_bias(): n_samples = 9 input_shape = (n_samples, 4) # 4 input features shape_weights = (4, n_out) shape_bias = (n_out, ) shape_out = (n_samples, n_out) # 11 output features # ignore batch size input_shape_dense = tuple(input_shape[1:]) def do_test(weights, bias, expected_warnings, verbose, nr_dead=None, perc_dead=None): def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense, use_bias=True, weights=[weights, bias], name='dense')) model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) # weights that correspond to all neurons dead weights_all_dead = np.zeros(shape_weights) weights_1_dead[:, 0] = 0 weights_2_dead[:, 0:2] = 0 bias = np.zeros(shape_bias) do_test(weights_1_dead, bias, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_1_dead, bias, verbose=False, expected_warnings=0) do_test(weights_2_dead, bias, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_all_dead, bias, verbose=True, # expected_warnings=1, nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_conv(): n_samples = 9 # (5, 5) kernel, 4 input featuremaps and 11 output featuremaps if K.image_data_format() == 'channels_last': input_shape = (n_samples, 5, 5, 4) else: input_shape = (n_samples, 4, 5, 5) # ignore batch size input_shape_conv = tuple(input_shape[1:]) shape_weights = (5, 5, 4, n_out) shape_out = (n_samples, n_out) def do_test(weights_bias, expected_warnings, verbose, nr_dead=None, perc_dead=None): """ :param perc_dead: as float, 10% should be written as 0.1 """ def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Conv2D(n_out, (5, 5), activation='relu', input_shape=input_shape_conv, use_bias=True, weights=weights_bias, name='conv')) model.add(Flatten()) # to handle Theano's categorical crossentropy model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) weights_1_dead[..., 0] = 0 # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) weights_2_dead[..., 0:2] = 0 # weights that correspond to NN with all neurons dead weights_all_dead = np.zeros(shape_weights) bias = np.zeros((11, )) weights_bias_1_dead = [weights_1_dead, bias] weights_bias_2_dead = [weights_2_dead, bias] weights_bias_all_dead = [weights_all_dead, bias] do_test(weights_bias_1_dead, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_bias_1_dead, verbose=False, expected_warnings=0) do_test(weights_bias_2_dead, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_bias_all_dead, verbose=True, expected_warnings=1, # nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_activation(): """ Tests that using "Activation" layer does not throw error """ input_data = Input(shape=(1,)) output_data = Activation('relu')(input_data) model = Model(input_data, output_data) model.compile(optimizer='adadelta', loss='binary_crossentropy') model.fit( np.array([[1]]), np.array([[1]]), epochs=1, validation_data=(np.array([[1]]), np.array([[1]])), callbacks=[callbacks.DeadReluDetector(np.array([[1]]))] ) if __name__ == '__main__': pytest.main([__file__])
keras-team/keras-contrib
tests/keras_contrib/callbacks/dead_relu_detector_test.py
keras_contrib/activations/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from keras import backend as K from keras import activations from keras import regularizers from keras import initializers from keras import constraints from keras.layers import Layer from keras_contrib.utils.test_utils import to_tuple class Capsule(Layer): """Capsule Layer implementation in Keras This implementation is based on Dynamic Routing of Capsules, Geoffrey Hinton et. al. The Capsule Layer is a Neural Network Layer which helps modeling relationships in image and sequential data better than just CNNs or RNNs. It achieves this by understanding the spatial relationships between objects (in images) or words (in text) by encoding additional information about the image or text, such as angle of rotation, thickness and brightness, relative proportions etc. This layer can be used instead of pooling layers to lower dimensions and still capture important information about the relationships and structures within the data. A normal pooling layer would lose a lot of this information. This layer can be used on the output of any layer which has a 3-D output (including batch_size). For example, in image classification, it can be used on the output of a Conv2D layer for Computer Vision applications. Also, it can be used on the output of a GRU or LSTM Layer (Bidirectional or Unidirectional) for NLP applications. The default activation function is 'linear'. But, this layer is generally used with the 'squash' activation function (recommended). To use the squash activation function, do : from keras_contrib.activations import squash capsule = Capsule(num_capsule=10, dim_capsule=10, routings=3, share_weights=True, activation=squash) # Example usage : 1). COMPUTER VISION input_image = Input(shape=(None, None, 3)) conv_2d = Conv2D(64, (3, 3), activation='relu')(input_image) capsule = Capsule(num_capsule=10, dim_capsule=16, routings=3, activation='relu', share_weights=True)(conv_2d) 2). NLP maxlen = 72 max_features = 120000 input_text = Input(shape=(maxlen,)) embedding = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(input_text) bi_gru = Bidirectional(GRU(64, return_seqeunces=True))(embedding) capsule = Capsule(num_capsule=5, dim_capsule=5, routings=4, activation='sigmoid', share_weights=True)(bi_gru) # Arguments num_capsule : Number of Capsules (int) dim_capsules : Dimensions of the vector output of each Capsule (int) routings : Number of dynamic routings in the Capsule Layer (int) share_weights : Whether to share weights between Capsules or not (boolean) activation : Activation function for the Capsules regularizer : Regularizer for the weights of the Capsules initializer : Initializer for the weights of the Caspules constraint : Constraint for the weights of the Capsules # Input shape 3D tensor with shape: (batch_size, input_num_capsule, input_dim_capsule) [any 3-D Tensor with the first dimension as batch_size] # Output shape 3D tensor with shape: (batch_size, num_capsule, dim_capsule) # References - [Dynamic-Routing-Between-Capsules] (https://arxiv.org/pdf/1710.09829.pdf) - [Keras-Examples-CIFAR10-CNN-Capsule]""" def __init__(self, num_capsule, dim_capsule, routings=3, share_weights=True, initializer='glorot_uniform', activation=None, regularizer=None, constraint=None, **kwargs): super(Capsule, self).__init__(**kwargs) self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.share_weights = share_weights self.activation = activations.get(activation) self.regularizer = regularizers.get(regularizer) self.initializer = initializers.get(initializer) self.constraint = constraints.get(constraint) def build(self, input_shape): input_shape = to_tuple(input_shape) input_dim_capsule = input_shape[-1] if self.share_weights: self.W = self.add_weight(name='capsule_kernel', shape=(1, input_dim_capsule, self.num_capsule * self.dim_capsule), initializer=self.initializer, regularizer=self.regularizer, constraint=self.constraint, trainable=True) else: input_num_capsule = input_shape[-2] self.W = self.add_weight(name='capsule_kernel', shape=(input_num_capsule, input_dim_capsule, self.num_capsule * self.dim_capsule), initializer=self.initializer, regularizer=self.regularizer, constraint=self.constraint, trainable=True) self.build = True def call(self, inputs): if self.share_weights: u_hat_vectors = K.conv1d(inputs, self.W) else: u_hat_vectors = K.local_conv1d(inputs, self.W, [1], [1]) # u_hat_vectors : The spatially transformed input vectors (with local_conv_1d) batch_size = K.shape(inputs)[0] input_num_capsule = K.shape(inputs)[1] u_hat_vectors = K.reshape(u_hat_vectors, (batch_size, input_num_capsule, self.num_capsule, self.dim_capsule)) u_hat_vectors = K.permute_dimensions(u_hat_vectors, (0, 2, 1, 3)) routing_weights = K.zeros_like(u_hat_vectors[:, :, :, 0]) for i in range(self.routings): capsule_weights = K.softmax(routing_weights, 1) outputs = K.batch_dot(capsule_weights, u_hat_vectors, [2, 2]) if K.ndim(outputs) == 4: outputs = K.sum(outputs, axis=1) if i < self.routings - 1: outputs = K.l2_normalize(outputs, -1) routing_weights = K.batch_dot(outputs, u_hat_vectors, [2, 3]) if K.ndim(routing_weights) == 4: routing_weights = K.sum(routing_weights, axis=1) return self.activation(outputs) def compute_output_shape(self, input_shape): return (None, self.num_capsule, self.dim_capsule) def get_config(self): config = {'num_capsule': self.num_capsule, 'dim_capsule': self.dim_capsule, 'routings': self.routings, 'share_weights': self.share_weights, 'activation': activations.serialize(self.activation), 'regularizer': regularizers.serialize(self.regularizer), 'initializer': initializers.serialize(self.initializer), 'constraint': constraints.serialize(self.constraint)} base_config = super(Capsule, self).get_config() return dict(list(base_config.items()) + list(config.items()))
import pytest import numpy as np import sys if sys.version_info > (3, 0): from io import StringIO else: from StringIO import StringIO from keras_contrib import callbacks from keras.models import Sequential, Model from keras.layers import Input, Dense, Conv2D, Flatten, Activation from keras import backend as K n_out = 11 # with 1 neuron dead, 1/11 is just below the threshold of 10% with verbose = False def check_print(do_train, expected_warnings, nr_dead=None, perc_dead=None): """ Receive stdout to check if correct warning message is delivered :param nr_dead: int :param perc_dead: float, 10% should be written as 0.1 """ saved_stdout = sys.stdout out = StringIO() out.flush() sys.stdout = out # overwrite current stdout do_train() # get prints, can be something like: "Layer # dense (#0) has 2 dead neurons (20.00%)!" stdoutput = out.getvalue().strip() str_to_count = "dead neurons" count = stdoutput.count(str_to_count) sys.stdout = saved_stdout # restore stdout out.close() assert expected_warnings == count if expected_warnings and (nr_dead is not None): str_to_check = 'has {} dead'.format(nr_dead) assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check, stdoutput) if expected_warnings and (perc_dead is not None): str_to_check = 'neurons ({:.2%})!'.format(perc_dead) assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check, stdoutput) def test_DeadDeadReluDetector(): n_samples = 9 input_shape = (n_samples, 3, 4) # 4 input features shape_out = (n_samples, 3, n_out) # 11 output features shape_weights = (4, n_out) # ignore batch size input_shape_dense = tuple(input_shape[1:]) def do_test(weights, expected_warnings, verbose, nr_dead=None, perc_dead=None): def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense, use_bias=False, weights=[weights], name='dense')) model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) # weights that correspond to all neurons dead weights_all_dead = np.zeros(shape_weights) weights_1_dead[:, 0] = 0 weights_2_dead[:, 0:2] = 0 do_test(weights_1_dead, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_1_dead, verbose=False, expected_warnings=0) do_test(weights_2_dead, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_all_dead, verbose=True, expected_warnings=1, # nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_bias(): n_samples = 9 input_shape = (n_samples, 4) # 4 input features shape_weights = (4, n_out) shape_bias = (n_out, ) shape_out = (n_samples, n_out) # 11 output features # ignore batch size input_shape_dense = tuple(input_shape[1:]) def do_test(weights, bias, expected_warnings, verbose, nr_dead=None, perc_dead=None): def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense, use_bias=True, weights=[weights, bias], name='dense')) model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) # weights that correspond to all neurons dead weights_all_dead = np.zeros(shape_weights) weights_1_dead[:, 0] = 0 weights_2_dead[:, 0:2] = 0 bias = np.zeros(shape_bias) do_test(weights_1_dead, bias, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_1_dead, bias, verbose=False, expected_warnings=0) do_test(weights_2_dead, bias, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_all_dead, bias, verbose=True, # expected_warnings=1, nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_conv(): n_samples = 9 # (5, 5) kernel, 4 input featuremaps and 11 output featuremaps if K.image_data_format() == 'channels_last': input_shape = (n_samples, 5, 5, 4) else: input_shape = (n_samples, 4, 5, 5) # ignore batch size input_shape_conv = tuple(input_shape[1:]) shape_weights = (5, 5, 4, n_out) shape_out = (n_samples, n_out) def do_test(weights_bias, expected_warnings, verbose, nr_dead=None, perc_dead=None): """ :param perc_dead: as float, 10% should be written as 0.1 """ def do_train(): dataset = np.ones(input_shape) # data to be fed as training model = Sequential() model.add(Conv2D(n_out, (5, 5), activation='relu', input_shape=input_shape_conv, use_bias=True, weights=weights_bias, name='conv')) model.add(Flatten()) # to handle Theano's categorical crossentropy model.compile(optimizer='sgd', loss='categorical_crossentropy') model.fit( dataset, np.ones(shape_out), batch_size=1, epochs=1, callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)], verbose=False ) check_print(do_train, expected_warnings, nr_dead, perc_dead) # weights that correspond to NN with 1/11 neurons dead weights_1_dead = np.ones(shape_weights) weights_1_dead[..., 0] = 0 # weights that correspond to NN with 2/11 neurons dead weights_2_dead = np.ones(shape_weights) weights_2_dead[..., 0:2] = 0 # weights that correspond to NN with all neurons dead weights_all_dead = np.zeros(shape_weights) bias = np.zeros((11, )) weights_bias_1_dead = [weights_1_dead, bias] weights_bias_2_dead = [weights_2_dead, bias] weights_bias_all_dead = [weights_all_dead, bias] do_test(weights_bias_1_dead, verbose=True, expected_warnings=1, nr_dead=1, perc_dead=1. / n_out) do_test(weights_bias_1_dead, verbose=False, expected_warnings=0) do_test(weights_bias_2_dead, verbose=True, expected_warnings=1, nr_dead=2, perc_dead=2. / n_out) # do_test(weights_bias_all_dead, verbose=True, expected_warnings=1, # nr_dead=n_out, perc_dead=1.) def test_DeadDeadReluDetector_activation(): """ Tests that using "Activation" layer does not throw error """ input_data = Input(shape=(1,)) output_data = Activation('relu')(input_data) model = Model(input_data, output_data) model.compile(optimizer='adadelta', loss='binary_crossentropy') model.fit( np.array([[1]]), np.array([[1]]), epochs=1, validation_data=(np.array([[1]]), np.array([[1]])), callbacks=[callbacks.DeadReluDetector(np.array([[1]]))] ) if __name__ == '__main__': pytest.main([__file__])
keras-team/keras-contrib
tests/keras_contrib/callbacks/dead_relu_detector_test.py
keras_contrib/layers/capsule.py
"""All methods needed to bootstrap a Home Assistant instance.""" import asyncio import logging.handlers from timeit import default_timer as timer from types import ModuleType from typing import Awaitable, Callable, Optional, Set from homeassistant import config as conf_util, core, loader, requirements from homeassistant.config import async_notify_setup_error from homeassistant.const import EVENT_COMPONENT_LOADED, PLATFORM_FORMAT from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_COMPONENT = "component" DATA_SETUP_DONE = "setup_done" DATA_SETUP_STARTED = "setup_started" DATA_SETUP = "setup_tasks" DATA_DEPS_REQS = "deps_reqs_processed" SLOW_SETUP_WARNING = 10 # Since its possible for databases to be # upwards of 36GiB (or larger) in the wild # we wait up to 3 hours for startup SLOW_SETUP_MAX_WAIT = 10800 @core.callback def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: Set[str]) -> None: """Set domains that are going to be loaded from the config. This will allow us to properly handle after_dependencies. """ hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains} def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool: """Set up a component and all its dependencies.""" return asyncio.run_coroutine_threadsafe( async_setup_component(hass, domain, config), hass.loop ).result() async def async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.setdefault(DATA_SETUP, {}) if domain in setup_tasks: return await setup_tasks[domain] # type: ignore task = setup_tasks[domain] = hass.async_create_task( _async_setup_component(hass, domain, config) ) try: return await task # type: ignore finally: if domain in hass.data.get(DATA_SETUP_DONE, {}): hass.data[DATA_SETUP_DONE].pop(domain).set() async def _async_process_dependencies( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> bool: """Ensure all dependencies are set up.""" tasks = { dep: hass.loop.create_task(async_setup_component(hass, dep, config)) for dep in integration.dependencies } to_be_loaded = hass.data.get(DATA_SETUP_DONE, {}) for dep in integration.after_dependencies: if dep in to_be_loaded and dep not in hass.config.components: tasks[dep] = hass.loop.create_task(to_be_loaded[dep].wait()) if not tasks: return True _LOGGER.debug("Dependency %s will wait for %s", integration.domain, list(tasks)) results = await asyncio.gather(*tasks.values()) failed = [ domain for idx, domain in enumerate(integration.dependencies) if not results[idx] ] if failed: _LOGGER.error( "Unable to set up dependencies of %s. Setup failed for dependencies: %s", integration.domain, ", ".join(failed), ) return False return True async def _async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component for Home Assistant. This method is a coroutine. """ def log_error(msg: str, link: Optional[str] = None) -> None: """Log helper.""" _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) try: integration = await loader.async_get_integration(hass, domain) except loader.IntegrationNotFound: log_error("Integration not found.") return False # Validate all dependencies exist and there are no circular dependencies if not await integration.resolve_dependencies(): return False # Process requirements as soon as possible, so we can import the component # without requiring imports to be in functions. try: await async_process_deps_reqs(hass, config, integration) except HomeAssistantError as err: log_error(str(err), integration.documentation) return False # Some integrations fail on import because they call functions incorrectly. # So we do it before validating config to catch these errors. try: component = integration.get_component() except ImportError as err: log_error(f"Unable to import component: {err}", integration.documentation) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Setup failed for %s: unknown error", domain) return False processed_config = await conf_util.async_process_component_config( hass, config, integration ) if processed_config is None: log_error("Invalid config.", integration.documentation) return False start = timer() _LOGGER.info("Setting up %s", domain) hass.data.setdefault(DATA_SETUP_STARTED, {})[domain] = dt_util.utcnow() if hasattr(component, "PLATFORM_SCHEMA"): # Entity components have their own warning warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING, ) try: if hasattr(component, "async_setup"): task = component.async_setup( # type: ignore hass, processed_config ) elif hasattr(component, "setup"): # This should not be replaced with hass.async_add_executor_job because # we don't want to track this task in case it blocks startup. task = hass.loop.run_in_executor( None, component.setup, hass, processed_config # type: ignore ) else: log_error("No setup function defined.") hass.data[DATA_SETUP_STARTED].pop(domain) return False result = await asyncio.wait_for(task, SLOW_SETUP_MAX_WAIT) except asyncio.TimeoutError: _LOGGER.error( "Setup of %s is taking longer than %s seconds." " Startup will proceed without waiting any longer", domain, SLOW_SETUP_MAX_WAIT, ) hass.data[DATA_SETUP_STARTED].pop(domain) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, integration.documentation) hass.data[DATA_SETUP_STARTED].pop(domain) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start) if result is False: log_error("Integration failed to initialize.") hass.data[DATA_SETUP_STARTED].pop(domain) return False if result is not True: log_error( f"Integration {domain!r} did not return boolean if setup was " "successful. Disabling component." ) hass.data[DATA_SETUP_STARTED].pop(domain) return False # Flush out async_setup calling create_task. Fragile but covered by test. await asyncio.sleep(0) await hass.config_entries.flow.async_wait_init_flow_finish(domain) await asyncio.gather( *[ entry.async_setup(hass, integration=integration) for entry in hass.config_entries.async_entries(domain) ] ) hass.config.components.add(domain) hass.data[DATA_SETUP_STARTED].pop(domain) # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain}) return True async def async_prepare_setup_platform( hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str ) -> Optional[ModuleType]: """Load a platform and makes sure dependencies are setup. This method is a coroutine. """ platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name) def log_error(msg: str) -> None: """Log helper.""" _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) try: integration = await loader.async_get_integration(hass, platform_name) except loader.IntegrationNotFound: log_error("Integration not found") return None # Process deps and reqs as soon as possible, so that requirements are # available when we import the platform. try: await async_process_deps_reqs(hass, hass_config, integration) except HomeAssistantError as err: log_error(str(err)) return None try: platform = integration.get_platform(domain) except ImportError as exc: log_error(f"Platform not found ({exc}).") return None # Already loaded if platform_path in hass.config.components: return platform # Platforms cannot exist on their own, they are part of their integration. # If the integration is not set up yet, and can be set up, set it up. if integration.domain not in hass.config.components: try: component = integration.get_component() except ImportError as exc: log_error(f"Unable to import the component ({exc}).") return None if hasattr(component, "setup") or hasattr(component, "async_setup"): if not await async_setup_component(hass, integration.domain, hass_config): log_error("Unable to set up component.") return None return platform async def async_process_deps_reqs( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> None: """Process all dependencies and requirements for a module. Module is a Python module of either a component or platform. """ processed = hass.data.get(DATA_DEPS_REQS) if processed is None: processed = hass.data[DATA_DEPS_REQS] = set() elif integration.domain in processed: return if not await _async_process_dependencies(hass, config, integration): raise HomeAssistantError("Could not set up all dependencies.") if not hass.config.skip_pip and integration.requirements: await requirements.async_get_integration_with_requirements( hass, integration.domain ) processed.add(integration.domain) @core.callback def async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: """Call a method when a component is setup.""" async def when_setup() -> None: """Call the callback.""" try: await when_setup_cb(hass, component) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error handling when_setup callback for %s", component) # Running it in a new task so that it always runs after if component in hass.config.components: hass.async_create_task(when_setup()) return unsub = None async def loaded_event(event: core.Event) -> None: """Call the callback.""" if event.data[ATTR_COMPONENT] != component: return unsub() # type: ignore await when_setup() unsub = hass.bus.async_listen(EVENT_COMPONENT_LOADED, loaded_event)
"""The tests the cover command line platform.""" import os import tempfile from unittest import mock import pytest import homeassistant.components.command_line.cover as cmd_rs from homeassistant.components.cover import DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_CLOSE_COVER, SERVICE_OPEN_COVER, SERVICE_STOP_COVER, ) from homeassistant.setup import async_setup_component @pytest.fixture def rs(hass): """Return CommandCover instance.""" return cmd_rs.CommandCover( hass, "foo", "command_open", "command_close", "command_stop", "command_state", None, ) def test_should_poll_new(rs): """Test the setting of polling.""" assert rs.should_poll is True rs._command_state = None assert rs.should_poll is False def test_query_state_value(rs): """Test with state value.""" with mock.patch("subprocess.check_output") as mock_run: mock_run.return_value = b" foo bar " result = rs._query_state_value("runme") assert "foo bar" == result assert mock_run.call_count == 1 assert mock_run.call_args == mock.call( "runme", shell=True, # nosec # shell by design ) async def test_state_value(hass): """Test with state value.""" with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, "cover_status") test_cover = { "command_state": f"cat {path}", "command_open": f"echo 1 > {path}", "command_close": f"echo 1 > {path}", "command_stop": f"echo 0 > {path}", "value_template": "{{ value }}", } assert ( await async_setup_component( hass, DOMAIN, {"cover": {"platform": "command_line", "covers": {"test": test_cover}}}, ) is True ) await hass.async_block_till_done() assert "unknown" == hass.states.get("cover.test").state await hass.services.async_call( DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True ) assert "open" == hass.states.get("cover.test").state await hass.services.async_call( DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True ) assert "open" == hass.states.get("cover.test").state await hass.services.async_call( DOMAIN, SERVICE_STOP_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True ) assert "closed" == hass.states.get("cover.test").state
mKeRix/home-assistant
tests/components/command_line/test_cover.py
homeassistant/setup.py
"""Config flow to configure demo component.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback import homeassistant.helpers.config_validation as cv # pylint: disable=unused-import from . import DOMAIN CONF_STRING = "string" CONF_BOOLEAN = "bool" CONF_INT = "int" CONF_SELECT = "select" CONF_MULTISELECT = "multi" class DemoConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Demo configuration flow.""" VERSION = 1 @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return OptionsFlowHandler(config_entry) async def async_step_import(self, import_info): """Set the config entry up from yaml.""" return self.async_create_entry(title="Demo", data={}) class OptionsFlowHandler(config_entries.OptionsFlow): """Handle options.""" def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry self.options = dict(config_entry.options) async def async_step_init(self, user_input=None): """Manage the options.""" return await self.async_step_options_1() async def async_step_options_1(self, user_input=None): """Manage the options.""" if user_input is not None: self.options.update(user_input) return await self.async_step_options_2() return self.async_show_form( step_id="options_1", data_schema=vol.Schema( { vol.Required("constant"): "Constant Value", vol.Optional( CONF_BOOLEAN, default=self.config_entry.options.get(CONF_BOOLEAN, False), ): bool, vol.Optional( CONF_INT, default=self.config_entry.options.get(CONF_INT, 10), ): int, } ), ) async def async_step_options_2(self, user_input=None): """Manage the options 2.""" if user_input is not None: self.options.update(user_input) return await self._update_options() return self.async_show_form( step_id="options_2", data_schema=vol.Schema( { vol.Optional( CONF_STRING, default=self.config_entry.options.get(CONF_STRING, "Default",), ): str, vol.Optional( CONF_SELECT, default=self.config_entry.options.get(CONF_SELECT, "default"), ): vol.In(["default", "other"]), vol.Optional( CONF_MULTISELECT, default=self.config_entry.options.get( CONF_MULTISELECT, ["default"] ), ): cv.multi_select({"default": "Default", "other": "Other"}), } ), ) async def _update_options(self): """Update config entry options.""" return self.async_create_entry(title="", data=self.options)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/demo/config_flow.py
"""Config flow for Sonarr.""" import logging from typing import Any, Dict, Optional from sonarr import Sonarr, SonarrAccessRestricted, SonarrError import voluptuous as vol from homeassistant.config_entries import CONN_CLASS_LOCAL_POLL, ConfigFlow, OptionsFlow from homeassistant.const import ( CONF_API_KEY, CONF_HOST, CONF_PORT, CONF_SSL, CONF_VERIFY_SSL, ) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.typing import ConfigType, HomeAssistantType from .const import ( CONF_BASE_PATH, CONF_UPCOMING_DAYS, CONF_WANTED_MAX_ITEMS, DEFAULT_BASE_PATH, DEFAULT_PORT, DEFAULT_SSL, DEFAULT_UPCOMING_DAYS, DEFAULT_VERIFY_SSL, DEFAULT_WANTED_MAX_ITEMS, ) from .const import DOMAIN # pylint: disable=unused-import _LOGGER = logging.getLogger(__name__) async def validate_input(hass: HomeAssistantType, data: dict) -> Dict[str, Any]: """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) sonarr = Sonarr( host=data[CONF_HOST], port=data[CONF_PORT], api_key=data[CONF_API_KEY], base_path=data[CONF_BASE_PATH], tls=data[CONF_SSL], verify_ssl=data[CONF_VERIFY_SSL], session=session, ) await sonarr.update() return True class SonarrConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Sonarr.""" VERSION = 1 CONNECTION_CLASS = CONN_CLASS_LOCAL_POLL @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return SonarrOptionsFlowHandler(config_entry) async def async_step_import( self, user_input: Optional[ConfigType] = None ) -> Dict[str, Any]: """Handle a flow initiated by configuration file.""" return await self.async_step_user(user_input) async def async_step_user( self, user_input: Optional[ConfigType] = None ) -> Dict[str, Any]: """Handle a flow initiated by the user.""" if user_input is None: return self._show_setup_form() if CONF_VERIFY_SSL not in user_input: user_input[CONF_VERIFY_SSL] = DEFAULT_VERIFY_SSL try: await validate_input(self.hass, user_input) except SonarrAccessRestricted: return self._show_setup_form({"base": "invalid_auth"}) except SonarrError: return self._show_setup_form({"base": "cannot_connect"}) except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") return self.async_create_entry(title=user_input[CONF_HOST], data=user_input) def _show_setup_form(self, errors: Optional[Dict] = None) -> Dict[str, Any]: """Show the setup form to the user.""" data_schema = { vol.Required(CONF_HOST): str, vol.Required(CONF_API_KEY): str, vol.Optional(CONF_BASE_PATH, default=DEFAULT_BASE_PATH): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_SSL, default=DEFAULT_SSL): bool, } if self.show_advanced_options: data_schema[ vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL) ] = bool return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors or {}, ) class SonarrOptionsFlowHandler(OptionsFlow): """Handle Sonarr client options.""" def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input: Optional[ConfigType] = None): """Manage Sonarr options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = { vol.Optional( CONF_UPCOMING_DAYS, default=self.config_entry.options.get( CONF_UPCOMING_DAYS, DEFAULT_UPCOMING_DAYS ), ): int, vol.Optional( CONF_WANTED_MAX_ITEMS, default=self.config_entry.options.get( CONF_WANTED_MAX_ITEMS, DEFAULT_WANTED_MAX_ITEMS ), ): int, } return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/sonarr/config_flow.py
"""Support to set a numeric value from a slider or text box.""" import logging import typing import voluptuous as vol from homeassistant.const import ( ATTR_EDITABLE, ATTR_MODE, ATTR_UNIT_OF_MEASUREMENT, CONF_ICON, CONF_ID, CONF_MODE, CONF_NAME, SERVICE_RELOAD, ) from homeassistant.core import callback from homeassistant.helpers import collection import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.restore_state import RestoreEntity import homeassistant.helpers.service from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceCallType _LOGGER = logging.getLogger(__name__) DOMAIN = "input_number" CONF_INITIAL = "initial" CONF_MIN = "min" CONF_MAX = "max" CONF_STEP = "step" MODE_SLIDER = "slider" MODE_BOX = "box" ATTR_INITIAL = "initial" ATTR_VALUE = "value" ATTR_MIN = "min" ATTR_MAX = "max" ATTR_STEP = "step" SERVICE_SET_VALUE = "set_value" SERVICE_INCREMENT = "increment" SERVICE_DECREMENT = "decrement" def _cv_input_number(cfg): """Configure validation helper for input number (voluptuous).""" minimum = cfg.get(CONF_MIN) maximum = cfg.get(CONF_MAX) if minimum >= maximum: raise vol.Invalid( f"Maximum ({minimum}) is not greater than minimum ({maximum})" ) state = cfg.get(CONF_INITIAL) if state is not None and (state < minimum or state > maximum): raise vol.Invalid(f"Initial value {state} not in range {minimum}-{maximum}") return cfg CREATE_FIELDS = { vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)), vol.Required(CONF_MIN): vol.Coerce(float), vol.Required(CONF_MAX): vol.Coerce(float), vol.Optional(CONF_INITIAL): vol.Coerce(float), vol.Optional(CONF_STEP, default=1): vol.All(vol.Coerce(float), vol.Range(min=1e-3)), vol.Optional(CONF_ICON): cv.icon, vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string, vol.Optional(CONF_MODE, default=MODE_SLIDER): vol.In([MODE_BOX, MODE_SLIDER]), } UPDATE_FIELDS = { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_MIN): vol.Coerce(float), vol.Optional(CONF_MAX): vol.Coerce(float), vol.Optional(CONF_INITIAL): vol.Coerce(float), vol.Optional(CONF_STEP): vol.All(vol.Coerce(float), vol.Range(min=1e-3)), vol.Optional(CONF_ICON): cv.icon, vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string, vol.Optional(CONF_MODE): vol.In([MODE_BOX, MODE_SLIDER]), } CONFIG_SCHEMA = vol.Schema( { DOMAIN: cv.schema_with_slug_keys( vol.All( { vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_MIN): vol.Coerce(float), vol.Required(CONF_MAX): vol.Coerce(float), vol.Optional(CONF_INITIAL): vol.Coerce(float), vol.Optional(CONF_STEP, default=1): vol.All( vol.Coerce(float), vol.Range(min=1e-3) ), vol.Optional(CONF_ICON): cv.icon, vol.Optional(ATTR_UNIT_OF_MEASUREMENT): cv.string, vol.Optional(CONF_MODE, default=MODE_SLIDER): vol.In( [MODE_BOX, MODE_SLIDER] ), }, _cv_input_number, ) ) }, extra=vol.ALLOW_EXTRA, ) RELOAD_SERVICE_SCHEMA = vol.Schema({}) STORAGE_KEY = DOMAIN STORAGE_VERSION = 1 async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up an input slider.""" component = EntityComponent(_LOGGER, DOMAIN, hass) id_manager = collection.IDManager() yaml_collection = collection.YamlCollection( logging.getLogger(f"{__name__}.yaml_collection"), id_manager ) collection.attach_entity_component_collection( component, yaml_collection, InputNumber.from_yaml ) storage_collection = NumberStorageCollection( Store(hass, STORAGE_VERSION, STORAGE_KEY), logging.getLogger(f"{__name__}.storage_collection"), id_manager, ) collection.attach_entity_component_collection( component, storage_collection, InputNumber ) await yaml_collection.async_load( [{CONF_ID: id_, **(conf or {})} for id_, conf in config.get(DOMAIN, {}).items()] ) await storage_collection.async_load() collection.StorageCollectionWebsocket( storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS ).async_setup(hass) collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, yaml_collection) collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN, storage_collection) async def reload_service_handler(service_call: ServiceCallType) -> None: """Reload yaml entities.""" conf = await component.async_prepare_reload(skip_reset=True) if conf is None: conf = {DOMAIN: {}} await yaml_collection.async_load( [{CONF_ID: id_, **conf} for id_, conf in conf.get(DOMAIN, {}).items()] ) homeassistant.helpers.service.async_register_admin_service( hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=RELOAD_SERVICE_SCHEMA, ) component.async_register_entity_service( SERVICE_SET_VALUE, {vol.Required(ATTR_VALUE): vol.Coerce(float)}, "async_set_value", ) component.async_register_entity_service(SERVICE_INCREMENT, {}, "async_increment") component.async_register_entity_service(SERVICE_DECREMENT, {}, "async_decrement") return True class NumberStorageCollection(collection.StorageCollection): """Input storage based collection.""" CREATE_SCHEMA = vol.Schema(vol.All(CREATE_FIELDS, _cv_input_number)) UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS) async def _process_create_data(self, data: typing.Dict) -> typing.Dict: """Validate the config is valid.""" return self.CREATE_SCHEMA(data) @callback def _get_suggested_id(self, info: typing.Dict) -> str: """Suggest an ID based on the config.""" return info[CONF_NAME] async def _update_data(self, data: dict, update_data: typing.Dict) -> typing.Dict: """Return a new updated data object.""" update_data = self.UPDATE_SCHEMA(update_data) return _cv_input_number({**data, **update_data}) class InputNumber(RestoreEntity): """Representation of a slider.""" def __init__(self, config: typing.Dict): """Initialize an input number.""" self._config = config self.editable = True self._current_value = config.get(CONF_INITIAL) @classmethod def from_yaml(cls, config: typing.Dict) -> "InputNumber": """Return entity instance initialized from yaml storage.""" input_num = cls(config) input_num.entity_id = f"{DOMAIN}.{config[CONF_ID]}" input_num.editable = False return input_num @property def should_poll(self): """If entity should be polled.""" return False @property def _minimum(self) -> float: """Return minimum allowed value.""" return self._config[CONF_MIN] @property def _maximum(self) -> float: """Return maximum allowed value.""" return self._config[CONF_MAX] @property def name(self): """Return the name of the input slider.""" return self._config.get(CONF_NAME) @property def icon(self): """Return the icon to be used for this entity.""" return self._config.get(CONF_ICON) @property def state(self): """Return the state of the component.""" return self._current_value @property def _step(self) -> int: """Return entity's increment/decrement step.""" return self._config[CONF_STEP] @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._config.get(ATTR_UNIT_OF_MEASUREMENT) @property def unique_id(self) -> typing.Optional[str]: """Return unique id of the entity.""" return self._config[CONF_ID] @property def state_attributes(self): """Return the state attributes.""" return { ATTR_INITIAL: self._config.get(CONF_INITIAL), ATTR_EDITABLE: self.editable, ATTR_MIN: self._minimum, ATTR_MAX: self._maximum, ATTR_STEP: self._step, ATTR_MODE: self._config[CONF_MODE], } async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() if self._current_value is not None: return state = await self.async_get_last_state() value = state and float(state.state) # Check against None because value can be 0 if value is not None and self._minimum <= value <= self._maximum: self._current_value = value else: self._current_value = self._minimum async def async_set_value(self, value): """Set new value.""" num_value = float(value) if num_value < self._minimum or num_value > self._maximum: raise vol.Invalid( f"Invalid value for {self.entity_id}: {value} (range {self._minimum} - {self._maximum})" ) self._current_value = num_value self.async_write_ha_state() async def async_increment(self): """Increment value.""" await self.async_set_value(min(self._current_value + self._step, self._maximum)) async def async_decrement(self): """Decrement value.""" await self.async_set_value(max(self._current_value - self._step, self._minimum)) async def async_update_config(self, config: typing.Dict) -> None: """Handle when the config is updated.""" self._config = config # just in case min/max values changed self._current_value = min(self._current_value, self._maximum) self._current_value = max(self._current_value, self._minimum) self.async_write_ha_state()
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/input_number/__init__.py
"""Support for interacting with Vultr subscriptions.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from . import ( ATTR_ALLOWED_BANDWIDTH, ATTR_AUTO_BACKUPS, ATTR_COST_PER_MONTH, ATTR_CREATED_AT, ATTR_DISK, ATTR_IPV4_ADDRESS, ATTR_IPV6_ADDRESS, ATTR_MEMORY, ATTR_OS, ATTR_REGION, ATTR_SUBSCRIPTION_ID, ATTR_SUBSCRIPTION_NAME, ATTR_VCPUS, CONF_SUBSCRIPTION, DATA_VULTR, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Vultr {}" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_SUBSCRIPTION): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vultr subscription switch.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return False add_entities([VultrSwitch(vultr, subscription, name)], True) class VultrSwitch(SwitchEntity): """Representation of a Vultr subscription switch.""" def __init__(self, vultr, subscription, name): """Initialize a new Vultr switch.""" self._vultr = vultr self._name = name self.subscription = subscription self.data = None @property def name(self): """Return the name of the switch.""" try: return self._name.format(self.data["label"]) except (TypeError, KeyError): return self._name @property def is_on(self): """Return true if switch is on.""" return self.data["power_status"] == "running" @property def icon(self): """Return the icon of this server.""" return "mdi:server" if self.is_on else "mdi:server-off" @property def device_state_attributes(self): """Return the state attributes of the Vultr subscription.""" return { ATTR_ALLOWED_BANDWIDTH: self.data.get("allowed_bandwidth_gb"), ATTR_AUTO_BACKUPS: self.data.get("auto_backups"), ATTR_COST_PER_MONTH: self.data.get("cost_per_month"), ATTR_CREATED_AT: self.data.get("date_created"), ATTR_DISK: self.data.get("disk"), ATTR_IPV4_ADDRESS: self.data.get("main_ip"), ATTR_IPV6_ADDRESS: self.data.get("v6_main_ip"), ATTR_MEMORY: self.data.get("ram"), ATTR_OS: self.data.get("os"), ATTR_REGION: self.data.get("location"), ATTR_SUBSCRIPTION_ID: self.data.get("SUBID"), ATTR_SUBSCRIPTION_NAME: self.data.get("label"), ATTR_VCPUS: self.data.get("vcpu_count"), } def turn_on(self, **kwargs): """Boot-up the subscription.""" if self.data["power_status"] != "running": self._vultr.start(self.subscription) def turn_off(self, **kwargs): """Halt the subscription.""" if self.data["power_status"] == "running": self._vultr.halt(self.subscription) def update(self): """Get the latest data from the device and update the data.""" self._vultr.update() self.data = self._vultr.data[self.subscription]
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/vultr/switch.py
"""The GIOS component.""" import logging from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout from gios import ApiError, Gios, InvalidSensorsData, NoStationError from homeassistant.core import Config, HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import CONF_STATION_ID, DOMAIN, SCAN_INTERVAL _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistant, config: Config) -> bool: """Set up configured GIOS.""" return True async def async_setup_entry(hass, config_entry): """Set up GIOS as config entry.""" station_id = config_entry.data[CONF_STATION_ID] _LOGGER.debug("Using station_id: %s", station_id) websession = async_get_clientsession(hass) coordinator = GiosDataUpdateCoordinator(hass, websession, station_id) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][config_entry.entry_id] = coordinator hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, "air_quality") ) return True async def async_unload_entry(hass, config_entry): """Unload a config entry.""" hass.data[DOMAIN].pop(config_entry.entry_id) await hass.config_entries.async_forward_entry_unload(config_entry, "air_quality") return True class GiosDataUpdateCoordinator(DataUpdateCoordinator): """Define an object to hold GIOS data.""" def __init__(self, hass, session, station_id): """Class to manage fetching GIOS data API.""" self.gios = Gios(station_id, session) super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL) async def _async_update_data(self): """Update data via library.""" try: with timeout(30): await self.gios.update() except ( ApiError, NoStationError, ClientConnectorError, InvalidSensorsData, ) as error: raise UpdateFailed(error) if not self.gios.data: raise UpdateFailed("Invalid sensors data") return self.gios.data
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/gios/__init__.py
"""Support for Lutron scenes.""" import logging from typing import Any from homeassistant.components.scene import Scene from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron scenes.""" devs = [] for scene_data in hass.data[LUTRON_DEVICES]["scene"]: (area_name, keypad_name, device, led) = scene_data dev = LutronScene( area_name, keypad_name, device, led, hass.data[LUTRON_CONTROLLER] ) devs.append(dev) add_entities(devs, True) class LutronScene(LutronDevice, Scene): """Representation of a Lutron Scene.""" def __init__(self, area_name, keypad_name, lutron_device, lutron_led, controller): """Initialize the scene/button.""" super().__init__(area_name, lutron_device, controller) self._keypad_name = keypad_name self._led = lutron_led def activate(self, **kwargs: Any) -> None: """Activate the scene.""" self._lutron_device.press() @property def name(self): """Return the name of the device.""" return f"{self._area_name} {self._keypad_name}: {self._lutron_device.name}"
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/lutron/scene.py
"""Config flow for NuHeat integration.""" import logging import nuheat import requests.exceptions import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, HTTP_BAD_REQUEST, HTTP_INTERNAL_SERVER_ERROR, ) from .const import CONF_SERIAL_NUMBER from .const import DOMAIN # pylint:disable=unused-import _LOGGER = logging.getLogger(__name__) DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_SERIAL_NUMBER): str, } ) async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ api = nuheat.NuHeat(data[CONF_USERNAME], data[CONF_PASSWORD]) try: await hass.async_add_executor_job(api.authenticate) except requests.exceptions.Timeout: raise CannotConnect except requests.exceptions.HTTPError as ex: if ( ex.response.status_code > HTTP_BAD_REQUEST and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): raise InvalidAuth raise CannotConnect # # The underlying module throws a generic exception on login failure # except Exception: # pylint: disable=broad-except raise InvalidAuth try: thermostat = await hass.async_add_executor_job( api.get_thermostat, data[CONF_SERIAL_NUMBER] ) except requests.exceptions.HTTPError: raise InvalidThermostat return {"title": thermostat.room, "serial_number": thermostat.serial_number} class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for NuHeat.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except InvalidThermostat: errors["base"] = "invalid_thermostat" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if "base" not in errors: await self.async_set_unique_id(info["serial_number"]) self._abort_if_unique_id_configured() return self.async_create_entry(title=info["title"], data=user_input) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) async def async_step_import(self, user_input): """Handle import.""" await self.async_set_unique_id(user_input[CONF_SERIAL_NUMBER]) self._abort_if_unique_id_configured() return await self.async_step_user(user_input) class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(exceptions.HomeAssistantError): """Error to indicate there is invalid auth.""" class InvalidThermostat(exceptions.HomeAssistantError): """Error to indicate there is invalid thermostat."""
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/nuheat/config_flow.py
"""Demo platform that offers a fake water heater device.""" from homeassistant.components.water_heater import ( SUPPORT_AWAY_MODE, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, WaterHeaterEntity, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT SUPPORT_FLAGS_HEATER = ( SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE | SUPPORT_AWAY_MODE ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo water_heater devices.""" async_add_entities( [ DemoWaterHeater("Demo Water Heater", 119, TEMP_FAHRENHEIT, False, "eco"), DemoWaterHeater("Demo Water Heater Celsius", 45, TEMP_CELSIUS, True, "eco"), ] ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" await async_setup_platform(hass, {}, async_add_entities) class DemoWaterHeater(WaterHeaterEntity): """Representation of a demo water_heater device.""" def __init__( self, name, target_temperature, unit_of_measurement, away, current_operation ): """Initialize the water_heater device.""" self._name = name self._support_flags = SUPPORT_FLAGS_HEATER if target_temperature is not None: self._support_flags = self._support_flags | SUPPORT_TARGET_TEMPERATURE if away is not None: self._support_flags = self._support_flags | SUPPORT_AWAY_MODE if current_operation is not None: self._support_flags = self._support_flags | SUPPORT_OPERATION_MODE self._target_temperature = target_temperature self._unit_of_measurement = unit_of_measurement self._away = away self._current_operation = current_operation self._operation_list = [ "eco", "electric", "performance", "high_demand", "heat_pump", "gas", "off", ] @property def supported_features(self): """Return the list of supported features.""" return self._support_flags @property def should_poll(self): """Return the polling state.""" return False @property def name(self): """Return the name of the water_heater device.""" return self._name @property def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def current_operation(self): """Return current operation ie. heat, cool, idle.""" return self._current_operation @property def operation_list(self): """Return the list of available operation modes.""" return self._operation_list @property def is_away_mode_on(self): """Return if away mode is on.""" return self._away def set_temperature(self, **kwargs): """Set new target temperatures.""" self._target_temperature = kwargs.get(ATTR_TEMPERATURE) self.schedule_update_ha_state() def set_operation_mode(self, operation_mode): """Set new operation mode.""" self._current_operation = operation_mode self.schedule_update_ha_state() def turn_away_mode_on(self): """Turn away mode on.""" self._away = True self.schedule_update_ha_state() def turn_away_mode_off(self): """Turn away mode off.""" self._away = False self.schedule_update_ha_state()
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/demo/water_heater.py
"""Constant values for pvpc_hourly_pricing.""" from aiopvpc import TARIFFS DOMAIN = "pvpc_hourly_pricing" PLATFORM = "sensor" ATTR_TARIFF = "tariff" DEFAULT_NAME = "PVPC" DEFAULT_TARIFF = TARIFFS[1]
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/pvpc_hourly_pricing/const.py
"""Support for locks which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.lock import PLATFORM_SCHEMA, LockEntity from homeassistant.const import ( CONF_NAME, CONF_OPTIMISTIC, CONF_VALUE_TEMPLATE, EVENT_HOMEASSISTANT_START, MATCH_ALL, STATE_LOCKED, STATE_ON, ) from homeassistant.core import callback from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.script import Script from . import extract_entities, initialise_templates from .const import CONF_AVAILABILITY_TEMPLATE _LOGGER = logging.getLogger(__name__) CONF_LOCK = "lock" CONF_UNLOCK = "unlock" DEFAULT_NAME = "Template Lock" DEFAULT_OPTIMISTIC = False PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_LOCK): cv.SCRIPT_SCHEMA, vol.Required(CONF_UNLOCK): cv.SCRIPT_SCHEMA, vol.Required(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template, vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean, } ) async def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Template lock.""" device = config.get(CONF_NAME) value_template = config.get(CONF_VALUE_TEMPLATE) availability_template = config.get(CONF_AVAILABILITY_TEMPLATE) templates = { CONF_VALUE_TEMPLATE: value_template, CONF_AVAILABILITY_TEMPLATE: availability_template, } initialise_templates(hass, templates) entity_ids = extract_entities(device, "lock", None, templates) async_add_devices( [ TemplateLock( hass, device, value_template, availability_template, entity_ids, config.get(CONF_LOCK), config.get(CONF_UNLOCK), config.get(CONF_OPTIMISTIC), ) ] ) class TemplateLock(LockEntity): """Representation of a template lock.""" def __init__( self, hass, name, value_template, availability_template, entity_ids, command_lock, command_unlock, optimistic, ): """Initialize the lock.""" self._state = None self._hass = hass self._name = name self._state_template = value_template self._availability_template = availability_template self._state_entities = entity_ids self._command_lock = Script(hass, command_lock) self._command_unlock = Script(hass, command_unlock) self._optimistic = optimistic self._available = True async def async_added_to_hass(self): """Register callbacks.""" @callback def template_lock_state_listener(event): """Handle target device state changes.""" self.async_schedule_update_ha_state(True) @callback def template_lock_startup(event): """Update template on startup.""" if self._state_entities != MATCH_ALL: # Track state change only for valid templates async_track_state_change_event( self._hass, self._state_entities, template_lock_state_listener ) self.async_schedule_update_ha_state(True) self._hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, template_lock_startup ) @property def assumed_state(self): """Return true if we do optimistic updates.""" return self._optimistic @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the lock.""" return self._name @property def is_locked(self): """Return true if lock is locked.""" return self._state @property def available(self) -> bool: """Return if the device is available.""" return self._available async def async_update(self): """Update the state from the template.""" try: self._state = self._state_template.async_render().lower() in ( "true", STATE_ON, STATE_LOCKED, ) except TemplateError as ex: self._state = None _LOGGER.error("Could not render template %s: %s", self._name, ex) if self._availability_template is not None: try: self._available = ( self._availability_template.async_render().lower() == "true" ) except (TemplateError, ValueError) as ex: _LOGGER.error( "Could not render %s template %s: %s", CONF_AVAILABILITY_TEMPLATE, self._name, ex, ) async def async_lock(self, **kwargs): """Lock the device.""" if self._optimistic: self._state = True self.async_write_ha_state() await self._command_lock.async_run(context=self._context) async def async_unlock(self, **kwargs): """Unlock the device.""" if self._optimistic: self._state = False self.async_write_ha_state() await self._command_unlock.async_run(context=self._context)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/template/lock.py
"""Support for iOS push notifications.""" import logging import requests from homeassistant.components import ios from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, ATTR_TITLE, ATTR_TITLE_DEFAULT, BaseNotificationService, ) import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) PUSH_URL = "https://ios-push.home-assistant.io/push" # pylint: disable=invalid-name def log_rate_limits(hass, target, resp, level=20): """Output rate limit log line at given level.""" rate_limits = resp["rateLimits"] resetsAt = dt_util.parse_datetime(rate_limits["resetsAt"]) resetsAtTime = resetsAt - dt_util.utcnow() rate_limit_msg = ( "iOS push notification rate limits for %s: " "%d sent, %d allowed, %d errors, " "resets in %s" ) _LOGGER.log( level, rate_limit_msg, ios.device_name_for_push_id(hass, target), rate_limits["successful"], rate_limits["maximum"], rate_limits["errors"], str(resetsAtTime).split(".")[0], ) def get_service(hass, config, discovery_info=None): """Get the iOS notification service.""" if "notify.ios" not in hass.config.components: # Need this to enable requirements checking in the app. hass.config.components.add("notify.ios") if not ios.devices_with_push(hass): return None return iOSNotificationService() class iOSNotificationService(BaseNotificationService): """Implement the notification service for iOS.""" def __init__(self): """Initialize the service.""" @property def targets(self): """Return a dictionary of registered targets.""" return ios.devices_with_push(self.hass) def send_message(self, message="", **kwargs): """Send a message to the Lambda APNS gateway.""" data = {ATTR_MESSAGE: message} if kwargs.get(ATTR_TITLE) is not None: # Remove default title from notifications. if kwargs.get(ATTR_TITLE) != ATTR_TITLE_DEFAULT: data[ATTR_TITLE] = kwargs.get(ATTR_TITLE) targets = kwargs.get(ATTR_TARGET) if not targets: targets = ios.enabled_push_ids(self.hass) if kwargs.get(ATTR_DATA) is not None: data[ATTR_DATA] = kwargs.get(ATTR_DATA) for target in targets: if target not in ios.enabled_push_ids(self.hass): _LOGGER.error("The target (%s) does not exist in .ios.conf", targets) return data[ATTR_TARGET] = target req = requests.post(PUSH_URL, json=data, timeout=10) if req.status_code != 201: fallback_error = req.json().get("errorMessage", "Unknown error") fallback_message = ( f"Internal server error, please try again later: {fallback_error}" ) message = req.json().get("message", fallback_message) if req.status_code == 429: _LOGGER.warning(message) log_rate_limits(self.hass, target, req.json(), 30) else: _LOGGER.error(message) else: log_rate_limits(self.hass, target, req.json())
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/ios/notify.py
"""Support for LG soundbars.""" import logging import temescal from homeassistant.components.media_player import MediaPlayerEntity from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, ) from homeassistant.const import STATE_ON _LOGGER = logging.getLogger(__name__) SUPPORT_LG = ( SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LG platform.""" if discovery_info is not None: add_entities([LGDevice(discovery_info)], True) class LGDevice(MediaPlayerEntity): """Representation of an LG soundbar device.""" def __init__(self, discovery_info): """Initialize the LG speakers.""" host = discovery_info.get("host") port = discovery_info.get("port") self._name = "" self._volume = 0 self._volume_min = 0 self._volume_max = 0 self._function = -1 self._functions = [] self._equaliser = -1 self._equalisers = [] self._mute = 0 self._rear_volume = 0 self._rear_volume_min = 0 self._rear_volume_max = 0 self._woofer_volume = 0 self._woofer_volume_min = 0 self._woofer_volume_max = 0 self._bass = 0 self._treble = 0 self._device = temescal.temescal(host, port=port, callback=self.handle_event) self.update() def handle_event(self, response): """Handle responses from the speakers.""" data = response["data"] if response["msg"] == "EQ_VIEW_INFO": if "i_bass" in data: self._bass = data["i_bass"] if "i_treble" in data: self._treble = data["i_treble"] if "ai_eq_list" in data: self._equalisers = data["ai_eq_list"] if "i_curr_eq" in data: self._equaliser = data["i_curr_eq"] elif response["msg"] == "SPK_LIST_VIEW_INFO": if "i_vol" in data: self._volume = data["i_vol"] if "s_user_name" in data: self._name = data["s_user_name"] if "i_vol_min" in data: self._volume_min = data["i_vol_min"] if "i_vol_max" in data: self._volume_max = data["i_vol_max"] if "b_mute" in data: self._mute = data["b_mute"] if "i_curr_func" in data: self._function = data["i_curr_func"] elif response["msg"] == "FUNC_VIEW_INFO": if "i_curr_func" in data: self._function = data["i_curr_func"] if "ai_func_list" in data: self._functions = data["ai_func_list"] elif response["msg"] == "SETTING_VIEW_INFO": if "i_rear_min" in data: self._rear_volume_min = data["i_rear_min"] if "i_rear_max" in data: self._rear_volume_max = data["i_rear_max"] if "i_rear_level" in data: self._rear_volume = data["i_rear_level"] if "i_woofer_min" in data: self._woofer_volume_min = data["i_woofer_min"] if "i_woofer_max" in data: self._woofer_volume_max = data["i_woofer_max"] if "i_woofer_level" in data: self._woofer_volume = data["i_woofer_level"] if "i_curr_eq" in data: self._equaliser = data["i_curr_eq"] if "s_user_name" in data: self._name = data["s_user_name"] self.schedule_update_ha_state() def update(self): """Trigger updates from the device.""" self._device.get_eq() self._device.get_info() self._device.get_func() self._device.get_settings() self._device.get_product_info() # Temporary fix until handling of unknown equaliser settings is integrated in the temescal library for equaliser in self._equalisers: if equaliser >= len(temescal.equalisers): temescal.equalisers.append("unknown " + str(equaliser)) @property def name(self): """Return the name of the device.""" return self._name @property def volume_level(self): """Volume level of the media player (0..1).""" if self._volume_max != 0: return self._volume / self._volume_max return 0 @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute @property def state(self): """Return the state of the device.""" return STATE_ON @property def sound_mode(self): """Return the current sound mode.""" if self._equaliser == -1 or self._equaliser >= len(temescal.equalisers): return None return temescal.equalisers[self._equaliser] @property def sound_mode_list(self): """Return the available sound modes.""" modes = [] for equaliser in self._equalisers: modes.append(temescal.equalisers[equaliser]) return sorted(modes) @property def source(self): """Return the current input source.""" if self._function == -1: return None return temescal.functions[self._function] @property def source_list(self): """List of available input sources.""" sources = [] for function in self._functions: sources.append(temescal.functions[function]) return sorted(sources) @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_LG def set_volume_level(self, volume): """Set volume level, range 0..1.""" volume = volume * self._volume_max self._device.set_volume(int(volume)) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self._device.set_mute(mute) def select_source(self, source): """Select input source.""" self._device.set_func(temescal.functions.index(source)) def select_sound_mode(self, sound_mode): """Set Sound Mode for Receiver..""" self._device.set_eq(temescal.equalisers.index(sound_mode))
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/lg_soundbar/media_player.py
"""Support for eQ-3 Bluetooth Smart thermostats.""" import logging # pylint: disable=import-error from bluepy.btle import BTLEException import eq3bt as eq3 # pylint: disable=import-error import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, PRESET_NONE, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_DEVICES, CONF_MAC, PRECISION_HALVES, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) STATE_BOOST = "boost" ATTR_STATE_WINDOW_OPEN = "window_open" ATTR_STATE_VALVE = "valve" ATTR_STATE_LOCKED = "is_locked" ATTR_STATE_LOW_BAT = "low_battery" ATTR_STATE_AWAY_END = "away_end" EQ_TO_HA_HVAC = { eq3.Mode.Open: HVAC_MODE_HEAT, eq3.Mode.Closed: HVAC_MODE_OFF, eq3.Mode.Auto: HVAC_MODE_AUTO, eq3.Mode.Manual: HVAC_MODE_HEAT, eq3.Mode.Boost: HVAC_MODE_AUTO, eq3.Mode.Away: HVAC_MODE_HEAT, } HA_TO_EQ_HVAC = { HVAC_MODE_HEAT: eq3.Mode.Manual, HVAC_MODE_OFF: eq3.Mode.Closed, HVAC_MODE_AUTO: eq3.Mode.Auto, } EQ_TO_HA_PRESET = {eq3.Mode.Boost: PRESET_BOOST, eq3.Mode.Away: PRESET_AWAY} HA_TO_EQ_PRESET = {PRESET_BOOST: eq3.Mode.Boost, PRESET_AWAY: eq3.Mode.Away} DEVICE_SCHEMA = vol.Schema({vol.Required(CONF_MAC): cv.string}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_DEVICES): vol.Schema({cv.string: DEVICE_SCHEMA})} ) SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the eQ-3 BLE thermostats.""" devices = [] for name, device_cfg in config[CONF_DEVICES].items(): mac = device_cfg[CONF_MAC] devices.append(EQ3BTSmartThermostat(mac, name)) add_entities(devices, True) class EQ3BTSmartThermostat(ClimateEntity): """Representation of an eQ-3 Bluetooth Smart thermostat.""" def __init__(self, _mac, _name): """Initialize the thermostat.""" # We want to avoid name clash with this module. self._name = _name self._thermostat = eq3.Thermostat(_mac) @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def available(self) -> bool: """Return if thermostat is available.""" return self._thermostat.mode >= 0 @property def name(self): """Return the name of the device.""" return self._name @property def temperature_unit(self): """Return the unit of measurement that is used.""" return TEMP_CELSIUS @property def precision(self): """Return eq3bt's precision 0.5.""" return PRECISION_HALVES @property def current_temperature(self): """Can not report temperature, so return target_temperature.""" return self.target_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._thermostat.target_temperature def set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._thermostat.target_temperature = temperature @property def hvac_mode(self): """Return the current operation mode.""" if self._thermostat.mode < 0: return HVAC_MODE_OFF return EQ_TO_HA_HVAC[self._thermostat.mode] @property def hvac_modes(self): """Return the list of available operation modes.""" return list(HA_TO_EQ_HVAC.keys()) def set_hvac_mode(self, hvac_mode): """Set operation mode.""" if self.preset_mode: return self._thermostat.mode = HA_TO_EQ_HVAC[hvac_mode] @property def min_temp(self): """Return the minimum temperature.""" return self._thermostat.min_temp @property def max_temp(self): """Return the maximum temperature.""" return self._thermostat.max_temp @property def device_state_attributes(self): """Return the device specific state attributes.""" dev_specific = { ATTR_STATE_AWAY_END: self._thermostat.away_end, ATTR_STATE_LOCKED: self._thermostat.locked, ATTR_STATE_LOW_BAT: self._thermostat.low_battery, ATTR_STATE_VALVE: self._thermostat.valve_state, ATTR_STATE_WINDOW_OPEN: self._thermostat.window_open, } return dev_specific @property def preset_mode(self): """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ return EQ_TO_HA_PRESET.get(self._thermostat.mode) @property def preset_modes(self): """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ return list(HA_TO_EQ_PRESET.keys()) def set_preset_mode(self, preset_mode): """Set new preset mode.""" if preset_mode == PRESET_NONE: self.set_hvac_mode(HVAC_MODE_HEAT) self._thermostat.mode = HA_TO_EQ_PRESET[preset_mode] def update(self): """Update the data from the thermostat.""" try: self._thermostat.update() except BTLEException as ex: _LOGGER.warning("Updating the state failed: %s", ex)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/eq3btsmart/climate.py
"""The songpal component.""" from collections import OrderedDict import logging import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv from homeassistant.helpers.typing import HomeAssistantType from .const import CONF_ENDPOINT, DOMAIN _LOGGER = logging.getLogger(__name__) SONGPAL_CONFIG_SCHEMA = vol.Schema( {vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_ENDPOINT): cv.string} ) CONFIG_SCHEMA = vol.Schema( {vol.Optional(DOMAIN): vol.All(cv.ensure_list, [SONGPAL_CONFIG_SCHEMA])}, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass: HomeAssistantType, config: OrderedDict) -> bool: """Set up songpal environment.""" conf = config.get(DOMAIN) if conf is None: return True for config_entry in conf: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=config_entry, ), ) return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up songpal media player.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "media_player") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Unload songpal media player.""" return await hass.config_entries.async_forward_entry_unload(entry, "media_player")
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/songpal/__init__.py
"""Support for Luftdaten stations.""" import logging from luftdaten import Luftdaten from luftdaten.exceptions import LuftdatenError import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SHOW_ON_MAP, TEMP_CELSIUS, UNIT_PERCENTAGE, ) from homeassistant.core import callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_track_time_interval from .config_flow import configured_sensors, duplicate_stations from .const import CONF_SENSOR_ID, DEFAULT_SCAN_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) DATA_LUFTDATEN = "luftdaten" DATA_LUFTDATEN_CLIENT = "data_luftdaten_client" DATA_LUFTDATEN_LISTENER = "data_luftdaten_listener" DEFAULT_ATTRIBUTION = "Data provided by luftdaten.info" SENSOR_HUMIDITY = "humidity" SENSOR_PM10 = "P1" SENSOR_PM2_5 = "P2" SENSOR_PRESSURE = "pressure" SENSOR_PRESSURE_AT_SEALEVEL = "pressure_at_sealevel" SENSOR_TEMPERATURE = "temperature" TOPIC_UPDATE = f"{DOMAIN}_data_update" SENSORS = { SENSOR_TEMPERATURE: ["Temperature", "mdi:thermometer", TEMP_CELSIUS], SENSOR_HUMIDITY: ["Humidity", "mdi:water-percent", UNIT_PERCENTAGE], SENSOR_PRESSURE: ["Pressure", "mdi:arrow-down-bold", "Pa"], SENSOR_PRESSURE_AT_SEALEVEL: ["Pressure at sealevel", "mdi:download", "Pa"], SENSOR_PM10: [ "PM10", "mdi:thought-bubble", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ], SENSOR_PM2_5: [ "PM2.5", "mdi:thought-bubble-outline", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ], } SENSOR_SCHEMA = vol.Schema( { vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSORS)): vol.All( cv.ensure_list, [vol.In(SENSORS)] ) } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_SENSOR_ID): cv.positive_int, vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA, vol.Optional(CONF_SHOW_ON_MAP, default=False): cv.boolean, vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL ): cv.time_period, } ) }, extra=vol.ALLOW_EXTRA, ) @callback def _async_fixup_sensor_id(hass, config_entry, sensor_id): hass.config_entries.async_update_entry( config_entry, data={**config_entry.data, CONF_SENSOR_ID: int(sensor_id)} ) async def async_setup(hass, config): """Set up the Luftdaten component.""" hass.data[DOMAIN] = {} hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT] = {} hass.data[DOMAIN][DATA_LUFTDATEN_LISTENER] = {} if DOMAIN not in config: return True conf = config[DOMAIN] station_id = conf[CONF_SENSOR_ID] if station_id not in configured_sensors(hass): hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_SENSORS: conf[CONF_SENSORS], CONF_SENSOR_ID: conf[CONF_SENSOR_ID], CONF_SHOW_ON_MAP: conf[CONF_SHOW_ON_MAP], }, ) ) hass.data[DOMAIN][CONF_SCAN_INTERVAL] = conf[CONF_SCAN_INTERVAL] return True async def async_setup_entry(hass, config_entry): """Set up Luftdaten as config entry.""" if not isinstance(config_entry.data[CONF_SENSOR_ID], int): _async_fixup_sensor_id(hass, config_entry, config_entry.data[CONF_SENSOR_ID]) if ( config_entry.data[CONF_SENSOR_ID] in duplicate_stations(hass) and config_entry.source == SOURCE_IMPORT ): _LOGGER.warning( "Removing duplicate sensors for station %s", config_entry.data[CONF_SENSOR_ID], ) hass.async_create_task(hass.config_entries.async_remove(config_entry.entry_id)) return False session = async_get_clientsession(hass) try: luftdaten = LuftDatenData( Luftdaten(config_entry.data[CONF_SENSOR_ID], hass.loop, session), config_entry.data.get(CONF_SENSORS, {}).get( CONF_MONITORED_CONDITIONS, list(SENSORS) ), ) await luftdaten.async_update() hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT][config_entry.entry_id] = luftdaten except LuftdatenError: raise ConfigEntryNotReady hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, "sensor") ) async def refresh_sensors(event_time): """Refresh Luftdaten data.""" await luftdaten.async_update() async_dispatcher_send(hass, TOPIC_UPDATE) hass.data[DOMAIN][DATA_LUFTDATEN_LISTENER][ config_entry.entry_id ] = async_track_time_interval( hass, refresh_sensors, hass.data[DOMAIN].get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL), ) return True async def async_unload_entry(hass, config_entry): """Unload an Luftdaten config entry.""" remove_listener = hass.data[DOMAIN][DATA_LUFTDATEN_LISTENER].pop( config_entry.entry_id ) remove_listener() hass.data[DOMAIN][DATA_LUFTDATEN_CLIENT].pop(config_entry.entry_id) return await hass.config_entries.async_forward_entry_unload(config_entry, "sensor") class LuftDatenData: """Define a generic Luftdaten object.""" def __init__(self, client, sensor_conditions): """Initialize the Luftdata object.""" self.client = client self.data = {} self.sensor_conditions = sensor_conditions async def async_update(self): """Update sensor/binary sensor data.""" try: await self.client.get_data() self.data[DATA_LUFTDATEN] = self.client.values self.data[DATA_LUFTDATEN].update(self.client.meta) except LuftdatenError: _LOGGER.error("Unable to retrieve data from luftdaten.info")
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/luftdaten/__init__.py
"""Support for Freebox Delta, Revolution and Mini 4K.""" import logging from typing import Dict from aiofreepybox.exceptions import InsufficientPermissionsError from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN from .router import FreeboxRouter _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the switch.""" router = hass.data[DOMAIN][entry.unique_id] async_add_entities([FreeboxWifiSwitch(router)], True) class FreeboxWifiSwitch(SwitchEntity): """Representation of a freebox wifi switch.""" def __init__(self, router: FreeboxRouter) -> None: """Initialize the Wifi switch.""" self._name = "Freebox WiFi" self._state = None self._router = router self._unique_id = f"{self._router.mac} {self._name}" @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def name(self) -> str: """Return the name of the switch.""" return self._name @property def is_on(self) -> bool: """Return true if device is on.""" return self._state @property def device_info(self) -> Dict[str, any]: """Return the device information.""" return self._router.device_info async def _async_set_state(self, enabled: bool): """Turn the switch on or off.""" wifi_config = {"enabled": enabled} try: await self._router.wifi.set_global_config(wifi_config) except InsufficientPermissionsError: _LOGGER.warning( "Home Assistant does not have permissions to modify the Freebox settings. Please refer to documentation" ) async def async_turn_on(self, **kwargs): """Turn the switch on.""" await self._async_set_state(True) async def async_turn_off(self, **kwargs): """Turn the switch off.""" await self._async_set_state(False) async def async_update(self): """Get the state and update it.""" datas = await self._router.wifi.get_global_config() active = datas["enabled"] self._state = bool(active)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/freebox/switch.py
"""Support for LIRC devices.""" # pylint: disable=no-member, import-error import logging import threading import time import lirc import voluptuous as vol from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP _LOGGER = logging.getLogger(__name__) BUTTON_NAME = "button_name" DOMAIN = "lirc" EVENT_IR_COMMAND_RECEIVED = "ir_command_received" ICON = "mdi:remote" CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the LIRC capability.""" # blocking=True gives unexpected behavior (multiple responses for 1 press) # also by not blocking, we allow hass to shut down the thread gracefully # on exit. lirc.init("home-assistant", blocking=False) lirc_interface = LircInterface(hass) def _start_lirc(_event): lirc_interface.start() def _stop_lirc(_event): lirc_interface.stopped.set() hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_lirc) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_lirc) return True class LircInterface(threading.Thread): """ This interfaces with the lirc daemon to read IR commands. When using lirc in blocking mode, sometimes repeated commands get produced in the next read of a command so we use a thread here to just wait around until a non-empty response is obtained from lirc. """ def __init__(self, hass): """Construct a LIRC interface object.""" threading.Thread.__init__(self) self.daemon = True self.stopped = threading.Event() self.hass = hass def run(self): """Run the loop of the LIRC interface thread.""" _LOGGER.debug("LIRC interface thread started") while not self.stopped.isSet(): try: code = lirc.nextcode() # list; empty if no buttons pressed except lirc.NextCodeError: _LOGGER.warning("Error reading next code from LIRC") code = None # interpret result from python-lirc if code: code = code[0] _LOGGER.info("Got new LIRC code %s", code) self.hass.bus.fire(EVENT_IR_COMMAND_RECEIVED, {BUTTON_NAME: code}) else: time.sleep(0.2) lirc.deinit() _LOGGER.debug("LIRC interface thread stopped")
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/lirc/__init__.py
"""Switches for the Elexa Guardian integration.""" from typing import Callable, Dict from aioguardian import Client from aioguardian.errors import GuardianError import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_FILENAME, CONF_PORT, CONF_URL from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import GuardianEntity from .const import API_VALVE_STATUS, DATA_CLIENT, DATA_COORDINATOR, DOMAIN, LOGGER ATTR_AVG_CURRENT = "average_current" ATTR_INST_CURRENT = "instantaneous_current" ATTR_INST_CURRENT_DDT = "instantaneous_current_ddt" ATTR_TRAVEL_COUNT = "travel_count" SERVICE_DISABLE_AP = "disable_ap" SERVICE_ENABLE_AP = "enable_ap" SERVICE_REBOOT = "reboot" SERVICE_RESET_VALVE_DIAGNOSTICS = "reset_valve_diagnostics" SERVICE_UPGRADE_FIRMWARE = "upgrade_firmware" async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable ) -> None: """Set up Guardian switches based on a config entry.""" platform = entity_platform.current_platform.get() for service_name, schema, method in [ (SERVICE_DISABLE_AP, {}, "async_disable_ap"), (SERVICE_ENABLE_AP, {}, "async_enable_ap"), (SERVICE_REBOOT, {}, "async_reboot"), (SERVICE_RESET_VALVE_DIAGNOSTICS, {}, "async_reset_valve_diagnostics"), ( SERVICE_UPGRADE_FIRMWARE, { vol.Optional(CONF_URL): cv.url, vol.Optional(CONF_PORT): cv.port, vol.Optional(CONF_FILENAME): cv.string, }, "async_upgrade_firmware", ), ]: platform.async_register_entity_service(service_name, schema, method) async_add_entities( [ GuardianSwitch( entry, hass.data[DOMAIN][DATA_CLIENT][entry.entry_id], hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id], ) ], True, ) class GuardianSwitch(GuardianEntity, SwitchEntity): """Define a switch to open/close the Guardian valve.""" def __init__( self, entry: ConfigEntry, client: Client, coordinators: Dict[str, DataUpdateCoordinator], ): """Initialize.""" super().__init__( entry, client, coordinators, "valve", "Valve", None, "mdi:water" ) self._is_on = True @property def available(self) -> bool: """Return whether the entity is available.""" return self._coordinators[API_VALVE_STATUS].last_update_success @property def is_on(self) -> bool: """Return True if the valve is open.""" return self._is_on async def _async_internal_added_to_hass(self): """Register API interest (and related tasks) when the entity is added.""" self.async_add_coordinator_update_listener(API_VALVE_STATUS) @callback def _async_update_from_latest_data(self) -> None: """Update the entity.""" self._is_on = self._coordinators[API_VALVE_STATUS].data["state"] in ( "start_opening", "opening", "finish_opening", "opened", ) self._attrs.update( { ATTR_AVG_CURRENT: self._coordinators[API_VALVE_STATUS].data[ "average_current" ], ATTR_INST_CURRENT: self._coordinators[API_VALVE_STATUS].data[ "instantaneous_current" ], ATTR_INST_CURRENT_DDT: self._coordinators[API_VALVE_STATUS].data[ "instantaneous_current_ddt" ], ATTR_TRAVEL_COUNT: self._coordinators[API_VALVE_STATUS].data[ "travel_count" ], } ) async def async_disable_ap(self): """Disable the device's onboard access point.""" try: async with self._client: await self._client.wifi.disable_ap() except GuardianError as err: LOGGER.error("Error during service call: %s", err) async def async_enable_ap(self): """Enable the device's onboard access point.""" try: async with self._client: await self._client.wifi.enable_ap() except GuardianError as err: LOGGER.error("Error during service call: %s", err) async def async_reboot(self): """Reboot the device.""" try: async with self._client: await self._client.system.reboot() except GuardianError as err: LOGGER.error("Error during service call: %s", err) async def async_reset_valve_diagnostics(self): """Fully reset system motor diagnostics.""" try: async with self._client: await self._client.valve.reset() except GuardianError as err: LOGGER.error("Error during service call: %s", err) async def async_upgrade_firmware(self, *, url, port, filename): """Upgrade the device firmware.""" try: async with self._client: await self._client.system.upgrade_firmware( url=url, port=port, filename=filename, ) except GuardianError as err: LOGGER.error("Error during service call: %s", err) async def async_turn_off(self, **kwargs) -> None: """Turn the valve off (closed).""" try: async with self._client: await self._client.valve.close() except GuardianError as err: LOGGER.error("Error while closing the valve: %s", err) return self._is_on = False self.async_write_ha_state() async def async_turn_on(self, **kwargs) -> None: """Turn the valve on (open).""" try: async with self._client: await self._client.valve.open() except GuardianError as err: LOGGER.error("Error while opening the valve: %s", err) return self._is_on = True self.async_write_ha_state()
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/guardian/switch.py
"""Config flow to configure Coolmaster.""" from pycoolmasternet import CoolMasterNet import voluptuous as vol from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_PORT # pylint: disable=unused-import from .const import AVAILABLE_MODES, CONF_SUPPORTED_MODES, DEFAULT_PORT, DOMAIN MODES_SCHEMA = {vol.Required(mode, default=True): bool for mode in AVAILABLE_MODES} DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str, **MODES_SCHEMA}) async def _validate_connection(hass: core.HomeAssistant, host): cool = CoolMasterNet(host, port=DEFAULT_PORT) devices = await hass.async_add_executor_job(cool.devices) return bool(devices) class CoolmasterConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Coolmaster config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL @core.callback def _async_get_entry(self, data): supported_modes = [ key for (key, value) in data.items() if key in AVAILABLE_MODES and value ] return self.async_create_entry( title=data[CONF_HOST], data={ CONF_HOST: data[CONF_HOST], CONF_PORT: DEFAULT_PORT, CONF_SUPPORTED_MODES: supported_modes, }, ) async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is None: return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA) errors = {} host = user_input[CONF_HOST] try: result = await _validate_connection(self.hass, host) if not result: errors["base"] = "no_units" except (ConnectionRefusedError, TimeoutError): errors["base"] = "connection_error" if errors: return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) return self._async_get_entry(user_input)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/coolmaster/config_flow.py
"""Support for LaMetric notifications.""" import logging from lmnotify import Model, SimpleFrame, Sound from oauthlib.oauth2 import TokenExpiredError from requests.exceptions import ConnectionError as RequestsConnectionError import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.const import CONF_ICON import homeassistant.helpers.config_validation as cv from . import DOMAIN as LAMETRIC_DOMAIN _LOGGER = logging.getLogger(__name__) AVAILABLE_PRIORITIES = ["info", "warning", "critical"] AVAILABLE_ICON_TYPES = ["none", "info", "alert"] CONF_CYCLES = "cycles" CONF_LIFETIME = "lifetime" CONF_PRIORITY = "priority" CONF_ICON_TYPE = "icon_type" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_ICON, default="a7956"): cv.string, vol.Optional(CONF_LIFETIME, default=10): cv.positive_int, vol.Optional(CONF_CYCLES, default=1): cv.positive_int, vol.Optional(CONF_PRIORITY, default="warning"): vol.In(AVAILABLE_PRIORITIES), vol.Optional(CONF_ICON_TYPE, default="info"): vol.In(AVAILABLE_ICON_TYPES), } ) def get_service(hass, config, discovery_info=None): """Get the LaMetric notification service.""" hlmn = hass.data.get(LAMETRIC_DOMAIN) return LaMetricNotificationService( hlmn, config[CONF_ICON], config[CONF_LIFETIME] * 1000, config[CONF_CYCLES], config[CONF_PRIORITY], config[CONF_ICON_TYPE], ) class LaMetricNotificationService(BaseNotificationService): """Implement the notification service for LaMetric.""" def __init__( self, hasslametricmanager, icon, lifetime, cycles, priority, icon_type ): """Initialize the service.""" self.hasslametricmanager = hasslametricmanager self._icon = icon self._lifetime = lifetime self._cycles = cycles self._priority = priority self._icon_type = icon_type self._devices = [] def send_message(self, message="", **kwargs): """Send a message to some LaMetric device.""" targets = kwargs.get(ATTR_TARGET) data = kwargs.get(ATTR_DATA) _LOGGER.debug("Targets/Data: %s/%s", targets, data) icon = self._icon cycles = self._cycles sound = None priority = self._priority icon_type = self._icon_type # Additional data? if data is not None: if "icon" in data: icon = data["icon"] if "sound" in data: try: sound = Sound(category="notifications", sound_id=data["sound"]) _LOGGER.debug("Adding notification sound %s", data["sound"]) except AssertionError: _LOGGER.error("Sound ID %s unknown, ignoring", data["sound"]) if "cycles" in data: cycles = int(data["cycles"]) if "icon_type" in data: if data["icon_type"] in AVAILABLE_ICON_TYPES: icon_type = data["icon_type"] else: _LOGGER.warning( "Priority %s invalid, using default %s", data["priority"], priority, ) if "priority" in data: if data["priority"] in AVAILABLE_PRIORITIES: priority = data["priority"] else: _LOGGER.warning( "Priority %s invalid, using default %s", data["priority"], priority, ) text_frame = SimpleFrame(icon, message) _LOGGER.debug( "Icon/Message/Cycles/Lifetime: %s, %s, %d, %d", icon, message, self._cycles, self._lifetime, ) frames = [text_frame] model = Model(frames=frames, cycles=cycles, sound=sound) lmn = self.hasslametricmanager.manager try: self._devices = lmn.get_devices() except TokenExpiredError: _LOGGER.debug("Token expired, fetching new token") lmn.get_token() self._devices = lmn.get_devices() except RequestsConnectionError: _LOGGER.warning( "Problem connecting to LaMetric, using cached devices instead" ) for dev in self._devices: if targets is None or dev["name"] in targets: try: lmn.set_device(dev) lmn.send_notification( model, lifetime=self._lifetime, priority=priority, icon_type=icon_type, ) _LOGGER.debug("Sent notification to LaMetric %s", dev["name"]) except OSError: _LOGGER.warning("Cannot connect to LaMetric %s", dev["name"])
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/lametric/notify.py
"""A platform which allows you to get information from Tautulli.""" from datetime import timedelta import logging from pytautulli import Tautulli import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_API_KEY, CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_PATH, CONF_PORT, CONF_SSL, CONF_VERIFY_SSL, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) CONF_MONITORED_USERS = "monitored_users" DEFAULT_NAME = "Tautulli" DEFAULT_PORT = "8181" DEFAULT_PATH = "" DEFAULT_SSL = False DEFAULT_VERIFY_SSL = True TIME_BETWEEN_UPDATES = timedelta(seconds=10) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_MONITORED_USERS): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.string, vol.Optional(CONF_PATH, default=DEFAULT_PATH): cv.string, vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Create the Tautulli sensor.""" name = config.get(CONF_NAME) host = config[CONF_HOST] port = config.get(CONF_PORT) path = config.get(CONF_PATH) api_key = config[CONF_API_KEY] monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) user = config.get(CONF_MONITORED_USERS) use_ssl = config[CONF_SSL] verify_ssl = config.get(CONF_VERIFY_SSL) session = async_get_clientsession(hass, verify_ssl) tautulli = TautulliData( Tautulli(host, port, api_key, hass.loop, session, use_ssl, path) ) if not await tautulli.test_connection(): raise PlatformNotReady sensor = [TautulliSensor(tautulli, name, monitored_conditions, user)] async_add_entities(sensor, True) class TautulliSensor(Entity): """Representation of a Tautulli sensor.""" def __init__(self, tautulli, name, monitored_conditions, users): """Initialize the Tautulli sensor.""" self.tautulli = tautulli self.monitored_conditions = monitored_conditions self.usernames = users self.sessions = {} self.home = {} self._attributes = {} self._name = name self._state = None async def async_update(self): """Get the latest data from the Tautulli API.""" await self.tautulli.async_update() self.home = self.tautulli.api.home_data self.sessions = self.tautulli.api.session_data self._attributes["Top Movie"] = self.home.get("movie") self._attributes["Top TV Show"] = self.home.get("tv") self._attributes["Top User"] = self.home.get("user") for key in self.sessions: if "sessions" not in key: self._attributes[key] = self.sessions[key] for user in self.tautulli.api.users: if self.usernames is None or user in self.usernames: userdata = self.tautulli.api.user_data self._attributes[user] = {} self._attributes[user]["Activity"] = userdata[user]["Activity"] if self.monitored_conditions: for key in self.monitored_conditions: try: self._attributes[user][key] = userdata[user][key] except (KeyError, TypeError): self._attributes[user][key] = "" @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self.sessions.get("stream_count") @property def icon(self): """Return the icon of the sensor.""" return "mdi:plex" @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return "Watching" @property def device_state_attributes(self): """Return attributes for the sensor.""" return self._attributes class TautulliData: """Get the latest data and update the states.""" def __init__(self, api): """Initialize the data object.""" self.api = api @Throttle(TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from Tautulli.""" await self.api.get_data() async def test_connection(self): """Test connection to Tautulli.""" await self.api.test_connection() connection_status = self.api.connection return connection_status
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/tautulli/sensor.py
"""Support for LIFX Cloud scenes.""" import asyncio import logging from typing import Any import aiohttp from aiohttp.hdrs import AUTHORIZATION import async_timeout import voluptuous as vol from homeassistant.components.scene import Scene from homeassistant.const import CONF_PLATFORM, CONF_TIMEOUT, CONF_TOKEN, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_TIMEOUT = 10 PLATFORM_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): "lifx_cloud", vol.Required(CONF_TOKEN): cv.string, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the scenes stored in the LIFX Cloud.""" token = config.get(CONF_TOKEN) timeout = config.get(CONF_TIMEOUT) headers = {AUTHORIZATION: f"Bearer {token}"} url = "https://api.lifx.com/v1/scenes" try: httpsession = async_get_clientsession(hass) with async_timeout.timeout(timeout): scenes_resp = await httpsession.get(url, headers=headers) except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.exception("Error on %s", url) return False status = scenes_resp.status if status == HTTP_OK: data = await scenes_resp.json() devices = [LifxCloudScene(hass, headers, timeout, scene) for scene in data] async_add_entities(devices) return True if status == 401: _LOGGER.error("Unauthorized (bad token?) on %s", url) return False _LOGGER.error("HTTP error %d on %s", scenes_resp.status, url) return False class LifxCloudScene(Scene): """Representation of a LIFX Cloud scene.""" def __init__(self, hass, headers, timeout, scene_data): """Initialize the scene.""" self.hass = hass self._headers = headers self._timeout = timeout self._name = scene_data["name"] self._uuid = scene_data["uuid"] @property def name(self): """Return the name of the scene.""" return self._name async def async_activate(self, **kwargs: Any) -> None: """Activate the scene.""" url = f"https://api.lifx.com/v1/scenes/scene_id:{self._uuid}/activate" try: httpsession = async_get_clientsession(self.hass) with async_timeout.timeout(self._timeout): await httpsession.put(url, headers=self._headers) except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.exception("Error on %s", url)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/lifx_cloud/scene.py
"""SMA Solar Webconnect interface.""" from datetime import timedelta import logging import pysma import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_SCAN_INTERVAL, CONF_SSL, CONF_VERIFY_SSL, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval _LOGGER = logging.getLogger(__name__) CONF_CUSTOM = "custom" CONF_FACTOR = "factor" CONF_GROUP = "group" CONF_KEY = "key" CONF_SENSORS = "sensors" CONF_UNIT = "unit" GROUPS = ["user", "installer"] def _check_sensor_schema(conf): """Check sensors and attributes are valid.""" try: valid = [s.name for s in pysma.Sensors()] except (ImportError, AttributeError): return conf customs = list(conf[CONF_CUSTOM].keys()) for sensor in conf[CONF_SENSORS]: if sensor in customs: _LOGGER.warning( "All custom sensors will be added automatically, no need to include them in sensors: %s", sensor, ) elif sensor not in valid: raise vol.Invalid(f"{sensor} does not exist") return conf CUSTOM_SCHEMA = vol.Any( { vol.Required(CONF_KEY): vol.All(cv.string, vol.Length(min=13, max=15)), vol.Required(CONF_UNIT): cv.string, vol.Optional(CONF_FACTOR, default=1): vol.Coerce(float), vol.Optional(CONF_PATH): vol.All(cv.ensure_list, [cv.string]), } ) PLATFORM_SCHEMA = vol.All( PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_SSL, default=False): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_GROUP, default=GROUPS[0]): vol.In(GROUPS), vol.Optional(CONF_SENSORS, default=[]): vol.Any( cv.schema_with_slug_keys(cv.ensure_list), # will be deprecated vol.All(cv.ensure_list, [str]), ), vol.Optional(CONF_CUSTOM, default={}): cv.schema_with_slug_keys( CUSTOM_SCHEMA ), }, extra=vol.PREVENT_EXTRA, ), _check_sensor_schema, ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up SMA WebConnect sensor.""" # Check config again during load - dependency available config = _check_sensor_schema(config) # Init all default sensors sensor_def = pysma.Sensors() # Sensor from the custom config sensor_def.add( [ pysma.Sensor(o[CONF_KEY], n, o[CONF_UNIT], o[CONF_FACTOR], o.get(CONF_PATH)) for n, o in config[CONF_CUSTOM].items() ] ) # Use all sensors by default config_sensors = config[CONF_SENSORS] hass_sensors = [] used_sensors = [] if isinstance(config_sensors, dict): # will be remove from 0.99 if not config_sensors: # Use all sensors by default config_sensors = {s.name: [] for s in sensor_def} # Prepare all Home Assistant sensor entities for name, attr in config_sensors.items(): sub_sensors = [sensor_def[s] for s in attr] hass_sensors.append(SMAsensor(sensor_def[name], sub_sensors)) used_sensors.append(name) used_sensors.extend(attr) if isinstance(config_sensors, list): if not config_sensors: # Use all sensors by default config_sensors = [s.name for s in sensor_def] used_sensors = list(set(config_sensors + list(config[CONF_CUSTOM].keys()))) for sensor in used_sensors: hass_sensors.append(SMAsensor(sensor_def[sensor], [])) used_sensors = [sensor_def[s] for s in set(used_sensors)] async_add_entities(hass_sensors) # Init the SMA interface session = async_get_clientsession(hass, verify_ssl=config[CONF_VERIFY_SSL]) grp = config[CONF_GROUP] protocol = "https" if config[CONF_SSL] else "http" url = f"{protocol}://{config[CONF_HOST]}" sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp) # Ensure we logout on shutdown async def async_close_session(event): """Close the session.""" await sma.close_session() hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_close_session) backoff = 0 backoff_step = 0 async def async_sma(event): """Update all the SMA sensors.""" nonlocal backoff, backoff_step if backoff > 1: backoff -= 1 return values = await sma.read(used_sensors) if not values: try: backoff = [1, 1, 1, 6, 30][backoff_step] backoff_step += 1 except IndexError: backoff = 60 return backoff_step = 0 for sensor in hass_sensors: sensor.async_update_values() interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5) async_track_time_interval(hass, async_sma, interval) class SMAsensor(Entity): """Representation of a SMA sensor.""" def __init__(self, pysma_sensor, sub_sensors): """Initialize the sensor.""" self._sensor = pysma_sensor self._sub_sensors = sub_sensors # Can be remove from 0.99 self._attr = {s.name: "" for s in sub_sensors} self._state = self._sensor.value @property def name(self): """Return the name of the sensor.""" return self._sensor.name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._sensor.unit @property def device_state_attributes(self): # Can be remove from 0.99 """Return the state attributes of the sensor.""" return self._attr @property def poll(self): """SMA sensors are updated & don't poll.""" return False @callback def async_update_values(self): """Update this sensor.""" update = False for sens in self._sub_sensors: # Can be remove from 0.99 newval = f"{sens.value} {sens.unit}" if self._attr[sens.name] != newval: update = True self._attr[sens.name] = newval if self._sensor.value != self._state: update = True self._state = self._sensor.value if update: self.async_write_ha_state() @property def unique_id(self): """Return a unique identifier for this sensor.""" return f"sma-{self._sensor.key}-{self._sensor.name}"
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/sma/sensor.py
"""Support for ComEd Hourly Pricing data.""" import asyncio from datetime import timedelta import json import logging import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, CONF_OFFSET from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) _RESOURCE = "https://hourlypricing.comed.com/api" SCAN_INTERVAL = timedelta(minutes=5) ATTRIBUTION = "Data provided by ComEd Hourly Pricing service" CONF_CURRENT_HOUR_AVERAGE = "current_hour_average" CONF_FIVE_MINUTE = "five_minute" CONF_MONITORED_FEEDS = "monitored_feeds" CONF_SENSOR_TYPE = "type" SENSOR_TYPES = { CONF_FIVE_MINUTE: ["ComEd 5 Minute Price", "c"], CONF_CURRENT_HOUR_AVERAGE: ["ComEd Current Hour Average Price", "c"], } TYPES_SCHEMA = vol.In(SENSOR_TYPES) SENSORS_SCHEMA = vol.Schema( { vol.Required(CONF_SENSOR_TYPE): TYPES_SCHEMA, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_OFFSET, default=0.0): vol.Coerce(float), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_MONITORED_FEEDS): [SENSORS_SCHEMA]} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ComEd Hourly Pricing sensor.""" websession = async_get_clientsession(hass) dev = [] for variable in config[CONF_MONITORED_FEEDS]: dev.append( ComedHourlyPricingSensor( hass.loop, websession, variable[CONF_SENSOR_TYPE], variable[CONF_OFFSET], variable.get(CONF_NAME), ) ) async_add_entities(dev, True) class ComedHourlyPricingSensor(Entity): """Implementation of a ComEd Hourly Pricing sensor.""" def __init__(self, loop, websession, sensor_type, offset, name): """Initialize the sensor.""" self.loop = loop self.websession = websession if name: self._name = name else: self._name = SENSOR_TYPES[sensor_type][0] self.type = sensor_type self.offset = offset self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def device_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} async def async_update(self): """Get the ComEd Hourly Pricing data from the web service.""" try: if self.type == CONF_FIVE_MINUTE or self.type == CONF_CURRENT_HOUR_AVERAGE: url_string = _RESOURCE if self.type == CONF_FIVE_MINUTE: url_string += "?type=5minutefeed" else: url_string += "?type=currenthouraverage" with async_timeout.timeout(60): response = await self.websession.get(url_string) # The API responds with MIME type 'text/html' text = await response.text() data = json.loads(text) self._state = round(float(data[0]["price"]) + self.offset, 2) else: self._state = None except (asyncio.TimeoutError, aiohttp.ClientError) as err: _LOGGER.error("Could not get data from ComEd API: %s", err) except (ValueError, KeyError): _LOGGER.warning("Could not update status for %s", self.name)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/comed_hourly_pricing/sensor.py
"""Support for Neato sensors.""" from datetime import timedelta import logging from pybotvac.exceptions import NeatoRobotException from homeassistant.components.sensor import DEVICE_CLASS_BATTERY from homeassistant.const import UNIT_PERCENTAGE from homeassistant.helpers.entity import Entity from .const import NEATO_DOMAIN, NEATO_LOGIN, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=SCAN_INTERVAL_MINUTES) BATTERY = "Battery" async def async_setup_entry(hass, entry, async_add_entities): """Set up the Neato sensor using config entry.""" dev = [] neato = hass.data.get(NEATO_LOGIN) for robot in hass.data[NEATO_ROBOTS]: dev.append(NeatoSensor(neato, robot)) if not dev: return _LOGGER.debug("Adding robots for sensors %s", dev) async_add_entities(dev, True) class NeatoSensor(Entity): """Neato sensor.""" def __init__(self, neato, robot): """Initialize Neato sensor.""" self.robot = robot self._available = neato.logged_in if neato is not None else False self._robot_name = f"{self.robot.name} {BATTERY}" self._robot_serial = self.robot.serial self._state = None def update(self): """Update Neato Sensor.""" try: self._state = self.robot.state except NeatoRobotException as ex: if self._available: _LOGGER.error( "Neato sensor connection error for '%s': %s", self.entity_id, ex ) self._state = None self._available = False return self._available = True _LOGGER.debug("self._state=%s", self._state) @property def name(self): """Return the name of this sensor.""" return self._robot_name @property def unique_id(self): """Return unique ID.""" return self._robot_serial @property def device_class(self): """Return the device class.""" return DEVICE_CLASS_BATTERY @property def available(self): """Return availability.""" return self._available @property def state(self): """Return the state.""" return self._state["details"]["charge"] @property def unit_of_measurement(self): """Return unit of measurement.""" return UNIT_PERCENTAGE @property def device_info(self): """Device info for neato robot.""" return {"identifiers": {(NEATO_DOMAIN, self._robot_serial)}}
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/neato/sensor.py
"""Support for the Environment Canada radar imagery.""" import datetime import logging from env_canada import ECRadar import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_UPDATED = "updated" CONF_ATTRIBUTION = "Data provided by Environment Canada" CONF_STATION = "station" CONF_LOOP = "loop" CONF_PRECIP_TYPE = "precip_type" MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(minutes=10) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_LOOP, default=True): cv.boolean, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_STATION): cv.matches_regex(r"^C[A-Z]{4}$|^[A-Z]{3}$"), vol.Inclusive(CONF_LATITUDE, "latlon"): cv.latitude, vol.Inclusive(CONF_LONGITUDE, "latlon"): cv.longitude, vol.Optional(CONF_PRECIP_TYPE): ["RAIN", "SNOW"], } ) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Environment Canada camera.""" if config.get(CONF_STATION): radar_object = ECRadar( station_id=config[CONF_STATION], precip_type=config.get(CONF_PRECIP_TYPE) ) else: lat = config.get(CONF_LATITUDE, hass.config.latitude) lon = config.get(CONF_LONGITUDE, hass.config.longitude) radar_object = ECRadar( coordinates=(lat, lon), precip_type=config.get(CONF_PRECIP_TYPE) ) add_devices([ECCamera(radar_object, config.get(CONF_NAME))], True) class ECCamera(Camera): """Implementation of an Environment Canada radar camera.""" def __init__(self, radar_object, camera_name): """Initialize the camera.""" super().__init__() self.radar_object = radar_object self.camera_name = camera_name self.content_type = "image/gif" self.image = None self.timestamp = None def camera_image(self): """Return bytes of camera image.""" self.update() return self.image @property def name(self): """Return the name of the camera.""" if self.camera_name is not None: return self.camera_name return "Environment Canada Radar" @property def device_state_attributes(self): """Return the state attributes of the device.""" attr = {ATTR_ATTRIBUTION: CONF_ATTRIBUTION, ATTR_UPDATED: self.timestamp} return attr @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update radar image.""" if CONF_LOOP: self.image = self.radar_object.get_loop() else: self.image = self.radar_object.get_latest_frame() self.timestamp = self.radar_object.timestamp
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/environment_canada/camera.py
"""Support for binary sensor using I2C MCP23017 chip.""" import logging from adafruit_mcp230xx.mcp23017 import MCP23017 # pylint: disable=import-error import board # pylint: disable=import-error import busio # pylint: disable=import-error import digitalio # pylint: disable=import-error import voluptuous as vol from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity from homeassistant.const import DEVICE_DEFAULT_NAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_INVERT_LOGIC = "invert_logic" CONF_I2C_ADDRESS = "i2c_address" CONF_PINS = "pins" CONF_PULL_MODE = "pull_mode" MODE_UP = "UP" MODE_DOWN = "DOWN" DEFAULT_INVERT_LOGIC = False DEFAULT_I2C_ADDRESS = 0x20 DEFAULT_PULL_MODE = MODE_UP _SENSORS_SCHEMA = vol.Schema({cv.positive_int: cv.string}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PINS): _SENSORS_SCHEMA, vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, vol.Optional(CONF_PULL_MODE, default=DEFAULT_PULL_MODE): vol.All( vol.Upper, vol.In([MODE_UP, MODE_DOWN]) ), vol.Optional(CONF_I2C_ADDRESS, default=DEFAULT_I2C_ADDRESS): vol.Coerce(int), } ) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the MCP23017 binary sensors.""" pull_mode = config[CONF_PULL_MODE] invert_logic = config[CONF_INVERT_LOGIC] i2c_address = config[CONF_I2C_ADDRESS] i2c = busio.I2C(board.SCL, board.SDA) mcp = MCP23017(i2c, address=i2c_address) binary_sensors = [] pins = config[CONF_PINS] for pin_num, pin_name in pins.items(): pin = mcp.get_pin(pin_num) binary_sensors.append( MCP23017BinarySensor(pin_name, pin, pull_mode, invert_logic) ) add_devices(binary_sensors, True) class MCP23017BinarySensor(BinarySensorEntity): """Represent a binary sensor that uses MCP23017.""" def __init__(self, name, pin, pull_mode, invert_logic): """Initialize the MCP23017 binary sensor.""" self._name = name or DEVICE_DEFAULT_NAME self._pin = pin self._pull_mode = pull_mode self._invert_logic = invert_logic self._state = None self._pin.direction = digitalio.Direction.INPUT self._pin.pull = digitalio.Pull.UP @property def name(self): """Return the name of the sensor.""" return self._name @property def is_on(self): """Return the state of the entity.""" return self._state != self._invert_logic def update(self): """Update the GPIO state.""" self._state = self._pin.value
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/mcp23017/binary_sensor.py
"""Allows to configure a switch using BeagleBone Black GPIO.""" import logging import voluptuous as vol from homeassistant.components import bbb_gpio from homeassistant.components.switch import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME, DEVICE_DEFAULT_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import ToggleEntity _LOGGER = logging.getLogger(__name__) CONF_PINS = "pins" CONF_INITIAL = "initial" CONF_INVERT_LOGIC = "invert_logic" PIN_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_INITIAL, default=False): cv.boolean, vol.Optional(CONF_INVERT_LOGIC, default=False): cv.boolean, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_PINS, default={}): vol.Schema({cv.string: PIN_SCHEMA})} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the BeagleBone Black GPIO devices.""" pins = config[CONF_PINS] switches = [] for pin, params in pins.items(): switches.append(BBBGPIOSwitch(pin, params)) add_entities(switches) class BBBGPIOSwitch(ToggleEntity): """Representation of a BeagleBone Black GPIO.""" def __init__(self, pin, params): """Initialize the pin.""" self._pin = pin self._name = params[CONF_NAME] or DEVICE_DEFAULT_NAME self._state = params[CONF_INITIAL] self._invert_logic = params[CONF_INVERT_LOGIC] bbb_gpio.setup_output(self._pin) if self._state is False: bbb_gpio.write_output(self._pin, 1 if self._invert_logic else 0) else: bbb_gpio.write_output(self._pin, 0 if self._invert_logic else 1) @property def name(self): """Return the name of the switch.""" return self._name @property def should_poll(self): """No polling needed.""" return False @property def is_on(self): """Return true if device is on.""" return self._state def turn_on(self, **kwargs): """Turn the device on.""" bbb_gpio.write_output(self._pin, 0 if self._invert_logic else 1) self._state = True self.schedule_update_ha_state() def turn_off(self, **kwargs): """Turn the device off.""" bbb_gpio.write_output(self._pin, 1 if self._invert_logic else 0) self._state = False self.schedule_update_ha_state()
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/components/bbb_gpio/switch.py
"""All methods needed to bootstrap a Home Assistant instance.""" import asyncio import logging.handlers from timeit import default_timer as timer from types import ModuleType from typing import Awaitable, Callable, Optional, Set from homeassistant import config as conf_util, core, loader, requirements from homeassistant.config import async_notify_setup_error from homeassistant.const import EVENT_COMPONENT_LOADED, PLATFORM_FORMAT from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_COMPONENT = "component" DATA_SETUP_DONE = "setup_done" DATA_SETUP_STARTED = "setup_started" DATA_SETUP = "setup_tasks" DATA_DEPS_REQS = "deps_reqs_processed" SLOW_SETUP_WARNING = 10 # Since its possible for databases to be # upwards of 36GiB (or larger) in the wild # we wait up to 3 hours for startup SLOW_SETUP_MAX_WAIT = 10800 @core.callback def async_set_domains_to_be_loaded(hass: core.HomeAssistant, domains: Set[str]) -> None: """Set domains that are going to be loaded from the config. This will allow us to properly handle after_dependencies. """ hass.data[DATA_SETUP_DONE] = {domain: asyncio.Event() for domain in domains} def setup_component(hass: core.HomeAssistant, domain: str, config: ConfigType) -> bool: """Set up a component and all its dependencies.""" return asyncio.run_coroutine_threadsafe( async_setup_component(hass, domain, config), hass.loop ).result() async def async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.setdefault(DATA_SETUP, {}) if domain in setup_tasks: return await setup_tasks[domain] # type: ignore task = setup_tasks[domain] = hass.async_create_task( _async_setup_component(hass, domain, config) ) try: return await task # type: ignore finally: if domain in hass.data.get(DATA_SETUP_DONE, {}): hass.data[DATA_SETUP_DONE].pop(domain).set() async def _async_process_dependencies( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> bool: """Ensure all dependencies are set up.""" tasks = { dep: hass.loop.create_task(async_setup_component(hass, dep, config)) for dep in integration.dependencies } to_be_loaded = hass.data.get(DATA_SETUP_DONE, {}) for dep in integration.after_dependencies: if dep in to_be_loaded and dep not in hass.config.components: tasks[dep] = hass.loop.create_task(to_be_loaded[dep].wait()) if not tasks: return True _LOGGER.debug("Dependency %s will wait for %s", integration.domain, list(tasks)) results = await asyncio.gather(*tasks.values()) failed = [ domain for idx, domain in enumerate(integration.dependencies) if not results[idx] ] if failed: _LOGGER.error( "Unable to set up dependencies of %s. Setup failed for dependencies: %s", integration.domain, ", ".join(failed), ) return False return True async def _async_setup_component( hass: core.HomeAssistant, domain: str, config: ConfigType ) -> bool: """Set up a component for Home Assistant. This method is a coroutine. """ def log_error(msg: str, link: Optional[str] = None) -> None: """Log helper.""" _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) try: integration = await loader.async_get_integration(hass, domain) except loader.IntegrationNotFound: log_error("Integration not found.") return False # Validate all dependencies exist and there are no circular dependencies if not await integration.resolve_dependencies(): return False # Process requirements as soon as possible, so we can import the component # without requiring imports to be in functions. try: await async_process_deps_reqs(hass, config, integration) except HomeAssistantError as err: log_error(str(err), integration.documentation) return False # Some integrations fail on import because they call functions incorrectly. # So we do it before validating config to catch these errors. try: component = integration.get_component() except ImportError as err: log_error(f"Unable to import component: {err}", integration.documentation) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Setup failed for %s: unknown error", domain) return False processed_config = await conf_util.async_process_component_config( hass, config, integration ) if processed_config is None: log_error("Invalid config.", integration.documentation) return False start = timer() _LOGGER.info("Setting up %s", domain) hass.data.setdefault(DATA_SETUP_STARTED, {})[domain] = dt_util.utcnow() if hasattr(component, "PLATFORM_SCHEMA"): # Entity components have their own warning warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING, ) try: if hasattr(component, "async_setup"): task = component.async_setup( # type: ignore hass, processed_config ) elif hasattr(component, "setup"): # This should not be replaced with hass.async_add_executor_job because # we don't want to track this task in case it blocks startup. task = hass.loop.run_in_executor( None, component.setup, hass, processed_config # type: ignore ) else: log_error("No setup function defined.") hass.data[DATA_SETUP_STARTED].pop(domain) return False result = await asyncio.wait_for(task, SLOW_SETUP_MAX_WAIT) except asyncio.TimeoutError: _LOGGER.error( "Setup of %s is taking longer than %s seconds." " Startup will proceed without waiting any longer", domain, SLOW_SETUP_MAX_WAIT, ) hass.data[DATA_SETUP_STARTED].pop(domain) return False except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, integration.documentation) hass.data[DATA_SETUP_STARTED].pop(domain) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds", domain, end - start) if result is False: log_error("Integration failed to initialize.") hass.data[DATA_SETUP_STARTED].pop(domain) return False if result is not True: log_error( f"Integration {domain!r} did not return boolean if setup was " "successful. Disabling component." ) hass.data[DATA_SETUP_STARTED].pop(domain) return False # Flush out async_setup calling create_task. Fragile but covered by test. await asyncio.sleep(0) await hass.config_entries.flow.async_wait_init_flow_finish(domain) await asyncio.gather( *[ entry.async_setup(hass, integration=integration) for entry in hass.config_entries.async_entries(domain) ] ) hass.config.components.add(domain) hass.data[DATA_SETUP_STARTED].pop(domain) # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: domain}) return True async def async_prepare_setup_platform( hass: core.HomeAssistant, hass_config: ConfigType, domain: str, platform_name: str ) -> Optional[ModuleType]: """Load a platform and makes sure dependencies are setup. This method is a coroutine. """ platform_path = PLATFORM_FORMAT.format(domain=domain, platform=platform_name) def log_error(msg: str) -> None: """Log helper.""" _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) try: integration = await loader.async_get_integration(hass, platform_name) except loader.IntegrationNotFound: log_error("Integration not found") return None # Process deps and reqs as soon as possible, so that requirements are # available when we import the platform. try: await async_process_deps_reqs(hass, hass_config, integration) except HomeAssistantError as err: log_error(str(err)) return None try: platform = integration.get_platform(domain) except ImportError as exc: log_error(f"Platform not found ({exc}).") return None # Already loaded if platform_path in hass.config.components: return platform # Platforms cannot exist on their own, they are part of their integration. # If the integration is not set up yet, and can be set up, set it up. if integration.domain not in hass.config.components: try: component = integration.get_component() except ImportError as exc: log_error(f"Unable to import the component ({exc}).") return None if hasattr(component, "setup") or hasattr(component, "async_setup"): if not await async_setup_component(hass, integration.domain, hass_config): log_error("Unable to set up component.") return None return platform async def async_process_deps_reqs( hass: core.HomeAssistant, config: ConfigType, integration: loader.Integration ) -> None: """Process all dependencies and requirements for a module. Module is a Python module of either a component or platform. """ processed = hass.data.get(DATA_DEPS_REQS) if processed is None: processed = hass.data[DATA_DEPS_REQS] = set() elif integration.domain in processed: return if not await _async_process_dependencies(hass, config, integration): raise HomeAssistantError("Could not set up all dependencies.") if not hass.config.skip_pip and integration.requirements: await requirements.async_get_integration_with_requirements( hass, integration.domain ) processed.add(integration.domain) @core.callback def async_when_setup( hass: core.HomeAssistant, component: str, when_setup_cb: Callable[[core.HomeAssistant, str], Awaitable[None]], ) -> None: """Call a method when a component is setup.""" async def when_setup() -> None: """Call the callback.""" try: await when_setup_cb(hass, component) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error handling when_setup callback for %s", component) # Running it in a new task so that it always runs after if component in hass.config.components: hass.async_create_task(when_setup()) return unsub = None async def loaded_event(event: core.Event) -> None: """Call the callback.""" if event.data[ATTR_COMPONENT] != component: return unsub() # type: ignore await when_setup() unsub = hass.bus.async_listen(EVENT_COMPONENT_LOADED, loaded_event)
"""Tests for light platform.""" from typing import Callable, NamedTuple from pyHS100 import SmartDeviceException import pytest from homeassistant.components import tplink from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, DOMAIN as LIGHT_DOMAIN, ) from homeassistant.components.tplink.common import ( CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, ) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.async_mock import Mock, PropertyMock, patch class LightMockData(NamedTuple): """Mock light data.""" sys_info: dict light_state: dict set_light_state: Callable[[dict], None] set_light_state_mock: Mock get_light_state_mock: Mock current_consumption_mock: Mock get_sysinfo_mock: Mock get_emeter_daily_mock: Mock get_emeter_monthly_mock: Mock class SmartSwitchMockData(NamedTuple): """Mock smart switch data.""" sys_info: dict state_mock: Mock brightness_mock: Mock get_sysinfo_mock: Mock @pytest.fixture(name="light_mock_data") def light_mock_data_fixture() -> None: """Create light mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "light", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "light1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": True, "is_dimmable": True, "is_variable_color_temp": True, "model": "LB120", "alias": "light1", } light_state = { "on_off": True, "dft_on_state": { "brightness": 12, "color_temp": 3200, "hue": 110, "saturation": 90, }, "brightness": 13, "color_temp": 3300, "hue": 110, "saturation": 90, } def set_light_state(state) -> None: nonlocal light_state drt_on_state = light_state["dft_on_state"] drt_on_state.update(state.get("dft_on_state", {})) light_state.update(state) light_state["dft_on_state"] = drt_on_state return light_state set_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.set_light_state", side_effect=set_light_state, ) get_light_state_patch = patch( "homeassistant.components.tplink.common.SmartBulb.get_light_state", return_value=light_state, ) current_consumption_patch = patch( "homeassistant.components.tplink.common.SmartDevice.current_consumption", return_value=3.23, ) get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) get_emeter_daily_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_daily", return_value={ 1: 1.01, 2: 1.02, 3: 1.03, 4: 1.04, 5: 1.05, 6: 1.06, 7: 1.07, 8: 1.08, 9: 1.09, 10: 1.10, 11: 1.11, 12: 1.12, }, ) get_emeter_monthly_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_emeter_monthly", return_value={ 1: 2.01, 2: 2.02, 3: 2.03, 4: 2.04, 5: 2.05, 6: 2.06, 7: 2.07, 8: 2.08, 9: 2.09, 10: 2.10, 11: 2.11, 12: 2.12, }, ) with set_light_state_patch as set_light_state_mock, get_light_state_patch as get_light_state_mock, current_consumption_patch as current_consumption_mock, get_sysinfo_patch as get_sysinfo_mock, get_emeter_daily_patch as get_emeter_daily_mock, get_emeter_monthly_patch as get_emeter_monthly_mock: yield LightMockData( sys_info=sys_info, light_state=light_state, set_light_state=set_light_state, set_light_state_mock=set_light_state_mock, get_light_state_mock=get_light_state_mock, current_consumption_mock=current_consumption_mock, get_sysinfo_mock=get_sysinfo_mock, get_emeter_daily_mock=get_emeter_daily_mock, get_emeter_monthly_mock=get_emeter_monthly_mock, ) @pytest.fixture(name="dimmer_switch_mock_data") def dimmer_switch_mock_data_fixture() -> None: """Create dimmer switch mock data.""" sys_info = { "sw_ver": "1.2.3", "hw_ver": "2.3.4", "mac": "aa:bb:cc:dd:ee:ff", "mic_mac": "00:11:22:33:44", "type": "switch", "hwId": "1234", "fwId": "4567", "oemId": "891011", "dev_name": "dimmer1", "rssi": 11, "latitude": "0", "longitude": "0", "is_color": False, "is_dimmable": True, "is_variable_color_temp": False, "model": "HS220", "alias": "dimmer1", "feature": ":", "relay_state": 1, "brightness": 13, } def state(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["relay_state"] if args[0] == "ON": sys_info["relay_state"] = 1 else: sys_info["relay_state"] = 0 def brightness(*args, **kwargs): nonlocal sys_info if len(args) == 0: return sys_info["brightness"] if sys_info["brightness"] == 0: sys_info["relay_state"] = 0 else: sys_info["relay_state"] = 1 sys_info["brightness"] = args[0] get_sysinfo_patch = patch( "homeassistant.components.tplink.common.SmartDevice.get_sysinfo", return_value=sys_info, ) state_patch = patch( "homeassistant.components.tplink.common.SmartPlug.state", new_callable=PropertyMock, side_effect=state, ) brightness_patch = patch( "homeassistant.components.tplink.common.SmartPlug.brightness", new_callable=PropertyMock, side_effect=brightness, ) with brightness_patch as brightness_mock, state_patch as state_mock, get_sysinfo_patch as get_sysinfo_mock: yield SmartSwitchMockData( sys_info=sys_info, brightness_mock=brightness_mock, state_mock=state_mock, get_sysinfo_mock=get_sysinfo_mock, ) async def update_entity(hass: HomeAssistant, entity_id: str) -> None: """Run an update action for an entity.""" await hass.services.async_call( HA_DOMAIN, SERVICE_UPDATE_ENTITY, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() async def test_smartswitch( hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData ) -> None: """Test function.""" sys_info = dimmer_switch_mock_data.sys_info await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_DIMMER: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.dimmer1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") assert hass.states.get("light.dimmer1").state == "off" assert sys_info["relay_state"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert sys_info["relay_state"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1", ATTR_BRIGHTNESS: 55}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert sys_info["brightness"] == 22 sys_info["relay_state"] = 0 sys_info["brightness"] = 66 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.dimmer1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.dimmer1") state = hass.states.get("light.dimmer1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert sys_info["brightness"] == 66 async def test_light(hass: HomeAssistant, light_mock_data: LightMockData) -> None: """Test function.""" light_state = light_mock_data.light_state set_light_state = light_mock_data.set_light_state await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() assert hass.states.get("light.light1") await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert hass.states.get("light.light1").state == "off" assert light_state["on_off"] == 0 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_COLOR_TEMP: 222, ATTR_BRIGHTNESS: 50}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 51 assert state.attributes["hs_color"] == (110, 90) assert state.attributes["color_temp"] == 222 assert light_state["on_off"] == 1 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1", ATTR_BRIGHTNESS: 55, ATTR_HS_COLOR: (23, 27)}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 56 assert state.attributes["hs_color"] == (23, 27) assert light_state["brightness"] == 22 assert light_state["hue"] == 23 assert light_state["saturation"] == 27 light_state["on_off"] = 0 light_state["dft_on_state"]["on_off"] = 0 light_state["brightness"] = 66 light_state["dft_on_state"]["brightness"] = 66 light_state["color_temp"] = 6400 light_state["dft_on_state"]["color_temp"] = 123 light_state["hue"] = 77 light_state["dft_on_state"]["hue"] = 77 light_state["saturation"] = 78 light_state["dft_on_state"]["saturation"] = 78 await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "off" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.state == "on" assert state.attributes["brightness"] == 168 assert state.attributes["hs_color"] == (77, 78) assert state.attributes["color_temp"] == 156 assert light_state["brightness"] == 66 assert light_state["hue"] == 77 assert light_state["saturation"] == 78 set_light_state({"brightness": 91, "dft_on_state": {"brightness": 91}}) await update_entity(hass, "light.light1") state = hass.states.get("light.light1") assert state.attributes["brightness"] == 232 async def test_get_light_state_retry( hass: HomeAssistant, light_mock_data: LightMockData ) -> None: """Test function.""" # Setup test for retries for sysinfo. get_sysinfo_call_count = 0 def get_sysinfo_side_effect(): nonlocal get_sysinfo_call_count get_sysinfo_call_count += 1 # Need to fail on the 2nd call because the first call is used to # determine if the device is online during the light platform's # setup hook. if get_sysinfo_call_count == 2: raise SmartDeviceException() return light_mock_data.sys_info light_mock_data.get_sysinfo_mock.side_effect = get_sysinfo_side_effect # Setup test for retries of getting state information. get_state_call_count = 0 def get_light_state_side_effect(): nonlocal get_state_call_count get_state_call_count += 1 if get_state_call_count == 1: raise SmartDeviceException() return light_mock_data.light_state light_mock_data.get_light_state_mock.side_effect = get_light_state_side_effect # Setup test for retries of setting state information. set_state_call_count = 0 def set_light_state_side_effect(state_data: dict): nonlocal set_state_call_count, light_mock_data set_state_call_count += 1 if set_state_call_count == 1: raise SmartDeviceException() return light_mock_data.set_light_state(state_data) light_mock_data.set_light_state_mock.side_effect = set_light_state_side_effect # Setup component. await async_setup_component(hass, HA_DOMAIN, {}) await hass.async_block_till_done() await async_setup_component( hass, tplink.DOMAIN, { tplink.DOMAIN: { CONF_DISCOVERY: False, CONF_LIGHT: [{CONF_HOST: "123.123.123.123"}], } }, ) await hass.async_block_till_done() await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "light.light1"}, blocking=True, ) await hass.async_block_till_done() await update_entity(hass, "light.light1") assert light_mock_data.get_sysinfo_mock.call_count > 1 assert light_mock_data.get_light_state_mock.call_count > 1 assert light_mock_data.set_light_state_mock.call_count > 1 assert light_mock_data.get_sysinfo_mock.call_count < 40 assert light_mock_data.get_light_state_mock.call_count < 40 assert light_mock_data.set_light_state_mock.call_count < 10
mKeRix/home-assistant
tests/components/tplink/test_light.py
homeassistant/setup.py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..core.has_props import abstract from ..core.properties import ( AnyRef, Bool, Int, NonNullable, Nullable, RestrictedDict, Seq, String, ) from ..model import Model #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'BooleanFilter', 'CustomJSFilter', 'Filter', 'GroupFilter', 'IndexFilter', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- @abstract class Filter(Model): ''' A Filter model represents a filtering operation that returns a row-wise subset of data when applied to a ``ColumnDataSource``. ''' class IndexFilter(Filter): ''' An ``IndexFilter`` filters data by returning the subset of data at a given set of indices. ''' indices = Nullable(Seq(Int), help=""" A list of integer indices representing the subset of data to select. """) def __init__(self, *args, **kw) -> None: if len(args) == 1 and "indices" not in kw: kw["indices"] = args[0] super().__init__(**kw) class BooleanFilter(Filter): ''' A ``BooleanFilter`` filters data by returning the subset of data corresponding to indices where the values of the booleans array is True. ''' booleans = Nullable(Seq(Bool), help=""" A list of booleans indicating which rows of data to select. """) def __init__(self, *args, **kw) -> None: if len(args) == 1 and "booleans" not in kw: kw["booleans"] = args[0] super().__init__(**kw) class GroupFilter(Filter): ''' A ``GroupFilter`` represents the rows of a ``ColumnDataSource`` where the values of the categorical column column_name match the group variable. ''' column_name = NonNullable(String, help=""" The name of the column to perform the group filtering operation on. """) group = NonNullable(String, help=""" The value of the column indicating the rows of data to keep. """) def __init__(self, *args, **kw) -> None: if len(args) == 2 and "column_name" not in kw and "group" not in kw: kw["column_name"] = args[0] kw["group"] = args[1] super().__init__(**kw) class CustomJSFilter(Filter): ''' Filter data sources with a custom defined JavaScript function. .. warning:: The explicit purpose of this Bokeh Model is to embed *raw JavaScript code* for a browser to execute. If any part of the code is derived from untrusted user inputs, then you must take appropriate care to sanitize the user input prior to passing to Bokeh. ''' args = RestrictedDict(String, AnyRef, disallow=("source",), help=""" A mapping of names to Python objects. In particular those can be bokeh's models. These objects are made available to the callback's code snippet as the values of named parameters to the callback. """) code = String(default="", help=""" A snippet of JavaScript code to filter data contained in a columnar data source. The code is made into the body of a function, and all of of the named objects in ``args`` are available as parameters that the code can use. The variable ``source`` will contain the data source that is associated with the ``CDSView`` this filter is added to. The code should either return the indices of the subset or an array of booleans to use to subset data source rows. Example: .. code-block code = ''' const indices = [] for (let i = 0; i <= source.data['some_column'].length; i++) { if (source.data['some_column'][i] == 'some_value') { indices.push(i) } } return indices ''' """) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from typing import TYPE_CHECKING, Tuple # External imports from flaky import flaky if TYPE_CHECKING: from selenium.webdriver.remote.webdriver import WebDriver # Bokeh imports from bokeh.core.validation import silenced from bokeh.core.validation.warnings import MISSING_RENDERERS from bokeh.io.webdriver import webdriver_control from bokeh.layouts import row from bokeh.models import ( ColumnDataSource, Plot, Range1d, Rect, ) from bokeh.plotting import figure from bokeh.resources import Resources # Module under test import bokeh.io.export as bie # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- @pytest.fixture(scope="module", params=["chromium", "firefox"]) def webdriver(request: pytest.FixtureRequest): driver = webdriver_control.create(request.param) try: yield driver finally: webdriver_control.terminate(driver) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- @flaky(max_runs=10) @pytest.mark.selenium @pytest.mark.parametrize("dimensions", [(14, 14), (44, 44), (144, 144), (444, 444), (1444, 1444)]) def test_get_screenshot_as_png(webdriver: WebDriver, dimensions: Tuple[int, int]) -> None: width, height = dimensions border = 5 layout = Plot(x_range=Range1d(), y_range=Range1d(), height=width, width=height, min_border=border, hidpi=False, toolbar_location=None, outline_line_color=None, background_fill_color="#00ff00", border_fill_color="#00ff00") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(layout, driver=webdriver) # a WxHpx image of white pixels assert png.size == (width, height) data = png.tobytes() assert len(data) == 4*width*height assert data == b"\x00\xff\x00\xff"*width*height @flaky(max_runs=10) @pytest.mark.selenium @pytest.mark.parametrize("dimensions", [(14, 14), (44, 44), (144, 144), (444, 444), (1444, 1444)]) def test_get_screenshot_as_png_with_glyph(webdriver: WebDriver, dimensions: Tuple[int, int]) -> None: width, height = dimensions border = 5 layout = Plot(x_range=Range1d(-1, 1), y_range=Range1d(-1, 1), height=width, width=height, toolbar_location=None, min_border=border, hidpi=False, outline_line_color=None, background_fill_color="#00ff00", border_fill_color="#00ff00") glyph = Rect(x="x", y="y", width=2, height=2, fill_color="#ff0000", line_color="#ff0000") source = ColumnDataSource(data=dict(x=[0], y=[0])) layout.add_glyph(source, glyph) png = bie.get_screenshot_as_png(layout, driver=webdriver) assert png.size == (width, height) data = png.tobytes() assert len(data) == 4*width*height # count red pixels in center area count = 0 for x in range(width*height): pixel = data[x*4:x*4+4] if pixel == b"\xff\x00\x00\xff": count += 1 w, h, b = width, height, border expected_count = w*h - 2*b*(w + h) + 4*b**2 assert count == expected_count @flaky(max_runs=10) @pytest.mark.selenium def test_get_screenshot_as_png_with_unicode_minified(webdriver: WebDriver) -> None: p = figure(title="유니 코드 지원을위한 작은 테스트") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=True)) assert len(png.tobytes()) > 0 @flaky(max_runs=10) @pytest.mark.selenium def test_get_screenshot_as_png_with_unicode_unminified(webdriver: WebDriver) -> None: p = figure(title="유니 코드 지원을위한 작은 테스트") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=False)) assert len(png.tobytes()) > 0 @flaky(max_runs=10) @pytest.mark.selenium def test_get_svg_no_svg_present() -> None: layout = Plot(x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None) with silenced(MISSING_RENDERERS): svgs = bie.get_svg(layout) assert svgs == [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<image width="20" height="20" preserveAspectRatio="none" xlink:href="' 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAbElEQVQ4T2P8//+/AwMDAwhTBTD+//+/gYGBoZ4' 'qpjEwMIwaCAnJN2/eMPz69YtgsLKxsTGIiIigqMMahs+ePWOQkpIiaCA2daMGQoJtNAxxJp+BSzbE5hRmZuYL4uLiBsheGC1tCJYHBBUAAA7h' 'kkaBfwzpAAAAAElFTkSuQmCC"/>' '</svg>', ] @flaky(max_runs=10) @pytest.mark.selenium def test_get_svg_with_svg_present(webdriver: WebDriver) -> None: plot = lambda color: Plot( x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color=color, output_backend="svg", ) layout = row([plot("red"), plot("blue")]) with silenced(MISSING_RENDERERS): svgs0 = bie.get_svg(layout, driver=webdriver) svgs1 = bie.get_svg(layout, driver=webdriver) svgs2 = [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="20">' '<defs/>' '<path fill="rgb(255,0,0)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '<g transform="matrix(1, 0, 0, 1, 20, 0)">' '<path fill="rgb(0,0,255)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</g>' '</svg>', ] assert svgs0 == svgs2 assert svgs1 == svgs2 @flaky(max_runs=10) @pytest.mark.selenium def test_get_svgs_no_svg_present() -> None: layout = Plot(x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None) with silenced(MISSING_RENDERERS): svgs = bie.get_svgs(layout) assert svgs == [] @flaky(max_runs=10) @pytest.mark.selenium def test_get_svgs_with_svg_present(webdriver: WebDriver) -> None: plot = lambda color: Plot( x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color=color, output_backend="svg", ) layout = row([plot("red"), plot("blue")]) with silenced(MISSING_RENDERERS): svgs0 = bie.get_svgs(layout, driver=webdriver) svgs1 = bie.get_svgs(layout, driver=webdriver) svgs2 = [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<path fill="rgb(255,0,0)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</svg>', '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<path fill="rgb(0,0,255)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</svg>', ] assert svgs0 == svgs2 assert svgs1 == svgs2 def test_get_layout_html_resets_plot_dims() -> None: initial_height, initial_width = 200, 250 layout = Plot(x_range=Range1d(), y_range=Range1d(), height=initial_height, width=initial_width) with silenced(MISSING_RENDERERS): bie.get_layout_html(layout, height=100, width=100) assert layout.height == initial_height assert layout.width == initial_width def test_layout_html_on_child_first() -> None: p = Plot(x_range=Range1d(), y_range=Range1d()) with silenced(MISSING_RENDERERS): bie.get_layout_html(p, height=100, width=100) with silenced(MISSING_RENDERERS): layout = row(p) bie.get_layout_html(layout) def test_layout_html_on_parent_first() -> None: p = Plot(x_range=Range1d(), y_range=Range1d()) with silenced(MISSING_RENDERERS): layout = row(p) bie.get_layout_html(layout) with silenced(MISSING_RENDERERS): bie.get_layout_html(p, height=100, width=100) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
bokeh/bokeh
tests/unit/bokeh/io/test_export.py
bokeh/models/filters.py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Display a variety of simple scatter marker shapes whose attributes can be associated with data columns from :class:`~bokeh.models.sources.ColumnDataSource` objects. .. warning:: The individual marker classes in this module are **deprecated since Bokeh 2.3.0.** Please replace all occurrences of ``Marker`` models with :class:`~bokeh.models.glyphs.Scatter` glyphs. For example: instead of ``Asterisk()``, use ``Scatter(marker="asterisk")``. For backwards compatibility, all markers in this module currently link to their respective replacements using the :class:`~bokeh.models.glyphs.Scatter` glyph. The full list of markers accessible through this module: .. toctree:: :maxdepth: 2 By definition, all markers accept the following set of properties: * ``x``, ``y`` position * ``size`` in pixels * ``line``, ``fill``, and ``hatch`` properties * ``angle`` The ``asterisk``, ``cross``, ``dash``, ``dot``, ``x``, and ``y`` only render line components. Those markers ignore any values that are passed to the ``fill`` and ``hatch`` properties. .. note:: When you draw ``circle`` markers with ``Scatter``, you can only assign a size in |screen units| (by passing a number of pixels to the ``size`` property). In case you want to define the radius of circles in |data units|, use the :class:`~bokeh.models.glyphs.Circle` glyph instead of the ``Scatter`` glyph. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ..util.deprecation import deprecated from . import glyphs from .glyphs import Circle, Marker, Scatter #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'Asterisk', 'Circle', 'CircleCross', 'CircleDot', 'CircleX', 'CircleY', 'Cross', 'Dash', 'Diamond', 'DiamondCross', 'DiamondDot', 'Dot', 'Hex', 'HexDot', 'InvertedTriangle', 'Marker', 'Plus', 'Scatter', 'Square', 'SquareCross', 'SquareDot', 'SquarePin', 'SquareX', 'Star', 'StarDot', 'Triangle', 'TriangleDot', 'TrianglePin', 'X', 'Y', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def Asterisk(*args, **kwargs): ''' Render asterisk '*' markers. (deprecated) ''' deprecated((2, 3, 0), "Asterisk()", "Scatter(marker='asterisk')") return Scatter(*args, **kwargs, marker="asterisk") def CircleCross(*args, **kwargs): ''' Render circle markers with a '+' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "CircleCross()", "Scatter(marker='circle_cross')") return Scatter(*args, **kwargs, marker="circle_cross") def CircleDot(*args, **kwargs): ''' Render circle markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "CircleDot()", "Scatter(marker='circle_dot')") return Scatter(*args, **kwargs, marker="circle_dot") def CircleX(*args, **kwargs): ''' Render circle markers with an 'X' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "CircleX()", "Scatter(marker='circle_x')") return Scatter(*args, **kwargs, marker="circle_x") def CircleY(*args, **kwargs): ''' Render circle markers with an 'Y' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "CircleY()", "Scatter(marker='circle_y')") return Scatter(*args, **kwargs, marker="circle_y") def Cross(*args, **kwargs): ''' Render '+' cross markers. (deprecated) ''' deprecated((2, 3, 0), "Cross()", "Scatter(marker='cross')") return Scatter(*args, **kwargs, marker="cross") def Dash(*args, **kwargs): ''' Render dash markers. (deprecated) ''' deprecated((2, 3, 0), "Dash()", "Scatter(marker='dash')") return Scatter(*args, **kwargs, marker="dash") def Diamond(*args, **kwargs): ''' Render diamond markers. (deprecated) ''' deprecated((2, 3, 0), "Diamond()", "Scatter(marker='diamond')") return Scatter(*args, **kwargs, marker="diamond") def DiamondCross(*args, **kwargs): ''' Render diamond markers with a '+' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "DiamondCross()", "Scatter(marker='diamond_cross')") return Scatter(*args, **kwargs, marker="diamond_cross") def DiamondDot(*args, **kwargs): ''' Render diamond markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "DiamondDot()", "Scatter(marker='diamond_dot')") return Scatter(*args, **kwargs, marker="diamond_dot") def Dot(*args, **kwargs): ''' Render dots (one-quarter radius circles). (deprecated) ''' deprecated((2, 3, 0), "Dot()", "Scatter(marker='dot')") return Scatter(*args, **kwargs, marker="dot") def Hex(*args, **kwargs): ''' Render hexagon markers. (deprecated) ''' deprecated((2, 3, 0), "Hex()", "Scatter(marker='hex')") return Scatter(*args, **kwargs, marker="hex") def HexDot(*args, **kwargs): ''' Render hexagon markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "HexDot()", "Scatter(marker='hex_dot')") return Scatter(*args, **kwargs, marker="hex_dot") def InvertedTriangle(*args, **kwargs): ''' Render upside-down triangle markers. (deprecated) ''' deprecated((2, 3, 0), "InvertedTriangle()", "Scatter(marker='inverted_triangle')") return Scatter(*args, **kwargs, marker="inverted_triangle") def Plus(*args, **kwargs): ''' Render filled plus markers ''' deprecated((2, 3, 0), "Plut()", "Scatter(marker='plus')") return Scatter(*args, **kwargs, marker="plus") def Square(*args, **kwargs): ''' Render square markers. (deprecated) ''' deprecated((2, 3, 0), "Square()", "Scatter(marker='square')") return Scatter(*args, **kwargs, marker="square") def SquareDot(*args, **kwargs): ''' Render square markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "SquareDot()", "Scatter(marker='square_dot')") return Scatter(*args, **kwargs, marker="square_dot") def SquarePin(*args, **kwargs): ''' Render pin-cushion square markers. (deprecated) ''' deprecated((2, 3, 0), "SquarePin()", "Scatter(marker='square_pin')") return Scatter(*args, **kwargs, marker="square_pin") def SquareCross(*args, **kwargs): ''' Render square markers with a '+' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "SquareCross()", "Scatter(marker='square_cross')") return Scatter(*args, **kwargs, marker="square_cross") def SquareX(*args, **kwargs): ''' Render square markers with an 'X' cross through the center. (deprecated) ''' deprecated((2, 3, 0), "SquareX()", "Scatter(marker='square_x')") return Scatter(*args, **kwargs, marker="square_x") def Star(*args, **kwargs): ''' Render star markers. (deprecated) ''' deprecated((2, 3, 0), "Star()", "Scatter(marker='star')") return Scatter(*args, **kwargs, marker="star") def StarDot(*args, **kwargs): ''' Render star markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "StarDot()", "Scatter(marker='star_dot')") return Scatter(*args, **kwargs, marker="star_dot") def Triangle(*args, **kwargs): ''' Render triangle markers. (deprecated) ''' deprecated((2, 3, 0), "Triangle()", "Scatter(marker='triangle')") return Scatter(*args, **kwargs, marker="triangle") def TriangleDot(*args, **kwargs): ''' Render triangle markers with center dots. (deprecated) ''' deprecated((2, 3, 0), "TriangleDot()", "Scatter(marker='triangle_dot')") return Scatter(*args, **kwargs, marker="triangle_dot") def TrianglePin(*args, **kwargs): ''' Render pin-cushion triangle markers. (deprecated) ''' deprecated((2, 3, 0), "TrianglePin()", "Scatter(marker='triangle_pin')") return Scatter(*args, **kwargs, marker="triangle_pin") def X(*args, **kwargs): ''' Render 'X' markers. (deprecated) ''' deprecated((2, 3, 0), "X()", "Scatter(marker='x')") return Scatter(*args, **kwargs, marker="x") def Y(*args, **kwargs): ''' Render 'Y' markers. (deprecated) ''' deprecated((2, 3, 0), "Y()", "Scatter(marker='y')") return Scatter(*args, **kwargs, marker="y") #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- marker_types = { "asterisk": Asterisk, "circle": Circle, "circle_cross": CircleCross, "circle_dot": CircleDot, "circle_x": CircleX, "circle_y": CircleY, "cross": Cross, "dash": Dash, "diamond": Diamond, "diamond_cross": DiamondCross, "diamond_dot": DiamondDot, "dot": Dot, "hex": Hex, "hex_dot": HexDot, "inverted_triangle": InvertedTriangle, "plus": Plus, "square": Square, "square_cross": SquareCross, "square_dot": SquareDot, "square_pin": SquarePin, "square_x": SquareX, "star": Star, "star_dot": StarDot, "triangle": Triangle, "triangle_dot": TriangleDot, "triangle_pin": TrianglePin, "x": X, "y": Y, } glyphs.Asterisk = Asterisk glyphs.CircleCross = CircleCross glyphs.CircleDot = CircleDot glyphs.CircleY = CircleY glyphs.CircleX = CircleX glyphs.Cross = Cross glyphs.Dash = Dash glyphs.Diamond = Diamond glyphs.DiamondCross = DiamondCross glyphs.DiamondDot = DiamondDot glyphs.Dot = Dot glyphs.Hex = Hex glyphs.HexDot = HexDot glyphs.InvertedTriangle = InvertedTriangle glyphs.Plus = Plus glyphs.Square = Square glyphs.SquareCross = SquareCross glyphs.SquareDot = SquareDot glyphs.SquarePin = SquarePin glyphs.SquareX = SquareX glyphs.Star = Star glyphs.StarDot = StarDot glyphs.Triangle = Triangle glyphs.TriangleDot = TriangleDot glyphs.TrianglePin = TrianglePin glyphs.X = X glyphs.Y = Y
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations # isort:skip import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from typing import TYPE_CHECKING, Tuple # External imports from flaky import flaky if TYPE_CHECKING: from selenium.webdriver.remote.webdriver import WebDriver # Bokeh imports from bokeh.core.validation import silenced from bokeh.core.validation.warnings import MISSING_RENDERERS from bokeh.io.webdriver import webdriver_control from bokeh.layouts import row from bokeh.models import ( ColumnDataSource, Plot, Range1d, Rect, ) from bokeh.plotting import figure from bokeh.resources import Resources # Module under test import bokeh.io.export as bie # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- @pytest.fixture(scope="module", params=["chromium", "firefox"]) def webdriver(request: pytest.FixtureRequest): driver = webdriver_control.create(request.param) try: yield driver finally: webdriver_control.terminate(driver) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- @flaky(max_runs=10) @pytest.mark.selenium @pytest.mark.parametrize("dimensions", [(14, 14), (44, 44), (144, 144), (444, 444), (1444, 1444)]) def test_get_screenshot_as_png(webdriver: WebDriver, dimensions: Tuple[int, int]) -> None: width, height = dimensions border = 5 layout = Plot(x_range=Range1d(), y_range=Range1d(), height=width, width=height, min_border=border, hidpi=False, toolbar_location=None, outline_line_color=None, background_fill_color="#00ff00", border_fill_color="#00ff00") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(layout, driver=webdriver) # a WxHpx image of white pixels assert png.size == (width, height) data = png.tobytes() assert len(data) == 4*width*height assert data == b"\x00\xff\x00\xff"*width*height @flaky(max_runs=10) @pytest.mark.selenium @pytest.mark.parametrize("dimensions", [(14, 14), (44, 44), (144, 144), (444, 444), (1444, 1444)]) def test_get_screenshot_as_png_with_glyph(webdriver: WebDriver, dimensions: Tuple[int, int]) -> None: width, height = dimensions border = 5 layout = Plot(x_range=Range1d(-1, 1), y_range=Range1d(-1, 1), height=width, width=height, toolbar_location=None, min_border=border, hidpi=False, outline_line_color=None, background_fill_color="#00ff00", border_fill_color="#00ff00") glyph = Rect(x="x", y="y", width=2, height=2, fill_color="#ff0000", line_color="#ff0000") source = ColumnDataSource(data=dict(x=[0], y=[0])) layout.add_glyph(source, glyph) png = bie.get_screenshot_as_png(layout, driver=webdriver) assert png.size == (width, height) data = png.tobytes() assert len(data) == 4*width*height # count red pixels in center area count = 0 for x in range(width*height): pixel = data[x*4:x*4+4] if pixel == b"\xff\x00\x00\xff": count += 1 w, h, b = width, height, border expected_count = w*h - 2*b*(w + h) + 4*b**2 assert count == expected_count @flaky(max_runs=10) @pytest.mark.selenium def test_get_screenshot_as_png_with_unicode_minified(webdriver: WebDriver) -> None: p = figure(title="유니 코드 지원을위한 작은 테스트") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=True)) assert len(png.tobytes()) > 0 @flaky(max_runs=10) @pytest.mark.selenium def test_get_screenshot_as_png_with_unicode_unminified(webdriver: WebDriver) -> None: p = figure(title="유니 코드 지원을위한 작은 테스트") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=False)) assert len(png.tobytes()) > 0 @flaky(max_runs=10) @pytest.mark.selenium def test_get_svg_no_svg_present() -> None: layout = Plot(x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None) with silenced(MISSING_RENDERERS): svgs = bie.get_svg(layout) assert svgs == [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<image width="20" height="20" preserveAspectRatio="none" xlink:href="' 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAbElEQVQ4T2P8//+/AwMDAwhTBTD+//+/gYGBoZ4' 'qpjEwMIwaCAnJN2/eMPz69YtgsLKxsTGIiIigqMMahs+ePWOQkpIiaCA2daMGQoJtNAxxJp+BSzbE5hRmZuYL4uLiBsheGC1tCJYHBBUAAA7h' 'kkaBfwzpAAAAAElFTkSuQmCC"/>' '</svg>', ] @flaky(max_runs=10) @pytest.mark.selenium def test_get_svg_with_svg_present(webdriver: WebDriver) -> None: plot = lambda color: Plot( x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color=color, output_backend="svg", ) layout = row([plot("red"), plot("blue")]) with silenced(MISSING_RENDERERS): svgs0 = bie.get_svg(layout, driver=webdriver) svgs1 = bie.get_svg(layout, driver=webdriver) svgs2 = [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="20">' '<defs/>' '<path fill="rgb(255,0,0)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '<g transform="matrix(1, 0, 0, 1, 20, 0)">' '<path fill="rgb(0,0,255)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</g>' '</svg>', ] assert svgs0 == svgs2 assert svgs1 == svgs2 @flaky(max_runs=10) @pytest.mark.selenium def test_get_svgs_no_svg_present() -> None: layout = Plot(x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None) with silenced(MISSING_RENDERERS): svgs = bie.get_svgs(layout) assert svgs == [] @flaky(max_runs=10) @pytest.mark.selenium def test_get_svgs_with_svg_present(webdriver: WebDriver) -> None: plot = lambda color: Plot( x_range=Range1d(), y_range=Range1d(), height=20, width=20, toolbar_location=None, outline_line_color=None, border_fill_color=None, background_fill_color=color, output_backend="svg", ) layout = row([plot("red"), plot("blue")]) with silenced(MISSING_RENDERERS): svgs0 = bie.get_svgs(layout, driver=webdriver) svgs1 = bie.get_svgs(layout, driver=webdriver) svgs2 = [ '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<path fill="rgb(255,0,0)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</svg>', '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20">' '<defs/>' '<path fill="rgb(0,0,255)" stroke="none" paint-order="stroke" d="M 5.5 5.5 L 15.5 5.5 L 15.5 15.5 L 5.5 15.5 L 5.5 5.5" fill-opacity="1"/>' '</svg>', ] assert svgs0 == svgs2 assert svgs1 == svgs2 def test_get_layout_html_resets_plot_dims() -> None: initial_height, initial_width = 200, 250 layout = Plot(x_range=Range1d(), y_range=Range1d(), height=initial_height, width=initial_width) with silenced(MISSING_RENDERERS): bie.get_layout_html(layout, height=100, width=100) assert layout.height == initial_height assert layout.width == initial_width def test_layout_html_on_child_first() -> None: p = Plot(x_range=Range1d(), y_range=Range1d()) with silenced(MISSING_RENDERERS): bie.get_layout_html(p, height=100, width=100) with silenced(MISSING_RENDERERS): layout = row(p) bie.get_layout_html(layout) def test_layout_html_on_parent_first() -> None: p = Plot(x_range=Range1d(), y_range=Range1d()) with silenced(MISSING_RENDERERS): layout = row(p) bie.get_layout_html(layout) with silenced(MISSING_RENDERERS): bie.get_layout_html(p, height=100, width=100) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
bokeh/bokeh
tests/unit/bokeh/io/test_export.py
bokeh/models/markers.py
# -*- coding: utf-8 -*- import functools from django.contrib.postgres.fields import ArrayField from django.db import models from osf.models.base import BaseModel, ObjectIDMixin def _serialize(fields, instance): return { field: getattr(instance, field if field != 'id' else 'license_id') for field in fields } serialize_node_license = functools.partial(_serialize, ('id', 'name', 'text')) def serialize_node_license_record(node_license_record): if node_license_record is None: return {} ret = serialize_node_license(node_license_record.node_license) ret.update(_serialize(('year', 'copyright_holders'), node_license_record)) return ret class NodeLicenseManager(models.Manager): PREPRINT_ONLY_LICENSES = { 'CCBYNCND', 'CCBYSA40', } def preprint_licenses(self): return self.all() def project_licenses(self): return self.exclude(license_id__in=self.PREPRINT_ONLY_LICENSES) class NodeLicense(ObjectIDMixin, BaseModel): license_id = models.CharField(max_length=128, null=False, unique=True) name = models.CharField(max_length=256, null=False, unique=True) text = models.TextField(null=False) url = models.URLField(blank=True) properties = ArrayField(models.CharField(max_length=128), default=list, blank=True) objects = NodeLicenseManager() def __unicode__(self): return '(license_id={}, name={})'.format(self.license_id, self.name) class Meta: unique_together = ['_id', 'license_id'] class NodeLicenseRecord(ObjectIDMixin, BaseModel): node_license = models.ForeignKey('NodeLicense', null=True, blank=True, on_delete=models.SET_NULL) # Deliberately left as a CharField to support year ranges (e.g. 2012-2015) year = models.CharField(max_length=128, null=True, blank=True) copyright_holders = ArrayField( models.CharField(max_length=256, blank=True, null=True), default=list, blank=True) def __unicode__(self): if self.node_license: return self.node_license.__unicode__() return super(NodeLicenseRecord, self).__unicode__() @property def name(self): return self.node_license.name if self.node_license else None @property def text(self): return self.node_license.text if self.node_license else None @property def license_id(self): return self.node_license.license_id if self.node_license else None @property def url(self): return self.node_license.url if self.node_license else None def to_json(self): return serialize_node_license_record(self) def copy(self): copied = NodeLicenseRecord( node_license=self.node_license, year=self.year, copyright_holders=self.copyright_holders ) copied.save() return copied
# -*- coding: utf-8 -*- import itsdangerous import mock from nose.tools import * # noqa: import unittest from django.utils import timezone import pytest from tests.base import ApiTestCase from osf_tests.factories import ( AuthUserFactory, ApiOAuth2ScopeFactory, ) from api.base.settings.defaults import API_BASE from framework.auth.cas import CasResponse from website import settings from osf.models import ApiOAuth2PersonalToken, Session from osf.utils.permissions import ADMIN @pytest.mark.enable_quickfiles_creation class TestWelcomeToApi(ApiTestCase): def setUp(self): super(TestWelcomeToApi, self).setUp() self.user = AuthUserFactory() self.url = '/{}'.format(API_BASE) def tearDown(self): self.app.reset() super(TestWelcomeToApi, self).tearDown() def test_returns_200_for_logged_out_user(self): res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal(res.json['meta']['current_user'], None) def test_returns_current_user_info_when_logged_in(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['given_name'], self.user.given_name ) def test_current_user_accepted_tos(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], False ) self.user.accepted_terms_of_service = timezone.now() self.user.save() res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_equal(res.content_type, 'application/vnd.api+json') assert_equal( res.json['meta']['current_user']['data']['attributes']['accepted_terms_of_service'], True ) def test_returns_302_redirect_for_base_url(self): res = self.app.get('/') assert_equal(res.status_code, 302) assert_equal(res.location, '/v2/') def test_cookie_has_admin(self): session = Session(data={'auth_user_id': self.user._id}) session.save() cookie = itsdangerous.Signer(settings.SECRET_KEY).sign(session._id) self.app.set_cookie(settings.COOKIE_NAME, str(cookie)) res = self.app.get(self.url) assert_equal(res.status_code, 200) assert_equal(res.json['meta'][ADMIN], True) def test_basic_auth_does_not_have_admin(self): res = self.app.get(self.url, auth=self.user.auth) assert_equal(res.status_code, 200) assert_not_in(ADMIN, res.json['meta'].keys()) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') # TODO: Remove when available outside of DEV_MODE @unittest.skipIf( not settings.DEV_MODE, 'DEV_MODE disabled, osf.admin unavailable' ) def test_admin_scoped_token_has_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'osf.admin' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_equal(res.json['meta'][ADMIN], True) @mock.patch('api.base.authentication.drf.OSFCASAuthentication.authenticate') def test_non_admin_scoped_token_does_not_have_admin(self, mock_auth): token = ApiOAuth2PersonalToken( owner=self.user, name='Admin Token', ) token.save() scope = ApiOAuth2ScopeFactory() scope.name = 'osf.full_write' scope.save() token.scopes.add(scope) mock_cas_resp = CasResponse( authenticated=True, user=self.user._id, attributes={ 'accessToken': token.token_id, 'accessTokenScope': [s.name for s in token.scopes.all()] } ) mock_auth.return_value = self.user, mock_cas_resp res = self.app.get( self.url, headers={ 'Authorization': 'Bearer {}'.format(token.token_id) } ) assert_equal(res.status_code, 200) assert_not_in(ADMIN, res.json['meta'].keys())
mfraezz/osf.io
api_tests/base/test_root.py
osf/models/licenses.py
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_blobs from sklearn.utils.class_weight import compute_class_weight from sklearn.utils.class_weight import compute_sample_weight from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raise_message def test_compute_class_weight(): # Test (and demo) compute_class_weight. y = np.asarray([2, 2, 2, 3, 3, 4]) classes = np.unique(y) cw = compute_class_weight("balanced", classes, y) # total effect of samples is preserved class_counts = np.bincount(y)[2:] assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) assert cw[0] < cw[1] < cw[2] def test_compute_class_weight_not_present(): # Raise error when y does not contain all class labels classes = np.arange(4) y = np.asarray([0, 0, 0, 1, 1, 2]) assert_raises(ValueError, compute_class_weight, "balanced", classes, y) # Fix exception in error message formatting when missing label is a string # https://github.com/scikit-learn/scikit-learn/issues/8312 assert_raise_message(ValueError, 'Class label label_not_present not present', compute_class_weight, {'label_not_present': 1.}, classes, y) # Raise error when y has items not in classes classes = np.arange(2) assert_raises(ValueError, compute_class_weight, "balanced", classes, y) assert_raises(ValueError, compute_class_weight, {0: 1., 1: 2.}, classes, y) def test_compute_class_weight_dict(): classes = np.arange(3) class_weights = {0: 1.0, 1: 2.0, 2: 3.0} y = np.asarray([0, 0, 1, 2]) cw = compute_class_weight(class_weights, classes, y) # When the user specifies class weights, compute_class_weights should just # return them. assert_array_almost_equal(np.asarray([1.0, 2.0, 3.0]), cw) # When a class weight is specified that isn't in classes, a ValueError # should get raised msg = 'Class label 4 not present.' class_weights = {0: 1.0, 1: 2.0, 2: 3.0, 4: 1.5} assert_raise_message(ValueError, msg, compute_class_weight, class_weights, classes, y) msg = 'Class label -1 not present.' class_weights = {-1: 5.0, 0: 1.0, 1: 2.0, 2: 3.0} assert_raise_message(ValueError, msg, compute_class_weight, class_weights, classes, y) def test_compute_class_weight_invariance(): # Test that results with class_weight="balanced" is invariant wrt # class imbalance if the number of samples is identical. # The test uses a balanced two class dataset with 100 datapoints. # It creates three versions, one where class 1 is duplicated # resulting in 150 points of class 1 and 50 of class 0, # one where there are 50 points in class 1 and 150 in class 0, # and one where there are 100 points of each class (this one is balanced # again). # With balancing class weights, all three should give the same model. X, y = make_blobs(centers=2, random_state=0) # create dataset where class 1 is duplicated twice X_1 = np.vstack([X] + [X[y == 1]] * 2) y_1 = np.hstack([y] + [y[y == 1]] * 2) # create dataset where class 0 is duplicated twice X_0 = np.vstack([X] + [X[y == 0]] * 2) y_0 = np.hstack([y] + [y[y == 0]] * 2) # duplicate everything X_ = np.vstack([X] * 2) y_ = np.hstack([y] * 2) # results should be identical logreg1 = LogisticRegression(class_weight="balanced").fit(X_1, y_1) logreg0 = LogisticRegression(class_weight="balanced").fit(X_0, y_0) logreg = LogisticRegression(class_weight="balanced").fit(X_, y_) assert_array_almost_equal(logreg1.coef_, logreg0.coef_) assert_array_almost_equal(logreg.coef_, logreg0.coef_) def test_compute_class_weight_balanced_negative(): # Test compute_class_weight when labels are negative # Test with balanced class labels. classes = np.array([-2, -1, 0]) y = np.asarray([-1, -1, 0, 0, -2, -2]) cw = compute_class_weight("balanced", classes, y) assert len(cw) == len(classes) assert_array_almost_equal(cw, np.array([1., 1., 1.])) # Test with unbalanced class labels. y = np.asarray([-1, 0, 0, -2, -2, -2]) cw = compute_class_weight("balanced", classes, y) assert len(cw) == len(classes) class_counts = np.bincount(y + 2) assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) assert_array_almost_equal(cw, [2. / 3, 2., 1.]) def test_compute_class_weight_balanced_unordered(): # Test compute_class_weight when classes are unordered classes = np.array([1, 0, 3]) y = np.asarray([1, 0, 0, 3, 3, 3]) cw = compute_class_weight("balanced", classes, y) class_counts = np.bincount(y)[classes] assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) assert_array_almost_equal(cw, [2., 1., 2. / 3]) def test_compute_class_weight_default(): # Test for the case where no weight is given for a present class. # Current behaviour is to assign the unweighted classes a weight of 1. y = np.asarray([2, 2, 2, 3, 3, 4]) classes = np.unique(y) classes_len = len(classes) # Test for non specified weights cw = compute_class_weight(None, classes, y) assert len(cw) == classes_len assert_array_almost_equal(cw, np.ones(3)) # Tests for partly specified weights cw = compute_class_weight({2: 1.5}, classes, y) assert len(cw) == classes_len assert_array_almost_equal(cw, [1.5, 1., 1.]) cw = compute_class_weight({2: 1.5, 4: 0.5}, classes, y) assert len(cw) == classes_len assert_array_almost_equal(cw, [1.5, 1., 0.5]) def test_compute_sample_weight(): # Test (and demo) compute_sample_weight. # Test with balanced classes y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("balanced", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with user-defined weights sample_weight = compute_sample_weight({1: 2, 2: 1}, y) assert_array_almost_equal(sample_weight, [2., 2., 2., 1., 1., 1.]) # Test with column vector of balanced classes y = np.asarray([[1], [1], [1], [2], [2], [2]]) sample_weight = compute_sample_weight("balanced", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with unbalanced classes y = np.asarray([1, 1, 1, 2, 2, 2, 3]) sample_weight = compute_sample_weight("balanced", y) expected_balanced = np.array([0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 2.3333]) assert_array_almost_equal(sample_weight, expected_balanced, decimal=4) # Test with `None` weights sample_weight = compute_sample_weight(None, y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 1.]) # Test with multi-output of balanced classes y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight("balanced", y) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with multi-output with user-defined weights y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) assert_array_almost_equal(sample_weight, [2., 2., 2., 2., 2., 2.]) # Test with multi-output of unbalanced classes y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) sample_weight = compute_sample_weight("balanced", y) assert_array_almost_equal(sample_weight, expected_balanced ** 2, decimal=3) def test_compute_sample_weight_with_subsample(): # Test compute_sample_weight with subsamples specified. # Test with balanced classes and all samples present y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("balanced", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with column vector of balanced classes and all samples present y = np.asarray([[1], [1], [1], [2], [2], [2]]) sample_weight = compute_sample_weight("balanced", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1.]) # Test with a subsample y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("balanced", y, range(4)) assert_array_almost_equal(sample_weight, [2. / 3, 2. / 3, 2. / 3, 2., 2., 2.]) # Test with a bootstrap subsample y = np.asarray([1, 1, 1, 2, 2, 2]) sample_weight = compute_sample_weight("balanced", y, [0, 1, 1, 2, 2, 3]) expected_balanced = np.asarray([0.6, 0.6, 0.6, 3., 3., 3.]) assert_array_almost_equal(sample_weight, expected_balanced) # Test with a bootstrap subsample for multi-output y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) sample_weight = compute_sample_weight("balanced", y, [0, 1, 1, 2, 2, 3]) assert_array_almost_equal(sample_weight, expected_balanced ** 2) # Test with a missing class y = np.asarray([1, 1, 1, 2, 2, 2, 3]) sample_weight = compute_sample_weight("balanced", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) # Test with a missing class for multi-output y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) sample_weight = compute_sample_weight("balanced", y, range(6)) assert_array_almost_equal(sample_weight, [1., 1., 1., 1., 1., 1., 0.]) def test_compute_sample_weight_errors(): # Test compute_sample_weight raises errors expected. # Invalid preset string y = np.asarray([1, 1, 1, 2, 2, 2]) y_ = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) assert_raises(ValueError, compute_sample_weight, "ni", y) assert_raises(ValueError, compute_sample_weight, "ni", y, range(4)) assert_raises(ValueError, compute_sample_weight, "ni", y_) assert_raises(ValueError, compute_sample_weight, "ni", y_, range(4)) # Not "balanced" for subsample assert_raises(ValueError, compute_sample_weight, {1: 2, 2: 1}, y, range(4)) # Not a list or preset for multi-output assert_raises(ValueError, compute_sample_weight, {1: 2, 2: 1}, y_) # Incorrect length list for multi-output assert_raises(ValueError, compute_sample_weight, [{1: 2, 2: 1}], y_) def test_compute_sample_weight_more_than_32(): # Non-regression smoke test for #12146 y = np.arange(50) # more than 32 distinct classes indices = np.arange(50) # use subsampling weight = compute_sample_weight('balanced', y, indices=indices) assert_array_almost_equal(weight, np.ones(y.shape[0]))
import numpy as np from numpy.testing import assert_array_almost_equal import pytest from sklearn.neighbors.kd_tree import (KDTree, NeighborsHeap, simultaneous_sort, kernel_norm, nodeheap_sort, DTYPE, ITYPE) from sklearn.neighbors.dist_metrics import DistanceMetric from sklearn.utils import check_random_state from sklearn.utils.testing import assert_allclose rng = np.random.RandomState(42) V = rng.random_sample((3, 3)) V = np.dot(V, V.T) DIMENSION = 3 METRICS = {'euclidean': {}, 'manhattan': {}, 'chebyshev': {}, 'minkowski': dict(p=3)} def brute_force_neighbors(X, Y, k, metric, **kwargs): D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] return dist, ind def check_neighbors(dualtree, breadth_first, k, metric, X, Y, kwargs): kdt = KDTree(X, leaf_size=1, metric=metric, **kwargs) dist1, ind1 = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) # don't check indices here: if there are any duplicate distances, # the indices may not match. Distances should not have this problem. assert_array_almost_equal(dist1, dist2) @pytest.mark.parametrize('metric', METRICS) @pytest.mark.parametrize('k', (1, 3, 5)) @pytest.mark.parametrize('dualtree', (True, False)) @pytest.mark.parametrize('breadth_first', (True, False)) def test_kd_tree_query(metric, k, dualtree, breadth_first): rng = check_random_state(0) X = rng.random_sample((40, DIMENSION)) Y = rng.random_sample((10, DIMENSION)) kwargs = METRICS[metric] check_neighbors(dualtree, breadth_first, k, metric, X, Y, kwargs) def test_kd_tree_query_radius(n_samples=100, n_features=10): rng = check_random_state(0) X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind = kdt.query_radius([query_pt], r + eps)[0] i = np.where(rad <= r + eps)[0] ind.sort() i.sort() assert_array_almost_equal(i, ind) def test_kd_tree_query_radius_distance(n_samples=100, n_features=10): rng = check_random_state(0) X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind, dist = kdt.query_radius([query_pt], r + eps, return_distance=True) ind = ind[0] dist = dist[0] d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1)) assert_array_almost_equal(d, dist) def compute_kernel_slow(Y, X, kernel, h): d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) norm = kernel_norm(h, X.shape[1], kernel) if kernel == 'gaussian': return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) elif kernel == 'tophat': return norm * (d < h).sum(-1) elif kernel == 'epanechnikov': return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) elif kernel == 'exponential': return norm * (np.exp(-d / h)).sum(-1) elif kernel == 'linear': return norm * ((1 - d / h) * (d < h)).sum(-1) elif kernel == 'cosine': return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) else: raise ValueError('kernel not recognized') def check_results(kernel, h, atol, rtol, breadth_first, Y, kdt, dens_true): dens = kdt.kernel_density(Y, h, atol=atol, rtol=rtol, kernel=kernel, breadth_first=breadth_first) assert_allclose(dens, dens_true, atol=atol, rtol=max(rtol, 1e-7)) @pytest.mark.parametrize('kernel', ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine']) @pytest.mark.parametrize('h', [0.01, 0.1, 1]) def test_kd_tree_kde(kernel, h): n_samples, n_features = (100, 3) rng = check_random_state(0) X = rng.random_sample((n_samples, n_features)) Y = rng.random_sample((n_samples, n_features)) kdt = KDTree(X, leaf_size=10) dens_true = compute_kernel_slow(Y, X, kernel, h) for rtol in [0, 1E-5]: for atol in [1E-6, 1E-2]: for breadth_first in (True, False): check_results(kernel, h, atol, rtol, breadth_first, Y, kdt, dens_true) def test_gaussian_kde(n_samples=1000): # Compare gaussian KDE results to scipy.stats.gaussian_kde from scipy.stats import gaussian_kde rng = check_random_state(0) x_in = rng.normal(0, 1, n_samples) x_out = np.linspace(-5, 5, 30) for h in [0.01, 0.1, 1]: kdt = KDTree(x_in[:, None]) gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) dens_kdt = kdt.kernel_density(x_out[:, None], h) / n_samples dens_gkde = gkde.evaluate(x_out) assert_array_almost_equal(dens_kdt, dens_gkde, decimal=3) @pytest.mark.parametrize('dualtree', (True, False)) def test_kd_tree_two_point(dualtree): n_samples, n_features = (100, 3) rng = check_random_state(0) X = rng.random_sample((n_samples, n_features)) Y = rng.random_sample((n_samples, n_features)) r = np.linspace(0, 1, 10) kdt = KDTree(X, leaf_size=10) D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) counts_true = [(D <= ri).sum() for ri in r] counts = kdt.two_point_correlation(Y, r=r, dualtree=dualtree) assert_array_almost_equal(counts, counts_true) @pytest.mark.parametrize('protocol', (0, 1, 2)) def test_kd_tree_pickle(protocol): import pickle rng = check_random_state(0) X = rng.random_sample((10, 3)) kdt1 = KDTree(X, leaf_size=1) ind1, dist1 = kdt1.query(X) def check_pickle_protocol(protocol): s = pickle.dumps(kdt1, protocol=protocol) kdt2 = pickle.loads(s) ind2, dist2 = kdt2.query(X) assert_array_almost_equal(ind1, ind2) assert_array_almost_equal(dist1, dist2) assert isinstance(kdt2, KDTree) check_pickle_protocol(protocol) def test_neighbors_heap(n_pts=5, n_nbrs=10): heap = NeighborsHeap(n_pts, n_nbrs) for row in range(n_pts): d_in = rng.random_sample(2 * n_nbrs).astype(DTYPE, copy=False) i_in = np.arange(2 * n_nbrs, dtype=ITYPE) for d, i in zip(d_in, i_in): heap.push(row, d, i) ind = np.argsort(d_in) d_in = d_in[ind] i_in = i_in[ind] d_heap, i_heap = heap.get_arrays(sort=True) assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) def test_node_heap(n_nodes=50): vals = rng.random_sample(n_nodes).astype(DTYPE, copy=False) i1 = np.argsort(vals) vals2, i2 = nodeheap_sort(vals) assert_array_almost_equal(i1, i2) assert_array_almost_equal(vals[i1], vals2) def test_simultaneous_sort(n_rows=10, n_pts=201): dist = rng.random_sample((n_rows, n_pts)).astype(DTYPE, copy=False) ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE, copy=False) dist2 = dist.copy() ind2 = ind.copy() # simultaneous sort rows using function simultaneous_sort(dist, ind) # simultaneous sort rows using numpy i = np.argsort(dist2, axis=1) row_ind = np.arange(n_rows)[:, None] dist2 = dist2[row_ind, i] ind2 = ind2[row_ind, i] assert_array_almost_equal(dist, dist2) assert_array_almost_equal(ind, ind2)
chrsrds/scikit-learn
sklearn/neighbors/tests/test_kd_tree.py
sklearn/utils/tests/test_class_weight.py
""" Our own implementation of the Newton algorithm Unlike the scipy.optimize version, this version of the Newton conjugate gradient solver uses only one function call to retrieve the func value, the gradient value and a callable for the Hessian matvec product. If the function call is very expensive (e.g. for logistic regression with large design matrix), this approach gives very significant speedups. """ # This is a modified file from scipy.optimize # Original authors: Travis Oliphant, Eric Jones # Modifications by Gael Varoquaux, Mathieu Blondel and Tom Dupre la Tour # License: BSD import numpy as np import warnings from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 from ..exceptions import ConvergenceWarning class _LineSearchError(RuntimeError): pass def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs): """ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if suitable step length is not found, and raise an exception if a suitable step length is not found. Raises ------ _LineSearchError If no suitable step size is found """ ret = line_search_wolfe1(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs) if ret[0] is None: # line search failed: try different one. ret = line_search_wolfe2(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs) if ret[0] is None: raise _LineSearchError() return ret def _cg(fhess_p, fgrad, maxiter, tol): """ Solve iteratively the linear system 'fhess_p . xsupi = fgrad' with a conjugate gradient descent. Parameters ---------- fhess_p : callable Function that takes the gradient as a parameter and returns the matrix product of the Hessian and gradient fgrad : ndarray, shape (n_features,) or (n_features + 1,) Gradient vector maxiter : int Number of CG iterations. tol : float Stopping criterion. Returns ------- xsupi : ndarray, shape (n_features,) or (n_features + 1,) Estimated solution """ xsupi = np.zeros(len(fgrad), dtype=fgrad.dtype) ri = fgrad psupi = -ri i = 0 dri0 = np.dot(ri, ri) while i <= maxiter: if np.sum(np.abs(ri)) <= tol: break Ap = fhess_p(psupi) # check curvature curv = np.dot(psupi, Ap) if 0 <= curv <= 3 * np.finfo(np.float64).eps: break elif curv < 0: if i > 0: break else: # fall back to steepest descent direction xsupi += dri0 / curv * psupi break alphai = dri0 / curv xsupi += alphai * psupi ri = ri + alphai * Ap dri1 = np.dot(ri, ri) betai = dri1 / dri0 psupi = -ri + betai * psupi i = i + 1 dri0 = dri1 # update np.dot(ri,ri) for next time. return xsupi def newton_cg(grad_hess, func, grad, x0, args=(), tol=1e-4, maxiter=100, maxinner=200, line_search=True, warn=True): """ Minimization of scalar function of one or more variables using the Newton-CG algorithm. Parameters ---------- grad_hess : callable Should return the gradient and a callable returning the matvec product of the Hessian. func : callable Should return the value of the function. grad : callable Should return the function value and the gradient. This is used by the linesearch functions. x0 : array of float Initial guess. args : tuple, optional Arguments passed to func_grad_hess, func and grad. tol : float Stopping criterion. The iteration will stop when ``max{|g_i | i = 1, ..., n} <= tol`` where ``g_i`` is the i-th component of the gradient. maxiter : int Number of Newton iterations. maxinner : int Number of CG iterations. line_search : boolean Whether to use a line search or not. warn : boolean Whether to warn when didn't converge. Returns ------- xk : ndarray of float Estimated minimum. """ x0 = np.asarray(x0).flatten() xk = x0 k = 0 if line_search: old_fval = func(x0, *args) old_old_fval = None # Outer loop: our Newton iteration while k < maxiter: # Compute a search direction pk by applying the CG method to # del2 f(xk) p = - fgrad f(xk) starting from 0. fgrad, fhess_p = grad_hess(xk, *args) absgrad = np.abs(fgrad) if np.max(absgrad) < tol: break maggrad = np.sum(absgrad) eta = min([0.5, np.sqrt(maggrad)]) termcond = eta * maggrad # Inner loop: solve the Newton update by conjugate gradient, to # avoid inverting the Hessian xsupi = _cg(fhess_p, fgrad, maxiter=maxinner, tol=termcond) alphak = 1.0 if line_search: try: alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \ _line_search_wolfe12(func, grad, xk, xsupi, fgrad, old_fval, old_old_fval, args=args) except _LineSearchError: warnings.warn('Line Search failed') break xk = xk + alphak * xsupi # upcast if necessary k += 1 if warn and k >= maxiter: warnings.warn("newton-cg failed to converge. Increase the " "number of iterations.", ConvergenceWarning) return xk, k def _check_optimize_result(solver, result, max_iter=None): """Check the OptimizeResult for successful convergence Parameters ---------- solver: str solver name. Currently only `lbfgs` is supported. result: OptimizeResult result of the scipy.optimize.minimize function max_iter: {int, None} expected maximum number of iterations Returns ------- n_iter: int number of iterations """ # handle both scipy and scikit-learn solver names if solver == "lbfgs": if result.status != 0: warnings.warn("{} failed to converge (status={}): {}. " "Increase the number of iterations." .format(solver, result.status, result.message), ConvergenceWarning) if max_iter is not None: # In scipy <= 1.0.0, nit may exceed maxiter for lbfgs. # See https://github.com/scipy/scipy/issues/7854 n_iter_i = min(result.nit, max_iter) else: n_iter_i = result.nit else: raise NotImplementedError return n_iter_i
import numpy as np from numpy.testing import assert_array_almost_equal import pytest from sklearn.neighbors.kd_tree import (KDTree, NeighborsHeap, simultaneous_sort, kernel_norm, nodeheap_sort, DTYPE, ITYPE) from sklearn.neighbors.dist_metrics import DistanceMetric from sklearn.utils import check_random_state from sklearn.utils.testing import assert_allclose rng = np.random.RandomState(42) V = rng.random_sample((3, 3)) V = np.dot(V, V.T) DIMENSION = 3 METRICS = {'euclidean': {}, 'manhattan': {}, 'chebyshev': {}, 'minkowski': dict(p=3)} def brute_force_neighbors(X, Y, k, metric, **kwargs): D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] return dist, ind def check_neighbors(dualtree, breadth_first, k, metric, X, Y, kwargs): kdt = KDTree(X, leaf_size=1, metric=metric, **kwargs) dist1, ind1 = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs) # don't check indices here: if there are any duplicate distances, # the indices may not match. Distances should not have this problem. assert_array_almost_equal(dist1, dist2) @pytest.mark.parametrize('metric', METRICS) @pytest.mark.parametrize('k', (1, 3, 5)) @pytest.mark.parametrize('dualtree', (True, False)) @pytest.mark.parametrize('breadth_first', (True, False)) def test_kd_tree_query(metric, k, dualtree, breadth_first): rng = check_random_state(0) X = rng.random_sample((40, DIMENSION)) Y = rng.random_sample((10, DIMENSION)) kwargs = METRICS[metric] check_neighbors(dualtree, breadth_first, k, metric, X, Y, kwargs) def test_kd_tree_query_radius(n_samples=100, n_features=10): rng = check_random_state(0) X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind = kdt.query_radius([query_pt], r + eps)[0] i = np.where(rad <= r + eps)[0] ind.sort() i.sort() assert_array_almost_equal(i, ind) def test_kd_tree_query_radius_distance(n_samples=100, n_features=10): rng = check_random_state(0) X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1 query_pt = np.zeros(n_features, dtype=float) eps = 1E-15 # roundoff error can cause test to fail kdt = KDTree(X, leaf_size=5) rad = np.sqrt(((X - query_pt) ** 2).sum(1)) for r in np.linspace(rad[0], rad[-1], 100): ind, dist = kdt.query_radius([query_pt], r + eps, return_distance=True) ind = ind[0] dist = dist[0] d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1)) assert_array_almost_equal(d, dist) def compute_kernel_slow(Y, X, kernel, h): d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1)) norm = kernel_norm(h, X.shape[1], kernel) if kernel == 'gaussian': return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1) elif kernel == 'tophat': return norm * (d < h).sum(-1) elif kernel == 'epanechnikov': return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1) elif kernel == 'exponential': return norm * (np.exp(-d / h)).sum(-1) elif kernel == 'linear': return norm * ((1 - d / h) * (d < h)).sum(-1) elif kernel == 'cosine': return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1) else: raise ValueError('kernel not recognized') def check_results(kernel, h, atol, rtol, breadth_first, Y, kdt, dens_true): dens = kdt.kernel_density(Y, h, atol=atol, rtol=rtol, kernel=kernel, breadth_first=breadth_first) assert_allclose(dens, dens_true, atol=atol, rtol=max(rtol, 1e-7)) @pytest.mark.parametrize('kernel', ['gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', 'cosine']) @pytest.mark.parametrize('h', [0.01, 0.1, 1]) def test_kd_tree_kde(kernel, h): n_samples, n_features = (100, 3) rng = check_random_state(0) X = rng.random_sample((n_samples, n_features)) Y = rng.random_sample((n_samples, n_features)) kdt = KDTree(X, leaf_size=10) dens_true = compute_kernel_slow(Y, X, kernel, h) for rtol in [0, 1E-5]: for atol in [1E-6, 1E-2]: for breadth_first in (True, False): check_results(kernel, h, atol, rtol, breadth_first, Y, kdt, dens_true) def test_gaussian_kde(n_samples=1000): # Compare gaussian KDE results to scipy.stats.gaussian_kde from scipy.stats import gaussian_kde rng = check_random_state(0) x_in = rng.normal(0, 1, n_samples) x_out = np.linspace(-5, 5, 30) for h in [0.01, 0.1, 1]: kdt = KDTree(x_in[:, None]) gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in)) dens_kdt = kdt.kernel_density(x_out[:, None], h) / n_samples dens_gkde = gkde.evaluate(x_out) assert_array_almost_equal(dens_kdt, dens_gkde, decimal=3) @pytest.mark.parametrize('dualtree', (True, False)) def test_kd_tree_two_point(dualtree): n_samples, n_features = (100, 3) rng = check_random_state(0) X = rng.random_sample((n_samples, n_features)) Y = rng.random_sample((n_samples, n_features)) r = np.linspace(0, 1, 10) kdt = KDTree(X, leaf_size=10) D = DistanceMetric.get_metric("euclidean").pairwise(Y, X) counts_true = [(D <= ri).sum() for ri in r] counts = kdt.two_point_correlation(Y, r=r, dualtree=dualtree) assert_array_almost_equal(counts, counts_true) @pytest.mark.parametrize('protocol', (0, 1, 2)) def test_kd_tree_pickle(protocol): import pickle rng = check_random_state(0) X = rng.random_sample((10, 3)) kdt1 = KDTree(X, leaf_size=1) ind1, dist1 = kdt1.query(X) def check_pickle_protocol(protocol): s = pickle.dumps(kdt1, protocol=protocol) kdt2 = pickle.loads(s) ind2, dist2 = kdt2.query(X) assert_array_almost_equal(ind1, ind2) assert_array_almost_equal(dist1, dist2) assert isinstance(kdt2, KDTree) check_pickle_protocol(protocol) def test_neighbors_heap(n_pts=5, n_nbrs=10): heap = NeighborsHeap(n_pts, n_nbrs) for row in range(n_pts): d_in = rng.random_sample(2 * n_nbrs).astype(DTYPE, copy=False) i_in = np.arange(2 * n_nbrs, dtype=ITYPE) for d, i in zip(d_in, i_in): heap.push(row, d, i) ind = np.argsort(d_in) d_in = d_in[ind] i_in = i_in[ind] d_heap, i_heap = heap.get_arrays(sort=True) assert_array_almost_equal(d_in[:n_nbrs], d_heap[row]) assert_array_almost_equal(i_in[:n_nbrs], i_heap[row]) def test_node_heap(n_nodes=50): vals = rng.random_sample(n_nodes).astype(DTYPE, copy=False) i1 = np.argsort(vals) vals2, i2 = nodeheap_sort(vals) assert_array_almost_equal(i1, i2) assert_array_almost_equal(vals[i1], vals2) def test_simultaneous_sort(n_rows=10, n_pts=201): dist = rng.random_sample((n_rows, n_pts)).astype(DTYPE, copy=False) ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(ITYPE, copy=False) dist2 = dist.copy() ind2 = ind.copy() # simultaneous sort rows using function simultaneous_sort(dist, ind) # simultaneous sort rows using numpy i = np.argsort(dist2, axis=1) row_ind = np.arange(n_rows)[:, None] dist2 = dist2[row_ind, i] ind2 = ind2[row_ind, i] assert_array_almost_equal(dist, dist2) assert_array_almost_equal(ind, ind2)
chrsrds/scikit-learn
sklearn/neighbors/tests/test_kd_tree.py
sklearn/utils/optimize.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """URL unescaper functions.""" # STDLIB from xml.sax import saxutils __all__ = ['unescape_all'] # This is DIY _bytes_entities = {b'&amp;': b'&', b'&lt;': b'<', b'&gt;': b'>', b'&amp;&amp;': b'&', b'&&': b'&', b'%2F': b'/'} _bytes_keys = [b'&amp;&amp;', b'&&', b'&amp;', b'&lt;', b'&gt;', b'%2F'] # This is used by saxutils _str_entities = {'&amp;&amp;': '&', '&&': '&', '%2F': '/'} _str_keys = ['&amp;&amp;', '&&', '&amp;', '&lt;', '&gt;', '%2F'] def unescape_all(url): """Recursively unescape a given URL. .. note:: '&amp;&amp;' becomes a single '&'. Parameters ---------- url : str or bytes URL to unescape. Returns ------- clean_url : str or bytes Unescaped URL. """ if isinstance(url, bytes): func2use = _unescape_bytes keys2use = _bytes_keys else: func2use = _unescape_str keys2use = _str_keys clean_url = func2use(url) not_done = [clean_url.count(key) > 0 for key in keys2use] if True in not_done: return unescape_all(clean_url) else: return clean_url def _unescape_str(url): return saxutils.unescape(url, _str_entities) def _unescape_bytes(url): clean_url = url for key in _bytes_keys: clean_url = clean_url.replace(key, _bytes_entities[key]) return clean_url
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Test the Quantity class and related.""" import copy import pickle import decimal import numbers from fractions import Fraction import pytest import numpy as np from numpy.testing import (assert_allclose, assert_array_equal, assert_array_almost_equal) from astropy.utils import isiterable, minversion from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning from astropy import units as u from astropy.units.quantity import _UNIT_NOT_INITIALISED """ The Quantity class will represent a number + unit + uncertainty """ class TestQuantityCreation: def test_1(self): # create objects through operations with Unit objects: quantity = 11.42 * u.meter # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = u.meter * 11.42 # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = 11.42 / u.meter assert isinstance(quantity, u.Quantity) quantity = u.meter / 11.42 assert isinstance(quantity, u.Quantity) quantity = 11.42 * u.meter / u.second assert isinstance(quantity, u.Quantity) with pytest.raises(TypeError): quantity = 182.234 + u.meter with pytest.raises(TypeError): quantity = 182.234 - u.meter with pytest.raises(TypeError): quantity = 182.234 % u.meter def test_2(self): # create objects using the Quantity constructor: _ = u.Quantity(11.412, unit=u.meter) _ = u.Quantity(21.52, "cm") q3 = u.Quantity(11.412) # By default quantities that don't specify a unit are unscaled # dimensionless assert q3.unit == u.Unit(1) with pytest.raises(TypeError): u.Quantity(object(), unit=u.m) def test_3(self): # with pytest.raises(u.UnitsError): with pytest.raises(ValueError): # Until @mdboom fixes the errors in units u.Quantity(11.412, unit="testingggg") def test_nan_inf(self): # Not-a-number q = u.Quantity('nan', unit='cm') assert np.isnan(q.value) q = u.Quantity('NaN', unit='cm') assert np.isnan(q.value) q = u.Quantity('-nan', unit='cm') # float() allows this assert np.isnan(q.value) q = u.Quantity('nan cm') assert np.isnan(q.value) assert q.unit == u.cm # Infinity q = u.Quantity('inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('-inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('inf cm') assert np.isinf(q.value) assert q.unit == u.cm q = u.Quantity('Infinity', unit='cm') # float() allows this assert np.isinf(q.value) # make sure these strings don't parse... with pytest.raises(TypeError): q = u.Quantity('', unit='cm') with pytest.raises(TypeError): q = u.Quantity('spam', unit='cm') def test_unit_property(self): # test getting and setting 'unit' attribute q1 = u.Quantity(11.4, unit=u.meter) with pytest.raises(AttributeError): q1.unit = u.cm def test_preserve_dtype(self): """Test that if an explicit dtype is given, it is used, while if not, numbers are converted to float (including decimal.Decimal, which numpy converts to an object; closes #1419) """ # If dtype is specified, use it, but if not, convert int, bool to float q1 = u.Quantity(12, unit=u.m / u.s, dtype=int) assert q1.dtype == int q2 = u.Quantity(q1) assert q2.dtype == float assert q2.value == float(q1.value) assert q2.unit == q1.unit # but we should preserve any float32 or even float16 a3_32 = np.array([1., 2.], dtype=np.float32) q3_32 = u.Quantity(a3_32, u.yr) assert q3_32.dtype == a3_32.dtype a3_16 = np.array([1., 2.], dtype=np.float16) q3_16 = u.Quantity(a3_16, u.yr) assert q3_16.dtype == a3_16.dtype # items stored as objects by numpy should be converted to float # by default q4 = u.Quantity(decimal.Decimal('10.25'), u.m) assert q4.dtype == float q5 = u.Quantity(decimal.Decimal('10.25'), u.m, dtype=object) assert q5.dtype == object def test_copy(self): # By default, a new quantity is constructed, but not if copy=False a = np.arange(10.) q0 = u.Quantity(a, unit=u.m / u.s) assert q0.base is not a q1 = u.Quantity(a, unit=u.m / u.s, copy=False) assert q1.base is a q2 = u.Quantity(q0) assert q2 is not q0 assert q2.base is not q0.base q2 = u.Quantity(q0, copy=False) assert q2 is q0 assert q2.base is q0.base q3 = u.Quantity(q0, q0.unit, copy=False) assert q3 is q0 assert q3.base is q0.base q4 = u.Quantity(q0, u.cm / u.s, copy=False) assert q4 is not q0 assert q4.base is not q0.base def test_subok(self): """Test subok can be used to keep class, or to insist on Quantity""" class MyQuantitySubclass(u.Quantity): pass myq = MyQuantitySubclass(np.arange(10.), u.m) # try both with and without changing the unit assert type(u.Quantity(myq)) is u.Quantity assert type(u.Quantity(myq, subok=True)) is MyQuantitySubclass assert type(u.Quantity(myq, u.km)) is u.Quantity assert type(u.Quantity(myq, u.km, subok=True)) is MyQuantitySubclass def test_order(self): """Test that order is correctly propagated to np.array""" ac = np.array(np.arange(10.), order='C') qcc = u.Quantity(ac, u.m, order='C') assert qcc.flags['C_CONTIGUOUS'] qcf = u.Quantity(ac, u.m, order='F') assert qcf.flags['F_CONTIGUOUS'] qca = u.Quantity(ac, u.m, order='A') assert qca.flags['C_CONTIGUOUS'] # check it works also when passing in a quantity assert u.Quantity(qcc, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='A').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='F').flags['F_CONTIGUOUS'] af = np.array(np.arange(10.), order='F') qfc = u.Quantity(af, u.m, order='C') assert qfc.flags['C_CONTIGUOUS'] qff = u.Quantity(ac, u.m, order='F') assert qff.flags['F_CONTIGUOUS'] qfa = u.Quantity(af, u.m, order='A') assert qfa.flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qff, order='A').flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='F').flags['F_CONTIGUOUS'] def test_ndmin(self): """Test that ndmin is correctly propagated to np.array""" a = np.arange(10.) q1 = u.Quantity(a, u.m, ndmin=1) assert q1.ndim == 1 and q1.shape == (10,) q2 = u.Quantity(a, u.m, ndmin=2) assert q2.ndim == 2 and q2.shape == (1, 10) # check it works also when passing in a quantity q3 = u.Quantity(q1, u.m, ndmin=3) assert q3.ndim == 3 and q3.shape == (1, 1, 10) # see github issue #10063 assert u.Quantity(u.Quantity(1, 'm'), 'm', ndmin=1).ndim == 1 assert u.Quantity(u.Quantity(1, 'cm'), 'm', ndmin=1).ndim == 1 def test_non_quantity_with_unit(self): """Test that unit attributes in objects get recognized.""" class MyQuantityLookalike(np.ndarray): pass a = np.arange(3.) mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = 'm' q1 = u.Quantity(mylookalike) assert isinstance(q1, u.Quantity) assert q1.unit is u.m assert np.all(q1.value == a) q2 = u.Quantity(mylookalike, u.mm) assert q2.unit is u.mm assert np.all(q2.value == 1000.*a) q3 = u.Quantity(mylookalike, copy=False) assert np.all(q3.value == mylookalike) q3[2] = 0 assert q3[2] == 0. assert mylookalike[2] == 0. mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = u.m q4 = u.Quantity(mylookalike, u.mm, copy=False) q4[2] = 0 assert q4[2] == 0. assert mylookalike[2] == 2. mylookalike.unit = 'nonsense' with pytest.raises(TypeError): u.Quantity(mylookalike) def test_creation_via_view(self): # This works but is no better than 1. * u.m q1 = 1. << u.m assert isinstance(q1, u.Quantity) assert q1.unit == u.m assert q1.value == 1. # With an array, we get an actual view. a2 = np.arange(10.) q2 = a2 << u.m / u.s assert isinstance(q2, u.Quantity) assert q2.unit == u.m / u.s assert np.all(q2.value == a2) a2[9] = 0. assert np.all(q2.value == a2) # But with a unit change we get a copy. q3 = q2 << u.mm / u.s assert isinstance(q3, u.Quantity) assert q3.unit == u.mm / u.s assert np.all(q3.value == a2 * 1000.) a2[8] = 0. assert q3[8].value == 8000. # Without a unit change, we do get a view. q4 = q2 << q2.unit a2[7] = 0. assert np.all(q4.value == a2) with pytest.raises(u.UnitsError): q2 << u.s # But one can do an in-place unit change. a2_copy = a2.copy() q2 <<= u.mm / u.s assert q2.unit == u.mm / u.s # Of course, this changes a2 as well. assert np.all(q2.value == a2) # Sanity check on the values. assert np.all(q2.value == a2_copy * 1000.) a2[8] = -1. # Using quantities, one can also work with strings. q5 = q2 << 'km/hr' assert q5.unit == u.km / u.hr assert np.all(q5 == q2) # Finally, we can use scalar quantities as units. not_quite_a_foot = 30. * u.cm a6 = np.arange(5.) q6 = a6 << not_quite_a_foot assert q6.unit == u.Unit(not_quite_a_foot) assert np.all(q6.to_value(u.cm) == 30. * a6) def test_rshift_warns(self): with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1 >> u.m assert len(warning_lines) == 1 q = 1. * u.km with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >> u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >>= u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1. >> q assert len(warning_lines) == 1 class TestQuantityOperations: q1 = u.Quantity(11.42, u.meter) q2 = u.Quantity(8.0, u.centimeter) def test_addition(self): # Take units from left object, q1 new_quantity = self.q1 + self.q2 assert new_quantity.value == 11.5 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 + self.q1 assert new_quantity.value == 1150.0 assert new_quantity.unit == u.centimeter new_q = u.Quantity(1500.1, u.m) + u.Quantity(13.5, u.km) assert new_q.unit == u.m assert new_q.value == 15000.1 def test_subtraction(self): # Take units from left object, q1 new_quantity = self.q1 - self.q2 assert new_quantity.value == 11.34 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 - self.q1 assert new_quantity.value == -1134.0 assert new_quantity.unit == u.centimeter def test_multiplication(self): # Take units from left object, q1 new_quantity = self.q1 * self.q2 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.meter * u.centimeter) # Take units from left object, q2 new_quantity = self.q2 * self.q1 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.centimeter * u.meter) # Multiply with a number new_quantity = 15. * self.q1 assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter # Multiply with a number new_quantity = self.q1 * 15. assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter def test_division(self): # Take units from left object, q1 new_quantity = self.q1 / self.q2 assert_array_almost_equal(new_quantity.value, 1.4275, decimal=5) assert new_quantity.unit == (u.meter / u.centimeter) # Take units from left object, q2 new_quantity = self.q2 / self.q1 assert_array_almost_equal(new_quantity.value, 0.70052539404553416, decimal=16) assert new_quantity.unit == (u.centimeter / u.meter) q1 = u.Quantity(11.4, unit=u.meter) q2 = u.Quantity(10.0, unit=u.second) new_quantity = q1 / q2 assert_array_almost_equal(new_quantity.value, 1.14, decimal=10) assert new_quantity.unit == (u.meter / u.second) # divide with a number new_quantity = self.q1 / 10. assert new_quantity.value == 1.142 assert new_quantity.unit == u.meter # divide with a number new_quantity = 11.42 / self.q1 assert new_quantity.value == 1. assert new_quantity.unit == u.Unit("1/m") def test_commutativity(self): """Regression test for issue #587.""" new_q = u.Quantity(11.42, 'm*s') assert self.q1 * u.s == u.s * self.q1 == new_q assert self.q1 / u.s == u.Quantity(11.42, 'm/s') assert u.s / self.q1 == u.Quantity(1 / 11.42, 's/m') def test_power(self): # raise quantity to a power new_quantity = self.q1 ** 2 assert_array_almost_equal(new_quantity.value, 130.4164, decimal=5) assert new_quantity.unit == u.Unit("m^2") new_quantity = self.q1 ** 3 assert_array_almost_equal(new_quantity.value, 1489.355288, decimal=7) assert new_quantity.unit == u.Unit("m^3") def test_matrix_multiplication(self): a = np.eye(3) q = a * u.m result1 = q @ a assert np.all(result1 == q) result2 = a @ q assert np.all(result2 == q) result3 = q @ q assert np.all(result3 == a * u.m ** 2) # less trivial case. q2 = np.array([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [[0., 1., 0.], [0., 0., 1.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]]]) / u.s result4 = q @ q2 assert np.all(result4 == np.matmul(a, q2.value) * q.unit * q2.unit) def test_unary(self): # Test the minus unary operator new_quantity = -self.q1 assert new_quantity.value == -self.q1.value assert new_quantity.unit == self.q1.unit new_quantity = -(-self.q1) assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit # Test the plus unary operator new_quantity = +self.q1 assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit def test_abs(self): q = 1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == q.value assert new_quantity.unit == q.unit q = -1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == -q.value assert new_quantity.unit == q.unit def test_incompatible_units(self): """ When trying to add or subtract units that aren't compatible, throw an error """ q1 = u.Quantity(11.412, unit=u.meter) q2 = u.Quantity(21.52, unit=u.second) with pytest.raises(u.UnitsError): q1 + q2 def test_non_number_type(self): q1 = u.Quantity(11.412, unit=u.meter) with pytest.raises(TypeError) as exc: q1 + {'a': 1} assert exc.value.args[0].startswith( "Unsupported operand type(s) for ufunc add:") with pytest.raises(TypeError): q1 + u.meter def test_dimensionless_operations(self): # test conversion to dimensionless dq = 3. * u.m / u.km dq1 = dq + 1. * u.mm / u.km assert dq1.value == 3.001 assert dq1.unit == dq.unit dq2 = dq + 1. assert dq2.value == 1.003 assert dq2.unit == u.dimensionless_unscaled # this test will check that operations with dimensionless Quantities # don't work with pytest.raises(u.UnitsError): self.q1 + u.Quantity(0.1, unit=u.Unit("")) with pytest.raises(u.UnitsError): self.q1 - u.Quantity(0.1, unit=u.Unit("")) # and test that scaling of integers works q = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int) q2 = q + np.array([4, 5, 6]) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, np.array([4.001, 5.002, 6.003])) # but not if doing it inplace with pytest.raises(TypeError): q += np.array([1, 2, 3]) # except if it is actually possible q = np.array([1, 2, 3]) * u.km / u.m q += np.array([4, 5, 6]) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == np.array([1004, 2005, 3006])) def test_complicated_operation(self): """ Perform a more complicated test """ from astropy.units import imperial # Multiple units distance = u.Quantity(15., u.meter) time = u.Quantity(11., u.second) velocity = (distance / time).to(imperial.mile / u.hour) assert_array_almost_equal( velocity.value, 3.05037, decimal=5) G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2) _ = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg)) # Area side1 = u.Quantity(11., u.centimeter) side2 = u.Quantity(7., u.centimeter) area = side1 * side2 assert_array_almost_equal(area.value, 77., decimal=15) assert area.unit == u.cm * u.cm def test_comparison(self): # equality/ non-equality is straightforward for quantity objects assert (1 / (u.cm * u.cm)) == 1 * u.cm ** -2 assert 1 * u.m == 100 * u.cm assert 1 * u.m != 1 * u.cm # when one is a unit, Quantity does not know what to do, # but unit is fine with it, so it still works unit = u.cm**3 q = 1. * unit assert q.__eq__(unit) is NotImplemented assert unit.__eq__(q) is True assert q == unit q = 1000. * u.mm**3 assert q == unit # mismatched types should never work assert not 1. * u.cm == 1. assert 1. * u.cm != 1. # comparison with zero should raise a deprecation warning for quantity in (1. * u.cm, 1. * u.dimensionless_unscaled): with pytest.warns(AstropyDeprecationWarning, match='The truth value of ' 'a Quantity is ambiguous. In the future this will ' 'raise a ValueError.'): bool(quantity) def test_numeric_converters(self): # float, int, long, and __index__ should only work for single # quantities, of appropriate type, and only if they are dimensionless. # for index, this should be unscaled as well # (Check on __index__ is also a regression test for #1557) # quantities with units should never convert, or be usable as an index q1 = u.Quantity(1, u.m) converter_err_msg = ("only dimensionless scalar quantities " "can be converted to Python scalars") index_err_msg = ("only integer dimensionless scalar quantities " "can be converted to a Python index") with pytest.raises(TypeError) as exc: float(q1) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q1) assert exc.value.args[0] == converter_err_msg # We used to test `q1 * ['a', 'b', 'c'] here, but that that worked # at all was a really odd confluence of bugs. Since it doesn't work # in numpy >=1.10 any more, just go directly for `__index__` (which # makes the test more similar to the `int`, `long`, etc., tests). with pytest.raises(TypeError) as exc: q1.__index__() assert exc.value.args[0] == index_err_msg # dimensionless but scaled is OK, however q2 = u.Quantity(1.23, u.m / u.km) assert float(q2) == float(q2.to_value(u.dimensionless_unscaled)) assert int(q2) == int(q2.to_value(u.dimensionless_unscaled)) with pytest.raises(TypeError) as exc: q2.__index__() assert exc.value.args[0] == index_err_msg # dimensionless unscaled is OK, though for index needs to be int q3 = u.Quantity(1.23, u.dimensionless_unscaled) assert float(q3) == 1.23 assert int(q3) == 1 with pytest.raises(TypeError) as exc: q3.__index__() assert exc.value.args[0] == index_err_msg # integer dimensionless unscaled is good for all q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert float(q4) == 2. assert int(q4) == 2 assert q4.__index__() == 2 # but arrays are not OK q5 = u.Quantity([1, 2], u.m) with pytest.raises(TypeError) as exc: float(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: q5.__index__() assert exc.value.args[0] == index_err_msg # See https://github.com/numpy/numpy/issues/5074 # It seems unlikely this will be resolved, so xfail'ing it. @pytest.mark.xfail(reason="list multiplication only works for numpy <=1.10") def test_numeric_converter_to_index_in_practice(self): """Test that use of __index__ actually works.""" q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert q4 * ['a', 'b', 'c'] == ['a', 'b', 'c', 'a', 'b', 'c'] def test_array_converters(self): # Scalar quantity q = u.Quantity(1.23, u.m) assert np.all(np.array(q) == np.array([1.23])) # Array quantity q = u.Quantity([1., 2., 3.], u.m) assert np.all(np.array(q) == np.array([1., 2., 3.])) def test_quantity_conversion(): q1 = u.Quantity(0.1, unit=u.meter) value = q1.value assert value == 0.1 value_in_km = q1.to_value(u.kilometer) assert value_in_km == 0.0001 new_quantity = q1.to(u.kilometer) assert new_quantity.value == 0.0001 with pytest.raises(u.UnitsError): q1.to(u.zettastokes) with pytest.raises(u.UnitsError): q1.to_value(u.zettastokes) def test_quantity_value_views(): q1 = u.Quantity([1., 2.], unit=u.meter) # views if the unit is the same. v1 = q1.value v1[0] = 0. assert np.all(q1 == [0., 2.] * u.meter) v2 = q1.to_value() v2[1] = 3. assert np.all(q1 == [0., 3.] * u.meter) v3 = q1.to_value('m') v3[0] = 1. assert np.all(q1 == [1., 3.] * u.meter) q2 = q1.to('m', copy=False) q2[0] = 2 * u.meter assert np.all(q1 == [2., 3.] * u.meter) v4 = q1.to_value('cm') v4[0] = 0. # copy if different unit. assert np.all(q1 == [2., 3.] * u.meter) def test_quantity_conversion_with_equiv(): q1 = u.Quantity(0.1, unit=u.meter) v2 = q1.to_value(u.Hz, equivalencies=u.spectral()) assert_allclose(v2, 2997924580.0) q2 = q1.to(u.Hz, equivalencies=u.spectral()) assert_allclose(q2.value, v2) q1 = u.Quantity(0.4, unit=u.arcsecond) v2 = q1.to_value(u.au, equivalencies=u.parallax()) q2 = q1.to(u.au, equivalencies=u.parallax()) v3 = q2.to_value(u.arcminute, equivalencies=u.parallax()) q3 = q2.to(u.arcminute, equivalencies=u.parallax()) assert_allclose(v2, 515662.015) assert_allclose(q2.value, v2) assert q2.unit == u.au assert_allclose(v3, 0.0066666667) assert_allclose(q3.value, v3) assert q3.unit == u.arcminute def test_quantity_conversion_equivalency_passed_on(): class MySpectral(u.Quantity): _equivalencies = u.spectral() def __quantity_view__(self, obj, unit): return obj.view(MySpectral) def __quantity_instance__(self, *args, **kwargs): return MySpectral(*args, **kwargs) q1 = MySpectral([1000, 2000], unit=u.Hz) q2 = q1.to(u.nm) assert q2.unit == u.nm q3 = q2.to(u.Hz) assert q3.unit == u.Hz assert_allclose(q3.value, q1.value) q4 = MySpectral([1000, 2000], unit=u.nm) q5 = q4.to(u.Hz).to(u.nm) assert q5.unit == u.nm assert_allclose(q4.value, q5.value) # Regression test for issue #2315, divide-by-zero error when examining 0*unit def test_self_equivalency(): assert u.deg.is_equivalent(0*u.radian) assert u.deg.is_equivalent(1*u.radian) def test_si(): q1 = 10. * u.m * u.s ** 2 / (200. * u.ms) ** 2 # 250 meters assert q1.si.value == 250 assert q1.si.unit == u.m q = 10. * u.m # 10 meters assert q.si.value == 10 assert q.si.unit == u.m q = 10. / u.m # 10 1 / meters assert q.si.value == 10 assert q.si.unit == (1 / u.m) def test_cgs(): q1 = 10. * u.cm * u.s ** 2 / (200. * u.ms) ** 2 # 250 centimeters assert q1.cgs.value == 250 assert q1.cgs.unit == u.cm q = 10. * u.m # 10 centimeters assert q.cgs.value == 1000 assert q.cgs.unit == u.cm q = 10. / u.cm # 10 1 / centimeters assert q.cgs.value == 10 assert q.cgs.unit == (1 / u.cm) q = 10. * u.Pa # 10 pascals assert q.cgs.value == 100 assert q.cgs.unit == u.barye class TestQuantityComparison: def test_quantity_equality(self): assert u.Quantity(1000, unit='m') == u.Quantity(1, unit='km') assert not (u.Quantity(1, unit='m') == u.Quantity(1, unit='km')) # for ==, !=, return False, True if units do not match assert (u.Quantity(1100, unit=u.m) != u.Quantity(1, unit=u.s)) is True assert (u.Quantity(1100, unit=u.m) == u.Quantity(1, unit=u.s)) is False assert (u.Quantity(0, unit=u.m) == u.Quantity(0, unit=u.s)) is False # But allow comparison with 0, +/-inf if latter unitless assert u.Quantity(0, u.m) == 0. assert u.Quantity(1, u.m) != 0. assert u.Quantity(1, u.m) != np.inf assert u.Quantity(np.inf, u.m) == np.inf def test_quantity_equality_array(self): a = u.Quantity([0., 1., 1000.], u.m) b = u.Quantity(1., u.km) eq = a == b ne = a != b assert np.all(eq == [False, False, True]) assert np.all(eq != ne) # For mismatched units, we should just get True, False c = u.Quantity(1., u.s) eq = a == c ne = a != c assert eq is False assert ne is True # Constants are treated as dimensionless, so False too. eq = a == 1. ne = a != 1. assert eq is False assert ne is True # But 0 can have any units, so we can compare. eq = a == 0 ne = a != 0 assert np.all(eq == [True, False, False]) assert np.all(eq != ne) # But we do not extend that to arrays; they should have the same unit. d = np.array([0, 1., 1000.]) eq = a == d ne = a != d assert eq is False assert ne is True def test_quantity_comparison(self): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second) assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity( 1100, unit=u.meter) >= u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second) assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer) class TestQuantityDisplay: scalarintq = u.Quantity(1, unit='m', dtype=int) scalarfloatq = u.Quantity(1.3, unit='m') arrq = u.Quantity([1, 2.3, 8.9], unit='m') scalar_complex_q = u.Quantity(complex(1.0, 2.0)) scalar_big_complex_q = u.Quantity(complex(1.0, 2.0e27) * 1e25) scalar_big_neg_complex_q = u.Quantity(complex(-1.0, -2.0e27) * 1e36) arr_complex_q = u.Quantity(np.arange(3) * (complex(-1.0, -2.0e27) * 1e36)) big_arr_complex_q = u.Quantity(np.arange(125) * (complex(-1.0, -2.0e27) * 1e36)) def test_dimensionless_quantity_repr(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert repr(self.scalarintq * q2) == "<Quantity 1.>" assert repr(self.arrq * q2) == "<Quantity [1. , 2.3, 8.9]>" assert repr(self.scalarintq * q3) == "<Quantity 1>" def test_dimensionless_quantity_str(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert str(self.scalarintq * q2) == "1.0" assert str(self.scalarintq * q3) == "1" assert str(self.arrq * q2) == "[1. 2.3 8.9]" def test_dimensionless_quantity_format(self): q1 = u.Quantity(3.14) assert format(q1, '.2f') == '3.14' def test_scalar_quantity_str(self): assert str(self.scalarintq) == "1 m" assert str(self.scalarfloatq) == "1.3 m" def test_scalar_quantity_repr(self): assert repr(self.scalarintq) == "<Quantity 1 m>" assert repr(self.scalarfloatq) == "<Quantity 1.3 m>" def test_array_quantity_str(self): assert str(self.arrq) == "[1. 2.3 8.9] m" def test_array_quantity_repr(self): assert repr(self.arrq) == "<Quantity [1. , 2.3, 8.9] m>" def test_scalar_quantity_format(self): assert format(self.scalarintq, '02d') == "01 m" assert format(self.scalarfloatq, '.1f') == "1.3 m" assert format(self.scalarfloatq, '.0f') == "1 m" def test_uninitialized_unit_format(self): bad_quantity = np.arange(10.).view(u.Quantity) assert str(bad_quantity).endswith(_UNIT_NOT_INITIALISED) assert repr(bad_quantity).endswith(_UNIT_NOT_INITIALISED + '>') def test_to_string(self): qscalar = u.Quantity(1.5e14, 'm/s') # __str__ is the default `format` assert str(qscalar) == qscalar.to_string() res = 'Quantity as KMS: 150000000000.0 km / s' assert f"Quantity as KMS: {qscalar.to_string(unit=u.km / u.s)}" == res # With precision set res = 'Quantity as KMS: 1.500e+11 km / s' assert f"Quantity as KMS: {qscalar.to_string(precision=3, unit=u.km / u.s)}" == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex") == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="inline") == res res = r'$\displaystyle 1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="display") == res def test_repr_latex(self): from astropy.units.quantity import conf q2scalar = u.Quantity(1.5e14, 'm/s') assert self.scalarintq._repr_latex_() == r'$1 \; \mathrm{m}$' assert self.scalarfloatq._repr_latex_() == r'$1.3 \; \mathrm{m}$' assert (q2scalar._repr_latex_() == r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$') assert self.arrq._repr_latex_() == r'$[1,~2.3,~8.9] \; \mathrm{m}$' # Complex quantities assert self.scalar_complex_q._repr_latex_() == r'$(1+2i) \; \mathrm{}$' assert (self.scalar_big_complex_q._repr_latex_() == r'$(1 \times 10^{25}+2 \times 10^{52}i) \; \mathrm{}$') assert (self.scalar_big_neg_complex_q._repr_latex_() == r'$(-1 \times 10^{36}-2 \times 10^{63}i) \; \mathrm{}$') assert (self.arr_complex_q._repr_latex_() == (r'$[(0-0i),~(-1 \times 10^{36}-2 \times 10^{63}i),' r'~(-2 \times 10^{36}-4 \times 10^{63}i)] \; \mathrm{}$')) assert r'\dots' in self.big_arr_complex_q._repr_latex_() qmed = np.arange(100)*u.m qbig = np.arange(1000)*u.m qvbig = np.arange(10000)*1e9*u.m pops = np.get_printoptions() oldlat = conf.latex_array_threshold try: # check precision behavior q = u.Quantity(987654321.123456789, 'm/s') qa = np.array([7.89123, 123456789.987654321, 0]) * u.cm np.set_printoptions(precision=8) assert q._repr_latex_() == r'$9.8765432 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.89123,~1.2345679 \times 10^{8},~0] \; \mathrm{cm}$' np.set_printoptions(precision=2) assert q._repr_latex_() == r'$9.9 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.9,~1.2 \times 10^{8},~0] \; \mathrm{cm}$' # check thresholding behavior conf.latex_array_threshold = 100 # should be default lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = 1001 lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' not in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = -1 # means use the numpy threshold np.set_printoptions(threshold=99) lsmed = qmed._repr_latex_() assert r'\dots' in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig finally: # prevent side-effects from influencing other tests np.set_printoptions(**pops) conf.latex_array_threshold = oldlat qinfnan = [np.inf, -np.inf, np.nan] * u.m assert qinfnan._repr_latex_() == r'$[\infty,~-\infty,~{\rm NaN}] \; \mathrm{m}$' def test_decompose(): q1 = 5 * u.N assert q1.decompose() == (5 * u.kg * u.m * u.s ** -2) def test_decompose_regression(): """ Regression test for bug #1163 If decompose was called multiple times on a Quantity with an array and a scale != 1, the result changed every time. This is because the value was being referenced not copied, then modified, which changed the original value. """ q = np.array([1, 2, 3]) * u.m / (2. * u.km) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) assert np.all(q == np.array([1, 2, 3]) * u.m / (2. * u.km)) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) def test_arrays(): """ Test using quantites with array values """ qsec = u.Quantity(np.arange(10), u.second) assert isinstance(qsec.value, np.ndarray) assert not qsec.isscalar # len and indexing should work for arrays assert len(qsec) == len(qsec.value) qsecsub25 = qsec[2:5] assert qsecsub25.unit == qsec.unit assert isinstance(qsecsub25, u.Quantity) assert len(qsecsub25) == 3 # make sure isscalar, len, and indexing behave correcly for non-arrays. qsecnotarray = u.Quantity(10., u.second) assert qsecnotarray.isscalar with pytest.raises(TypeError): len(qsecnotarray) with pytest.raises(TypeError): qsecnotarray[0] qseclen0array = u.Quantity(np.array(10), u.second, dtype=int) # 0d numpy array should act basically like a scalar assert qseclen0array.isscalar with pytest.raises(TypeError): len(qseclen0array) with pytest.raises(TypeError): qseclen0array[0] assert isinstance(qseclen0array.value, numbers.Integral) a = np.array([(1., 2., 3.), (4., 5., 6.), (7., 8., 9.)], dtype=[('x', float), ('y', float), ('z', float)]) qkpc = u.Quantity(a, u.kpc) assert not qkpc.isscalar qkpc0 = qkpc[0] assert qkpc0.value == a[0] assert qkpc0.unit == qkpc.unit assert isinstance(qkpc0, u.Quantity) assert qkpc0.isscalar qkpcx = qkpc['x'] assert np.all(qkpcx.value == a['x']) assert qkpcx.unit == qkpc.unit assert isinstance(qkpcx, u.Quantity) assert not qkpcx.isscalar qkpcx1 = qkpc['x'][1] assert qkpcx1.unit == qkpc.unit assert isinstance(qkpcx1, u.Quantity) assert qkpcx1.isscalar qkpc1x = qkpc[1]['x'] assert qkpc1x.isscalar assert qkpc1x == qkpcx1 # can also create from lists, will auto-convert to arrays qsec = u.Quantity(list(range(10)), u.second) assert isinstance(qsec.value, np.ndarray) # quantity math should work with arrays assert_array_equal((qsec * 2).value, (np.arange(10) * 2)) assert_array_equal((qsec / 2).value, (np.arange(10) / 2)) # quantity addition/subtraction should *not* work with arrays b/c unit # ambiguous with pytest.raises(u.UnitsError): assert_array_equal((qsec + 2).value, (np.arange(10) + 2)) with pytest.raises(u.UnitsError): assert_array_equal((qsec - 2).value, (np.arange(10) + 2)) # should create by unit multiplication, too qsec2 = np.arange(10) * u.second qsec3 = u.second * np.arange(10) assert np.all(qsec == qsec2) assert np.all(qsec2 == qsec3) # make sure numerical-converters fail when arrays are present with pytest.raises(TypeError): float(qsec) with pytest.raises(TypeError): int(qsec) def test_array_indexing_slicing(): q = np.array([1., 2., 3.]) * u.m assert q[0] == 1. * u.m assert np.all(q[0:2] == u.Quantity([1., 2.], u.m)) def test_array_setslice(): q = np.array([1., 2., 3.]) * u.m q[1:2] = np.array([400.]) * u.cm assert np.all(q == np.array([1., 4., 3.]) * u.m) def test_inverse_quantity(): """ Regression test from issue #679 """ q = u.Quantity(4., u.meter / u.second) qot = q / 2 toq = 2 / q npqot = q / np.array(2) assert npqot.value == 2.0 assert npqot.unit == (u.meter / u.second) assert qot.value == 2.0 assert qot.unit == (u.meter / u.second) assert toq.value == 0.5 assert toq.unit == (u.second / u.meter) def test_quantity_mutability(): q = u.Quantity(9.8, u.meter / u.second / u.second) with pytest.raises(AttributeError): q.value = 3 with pytest.raises(AttributeError): q.unit = u.kg def test_quantity_initialized_with_quantity(): q1 = u.Quantity(60, u.second) q2 = u.Quantity(q1, u.minute) assert q2.value == 1 q3 = u.Quantity([q1, q2], u.second) assert q3[0].value == 60 assert q3[1].value == 60 q4 = u.Quantity([q2, q1]) assert q4.unit == q2.unit assert q4[0].value == 1 assert q4[1].value == 1 def test_quantity_string_unit(): q1 = 1. * u.m / 's' assert q1.value == 1 assert q1.unit == (u.m / u.s) q2 = q1 * "m" assert q2.unit == ((u.m * u.m) / u.s) def test_quantity_invalid_unit_string(): with pytest.raises(ValueError): "foo" * u.m def test_implicit_conversion(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True assert_allclose(q.centimeter, 100) assert_allclose(q.cm, 100) assert_allclose(q.parsec, 3.240779289469756e-17) def test_implicit_conversion_autocomplete(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True q.foo = 42 attrs = dir(q) assert 'centimeter' in attrs assert 'cm' in attrs assert 'parsec' in attrs assert 'foo' in attrs assert 'to' in attrs assert 'value' in attrs # Something from the base class, object assert '__setattr__' in attrs with pytest.raises(AttributeError): q.l def test_quantity_iterability(): """Regressiont est for issue #878. Scalar quantities should not be iterable and should raise a type error on iteration. """ q1 = [15.0, 17.0] * u.m assert isiterable(q1) q2 = next(iter(q1)) assert q2 == 15.0 * u.m assert not isiterable(q2) pytest.raises(TypeError, iter, q2) def test_copy(): q1 = u.Quantity(np.array([[1., 2., 3.], [4., 5., 6.]]), unit=u.m) q2 = q1.copy() assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value q3 = q1.copy(order='F') assert q3.flags['F_CONTIGUOUS'] assert np.all(q1.value == q3.value) assert q1.unit == q3.unit assert q1.dtype == q3.dtype assert q1.value is not q3.value q4 = q1.copy(order='C') assert q4.flags['C_CONTIGUOUS'] assert np.all(q1.value == q4.value) assert q1.unit == q4.unit assert q1.dtype == q4.dtype assert q1.value is not q4.value def test_deepcopy(): q1 = u.Quantity(np.array([1., 2., 3.]), unit=u.m) q2 = copy.deepcopy(q1) assert isinstance(q2, u.Quantity) assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value def test_equality_numpy_scalar(): """ A regression test to ensure that numpy scalars are correctly compared (which originally failed due to the lack of ``__array_priority__``). """ assert 10 != 10. * u.m assert np.int64(10) != 10 * u.m assert 10 * u.m != np.int64(10) def test_quantity_pickelability(): """ Testing pickleability of quantity """ q1 = np.arange(10) * u.m q2 = pickle.loads(pickle.dumps(q1)) assert np.all(q1.value == q2.value) assert q1.unit.is_equivalent(q2.unit) assert q1.unit == q2.unit def test_quantity_initialisation_from_string(): q = u.Quantity('1') assert q.unit == u.dimensionless_unscaled assert q.value == 1. q = u.Quantity('1.5 m/s') assert q.unit == u.m/u.s assert q.value == 1.5 assert u.Unit(q) == u.Unit('1.5 m/s') q = u.Quantity('.5 m') assert q == u.Quantity(0.5, u.m) q = u.Quantity('-1e1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('-1e+1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('+.5km') assert q == u.Quantity(.5, u.km) q = u.Quantity('+5e-1km') assert q == u.Quantity(.5, u.km) q = u.Quantity('5', u.m) assert q == u.Quantity(5., u.m) q = u.Quantity('5 km', u.m) assert q.value == 5000. assert q.unit == u.m q = u.Quantity('5Em') assert q == u.Quantity(5., u.Em) with pytest.raises(TypeError): u.Quantity('') with pytest.raises(TypeError): u.Quantity('m') with pytest.raises(TypeError): u.Quantity('1.2.3 deg') with pytest.raises(TypeError): u.Quantity('1+deg') with pytest.raises(TypeError): u.Quantity('1-2deg') with pytest.raises(TypeError): u.Quantity('1.2e-13.3m') with pytest.raises(TypeError): u.Quantity(['5']) with pytest.raises(TypeError): u.Quantity(np.array(['5'])) with pytest.raises(ValueError): u.Quantity('5E') with pytest.raises(ValueError): u.Quantity('5 foo') def test_unsupported(): q1 = np.arange(10) * u.m with pytest.raises(TypeError): np.bitwise_and(q1, q1) def test_unit_identity(): q = 1.0 * u.hour assert q.unit is u.hour def test_quantity_to_view(): q1 = np.array([1000, 2000]) * u.m q2 = q1.to(u.km) assert q1.value[0] == 1000 assert q2.value[0] == 1 def test_quantity_tuple_power(): with pytest.raises(ValueError): (5.0 * u.m) ** (1, 2) def test_quantity_fraction_power(): q = (25.0 * u.m**2) ** Fraction(1, 2) assert q.value == 5. assert q.unit == u.m # Regression check to ensure we didn't create an object type by raising # the value of the quantity to a Fraction. [#3922] assert q.dtype.kind == 'f' def test_quantity_from_table(): """ Checks that units from tables are respected when converted to a Quantity. This also generically checks the use of *anything* with a `unit` attribute passed into Quantity """ from astropy.table import Table t = Table(data=[np.arange(5), np.arange(5)], names=['a', 'b']) t['a'].unit = u.kpc qa = u.Quantity(t['a']) assert qa.unit == u.kpc assert_array_equal(qa.value, t['a']) qb = u.Quantity(t['b']) assert qb.unit == u.dimensionless_unscaled assert_array_equal(qb.value, t['b']) # This does *not* auto-convert, because it's not necessarily obvious that's # desired. Instead we revert to standard `Quantity` behavior qap = u.Quantity(t['a'], u.pc) assert qap.unit == u.pc assert_array_equal(qap.value, t['a'] * 1000) qbp = u.Quantity(t['b'], u.pc) assert qbp.unit == u.pc assert_array_equal(qbp.value, t['b']) # Also check with a function unit (regression test for gh-8430) t['a'].unit = u.dex(u.cm/u.s**2) fq = u.Dex(t['a']) assert fq.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq.value, t['a']) fq2 = u.Quantity(t['a'], subok=True) assert isinstance(fq2, u.Dex) assert fq2.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq2.value, t['a']) with pytest.raises(u.UnitTypeError): u.Quantity(t['a']) def test_assign_slice_with_quantity_like(): # Regression tests for gh-5961 from astropy.table import Table, Column # first check directly that we can use a Column to assign to a slice. c = Column(np.arange(10.), unit=u.mm) q = u.Quantity(c) q[:2] = c[:2] # next check that we do not fail the original problem. t = Table() t['x'] = np.arange(10) * u.mm t['y'] = np.ones(10) * u.mm assert type(t['x']) is Column xy = np.vstack([t['x'], t['y']]).T * u.mm ii = [0, 2, 4] assert xy[ii, 0].unit == t['x'][ii].unit # should not raise anything xy[ii, 0] = t['x'][ii] def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]]) def test_repr_array_of_quantity(): """ Test print/repr of object arrays of Quantity objects with different units. Regression test for the issue first reported in https://github.com/astropy/astropy/issues/3777 """ a = np.array([1 * u.m, 2 * u.s], dtype=object) assert repr(a) == 'array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)' assert str(a) == '[<Quantity 1. m> <Quantity 2. s>]' class TestSpecificTypeQuantity: def setup(self): class Length(u.SpecificTypeQuantity): _equivalent_unit = u.m class Length2(Length): _default_unit = u.m class Length3(Length): _unit = u.m self.Length = Length self.Length2 = Length2 self.Length3 = Length3 def test_creation(self): l = self.Length(np.arange(10.)*u.km) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.) * u.hour) with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.)) l2 = self.Length2(np.arange(5.)) assert type(l2) is self.Length2 assert l2._default_unit is self.Length2._default_unit with pytest.raises(u.UnitTypeError): self.Length3(np.arange(10.)) def test_view(self): l = (np.arange(5.) * u.km).view(self.Length) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): (np.arange(5.) * u.s).view(self.Length) v = np.arange(5.).view(self.Length) assert type(v) is self.Length assert v._unit is None l3 = np.ones((2, 2)).view(self.Length3) assert type(l3) is self.Length3 assert l3.unit is self.Length3._unit def test_operation_precedence_and_fallback(self): l = self.Length(np.arange(5.)*u.cm) sum1 = l + 1.*u.m assert type(sum1) is self.Length sum2 = 1.*u.km + l assert type(sum2) is self.Length sum3 = l + l assert type(sum3) is self.Length res1 = l * (1.*u.m) assert type(res1) is u.Quantity res2 = l * l assert type(res2) is u.Quantity def test_unit_class_override(): class MyQuantity(u.Quantity): pass my_unit = u.Unit("my_deg", u.deg) my_unit._quantity_class = MyQuantity q1 = u.Quantity(1., my_unit) assert type(q1) is u.Quantity q2 = u.Quantity(1., my_unit, subok=True) assert type(q2) is MyQuantity class QuantityMimic: def __init__(self, value, unit): self.value = value self.unit = unit def __array__(self): return np.array(self.value) class QuantityMimic2(QuantityMimic): def to(self, unit): return u.Quantity(self.value, self.unit).to(unit) def to_value(self, unit): return u.Quantity(self.value, self.unit).to_value(unit) class TestQuantityMimics: """Test Quantity Mimics that are not ndarray subclasses.""" @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_input(self, Mimic): value = np.arange(10.) mimic = Mimic(value, u.m) q = u.Quantity(mimic) assert q.unit == u.m assert np.all(q.value == value) q2 = u.Quantity(mimic, u.cm) assert q2.unit == u.cm assert np.all(q2.value == 100 * value) @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_setting(self, Mimic): mimic = Mimic([1., 2.], u.m) q = u.Quantity(np.arange(10.), u.cm) q[8:] = mimic assert np.all(q[:8].value == np.arange(8.)) assert np.all(q[8:].value == [100., 200.]) def test_mimic_function_unit(self): mimic = QuantityMimic([1., 2.], u.dex(u.cm/u.s**2)) d = u.Dex(mimic) assert isinstance(d, u.Dex) assert d.unit == u.dex(u.cm/u.s**2) assert np.all(d.value == [1., 2.]) q = u.Quantity(mimic, subok=True) assert isinstance(q, u.Dex) assert q.unit == u.dex(u.cm/u.s**2) assert np.all(q.value == [1., 2.]) with pytest.raises(u.UnitTypeError): u.Quantity(mimic) def test_masked_quantity_str_repr(): """Ensure we don't break masked Quantity representation.""" # Really, masked quantities do not work well, but at least let the # basics work. masked_quantity = np.ma.array([1, 2, 3, 4] * u.kg, mask=[True, False, True, False]) str(masked_quantity) repr(masked_quantity) class TestQuantitySubclassAboveAndBelow: @classmethod def setup_class(self): class MyArray(np.ndarray): def __array_finalize__(self, obj): super_array_finalize = super().__array_finalize__ if super_array_finalize is not None: super_array_finalize(obj) if hasattr(obj, 'my_attr'): self.my_attr = obj.my_attr self.MyArray = MyArray self.MyQuantity1 = type('MyQuantity1', (u.Quantity, MyArray), dict(my_attr='1')) self.MyQuantity2 = type('MyQuantity2', (MyArray, u.Quantity), dict(my_attr='2')) def test_setup(self): mq1 = self.MyQuantity1(10, u.m) assert isinstance(mq1, self.MyQuantity1) assert mq1.my_attr == '1' assert mq1.unit is u.m mq2 = self.MyQuantity2(10, u.m) assert isinstance(mq2, self.MyQuantity2) assert mq2.my_attr == '2' assert mq2.unit is u.m def test_attr_propagation(self): mq1 = self.MyQuantity1(10, u.m) mq12 = self.MyQuantity2(mq1) assert isinstance(mq12, self.MyQuantity2) assert not isinstance(mq12, self.MyQuantity1) assert mq12.my_attr == '1' assert mq12.unit is u.m mq2 = self.MyQuantity2(10, u.m) mq21 = self.MyQuantity1(mq2) assert isinstance(mq21, self.MyQuantity1) assert not isinstance(mq21, self.MyQuantity2) assert mq21.my_attr == '2' assert mq21.unit is u.m
dhomeier/astropy
astropy/units/tests/test_quantity.py
astropy/utils/xml/unescaper.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ import pickle __all__ = ['fnpickle', 'fnunpickle'] def fnunpickle(fileorname, number=0): """ Unpickle pickled objects from a specified file and return the contents. Parameters ---------- fileorname : str or file-like The file name or file from which to unpickle objects. If a file object, it should have been opened in binary mode. number : int If 0, a single object will be returned (the first in the file). If >0, this specifies the number of objects to be unpickled, and a list will be returned with exactly that many objects. If <0, all objects in the file will be unpickled and returned as a list. Raises ------ EOFError If ``number`` is >0 and there are fewer than ``number`` objects in the pickled file. Returns ------- contents : obj or list If ``number`` is 0, this is a individual object - the first one unpickled from the file. Otherwise, it is a list of objects unpickled from the file. """ if isinstance(fileorname, str): f = open(fileorname, 'rb') close = True else: f = fileorname close = False try: if number > 0: # get that number res = [] for i in range(number): res.append(pickle.load(f)) elif number < 0: # get all objects res = [] eof = False while not eof: try: res.append(pickle.load(f)) except EOFError: eof = True else: # number==0 res = pickle.load(f) finally: if close: f.close() return res def fnpickle(object, fileorname, protocol=None, append=False): """Pickle an object to a specified file. Parameters ---------- object The python object to pickle. fileorname : str or file-like The filename or file into which the `object` should be pickled. If a file object, it should have been opened in binary mode. protocol : int or None Pickle protocol to use - see the :mod:`pickle` module for details on these options. If None, the most recent protocol will be used. append : bool If True, the object is appended to the end of the file, otherwise the file will be overwritten (if a file object is given instead of a file name, this has no effect). """ if protocol is None: protocol = pickle.HIGHEST_PROTOCOL if isinstance(fileorname, str): f = open(fileorname, 'ab' if append else 'wb') close = True else: f = fileorname close = False try: pickle.dump(object, f, protocol=protocol) finally: if close: f.close()
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Test the Quantity class and related.""" import copy import pickle import decimal import numbers from fractions import Fraction import pytest import numpy as np from numpy.testing import (assert_allclose, assert_array_equal, assert_array_almost_equal) from astropy.utils import isiterable, minversion from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning from astropy import units as u from astropy.units.quantity import _UNIT_NOT_INITIALISED """ The Quantity class will represent a number + unit + uncertainty """ class TestQuantityCreation: def test_1(self): # create objects through operations with Unit objects: quantity = 11.42 * u.meter # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = u.meter * 11.42 # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = 11.42 / u.meter assert isinstance(quantity, u.Quantity) quantity = u.meter / 11.42 assert isinstance(quantity, u.Quantity) quantity = 11.42 * u.meter / u.second assert isinstance(quantity, u.Quantity) with pytest.raises(TypeError): quantity = 182.234 + u.meter with pytest.raises(TypeError): quantity = 182.234 - u.meter with pytest.raises(TypeError): quantity = 182.234 % u.meter def test_2(self): # create objects using the Quantity constructor: _ = u.Quantity(11.412, unit=u.meter) _ = u.Quantity(21.52, "cm") q3 = u.Quantity(11.412) # By default quantities that don't specify a unit are unscaled # dimensionless assert q3.unit == u.Unit(1) with pytest.raises(TypeError): u.Quantity(object(), unit=u.m) def test_3(self): # with pytest.raises(u.UnitsError): with pytest.raises(ValueError): # Until @mdboom fixes the errors in units u.Quantity(11.412, unit="testingggg") def test_nan_inf(self): # Not-a-number q = u.Quantity('nan', unit='cm') assert np.isnan(q.value) q = u.Quantity('NaN', unit='cm') assert np.isnan(q.value) q = u.Quantity('-nan', unit='cm') # float() allows this assert np.isnan(q.value) q = u.Quantity('nan cm') assert np.isnan(q.value) assert q.unit == u.cm # Infinity q = u.Quantity('inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('-inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('inf cm') assert np.isinf(q.value) assert q.unit == u.cm q = u.Quantity('Infinity', unit='cm') # float() allows this assert np.isinf(q.value) # make sure these strings don't parse... with pytest.raises(TypeError): q = u.Quantity('', unit='cm') with pytest.raises(TypeError): q = u.Quantity('spam', unit='cm') def test_unit_property(self): # test getting and setting 'unit' attribute q1 = u.Quantity(11.4, unit=u.meter) with pytest.raises(AttributeError): q1.unit = u.cm def test_preserve_dtype(self): """Test that if an explicit dtype is given, it is used, while if not, numbers are converted to float (including decimal.Decimal, which numpy converts to an object; closes #1419) """ # If dtype is specified, use it, but if not, convert int, bool to float q1 = u.Quantity(12, unit=u.m / u.s, dtype=int) assert q1.dtype == int q2 = u.Quantity(q1) assert q2.dtype == float assert q2.value == float(q1.value) assert q2.unit == q1.unit # but we should preserve any float32 or even float16 a3_32 = np.array([1., 2.], dtype=np.float32) q3_32 = u.Quantity(a3_32, u.yr) assert q3_32.dtype == a3_32.dtype a3_16 = np.array([1., 2.], dtype=np.float16) q3_16 = u.Quantity(a3_16, u.yr) assert q3_16.dtype == a3_16.dtype # items stored as objects by numpy should be converted to float # by default q4 = u.Quantity(decimal.Decimal('10.25'), u.m) assert q4.dtype == float q5 = u.Quantity(decimal.Decimal('10.25'), u.m, dtype=object) assert q5.dtype == object def test_copy(self): # By default, a new quantity is constructed, but not if copy=False a = np.arange(10.) q0 = u.Quantity(a, unit=u.m / u.s) assert q0.base is not a q1 = u.Quantity(a, unit=u.m / u.s, copy=False) assert q1.base is a q2 = u.Quantity(q0) assert q2 is not q0 assert q2.base is not q0.base q2 = u.Quantity(q0, copy=False) assert q2 is q0 assert q2.base is q0.base q3 = u.Quantity(q0, q0.unit, copy=False) assert q3 is q0 assert q3.base is q0.base q4 = u.Quantity(q0, u.cm / u.s, copy=False) assert q4 is not q0 assert q4.base is not q0.base def test_subok(self): """Test subok can be used to keep class, or to insist on Quantity""" class MyQuantitySubclass(u.Quantity): pass myq = MyQuantitySubclass(np.arange(10.), u.m) # try both with and without changing the unit assert type(u.Quantity(myq)) is u.Quantity assert type(u.Quantity(myq, subok=True)) is MyQuantitySubclass assert type(u.Quantity(myq, u.km)) is u.Quantity assert type(u.Quantity(myq, u.km, subok=True)) is MyQuantitySubclass def test_order(self): """Test that order is correctly propagated to np.array""" ac = np.array(np.arange(10.), order='C') qcc = u.Quantity(ac, u.m, order='C') assert qcc.flags['C_CONTIGUOUS'] qcf = u.Quantity(ac, u.m, order='F') assert qcf.flags['F_CONTIGUOUS'] qca = u.Quantity(ac, u.m, order='A') assert qca.flags['C_CONTIGUOUS'] # check it works also when passing in a quantity assert u.Quantity(qcc, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='A').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='F').flags['F_CONTIGUOUS'] af = np.array(np.arange(10.), order='F') qfc = u.Quantity(af, u.m, order='C') assert qfc.flags['C_CONTIGUOUS'] qff = u.Quantity(ac, u.m, order='F') assert qff.flags['F_CONTIGUOUS'] qfa = u.Quantity(af, u.m, order='A') assert qfa.flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qff, order='A').flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='F').flags['F_CONTIGUOUS'] def test_ndmin(self): """Test that ndmin is correctly propagated to np.array""" a = np.arange(10.) q1 = u.Quantity(a, u.m, ndmin=1) assert q1.ndim == 1 and q1.shape == (10,) q2 = u.Quantity(a, u.m, ndmin=2) assert q2.ndim == 2 and q2.shape == (1, 10) # check it works also when passing in a quantity q3 = u.Quantity(q1, u.m, ndmin=3) assert q3.ndim == 3 and q3.shape == (1, 1, 10) # see github issue #10063 assert u.Quantity(u.Quantity(1, 'm'), 'm', ndmin=1).ndim == 1 assert u.Quantity(u.Quantity(1, 'cm'), 'm', ndmin=1).ndim == 1 def test_non_quantity_with_unit(self): """Test that unit attributes in objects get recognized.""" class MyQuantityLookalike(np.ndarray): pass a = np.arange(3.) mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = 'm' q1 = u.Quantity(mylookalike) assert isinstance(q1, u.Quantity) assert q1.unit is u.m assert np.all(q1.value == a) q2 = u.Quantity(mylookalike, u.mm) assert q2.unit is u.mm assert np.all(q2.value == 1000.*a) q3 = u.Quantity(mylookalike, copy=False) assert np.all(q3.value == mylookalike) q3[2] = 0 assert q3[2] == 0. assert mylookalike[2] == 0. mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = u.m q4 = u.Quantity(mylookalike, u.mm, copy=False) q4[2] = 0 assert q4[2] == 0. assert mylookalike[2] == 2. mylookalike.unit = 'nonsense' with pytest.raises(TypeError): u.Quantity(mylookalike) def test_creation_via_view(self): # This works but is no better than 1. * u.m q1 = 1. << u.m assert isinstance(q1, u.Quantity) assert q1.unit == u.m assert q1.value == 1. # With an array, we get an actual view. a2 = np.arange(10.) q2 = a2 << u.m / u.s assert isinstance(q2, u.Quantity) assert q2.unit == u.m / u.s assert np.all(q2.value == a2) a2[9] = 0. assert np.all(q2.value == a2) # But with a unit change we get a copy. q3 = q2 << u.mm / u.s assert isinstance(q3, u.Quantity) assert q3.unit == u.mm / u.s assert np.all(q3.value == a2 * 1000.) a2[8] = 0. assert q3[8].value == 8000. # Without a unit change, we do get a view. q4 = q2 << q2.unit a2[7] = 0. assert np.all(q4.value == a2) with pytest.raises(u.UnitsError): q2 << u.s # But one can do an in-place unit change. a2_copy = a2.copy() q2 <<= u.mm / u.s assert q2.unit == u.mm / u.s # Of course, this changes a2 as well. assert np.all(q2.value == a2) # Sanity check on the values. assert np.all(q2.value == a2_copy * 1000.) a2[8] = -1. # Using quantities, one can also work with strings. q5 = q2 << 'km/hr' assert q5.unit == u.km / u.hr assert np.all(q5 == q2) # Finally, we can use scalar quantities as units. not_quite_a_foot = 30. * u.cm a6 = np.arange(5.) q6 = a6 << not_quite_a_foot assert q6.unit == u.Unit(not_quite_a_foot) assert np.all(q6.to_value(u.cm) == 30. * a6) def test_rshift_warns(self): with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1 >> u.m assert len(warning_lines) == 1 q = 1. * u.km with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >> u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >>= u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1. >> q assert len(warning_lines) == 1 class TestQuantityOperations: q1 = u.Quantity(11.42, u.meter) q2 = u.Quantity(8.0, u.centimeter) def test_addition(self): # Take units from left object, q1 new_quantity = self.q1 + self.q2 assert new_quantity.value == 11.5 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 + self.q1 assert new_quantity.value == 1150.0 assert new_quantity.unit == u.centimeter new_q = u.Quantity(1500.1, u.m) + u.Quantity(13.5, u.km) assert new_q.unit == u.m assert new_q.value == 15000.1 def test_subtraction(self): # Take units from left object, q1 new_quantity = self.q1 - self.q2 assert new_quantity.value == 11.34 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 - self.q1 assert new_quantity.value == -1134.0 assert new_quantity.unit == u.centimeter def test_multiplication(self): # Take units from left object, q1 new_quantity = self.q1 * self.q2 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.meter * u.centimeter) # Take units from left object, q2 new_quantity = self.q2 * self.q1 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.centimeter * u.meter) # Multiply with a number new_quantity = 15. * self.q1 assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter # Multiply with a number new_quantity = self.q1 * 15. assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter def test_division(self): # Take units from left object, q1 new_quantity = self.q1 / self.q2 assert_array_almost_equal(new_quantity.value, 1.4275, decimal=5) assert new_quantity.unit == (u.meter / u.centimeter) # Take units from left object, q2 new_quantity = self.q2 / self.q1 assert_array_almost_equal(new_quantity.value, 0.70052539404553416, decimal=16) assert new_quantity.unit == (u.centimeter / u.meter) q1 = u.Quantity(11.4, unit=u.meter) q2 = u.Quantity(10.0, unit=u.second) new_quantity = q1 / q2 assert_array_almost_equal(new_quantity.value, 1.14, decimal=10) assert new_quantity.unit == (u.meter / u.second) # divide with a number new_quantity = self.q1 / 10. assert new_quantity.value == 1.142 assert new_quantity.unit == u.meter # divide with a number new_quantity = 11.42 / self.q1 assert new_quantity.value == 1. assert new_quantity.unit == u.Unit("1/m") def test_commutativity(self): """Regression test for issue #587.""" new_q = u.Quantity(11.42, 'm*s') assert self.q1 * u.s == u.s * self.q1 == new_q assert self.q1 / u.s == u.Quantity(11.42, 'm/s') assert u.s / self.q1 == u.Quantity(1 / 11.42, 's/m') def test_power(self): # raise quantity to a power new_quantity = self.q1 ** 2 assert_array_almost_equal(new_quantity.value, 130.4164, decimal=5) assert new_quantity.unit == u.Unit("m^2") new_quantity = self.q1 ** 3 assert_array_almost_equal(new_quantity.value, 1489.355288, decimal=7) assert new_quantity.unit == u.Unit("m^3") def test_matrix_multiplication(self): a = np.eye(3) q = a * u.m result1 = q @ a assert np.all(result1 == q) result2 = a @ q assert np.all(result2 == q) result3 = q @ q assert np.all(result3 == a * u.m ** 2) # less trivial case. q2 = np.array([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [[0., 1., 0.], [0., 0., 1.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]]]) / u.s result4 = q @ q2 assert np.all(result4 == np.matmul(a, q2.value) * q.unit * q2.unit) def test_unary(self): # Test the minus unary operator new_quantity = -self.q1 assert new_quantity.value == -self.q1.value assert new_quantity.unit == self.q1.unit new_quantity = -(-self.q1) assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit # Test the plus unary operator new_quantity = +self.q1 assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit def test_abs(self): q = 1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == q.value assert new_quantity.unit == q.unit q = -1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == -q.value assert new_quantity.unit == q.unit def test_incompatible_units(self): """ When trying to add or subtract units that aren't compatible, throw an error """ q1 = u.Quantity(11.412, unit=u.meter) q2 = u.Quantity(21.52, unit=u.second) with pytest.raises(u.UnitsError): q1 + q2 def test_non_number_type(self): q1 = u.Quantity(11.412, unit=u.meter) with pytest.raises(TypeError) as exc: q1 + {'a': 1} assert exc.value.args[0].startswith( "Unsupported operand type(s) for ufunc add:") with pytest.raises(TypeError): q1 + u.meter def test_dimensionless_operations(self): # test conversion to dimensionless dq = 3. * u.m / u.km dq1 = dq + 1. * u.mm / u.km assert dq1.value == 3.001 assert dq1.unit == dq.unit dq2 = dq + 1. assert dq2.value == 1.003 assert dq2.unit == u.dimensionless_unscaled # this test will check that operations with dimensionless Quantities # don't work with pytest.raises(u.UnitsError): self.q1 + u.Quantity(0.1, unit=u.Unit("")) with pytest.raises(u.UnitsError): self.q1 - u.Quantity(0.1, unit=u.Unit("")) # and test that scaling of integers works q = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int) q2 = q + np.array([4, 5, 6]) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, np.array([4.001, 5.002, 6.003])) # but not if doing it inplace with pytest.raises(TypeError): q += np.array([1, 2, 3]) # except if it is actually possible q = np.array([1, 2, 3]) * u.km / u.m q += np.array([4, 5, 6]) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == np.array([1004, 2005, 3006])) def test_complicated_operation(self): """ Perform a more complicated test """ from astropy.units import imperial # Multiple units distance = u.Quantity(15., u.meter) time = u.Quantity(11., u.second) velocity = (distance / time).to(imperial.mile / u.hour) assert_array_almost_equal( velocity.value, 3.05037, decimal=5) G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2) _ = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg)) # Area side1 = u.Quantity(11., u.centimeter) side2 = u.Quantity(7., u.centimeter) area = side1 * side2 assert_array_almost_equal(area.value, 77., decimal=15) assert area.unit == u.cm * u.cm def test_comparison(self): # equality/ non-equality is straightforward for quantity objects assert (1 / (u.cm * u.cm)) == 1 * u.cm ** -2 assert 1 * u.m == 100 * u.cm assert 1 * u.m != 1 * u.cm # when one is a unit, Quantity does not know what to do, # but unit is fine with it, so it still works unit = u.cm**3 q = 1. * unit assert q.__eq__(unit) is NotImplemented assert unit.__eq__(q) is True assert q == unit q = 1000. * u.mm**3 assert q == unit # mismatched types should never work assert not 1. * u.cm == 1. assert 1. * u.cm != 1. # comparison with zero should raise a deprecation warning for quantity in (1. * u.cm, 1. * u.dimensionless_unscaled): with pytest.warns(AstropyDeprecationWarning, match='The truth value of ' 'a Quantity is ambiguous. In the future this will ' 'raise a ValueError.'): bool(quantity) def test_numeric_converters(self): # float, int, long, and __index__ should only work for single # quantities, of appropriate type, and only if they are dimensionless. # for index, this should be unscaled as well # (Check on __index__ is also a regression test for #1557) # quantities with units should never convert, or be usable as an index q1 = u.Quantity(1, u.m) converter_err_msg = ("only dimensionless scalar quantities " "can be converted to Python scalars") index_err_msg = ("only integer dimensionless scalar quantities " "can be converted to a Python index") with pytest.raises(TypeError) as exc: float(q1) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q1) assert exc.value.args[0] == converter_err_msg # We used to test `q1 * ['a', 'b', 'c'] here, but that that worked # at all was a really odd confluence of bugs. Since it doesn't work # in numpy >=1.10 any more, just go directly for `__index__` (which # makes the test more similar to the `int`, `long`, etc., tests). with pytest.raises(TypeError) as exc: q1.__index__() assert exc.value.args[0] == index_err_msg # dimensionless but scaled is OK, however q2 = u.Quantity(1.23, u.m / u.km) assert float(q2) == float(q2.to_value(u.dimensionless_unscaled)) assert int(q2) == int(q2.to_value(u.dimensionless_unscaled)) with pytest.raises(TypeError) as exc: q2.__index__() assert exc.value.args[0] == index_err_msg # dimensionless unscaled is OK, though for index needs to be int q3 = u.Quantity(1.23, u.dimensionless_unscaled) assert float(q3) == 1.23 assert int(q3) == 1 with pytest.raises(TypeError) as exc: q3.__index__() assert exc.value.args[0] == index_err_msg # integer dimensionless unscaled is good for all q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert float(q4) == 2. assert int(q4) == 2 assert q4.__index__() == 2 # but arrays are not OK q5 = u.Quantity([1, 2], u.m) with pytest.raises(TypeError) as exc: float(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: q5.__index__() assert exc.value.args[0] == index_err_msg # See https://github.com/numpy/numpy/issues/5074 # It seems unlikely this will be resolved, so xfail'ing it. @pytest.mark.xfail(reason="list multiplication only works for numpy <=1.10") def test_numeric_converter_to_index_in_practice(self): """Test that use of __index__ actually works.""" q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert q4 * ['a', 'b', 'c'] == ['a', 'b', 'c', 'a', 'b', 'c'] def test_array_converters(self): # Scalar quantity q = u.Quantity(1.23, u.m) assert np.all(np.array(q) == np.array([1.23])) # Array quantity q = u.Quantity([1., 2., 3.], u.m) assert np.all(np.array(q) == np.array([1., 2., 3.])) def test_quantity_conversion(): q1 = u.Quantity(0.1, unit=u.meter) value = q1.value assert value == 0.1 value_in_km = q1.to_value(u.kilometer) assert value_in_km == 0.0001 new_quantity = q1.to(u.kilometer) assert new_quantity.value == 0.0001 with pytest.raises(u.UnitsError): q1.to(u.zettastokes) with pytest.raises(u.UnitsError): q1.to_value(u.zettastokes) def test_quantity_value_views(): q1 = u.Quantity([1., 2.], unit=u.meter) # views if the unit is the same. v1 = q1.value v1[0] = 0. assert np.all(q1 == [0., 2.] * u.meter) v2 = q1.to_value() v2[1] = 3. assert np.all(q1 == [0., 3.] * u.meter) v3 = q1.to_value('m') v3[0] = 1. assert np.all(q1 == [1., 3.] * u.meter) q2 = q1.to('m', copy=False) q2[0] = 2 * u.meter assert np.all(q1 == [2., 3.] * u.meter) v4 = q1.to_value('cm') v4[0] = 0. # copy if different unit. assert np.all(q1 == [2., 3.] * u.meter) def test_quantity_conversion_with_equiv(): q1 = u.Quantity(0.1, unit=u.meter) v2 = q1.to_value(u.Hz, equivalencies=u.spectral()) assert_allclose(v2, 2997924580.0) q2 = q1.to(u.Hz, equivalencies=u.spectral()) assert_allclose(q2.value, v2) q1 = u.Quantity(0.4, unit=u.arcsecond) v2 = q1.to_value(u.au, equivalencies=u.parallax()) q2 = q1.to(u.au, equivalencies=u.parallax()) v3 = q2.to_value(u.arcminute, equivalencies=u.parallax()) q3 = q2.to(u.arcminute, equivalencies=u.parallax()) assert_allclose(v2, 515662.015) assert_allclose(q2.value, v2) assert q2.unit == u.au assert_allclose(v3, 0.0066666667) assert_allclose(q3.value, v3) assert q3.unit == u.arcminute def test_quantity_conversion_equivalency_passed_on(): class MySpectral(u.Quantity): _equivalencies = u.spectral() def __quantity_view__(self, obj, unit): return obj.view(MySpectral) def __quantity_instance__(self, *args, **kwargs): return MySpectral(*args, **kwargs) q1 = MySpectral([1000, 2000], unit=u.Hz) q2 = q1.to(u.nm) assert q2.unit == u.nm q3 = q2.to(u.Hz) assert q3.unit == u.Hz assert_allclose(q3.value, q1.value) q4 = MySpectral([1000, 2000], unit=u.nm) q5 = q4.to(u.Hz).to(u.nm) assert q5.unit == u.nm assert_allclose(q4.value, q5.value) # Regression test for issue #2315, divide-by-zero error when examining 0*unit def test_self_equivalency(): assert u.deg.is_equivalent(0*u.radian) assert u.deg.is_equivalent(1*u.radian) def test_si(): q1 = 10. * u.m * u.s ** 2 / (200. * u.ms) ** 2 # 250 meters assert q1.si.value == 250 assert q1.si.unit == u.m q = 10. * u.m # 10 meters assert q.si.value == 10 assert q.si.unit == u.m q = 10. / u.m # 10 1 / meters assert q.si.value == 10 assert q.si.unit == (1 / u.m) def test_cgs(): q1 = 10. * u.cm * u.s ** 2 / (200. * u.ms) ** 2 # 250 centimeters assert q1.cgs.value == 250 assert q1.cgs.unit == u.cm q = 10. * u.m # 10 centimeters assert q.cgs.value == 1000 assert q.cgs.unit == u.cm q = 10. / u.cm # 10 1 / centimeters assert q.cgs.value == 10 assert q.cgs.unit == (1 / u.cm) q = 10. * u.Pa # 10 pascals assert q.cgs.value == 100 assert q.cgs.unit == u.barye class TestQuantityComparison: def test_quantity_equality(self): assert u.Quantity(1000, unit='m') == u.Quantity(1, unit='km') assert not (u.Quantity(1, unit='m') == u.Quantity(1, unit='km')) # for ==, !=, return False, True if units do not match assert (u.Quantity(1100, unit=u.m) != u.Quantity(1, unit=u.s)) is True assert (u.Quantity(1100, unit=u.m) == u.Quantity(1, unit=u.s)) is False assert (u.Quantity(0, unit=u.m) == u.Quantity(0, unit=u.s)) is False # But allow comparison with 0, +/-inf if latter unitless assert u.Quantity(0, u.m) == 0. assert u.Quantity(1, u.m) != 0. assert u.Quantity(1, u.m) != np.inf assert u.Quantity(np.inf, u.m) == np.inf def test_quantity_equality_array(self): a = u.Quantity([0., 1., 1000.], u.m) b = u.Quantity(1., u.km) eq = a == b ne = a != b assert np.all(eq == [False, False, True]) assert np.all(eq != ne) # For mismatched units, we should just get True, False c = u.Quantity(1., u.s) eq = a == c ne = a != c assert eq is False assert ne is True # Constants are treated as dimensionless, so False too. eq = a == 1. ne = a != 1. assert eq is False assert ne is True # But 0 can have any units, so we can compare. eq = a == 0 ne = a != 0 assert np.all(eq == [True, False, False]) assert np.all(eq != ne) # But we do not extend that to arrays; they should have the same unit. d = np.array([0, 1., 1000.]) eq = a == d ne = a != d assert eq is False assert ne is True def test_quantity_comparison(self): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second) assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity( 1100, unit=u.meter) >= u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second) assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer) class TestQuantityDisplay: scalarintq = u.Quantity(1, unit='m', dtype=int) scalarfloatq = u.Quantity(1.3, unit='m') arrq = u.Quantity([1, 2.3, 8.9], unit='m') scalar_complex_q = u.Quantity(complex(1.0, 2.0)) scalar_big_complex_q = u.Quantity(complex(1.0, 2.0e27) * 1e25) scalar_big_neg_complex_q = u.Quantity(complex(-1.0, -2.0e27) * 1e36) arr_complex_q = u.Quantity(np.arange(3) * (complex(-1.0, -2.0e27) * 1e36)) big_arr_complex_q = u.Quantity(np.arange(125) * (complex(-1.0, -2.0e27) * 1e36)) def test_dimensionless_quantity_repr(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert repr(self.scalarintq * q2) == "<Quantity 1.>" assert repr(self.arrq * q2) == "<Quantity [1. , 2.3, 8.9]>" assert repr(self.scalarintq * q3) == "<Quantity 1>" def test_dimensionless_quantity_str(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert str(self.scalarintq * q2) == "1.0" assert str(self.scalarintq * q3) == "1" assert str(self.arrq * q2) == "[1. 2.3 8.9]" def test_dimensionless_quantity_format(self): q1 = u.Quantity(3.14) assert format(q1, '.2f') == '3.14' def test_scalar_quantity_str(self): assert str(self.scalarintq) == "1 m" assert str(self.scalarfloatq) == "1.3 m" def test_scalar_quantity_repr(self): assert repr(self.scalarintq) == "<Quantity 1 m>" assert repr(self.scalarfloatq) == "<Quantity 1.3 m>" def test_array_quantity_str(self): assert str(self.arrq) == "[1. 2.3 8.9] m" def test_array_quantity_repr(self): assert repr(self.arrq) == "<Quantity [1. , 2.3, 8.9] m>" def test_scalar_quantity_format(self): assert format(self.scalarintq, '02d') == "01 m" assert format(self.scalarfloatq, '.1f') == "1.3 m" assert format(self.scalarfloatq, '.0f') == "1 m" def test_uninitialized_unit_format(self): bad_quantity = np.arange(10.).view(u.Quantity) assert str(bad_quantity).endswith(_UNIT_NOT_INITIALISED) assert repr(bad_quantity).endswith(_UNIT_NOT_INITIALISED + '>') def test_to_string(self): qscalar = u.Quantity(1.5e14, 'm/s') # __str__ is the default `format` assert str(qscalar) == qscalar.to_string() res = 'Quantity as KMS: 150000000000.0 km / s' assert f"Quantity as KMS: {qscalar.to_string(unit=u.km / u.s)}" == res # With precision set res = 'Quantity as KMS: 1.500e+11 km / s' assert f"Quantity as KMS: {qscalar.to_string(precision=3, unit=u.km / u.s)}" == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex") == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="inline") == res res = r'$\displaystyle 1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="display") == res def test_repr_latex(self): from astropy.units.quantity import conf q2scalar = u.Quantity(1.5e14, 'm/s') assert self.scalarintq._repr_latex_() == r'$1 \; \mathrm{m}$' assert self.scalarfloatq._repr_latex_() == r'$1.3 \; \mathrm{m}$' assert (q2scalar._repr_latex_() == r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$') assert self.arrq._repr_latex_() == r'$[1,~2.3,~8.9] \; \mathrm{m}$' # Complex quantities assert self.scalar_complex_q._repr_latex_() == r'$(1+2i) \; \mathrm{}$' assert (self.scalar_big_complex_q._repr_latex_() == r'$(1 \times 10^{25}+2 \times 10^{52}i) \; \mathrm{}$') assert (self.scalar_big_neg_complex_q._repr_latex_() == r'$(-1 \times 10^{36}-2 \times 10^{63}i) \; \mathrm{}$') assert (self.arr_complex_q._repr_latex_() == (r'$[(0-0i),~(-1 \times 10^{36}-2 \times 10^{63}i),' r'~(-2 \times 10^{36}-4 \times 10^{63}i)] \; \mathrm{}$')) assert r'\dots' in self.big_arr_complex_q._repr_latex_() qmed = np.arange(100)*u.m qbig = np.arange(1000)*u.m qvbig = np.arange(10000)*1e9*u.m pops = np.get_printoptions() oldlat = conf.latex_array_threshold try: # check precision behavior q = u.Quantity(987654321.123456789, 'm/s') qa = np.array([7.89123, 123456789.987654321, 0]) * u.cm np.set_printoptions(precision=8) assert q._repr_latex_() == r'$9.8765432 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.89123,~1.2345679 \times 10^{8},~0] \; \mathrm{cm}$' np.set_printoptions(precision=2) assert q._repr_latex_() == r'$9.9 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.9,~1.2 \times 10^{8},~0] \; \mathrm{cm}$' # check thresholding behavior conf.latex_array_threshold = 100 # should be default lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = 1001 lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' not in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = -1 # means use the numpy threshold np.set_printoptions(threshold=99) lsmed = qmed._repr_latex_() assert r'\dots' in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig finally: # prevent side-effects from influencing other tests np.set_printoptions(**pops) conf.latex_array_threshold = oldlat qinfnan = [np.inf, -np.inf, np.nan] * u.m assert qinfnan._repr_latex_() == r'$[\infty,~-\infty,~{\rm NaN}] \; \mathrm{m}$' def test_decompose(): q1 = 5 * u.N assert q1.decompose() == (5 * u.kg * u.m * u.s ** -2) def test_decompose_regression(): """ Regression test for bug #1163 If decompose was called multiple times on a Quantity with an array and a scale != 1, the result changed every time. This is because the value was being referenced not copied, then modified, which changed the original value. """ q = np.array([1, 2, 3]) * u.m / (2. * u.km) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) assert np.all(q == np.array([1, 2, 3]) * u.m / (2. * u.km)) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) def test_arrays(): """ Test using quantites with array values """ qsec = u.Quantity(np.arange(10), u.second) assert isinstance(qsec.value, np.ndarray) assert not qsec.isscalar # len and indexing should work for arrays assert len(qsec) == len(qsec.value) qsecsub25 = qsec[2:5] assert qsecsub25.unit == qsec.unit assert isinstance(qsecsub25, u.Quantity) assert len(qsecsub25) == 3 # make sure isscalar, len, and indexing behave correcly for non-arrays. qsecnotarray = u.Quantity(10., u.second) assert qsecnotarray.isscalar with pytest.raises(TypeError): len(qsecnotarray) with pytest.raises(TypeError): qsecnotarray[0] qseclen0array = u.Quantity(np.array(10), u.second, dtype=int) # 0d numpy array should act basically like a scalar assert qseclen0array.isscalar with pytest.raises(TypeError): len(qseclen0array) with pytest.raises(TypeError): qseclen0array[0] assert isinstance(qseclen0array.value, numbers.Integral) a = np.array([(1., 2., 3.), (4., 5., 6.), (7., 8., 9.)], dtype=[('x', float), ('y', float), ('z', float)]) qkpc = u.Quantity(a, u.kpc) assert not qkpc.isscalar qkpc0 = qkpc[0] assert qkpc0.value == a[0] assert qkpc0.unit == qkpc.unit assert isinstance(qkpc0, u.Quantity) assert qkpc0.isscalar qkpcx = qkpc['x'] assert np.all(qkpcx.value == a['x']) assert qkpcx.unit == qkpc.unit assert isinstance(qkpcx, u.Quantity) assert not qkpcx.isscalar qkpcx1 = qkpc['x'][1] assert qkpcx1.unit == qkpc.unit assert isinstance(qkpcx1, u.Quantity) assert qkpcx1.isscalar qkpc1x = qkpc[1]['x'] assert qkpc1x.isscalar assert qkpc1x == qkpcx1 # can also create from lists, will auto-convert to arrays qsec = u.Quantity(list(range(10)), u.second) assert isinstance(qsec.value, np.ndarray) # quantity math should work with arrays assert_array_equal((qsec * 2).value, (np.arange(10) * 2)) assert_array_equal((qsec / 2).value, (np.arange(10) / 2)) # quantity addition/subtraction should *not* work with arrays b/c unit # ambiguous with pytest.raises(u.UnitsError): assert_array_equal((qsec + 2).value, (np.arange(10) + 2)) with pytest.raises(u.UnitsError): assert_array_equal((qsec - 2).value, (np.arange(10) + 2)) # should create by unit multiplication, too qsec2 = np.arange(10) * u.second qsec3 = u.second * np.arange(10) assert np.all(qsec == qsec2) assert np.all(qsec2 == qsec3) # make sure numerical-converters fail when arrays are present with pytest.raises(TypeError): float(qsec) with pytest.raises(TypeError): int(qsec) def test_array_indexing_slicing(): q = np.array([1., 2., 3.]) * u.m assert q[0] == 1. * u.m assert np.all(q[0:2] == u.Quantity([1., 2.], u.m)) def test_array_setslice(): q = np.array([1., 2., 3.]) * u.m q[1:2] = np.array([400.]) * u.cm assert np.all(q == np.array([1., 4., 3.]) * u.m) def test_inverse_quantity(): """ Regression test from issue #679 """ q = u.Quantity(4., u.meter / u.second) qot = q / 2 toq = 2 / q npqot = q / np.array(2) assert npqot.value == 2.0 assert npqot.unit == (u.meter / u.second) assert qot.value == 2.0 assert qot.unit == (u.meter / u.second) assert toq.value == 0.5 assert toq.unit == (u.second / u.meter) def test_quantity_mutability(): q = u.Quantity(9.8, u.meter / u.second / u.second) with pytest.raises(AttributeError): q.value = 3 with pytest.raises(AttributeError): q.unit = u.kg def test_quantity_initialized_with_quantity(): q1 = u.Quantity(60, u.second) q2 = u.Quantity(q1, u.minute) assert q2.value == 1 q3 = u.Quantity([q1, q2], u.second) assert q3[0].value == 60 assert q3[1].value == 60 q4 = u.Quantity([q2, q1]) assert q4.unit == q2.unit assert q4[0].value == 1 assert q4[1].value == 1 def test_quantity_string_unit(): q1 = 1. * u.m / 's' assert q1.value == 1 assert q1.unit == (u.m / u.s) q2 = q1 * "m" assert q2.unit == ((u.m * u.m) / u.s) def test_quantity_invalid_unit_string(): with pytest.raises(ValueError): "foo" * u.m def test_implicit_conversion(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True assert_allclose(q.centimeter, 100) assert_allclose(q.cm, 100) assert_allclose(q.parsec, 3.240779289469756e-17) def test_implicit_conversion_autocomplete(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True q.foo = 42 attrs = dir(q) assert 'centimeter' in attrs assert 'cm' in attrs assert 'parsec' in attrs assert 'foo' in attrs assert 'to' in attrs assert 'value' in attrs # Something from the base class, object assert '__setattr__' in attrs with pytest.raises(AttributeError): q.l def test_quantity_iterability(): """Regressiont est for issue #878. Scalar quantities should not be iterable and should raise a type error on iteration. """ q1 = [15.0, 17.0] * u.m assert isiterable(q1) q2 = next(iter(q1)) assert q2 == 15.0 * u.m assert not isiterable(q2) pytest.raises(TypeError, iter, q2) def test_copy(): q1 = u.Quantity(np.array([[1., 2., 3.], [4., 5., 6.]]), unit=u.m) q2 = q1.copy() assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value q3 = q1.copy(order='F') assert q3.flags['F_CONTIGUOUS'] assert np.all(q1.value == q3.value) assert q1.unit == q3.unit assert q1.dtype == q3.dtype assert q1.value is not q3.value q4 = q1.copy(order='C') assert q4.flags['C_CONTIGUOUS'] assert np.all(q1.value == q4.value) assert q1.unit == q4.unit assert q1.dtype == q4.dtype assert q1.value is not q4.value def test_deepcopy(): q1 = u.Quantity(np.array([1., 2., 3.]), unit=u.m) q2 = copy.deepcopy(q1) assert isinstance(q2, u.Quantity) assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value def test_equality_numpy_scalar(): """ A regression test to ensure that numpy scalars are correctly compared (which originally failed due to the lack of ``__array_priority__``). """ assert 10 != 10. * u.m assert np.int64(10) != 10 * u.m assert 10 * u.m != np.int64(10) def test_quantity_pickelability(): """ Testing pickleability of quantity """ q1 = np.arange(10) * u.m q2 = pickle.loads(pickle.dumps(q1)) assert np.all(q1.value == q2.value) assert q1.unit.is_equivalent(q2.unit) assert q1.unit == q2.unit def test_quantity_initialisation_from_string(): q = u.Quantity('1') assert q.unit == u.dimensionless_unscaled assert q.value == 1. q = u.Quantity('1.5 m/s') assert q.unit == u.m/u.s assert q.value == 1.5 assert u.Unit(q) == u.Unit('1.5 m/s') q = u.Quantity('.5 m') assert q == u.Quantity(0.5, u.m) q = u.Quantity('-1e1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('-1e+1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('+.5km') assert q == u.Quantity(.5, u.km) q = u.Quantity('+5e-1km') assert q == u.Quantity(.5, u.km) q = u.Quantity('5', u.m) assert q == u.Quantity(5., u.m) q = u.Quantity('5 km', u.m) assert q.value == 5000. assert q.unit == u.m q = u.Quantity('5Em') assert q == u.Quantity(5., u.Em) with pytest.raises(TypeError): u.Quantity('') with pytest.raises(TypeError): u.Quantity('m') with pytest.raises(TypeError): u.Quantity('1.2.3 deg') with pytest.raises(TypeError): u.Quantity('1+deg') with pytest.raises(TypeError): u.Quantity('1-2deg') with pytest.raises(TypeError): u.Quantity('1.2e-13.3m') with pytest.raises(TypeError): u.Quantity(['5']) with pytest.raises(TypeError): u.Quantity(np.array(['5'])) with pytest.raises(ValueError): u.Quantity('5E') with pytest.raises(ValueError): u.Quantity('5 foo') def test_unsupported(): q1 = np.arange(10) * u.m with pytest.raises(TypeError): np.bitwise_and(q1, q1) def test_unit_identity(): q = 1.0 * u.hour assert q.unit is u.hour def test_quantity_to_view(): q1 = np.array([1000, 2000]) * u.m q2 = q1.to(u.km) assert q1.value[0] == 1000 assert q2.value[0] == 1 def test_quantity_tuple_power(): with pytest.raises(ValueError): (5.0 * u.m) ** (1, 2) def test_quantity_fraction_power(): q = (25.0 * u.m**2) ** Fraction(1, 2) assert q.value == 5. assert q.unit == u.m # Regression check to ensure we didn't create an object type by raising # the value of the quantity to a Fraction. [#3922] assert q.dtype.kind == 'f' def test_quantity_from_table(): """ Checks that units from tables are respected when converted to a Quantity. This also generically checks the use of *anything* with a `unit` attribute passed into Quantity """ from astropy.table import Table t = Table(data=[np.arange(5), np.arange(5)], names=['a', 'b']) t['a'].unit = u.kpc qa = u.Quantity(t['a']) assert qa.unit == u.kpc assert_array_equal(qa.value, t['a']) qb = u.Quantity(t['b']) assert qb.unit == u.dimensionless_unscaled assert_array_equal(qb.value, t['b']) # This does *not* auto-convert, because it's not necessarily obvious that's # desired. Instead we revert to standard `Quantity` behavior qap = u.Quantity(t['a'], u.pc) assert qap.unit == u.pc assert_array_equal(qap.value, t['a'] * 1000) qbp = u.Quantity(t['b'], u.pc) assert qbp.unit == u.pc assert_array_equal(qbp.value, t['b']) # Also check with a function unit (regression test for gh-8430) t['a'].unit = u.dex(u.cm/u.s**2) fq = u.Dex(t['a']) assert fq.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq.value, t['a']) fq2 = u.Quantity(t['a'], subok=True) assert isinstance(fq2, u.Dex) assert fq2.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq2.value, t['a']) with pytest.raises(u.UnitTypeError): u.Quantity(t['a']) def test_assign_slice_with_quantity_like(): # Regression tests for gh-5961 from astropy.table import Table, Column # first check directly that we can use a Column to assign to a slice. c = Column(np.arange(10.), unit=u.mm) q = u.Quantity(c) q[:2] = c[:2] # next check that we do not fail the original problem. t = Table() t['x'] = np.arange(10) * u.mm t['y'] = np.ones(10) * u.mm assert type(t['x']) is Column xy = np.vstack([t['x'], t['y']]).T * u.mm ii = [0, 2, 4] assert xy[ii, 0].unit == t['x'][ii].unit # should not raise anything xy[ii, 0] = t['x'][ii] def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]]) def test_repr_array_of_quantity(): """ Test print/repr of object arrays of Quantity objects with different units. Regression test for the issue first reported in https://github.com/astropy/astropy/issues/3777 """ a = np.array([1 * u.m, 2 * u.s], dtype=object) assert repr(a) == 'array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)' assert str(a) == '[<Quantity 1. m> <Quantity 2. s>]' class TestSpecificTypeQuantity: def setup(self): class Length(u.SpecificTypeQuantity): _equivalent_unit = u.m class Length2(Length): _default_unit = u.m class Length3(Length): _unit = u.m self.Length = Length self.Length2 = Length2 self.Length3 = Length3 def test_creation(self): l = self.Length(np.arange(10.)*u.km) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.) * u.hour) with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.)) l2 = self.Length2(np.arange(5.)) assert type(l2) is self.Length2 assert l2._default_unit is self.Length2._default_unit with pytest.raises(u.UnitTypeError): self.Length3(np.arange(10.)) def test_view(self): l = (np.arange(5.) * u.km).view(self.Length) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): (np.arange(5.) * u.s).view(self.Length) v = np.arange(5.).view(self.Length) assert type(v) is self.Length assert v._unit is None l3 = np.ones((2, 2)).view(self.Length3) assert type(l3) is self.Length3 assert l3.unit is self.Length3._unit def test_operation_precedence_and_fallback(self): l = self.Length(np.arange(5.)*u.cm) sum1 = l + 1.*u.m assert type(sum1) is self.Length sum2 = 1.*u.km + l assert type(sum2) is self.Length sum3 = l + l assert type(sum3) is self.Length res1 = l * (1.*u.m) assert type(res1) is u.Quantity res2 = l * l assert type(res2) is u.Quantity def test_unit_class_override(): class MyQuantity(u.Quantity): pass my_unit = u.Unit("my_deg", u.deg) my_unit._quantity_class = MyQuantity q1 = u.Quantity(1., my_unit) assert type(q1) is u.Quantity q2 = u.Quantity(1., my_unit, subok=True) assert type(q2) is MyQuantity class QuantityMimic: def __init__(self, value, unit): self.value = value self.unit = unit def __array__(self): return np.array(self.value) class QuantityMimic2(QuantityMimic): def to(self, unit): return u.Quantity(self.value, self.unit).to(unit) def to_value(self, unit): return u.Quantity(self.value, self.unit).to_value(unit) class TestQuantityMimics: """Test Quantity Mimics that are not ndarray subclasses.""" @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_input(self, Mimic): value = np.arange(10.) mimic = Mimic(value, u.m) q = u.Quantity(mimic) assert q.unit == u.m assert np.all(q.value == value) q2 = u.Quantity(mimic, u.cm) assert q2.unit == u.cm assert np.all(q2.value == 100 * value) @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_setting(self, Mimic): mimic = Mimic([1., 2.], u.m) q = u.Quantity(np.arange(10.), u.cm) q[8:] = mimic assert np.all(q[:8].value == np.arange(8.)) assert np.all(q[8:].value == [100., 200.]) def test_mimic_function_unit(self): mimic = QuantityMimic([1., 2.], u.dex(u.cm/u.s**2)) d = u.Dex(mimic) assert isinstance(d, u.Dex) assert d.unit == u.dex(u.cm/u.s**2) assert np.all(d.value == [1., 2.]) q = u.Quantity(mimic, subok=True) assert isinstance(q, u.Dex) assert q.unit == u.dex(u.cm/u.s**2) assert np.all(q.value == [1., 2.]) with pytest.raises(u.UnitTypeError): u.Quantity(mimic) def test_masked_quantity_str_repr(): """Ensure we don't break masked Quantity representation.""" # Really, masked quantities do not work well, but at least let the # basics work. masked_quantity = np.ma.array([1, 2, 3, 4] * u.kg, mask=[True, False, True, False]) str(masked_quantity) repr(masked_quantity) class TestQuantitySubclassAboveAndBelow: @classmethod def setup_class(self): class MyArray(np.ndarray): def __array_finalize__(self, obj): super_array_finalize = super().__array_finalize__ if super_array_finalize is not None: super_array_finalize(obj) if hasattr(obj, 'my_attr'): self.my_attr = obj.my_attr self.MyArray = MyArray self.MyQuantity1 = type('MyQuantity1', (u.Quantity, MyArray), dict(my_attr='1')) self.MyQuantity2 = type('MyQuantity2', (MyArray, u.Quantity), dict(my_attr='2')) def test_setup(self): mq1 = self.MyQuantity1(10, u.m) assert isinstance(mq1, self.MyQuantity1) assert mq1.my_attr == '1' assert mq1.unit is u.m mq2 = self.MyQuantity2(10, u.m) assert isinstance(mq2, self.MyQuantity2) assert mq2.my_attr == '2' assert mq2.unit is u.m def test_attr_propagation(self): mq1 = self.MyQuantity1(10, u.m) mq12 = self.MyQuantity2(mq1) assert isinstance(mq12, self.MyQuantity2) assert not isinstance(mq12, self.MyQuantity1) assert mq12.my_attr == '1' assert mq12.unit is u.m mq2 = self.MyQuantity2(10, u.m) mq21 = self.MyQuantity1(mq2) assert isinstance(mq21, self.MyQuantity1) assert not isinstance(mq21, self.MyQuantity2) assert mq21.my_attr == '2' assert mq21.unit is u.m
dhomeier/astropy
astropy/units/tests/test_quantity.py
astropy/io/misc/pickle_helpers.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import io import os from os.path import join import os.path import shutil import sys from collections import defaultdict from setuptools import Extension from setuptools.dep_util import newer_group import numpy from extension_helpers import import_file, write_if_different, get_compiler, pkg_config WCSROOT = os.path.relpath(os.path.dirname(__file__)) WCSVERSION = "7.6" def b(s): return s.encode('ascii') def string_escape(s): s = s.decode('ascii').encode('ascii', 'backslashreplace') s = s.replace(b'\n', b'\\n') s = s.replace(b'\0', b'\\0') return s.decode('ascii') def determine_64_bit_int(): """ The only configuration parameter needed at compile-time is how to specify a 64-bit signed integer. Python's ctypes module can get us that information. If we can't be absolutely certain, we default to "long long int", which is correct on most platforms (x86, x86_64). If we find platforms where this heuristic doesn't work, we may need to hardcode for them. """ try: try: import ctypes except ImportError: raise ValueError() if ctypes.sizeof(ctypes.c_longlong) == 8: return "long long int" elif ctypes.sizeof(ctypes.c_long) == 8: return "long int" elif ctypes.sizeof(ctypes.c_int) == 8: return "int" else: raise ValueError() except ValueError: return "long long int" def write_wcsconfig_h(paths): """ Writes out the wcsconfig.h header with local configuration. """ h_file = io.StringIO() h_file.write(""" /* The bundled version has WCSLIB_VERSION */ #define HAVE_WCSLIB_VERSION 1 /* WCSLIB library version number. */ #define WCSLIB_VERSION {} /* 64-bit integer data type. */ #define WCSLIB_INT64 {} /* Windows needs some other defines to prevent inclusion of wcsset() which conflicts with wcslib's wcsset(). These need to be set on code that *uses* astropy.wcs, in addition to astropy.wcs itself. */ #if defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) || defined (__MINGW64__) #ifndef YY_NO_UNISTD_H #define YY_NO_UNISTD_H #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _NO_OLDNAMES #define _NO_OLDNAMES #endif #ifndef NO_OLDNAMES #define NO_OLDNAMES #endif #ifndef __STDC__ #define __STDC__ 1 #endif #endif """.format(WCSVERSION, determine_64_bit_int())) content = h_file.getvalue().encode('ascii') for path in paths: write_if_different(path, content) ###################################################################### # GENERATE DOCSTRINGS IN C def generate_c_docstrings(): docstrings = import_file(os.path.join(WCSROOT, 'docstrings.py')) docstrings = docstrings.__dict__ keys = [ key for key, val in docstrings.items() if not key.startswith('__') and isinstance(val, str)] keys.sort() docs = {} for key in keys: docs[key] = docstrings[key].encode('utf8').lstrip() + b'\0' h_file = io.StringIO() h_file.write("""/* DO NOT EDIT! This file is autogenerated by astropy/wcs/setup_package.py. To edit its contents, edit astropy/wcs/docstrings.py */ #ifndef __DOCSTRINGS_H__ #define __DOCSTRINGS_H__ """) for key in keys: val = docs[key] h_file.write(f'extern char doc_{key}[{len(val)}];\n') h_file.write("\n#endif\n\n") write_if_different( join(WCSROOT, 'include', 'astropy_wcs', 'docstrings.h'), h_file.getvalue().encode('utf-8')) c_file = io.StringIO() c_file.write("""/* DO NOT EDIT! This file is autogenerated by astropy/wcs/setup_package.py. To edit its contents, edit astropy/wcs/docstrings.py The weirdness here with strncpy is because some C compilers, notably MSVC, do not support string literals greater than 256 characters. */ #include <string.h> #include "astropy_wcs/docstrings.h" """) for key in keys: val = docs[key] c_file.write(f'char doc_{key}[{len(val)}] = {{\n') for i in range(0, len(val), 12): section = val[i:i+12] c_file.write(' ') c_file.write(''.join(f'0x{x:02x}, ' for x in section)) c_file.write('\n') c_file.write(" };\n\n") write_if_different( join(WCSROOT, 'src', 'docstrings.c'), c_file.getvalue().encode('utf-8')) def get_wcslib_cfg(cfg, wcslib_files, include_paths): debug = '--debug' in sys.argv cfg['include_dirs'].append(numpy.get_include()) cfg['define_macros'].extend([ ('ECHO', None), ('WCSTRIG_MACRO', None), ('ASTROPY_WCS_BUILD', None), ('_GNU_SOURCE', None)]) if ((int(os.environ.get('ASTROPY_USE_SYSTEM_WCSLIB', 0)) or int(os.environ.get('ASTROPY_USE_SYSTEM_ALL', 0))) and not sys.platform == 'win32'): wcsconfig_h_path = join(WCSROOT, 'include', 'wcsconfig.h') if os.path.exists(wcsconfig_h_path): os.unlink(wcsconfig_h_path) for k, v in pkg_config(['wcslib'], ['wcs']).items(): cfg[k].extend(v) else: write_wcsconfig_h(include_paths) wcslib_path = join("cextern", "wcslib") # Path to wcslib wcslib_cpath = join(wcslib_path, "C") # Path to wcslib source files cfg['sources'].extend(join(wcslib_cpath, x) for x in wcslib_files) cfg['include_dirs'].append(wcslib_cpath) if debug: cfg['define_macros'].append(('DEBUG', None)) cfg['undef_macros'].append('NDEBUG') if (not sys.platform.startswith('sun') and not sys.platform == 'win32'): cfg['extra_compile_args'].extend(["-fno-inline", "-O0", "-g"]) else: # Define ECHO as nothing to prevent spurious newlines from # printing within the libwcs parser cfg['define_macros'].append(('NDEBUG', None)) cfg['undef_macros'].append('DEBUG') if sys.platform == 'win32': # These are written into wcsconfig.h, but that file is not # used by all parts of wcslib. cfg['define_macros'].extend([ ('YY_NO_UNISTD_H', None), ('_CRT_SECURE_NO_WARNINGS', None), ('_NO_OLDNAMES', None), # for mingw32 ('NO_OLDNAMES', None), # for mingw64 ('__STDC__', None) # for MSVC ]) if sys.platform.startswith('linux'): cfg['define_macros'].append(('HAVE_SINCOS', None)) # For 4.7+ enable C99 syntax in older compilers (need 'gnu99' std for gcc) if determine_64_bit_int() != 'int' and get_compiler() == 'unix': cfg['extra_compile_args'].extend(['-std=gnu99']) else: cfg['extra_compile_args'].extend(['-std=c99']) # Squelch a few compilation warnings in WCSLIB if get_compiler() in ('unix', 'mingw32'): if not debug: cfg['extra_compile_args'].extend([ '-Wno-strict-prototypes', '-Wno-unused-function', '-Wno-unused-value', '-Wno-uninitialized']) def get_extensions(): generate_c_docstrings() ###################################################################### # DISTUTILS SETUP cfg = defaultdict(list) wcslib_files = [ # List of wcslib files to compile 'flexed/wcsbth.c', 'flexed/wcspih.c', 'flexed/wcsulex.c', 'flexed/wcsutrn.c', 'cel.c', 'dis.c', 'lin.c', 'log.c', 'prj.c', 'spc.c', 'sph.c', 'spx.c', 'tab.c', 'wcs.c', 'wcserr.c', 'wcsfix.c', 'wcshdr.c', 'wcsprintf.c', 'wcsunits.c', 'wcsutil.c' ] wcslib_config_paths = [ join(WCSROOT, 'include', 'astropy_wcs', 'wcsconfig.h'), join(WCSROOT, 'include', 'wcsconfig.h') ] get_wcslib_cfg(cfg, wcslib_files, wcslib_config_paths) cfg['include_dirs'].append(join(WCSROOT, "include")) astropy_wcs_files = [ # List of astropy.wcs files to compile 'distortion.c', 'distortion_wrap.c', 'docstrings.c', 'pipeline.c', 'pyutil.c', 'astropy_wcs.c', 'astropy_wcs_api.c', 'sip.c', 'sip_wrap.c', 'str_list_proxy.c', 'unit_list_proxy.c', 'util.c', 'wcslib_wrap.c', 'wcslib_auxprm_wrap.c', 'wcslib_tabprm_wrap.c', 'wcslib_wtbarr_wrap.c' ] cfg['sources'].extend(join(WCSROOT, 'src', x) for x in astropy_wcs_files) cfg['sources'] = [str(x) for x in cfg['sources']] cfg = dict((str(key), val) for key, val in cfg.items()) # Copy over header files from WCSLIB into the installed version of Astropy # so that other Python packages can write extensions that link to it. We # do the copying here then include the data in [options.package_data] in # the setup.cfg file wcslib_headers = [ 'cel.h', 'lin.h', 'prj.h', 'spc.h', 'spx.h', 'tab.h', 'wcs.h', 'wcserr.h', 'wcsmath.h', 'wcsprintf.h', ] if not (int(os.environ.get('ASTROPY_USE_SYSTEM_WCSLIB', 0)) or int(os.environ.get('ASTROPY_USE_SYSTEM_ALL', 0))): for header in wcslib_headers: source = join('cextern', 'wcslib', 'C', header) dest = join('astropy', 'wcs', 'include', 'wcslib', header) if newer_group([source], dest, 'newer'): shutil.copy(source, dest) return [Extension('astropy.wcs._wcs', **cfg)]
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Test the Quantity class and related.""" import copy import pickle import decimal import numbers from fractions import Fraction import pytest import numpy as np from numpy.testing import (assert_allclose, assert_array_equal, assert_array_almost_equal) from astropy.utils import isiterable, minversion from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning from astropy import units as u from astropy.units.quantity import _UNIT_NOT_INITIALISED """ The Quantity class will represent a number + unit + uncertainty """ class TestQuantityCreation: def test_1(self): # create objects through operations with Unit objects: quantity = 11.42 * u.meter # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = u.meter * 11.42 # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = 11.42 / u.meter assert isinstance(quantity, u.Quantity) quantity = u.meter / 11.42 assert isinstance(quantity, u.Quantity) quantity = 11.42 * u.meter / u.second assert isinstance(quantity, u.Quantity) with pytest.raises(TypeError): quantity = 182.234 + u.meter with pytest.raises(TypeError): quantity = 182.234 - u.meter with pytest.raises(TypeError): quantity = 182.234 % u.meter def test_2(self): # create objects using the Quantity constructor: _ = u.Quantity(11.412, unit=u.meter) _ = u.Quantity(21.52, "cm") q3 = u.Quantity(11.412) # By default quantities that don't specify a unit are unscaled # dimensionless assert q3.unit == u.Unit(1) with pytest.raises(TypeError): u.Quantity(object(), unit=u.m) def test_3(self): # with pytest.raises(u.UnitsError): with pytest.raises(ValueError): # Until @mdboom fixes the errors in units u.Quantity(11.412, unit="testingggg") def test_nan_inf(self): # Not-a-number q = u.Quantity('nan', unit='cm') assert np.isnan(q.value) q = u.Quantity('NaN', unit='cm') assert np.isnan(q.value) q = u.Quantity('-nan', unit='cm') # float() allows this assert np.isnan(q.value) q = u.Quantity('nan cm') assert np.isnan(q.value) assert q.unit == u.cm # Infinity q = u.Quantity('inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('-inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('inf cm') assert np.isinf(q.value) assert q.unit == u.cm q = u.Quantity('Infinity', unit='cm') # float() allows this assert np.isinf(q.value) # make sure these strings don't parse... with pytest.raises(TypeError): q = u.Quantity('', unit='cm') with pytest.raises(TypeError): q = u.Quantity('spam', unit='cm') def test_unit_property(self): # test getting and setting 'unit' attribute q1 = u.Quantity(11.4, unit=u.meter) with pytest.raises(AttributeError): q1.unit = u.cm def test_preserve_dtype(self): """Test that if an explicit dtype is given, it is used, while if not, numbers are converted to float (including decimal.Decimal, which numpy converts to an object; closes #1419) """ # If dtype is specified, use it, but if not, convert int, bool to float q1 = u.Quantity(12, unit=u.m / u.s, dtype=int) assert q1.dtype == int q2 = u.Quantity(q1) assert q2.dtype == float assert q2.value == float(q1.value) assert q2.unit == q1.unit # but we should preserve any float32 or even float16 a3_32 = np.array([1., 2.], dtype=np.float32) q3_32 = u.Quantity(a3_32, u.yr) assert q3_32.dtype == a3_32.dtype a3_16 = np.array([1., 2.], dtype=np.float16) q3_16 = u.Quantity(a3_16, u.yr) assert q3_16.dtype == a3_16.dtype # items stored as objects by numpy should be converted to float # by default q4 = u.Quantity(decimal.Decimal('10.25'), u.m) assert q4.dtype == float q5 = u.Quantity(decimal.Decimal('10.25'), u.m, dtype=object) assert q5.dtype == object def test_copy(self): # By default, a new quantity is constructed, but not if copy=False a = np.arange(10.) q0 = u.Quantity(a, unit=u.m / u.s) assert q0.base is not a q1 = u.Quantity(a, unit=u.m / u.s, copy=False) assert q1.base is a q2 = u.Quantity(q0) assert q2 is not q0 assert q2.base is not q0.base q2 = u.Quantity(q0, copy=False) assert q2 is q0 assert q2.base is q0.base q3 = u.Quantity(q0, q0.unit, copy=False) assert q3 is q0 assert q3.base is q0.base q4 = u.Quantity(q0, u.cm / u.s, copy=False) assert q4 is not q0 assert q4.base is not q0.base def test_subok(self): """Test subok can be used to keep class, or to insist on Quantity""" class MyQuantitySubclass(u.Quantity): pass myq = MyQuantitySubclass(np.arange(10.), u.m) # try both with and without changing the unit assert type(u.Quantity(myq)) is u.Quantity assert type(u.Quantity(myq, subok=True)) is MyQuantitySubclass assert type(u.Quantity(myq, u.km)) is u.Quantity assert type(u.Quantity(myq, u.km, subok=True)) is MyQuantitySubclass def test_order(self): """Test that order is correctly propagated to np.array""" ac = np.array(np.arange(10.), order='C') qcc = u.Quantity(ac, u.m, order='C') assert qcc.flags['C_CONTIGUOUS'] qcf = u.Quantity(ac, u.m, order='F') assert qcf.flags['F_CONTIGUOUS'] qca = u.Quantity(ac, u.m, order='A') assert qca.flags['C_CONTIGUOUS'] # check it works also when passing in a quantity assert u.Quantity(qcc, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='A').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='F').flags['F_CONTIGUOUS'] af = np.array(np.arange(10.), order='F') qfc = u.Quantity(af, u.m, order='C') assert qfc.flags['C_CONTIGUOUS'] qff = u.Quantity(ac, u.m, order='F') assert qff.flags['F_CONTIGUOUS'] qfa = u.Quantity(af, u.m, order='A') assert qfa.flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qff, order='A').flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='F').flags['F_CONTIGUOUS'] def test_ndmin(self): """Test that ndmin is correctly propagated to np.array""" a = np.arange(10.) q1 = u.Quantity(a, u.m, ndmin=1) assert q1.ndim == 1 and q1.shape == (10,) q2 = u.Quantity(a, u.m, ndmin=2) assert q2.ndim == 2 and q2.shape == (1, 10) # check it works also when passing in a quantity q3 = u.Quantity(q1, u.m, ndmin=3) assert q3.ndim == 3 and q3.shape == (1, 1, 10) # see github issue #10063 assert u.Quantity(u.Quantity(1, 'm'), 'm', ndmin=1).ndim == 1 assert u.Quantity(u.Quantity(1, 'cm'), 'm', ndmin=1).ndim == 1 def test_non_quantity_with_unit(self): """Test that unit attributes in objects get recognized.""" class MyQuantityLookalike(np.ndarray): pass a = np.arange(3.) mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = 'm' q1 = u.Quantity(mylookalike) assert isinstance(q1, u.Quantity) assert q1.unit is u.m assert np.all(q1.value == a) q2 = u.Quantity(mylookalike, u.mm) assert q2.unit is u.mm assert np.all(q2.value == 1000.*a) q3 = u.Quantity(mylookalike, copy=False) assert np.all(q3.value == mylookalike) q3[2] = 0 assert q3[2] == 0. assert mylookalike[2] == 0. mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = u.m q4 = u.Quantity(mylookalike, u.mm, copy=False) q4[2] = 0 assert q4[2] == 0. assert mylookalike[2] == 2. mylookalike.unit = 'nonsense' with pytest.raises(TypeError): u.Quantity(mylookalike) def test_creation_via_view(self): # This works but is no better than 1. * u.m q1 = 1. << u.m assert isinstance(q1, u.Quantity) assert q1.unit == u.m assert q1.value == 1. # With an array, we get an actual view. a2 = np.arange(10.) q2 = a2 << u.m / u.s assert isinstance(q2, u.Quantity) assert q2.unit == u.m / u.s assert np.all(q2.value == a2) a2[9] = 0. assert np.all(q2.value == a2) # But with a unit change we get a copy. q3 = q2 << u.mm / u.s assert isinstance(q3, u.Quantity) assert q3.unit == u.mm / u.s assert np.all(q3.value == a2 * 1000.) a2[8] = 0. assert q3[8].value == 8000. # Without a unit change, we do get a view. q4 = q2 << q2.unit a2[7] = 0. assert np.all(q4.value == a2) with pytest.raises(u.UnitsError): q2 << u.s # But one can do an in-place unit change. a2_copy = a2.copy() q2 <<= u.mm / u.s assert q2.unit == u.mm / u.s # Of course, this changes a2 as well. assert np.all(q2.value == a2) # Sanity check on the values. assert np.all(q2.value == a2_copy * 1000.) a2[8] = -1. # Using quantities, one can also work with strings. q5 = q2 << 'km/hr' assert q5.unit == u.km / u.hr assert np.all(q5 == q2) # Finally, we can use scalar quantities as units. not_quite_a_foot = 30. * u.cm a6 = np.arange(5.) q6 = a6 << not_quite_a_foot assert q6.unit == u.Unit(not_quite_a_foot) assert np.all(q6.to_value(u.cm) == 30. * a6) def test_rshift_warns(self): with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1 >> u.m assert len(warning_lines) == 1 q = 1. * u.km with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >> u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >>= u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1. >> q assert len(warning_lines) == 1 class TestQuantityOperations: q1 = u.Quantity(11.42, u.meter) q2 = u.Quantity(8.0, u.centimeter) def test_addition(self): # Take units from left object, q1 new_quantity = self.q1 + self.q2 assert new_quantity.value == 11.5 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 + self.q1 assert new_quantity.value == 1150.0 assert new_quantity.unit == u.centimeter new_q = u.Quantity(1500.1, u.m) + u.Quantity(13.5, u.km) assert new_q.unit == u.m assert new_q.value == 15000.1 def test_subtraction(self): # Take units from left object, q1 new_quantity = self.q1 - self.q2 assert new_quantity.value == 11.34 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 - self.q1 assert new_quantity.value == -1134.0 assert new_quantity.unit == u.centimeter def test_multiplication(self): # Take units from left object, q1 new_quantity = self.q1 * self.q2 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.meter * u.centimeter) # Take units from left object, q2 new_quantity = self.q2 * self.q1 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.centimeter * u.meter) # Multiply with a number new_quantity = 15. * self.q1 assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter # Multiply with a number new_quantity = self.q1 * 15. assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter def test_division(self): # Take units from left object, q1 new_quantity = self.q1 / self.q2 assert_array_almost_equal(new_quantity.value, 1.4275, decimal=5) assert new_quantity.unit == (u.meter / u.centimeter) # Take units from left object, q2 new_quantity = self.q2 / self.q1 assert_array_almost_equal(new_quantity.value, 0.70052539404553416, decimal=16) assert new_quantity.unit == (u.centimeter / u.meter) q1 = u.Quantity(11.4, unit=u.meter) q2 = u.Quantity(10.0, unit=u.second) new_quantity = q1 / q2 assert_array_almost_equal(new_quantity.value, 1.14, decimal=10) assert new_quantity.unit == (u.meter / u.second) # divide with a number new_quantity = self.q1 / 10. assert new_quantity.value == 1.142 assert new_quantity.unit == u.meter # divide with a number new_quantity = 11.42 / self.q1 assert new_quantity.value == 1. assert new_quantity.unit == u.Unit("1/m") def test_commutativity(self): """Regression test for issue #587.""" new_q = u.Quantity(11.42, 'm*s') assert self.q1 * u.s == u.s * self.q1 == new_q assert self.q1 / u.s == u.Quantity(11.42, 'm/s') assert u.s / self.q1 == u.Quantity(1 / 11.42, 's/m') def test_power(self): # raise quantity to a power new_quantity = self.q1 ** 2 assert_array_almost_equal(new_quantity.value, 130.4164, decimal=5) assert new_quantity.unit == u.Unit("m^2") new_quantity = self.q1 ** 3 assert_array_almost_equal(new_quantity.value, 1489.355288, decimal=7) assert new_quantity.unit == u.Unit("m^3") def test_matrix_multiplication(self): a = np.eye(3) q = a * u.m result1 = q @ a assert np.all(result1 == q) result2 = a @ q assert np.all(result2 == q) result3 = q @ q assert np.all(result3 == a * u.m ** 2) # less trivial case. q2 = np.array([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [[0., 1., 0.], [0., 0., 1.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]]]) / u.s result4 = q @ q2 assert np.all(result4 == np.matmul(a, q2.value) * q.unit * q2.unit) def test_unary(self): # Test the minus unary operator new_quantity = -self.q1 assert new_quantity.value == -self.q1.value assert new_quantity.unit == self.q1.unit new_quantity = -(-self.q1) assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit # Test the plus unary operator new_quantity = +self.q1 assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit def test_abs(self): q = 1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == q.value assert new_quantity.unit == q.unit q = -1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == -q.value assert new_quantity.unit == q.unit def test_incompatible_units(self): """ When trying to add or subtract units that aren't compatible, throw an error """ q1 = u.Quantity(11.412, unit=u.meter) q2 = u.Quantity(21.52, unit=u.second) with pytest.raises(u.UnitsError): q1 + q2 def test_non_number_type(self): q1 = u.Quantity(11.412, unit=u.meter) with pytest.raises(TypeError) as exc: q1 + {'a': 1} assert exc.value.args[0].startswith( "Unsupported operand type(s) for ufunc add:") with pytest.raises(TypeError): q1 + u.meter def test_dimensionless_operations(self): # test conversion to dimensionless dq = 3. * u.m / u.km dq1 = dq + 1. * u.mm / u.km assert dq1.value == 3.001 assert dq1.unit == dq.unit dq2 = dq + 1. assert dq2.value == 1.003 assert dq2.unit == u.dimensionless_unscaled # this test will check that operations with dimensionless Quantities # don't work with pytest.raises(u.UnitsError): self.q1 + u.Quantity(0.1, unit=u.Unit("")) with pytest.raises(u.UnitsError): self.q1 - u.Quantity(0.1, unit=u.Unit("")) # and test that scaling of integers works q = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int) q2 = q + np.array([4, 5, 6]) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, np.array([4.001, 5.002, 6.003])) # but not if doing it inplace with pytest.raises(TypeError): q += np.array([1, 2, 3]) # except if it is actually possible q = np.array([1, 2, 3]) * u.km / u.m q += np.array([4, 5, 6]) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == np.array([1004, 2005, 3006])) def test_complicated_operation(self): """ Perform a more complicated test """ from astropy.units import imperial # Multiple units distance = u.Quantity(15., u.meter) time = u.Quantity(11., u.second) velocity = (distance / time).to(imperial.mile / u.hour) assert_array_almost_equal( velocity.value, 3.05037, decimal=5) G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2) _ = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg)) # Area side1 = u.Quantity(11., u.centimeter) side2 = u.Quantity(7., u.centimeter) area = side1 * side2 assert_array_almost_equal(area.value, 77., decimal=15) assert area.unit == u.cm * u.cm def test_comparison(self): # equality/ non-equality is straightforward for quantity objects assert (1 / (u.cm * u.cm)) == 1 * u.cm ** -2 assert 1 * u.m == 100 * u.cm assert 1 * u.m != 1 * u.cm # when one is a unit, Quantity does not know what to do, # but unit is fine with it, so it still works unit = u.cm**3 q = 1. * unit assert q.__eq__(unit) is NotImplemented assert unit.__eq__(q) is True assert q == unit q = 1000. * u.mm**3 assert q == unit # mismatched types should never work assert not 1. * u.cm == 1. assert 1. * u.cm != 1. # comparison with zero should raise a deprecation warning for quantity in (1. * u.cm, 1. * u.dimensionless_unscaled): with pytest.warns(AstropyDeprecationWarning, match='The truth value of ' 'a Quantity is ambiguous. In the future this will ' 'raise a ValueError.'): bool(quantity) def test_numeric_converters(self): # float, int, long, and __index__ should only work for single # quantities, of appropriate type, and only if they are dimensionless. # for index, this should be unscaled as well # (Check on __index__ is also a regression test for #1557) # quantities with units should never convert, or be usable as an index q1 = u.Quantity(1, u.m) converter_err_msg = ("only dimensionless scalar quantities " "can be converted to Python scalars") index_err_msg = ("only integer dimensionless scalar quantities " "can be converted to a Python index") with pytest.raises(TypeError) as exc: float(q1) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q1) assert exc.value.args[0] == converter_err_msg # We used to test `q1 * ['a', 'b', 'c'] here, but that that worked # at all was a really odd confluence of bugs. Since it doesn't work # in numpy >=1.10 any more, just go directly for `__index__` (which # makes the test more similar to the `int`, `long`, etc., tests). with pytest.raises(TypeError) as exc: q1.__index__() assert exc.value.args[0] == index_err_msg # dimensionless but scaled is OK, however q2 = u.Quantity(1.23, u.m / u.km) assert float(q2) == float(q2.to_value(u.dimensionless_unscaled)) assert int(q2) == int(q2.to_value(u.dimensionless_unscaled)) with pytest.raises(TypeError) as exc: q2.__index__() assert exc.value.args[0] == index_err_msg # dimensionless unscaled is OK, though for index needs to be int q3 = u.Quantity(1.23, u.dimensionless_unscaled) assert float(q3) == 1.23 assert int(q3) == 1 with pytest.raises(TypeError) as exc: q3.__index__() assert exc.value.args[0] == index_err_msg # integer dimensionless unscaled is good for all q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert float(q4) == 2. assert int(q4) == 2 assert q4.__index__() == 2 # but arrays are not OK q5 = u.Quantity([1, 2], u.m) with pytest.raises(TypeError) as exc: float(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: q5.__index__() assert exc.value.args[0] == index_err_msg # See https://github.com/numpy/numpy/issues/5074 # It seems unlikely this will be resolved, so xfail'ing it. @pytest.mark.xfail(reason="list multiplication only works for numpy <=1.10") def test_numeric_converter_to_index_in_practice(self): """Test that use of __index__ actually works.""" q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert q4 * ['a', 'b', 'c'] == ['a', 'b', 'c', 'a', 'b', 'c'] def test_array_converters(self): # Scalar quantity q = u.Quantity(1.23, u.m) assert np.all(np.array(q) == np.array([1.23])) # Array quantity q = u.Quantity([1., 2., 3.], u.m) assert np.all(np.array(q) == np.array([1., 2., 3.])) def test_quantity_conversion(): q1 = u.Quantity(0.1, unit=u.meter) value = q1.value assert value == 0.1 value_in_km = q1.to_value(u.kilometer) assert value_in_km == 0.0001 new_quantity = q1.to(u.kilometer) assert new_quantity.value == 0.0001 with pytest.raises(u.UnitsError): q1.to(u.zettastokes) with pytest.raises(u.UnitsError): q1.to_value(u.zettastokes) def test_quantity_value_views(): q1 = u.Quantity([1., 2.], unit=u.meter) # views if the unit is the same. v1 = q1.value v1[0] = 0. assert np.all(q1 == [0., 2.] * u.meter) v2 = q1.to_value() v2[1] = 3. assert np.all(q1 == [0., 3.] * u.meter) v3 = q1.to_value('m') v3[0] = 1. assert np.all(q1 == [1., 3.] * u.meter) q2 = q1.to('m', copy=False) q2[0] = 2 * u.meter assert np.all(q1 == [2., 3.] * u.meter) v4 = q1.to_value('cm') v4[0] = 0. # copy if different unit. assert np.all(q1 == [2., 3.] * u.meter) def test_quantity_conversion_with_equiv(): q1 = u.Quantity(0.1, unit=u.meter) v2 = q1.to_value(u.Hz, equivalencies=u.spectral()) assert_allclose(v2, 2997924580.0) q2 = q1.to(u.Hz, equivalencies=u.spectral()) assert_allclose(q2.value, v2) q1 = u.Quantity(0.4, unit=u.arcsecond) v2 = q1.to_value(u.au, equivalencies=u.parallax()) q2 = q1.to(u.au, equivalencies=u.parallax()) v3 = q2.to_value(u.arcminute, equivalencies=u.parallax()) q3 = q2.to(u.arcminute, equivalencies=u.parallax()) assert_allclose(v2, 515662.015) assert_allclose(q2.value, v2) assert q2.unit == u.au assert_allclose(v3, 0.0066666667) assert_allclose(q3.value, v3) assert q3.unit == u.arcminute def test_quantity_conversion_equivalency_passed_on(): class MySpectral(u.Quantity): _equivalencies = u.spectral() def __quantity_view__(self, obj, unit): return obj.view(MySpectral) def __quantity_instance__(self, *args, **kwargs): return MySpectral(*args, **kwargs) q1 = MySpectral([1000, 2000], unit=u.Hz) q2 = q1.to(u.nm) assert q2.unit == u.nm q3 = q2.to(u.Hz) assert q3.unit == u.Hz assert_allclose(q3.value, q1.value) q4 = MySpectral([1000, 2000], unit=u.nm) q5 = q4.to(u.Hz).to(u.nm) assert q5.unit == u.nm assert_allclose(q4.value, q5.value) # Regression test for issue #2315, divide-by-zero error when examining 0*unit def test_self_equivalency(): assert u.deg.is_equivalent(0*u.radian) assert u.deg.is_equivalent(1*u.radian) def test_si(): q1 = 10. * u.m * u.s ** 2 / (200. * u.ms) ** 2 # 250 meters assert q1.si.value == 250 assert q1.si.unit == u.m q = 10. * u.m # 10 meters assert q.si.value == 10 assert q.si.unit == u.m q = 10. / u.m # 10 1 / meters assert q.si.value == 10 assert q.si.unit == (1 / u.m) def test_cgs(): q1 = 10. * u.cm * u.s ** 2 / (200. * u.ms) ** 2 # 250 centimeters assert q1.cgs.value == 250 assert q1.cgs.unit == u.cm q = 10. * u.m # 10 centimeters assert q.cgs.value == 1000 assert q.cgs.unit == u.cm q = 10. / u.cm # 10 1 / centimeters assert q.cgs.value == 10 assert q.cgs.unit == (1 / u.cm) q = 10. * u.Pa # 10 pascals assert q.cgs.value == 100 assert q.cgs.unit == u.barye class TestQuantityComparison: def test_quantity_equality(self): assert u.Quantity(1000, unit='m') == u.Quantity(1, unit='km') assert not (u.Quantity(1, unit='m') == u.Quantity(1, unit='km')) # for ==, !=, return False, True if units do not match assert (u.Quantity(1100, unit=u.m) != u.Quantity(1, unit=u.s)) is True assert (u.Quantity(1100, unit=u.m) == u.Quantity(1, unit=u.s)) is False assert (u.Quantity(0, unit=u.m) == u.Quantity(0, unit=u.s)) is False # But allow comparison with 0, +/-inf if latter unitless assert u.Quantity(0, u.m) == 0. assert u.Quantity(1, u.m) != 0. assert u.Quantity(1, u.m) != np.inf assert u.Quantity(np.inf, u.m) == np.inf def test_quantity_equality_array(self): a = u.Quantity([0., 1., 1000.], u.m) b = u.Quantity(1., u.km) eq = a == b ne = a != b assert np.all(eq == [False, False, True]) assert np.all(eq != ne) # For mismatched units, we should just get True, False c = u.Quantity(1., u.s) eq = a == c ne = a != c assert eq is False assert ne is True # Constants are treated as dimensionless, so False too. eq = a == 1. ne = a != 1. assert eq is False assert ne is True # But 0 can have any units, so we can compare. eq = a == 0 ne = a != 0 assert np.all(eq == [True, False, False]) assert np.all(eq != ne) # But we do not extend that to arrays; they should have the same unit. d = np.array([0, 1., 1000.]) eq = a == d ne = a != d assert eq is False assert ne is True def test_quantity_comparison(self): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second) assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity( 1100, unit=u.meter) >= u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second) assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer) class TestQuantityDisplay: scalarintq = u.Quantity(1, unit='m', dtype=int) scalarfloatq = u.Quantity(1.3, unit='m') arrq = u.Quantity([1, 2.3, 8.9], unit='m') scalar_complex_q = u.Quantity(complex(1.0, 2.0)) scalar_big_complex_q = u.Quantity(complex(1.0, 2.0e27) * 1e25) scalar_big_neg_complex_q = u.Quantity(complex(-1.0, -2.0e27) * 1e36) arr_complex_q = u.Quantity(np.arange(3) * (complex(-1.0, -2.0e27) * 1e36)) big_arr_complex_q = u.Quantity(np.arange(125) * (complex(-1.0, -2.0e27) * 1e36)) def test_dimensionless_quantity_repr(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert repr(self.scalarintq * q2) == "<Quantity 1.>" assert repr(self.arrq * q2) == "<Quantity [1. , 2.3, 8.9]>" assert repr(self.scalarintq * q3) == "<Quantity 1>" def test_dimensionless_quantity_str(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert str(self.scalarintq * q2) == "1.0" assert str(self.scalarintq * q3) == "1" assert str(self.arrq * q2) == "[1. 2.3 8.9]" def test_dimensionless_quantity_format(self): q1 = u.Quantity(3.14) assert format(q1, '.2f') == '3.14' def test_scalar_quantity_str(self): assert str(self.scalarintq) == "1 m" assert str(self.scalarfloatq) == "1.3 m" def test_scalar_quantity_repr(self): assert repr(self.scalarintq) == "<Quantity 1 m>" assert repr(self.scalarfloatq) == "<Quantity 1.3 m>" def test_array_quantity_str(self): assert str(self.arrq) == "[1. 2.3 8.9] m" def test_array_quantity_repr(self): assert repr(self.arrq) == "<Quantity [1. , 2.3, 8.9] m>" def test_scalar_quantity_format(self): assert format(self.scalarintq, '02d') == "01 m" assert format(self.scalarfloatq, '.1f') == "1.3 m" assert format(self.scalarfloatq, '.0f') == "1 m" def test_uninitialized_unit_format(self): bad_quantity = np.arange(10.).view(u.Quantity) assert str(bad_quantity).endswith(_UNIT_NOT_INITIALISED) assert repr(bad_quantity).endswith(_UNIT_NOT_INITIALISED + '>') def test_to_string(self): qscalar = u.Quantity(1.5e14, 'm/s') # __str__ is the default `format` assert str(qscalar) == qscalar.to_string() res = 'Quantity as KMS: 150000000000.0 km / s' assert f"Quantity as KMS: {qscalar.to_string(unit=u.km / u.s)}" == res # With precision set res = 'Quantity as KMS: 1.500e+11 km / s' assert f"Quantity as KMS: {qscalar.to_string(precision=3, unit=u.km / u.s)}" == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex") == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="inline") == res res = r'$\displaystyle 1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="display") == res def test_repr_latex(self): from astropy.units.quantity import conf q2scalar = u.Quantity(1.5e14, 'm/s') assert self.scalarintq._repr_latex_() == r'$1 \; \mathrm{m}$' assert self.scalarfloatq._repr_latex_() == r'$1.3 \; \mathrm{m}$' assert (q2scalar._repr_latex_() == r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$') assert self.arrq._repr_latex_() == r'$[1,~2.3,~8.9] \; \mathrm{m}$' # Complex quantities assert self.scalar_complex_q._repr_latex_() == r'$(1+2i) \; \mathrm{}$' assert (self.scalar_big_complex_q._repr_latex_() == r'$(1 \times 10^{25}+2 \times 10^{52}i) \; \mathrm{}$') assert (self.scalar_big_neg_complex_q._repr_latex_() == r'$(-1 \times 10^{36}-2 \times 10^{63}i) \; \mathrm{}$') assert (self.arr_complex_q._repr_latex_() == (r'$[(0-0i),~(-1 \times 10^{36}-2 \times 10^{63}i),' r'~(-2 \times 10^{36}-4 \times 10^{63}i)] \; \mathrm{}$')) assert r'\dots' in self.big_arr_complex_q._repr_latex_() qmed = np.arange(100)*u.m qbig = np.arange(1000)*u.m qvbig = np.arange(10000)*1e9*u.m pops = np.get_printoptions() oldlat = conf.latex_array_threshold try: # check precision behavior q = u.Quantity(987654321.123456789, 'm/s') qa = np.array([7.89123, 123456789.987654321, 0]) * u.cm np.set_printoptions(precision=8) assert q._repr_latex_() == r'$9.8765432 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.89123,~1.2345679 \times 10^{8},~0] \; \mathrm{cm}$' np.set_printoptions(precision=2) assert q._repr_latex_() == r'$9.9 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.9,~1.2 \times 10^{8},~0] \; \mathrm{cm}$' # check thresholding behavior conf.latex_array_threshold = 100 # should be default lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = 1001 lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' not in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = -1 # means use the numpy threshold np.set_printoptions(threshold=99) lsmed = qmed._repr_latex_() assert r'\dots' in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig finally: # prevent side-effects from influencing other tests np.set_printoptions(**pops) conf.latex_array_threshold = oldlat qinfnan = [np.inf, -np.inf, np.nan] * u.m assert qinfnan._repr_latex_() == r'$[\infty,~-\infty,~{\rm NaN}] \; \mathrm{m}$' def test_decompose(): q1 = 5 * u.N assert q1.decompose() == (5 * u.kg * u.m * u.s ** -2) def test_decompose_regression(): """ Regression test for bug #1163 If decompose was called multiple times on a Quantity with an array and a scale != 1, the result changed every time. This is because the value was being referenced not copied, then modified, which changed the original value. """ q = np.array([1, 2, 3]) * u.m / (2. * u.km) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) assert np.all(q == np.array([1, 2, 3]) * u.m / (2. * u.km)) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) def test_arrays(): """ Test using quantites with array values """ qsec = u.Quantity(np.arange(10), u.second) assert isinstance(qsec.value, np.ndarray) assert not qsec.isscalar # len and indexing should work for arrays assert len(qsec) == len(qsec.value) qsecsub25 = qsec[2:5] assert qsecsub25.unit == qsec.unit assert isinstance(qsecsub25, u.Quantity) assert len(qsecsub25) == 3 # make sure isscalar, len, and indexing behave correcly for non-arrays. qsecnotarray = u.Quantity(10., u.second) assert qsecnotarray.isscalar with pytest.raises(TypeError): len(qsecnotarray) with pytest.raises(TypeError): qsecnotarray[0] qseclen0array = u.Quantity(np.array(10), u.second, dtype=int) # 0d numpy array should act basically like a scalar assert qseclen0array.isscalar with pytest.raises(TypeError): len(qseclen0array) with pytest.raises(TypeError): qseclen0array[0] assert isinstance(qseclen0array.value, numbers.Integral) a = np.array([(1., 2., 3.), (4., 5., 6.), (7., 8., 9.)], dtype=[('x', float), ('y', float), ('z', float)]) qkpc = u.Quantity(a, u.kpc) assert not qkpc.isscalar qkpc0 = qkpc[0] assert qkpc0.value == a[0] assert qkpc0.unit == qkpc.unit assert isinstance(qkpc0, u.Quantity) assert qkpc0.isscalar qkpcx = qkpc['x'] assert np.all(qkpcx.value == a['x']) assert qkpcx.unit == qkpc.unit assert isinstance(qkpcx, u.Quantity) assert not qkpcx.isscalar qkpcx1 = qkpc['x'][1] assert qkpcx1.unit == qkpc.unit assert isinstance(qkpcx1, u.Quantity) assert qkpcx1.isscalar qkpc1x = qkpc[1]['x'] assert qkpc1x.isscalar assert qkpc1x == qkpcx1 # can also create from lists, will auto-convert to arrays qsec = u.Quantity(list(range(10)), u.second) assert isinstance(qsec.value, np.ndarray) # quantity math should work with arrays assert_array_equal((qsec * 2).value, (np.arange(10) * 2)) assert_array_equal((qsec / 2).value, (np.arange(10) / 2)) # quantity addition/subtraction should *not* work with arrays b/c unit # ambiguous with pytest.raises(u.UnitsError): assert_array_equal((qsec + 2).value, (np.arange(10) + 2)) with pytest.raises(u.UnitsError): assert_array_equal((qsec - 2).value, (np.arange(10) + 2)) # should create by unit multiplication, too qsec2 = np.arange(10) * u.second qsec3 = u.second * np.arange(10) assert np.all(qsec == qsec2) assert np.all(qsec2 == qsec3) # make sure numerical-converters fail when arrays are present with pytest.raises(TypeError): float(qsec) with pytest.raises(TypeError): int(qsec) def test_array_indexing_slicing(): q = np.array([1., 2., 3.]) * u.m assert q[0] == 1. * u.m assert np.all(q[0:2] == u.Quantity([1., 2.], u.m)) def test_array_setslice(): q = np.array([1., 2., 3.]) * u.m q[1:2] = np.array([400.]) * u.cm assert np.all(q == np.array([1., 4., 3.]) * u.m) def test_inverse_quantity(): """ Regression test from issue #679 """ q = u.Quantity(4., u.meter / u.second) qot = q / 2 toq = 2 / q npqot = q / np.array(2) assert npqot.value == 2.0 assert npqot.unit == (u.meter / u.second) assert qot.value == 2.0 assert qot.unit == (u.meter / u.second) assert toq.value == 0.5 assert toq.unit == (u.second / u.meter) def test_quantity_mutability(): q = u.Quantity(9.8, u.meter / u.second / u.second) with pytest.raises(AttributeError): q.value = 3 with pytest.raises(AttributeError): q.unit = u.kg def test_quantity_initialized_with_quantity(): q1 = u.Quantity(60, u.second) q2 = u.Quantity(q1, u.minute) assert q2.value == 1 q3 = u.Quantity([q1, q2], u.second) assert q3[0].value == 60 assert q3[1].value == 60 q4 = u.Quantity([q2, q1]) assert q4.unit == q2.unit assert q4[0].value == 1 assert q4[1].value == 1 def test_quantity_string_unit(): q1 = 1. * u.m / 's' assert q1.value == 1 assert q1.unit == (u.m / u.s) q2 = q1 * "m" assert q2.unit == ((u.m * u.m) / u.s) def test_quantity_invalid_unit_string(): with pytest.raises(ValueError): "foo" * u.m def test_implicit_conversion(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True assert_allclose(q.centimeter, 100) assert_allclose(q.cm, 100) assert_allclose(q.parsec, 3.240779289469756e-17) def test_implicit_conversion_autocomplete(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True q.foo = 42 attrs = dir(q) assert 'centimeter' in attrs assert 'cm' in attrs assert 'parsec' in attrs assert 'foo' in attrs assert 'to' in attrs assert 'value' in attrs # Something from the base class, object assert '__setattr__' in attrs with pytest.raises(AttributeError): q.l def test_quantity_iterability(): """Regressiont est for issue #878. Scalar quantities should not be iterable and should raise a type error on iteration. """ q1 = [15.0, 17.0] * u.m assert isiterable(q1) q2 = next(iter(q1)) assert q2 == 15.0 * u.m assert not isiterable(q2) pytest.raises(TypeError, iter, q2) def test_copy(): q1 = u.Quantity(np.array([[1., 2., 3.], [4., 5., 6.]]), unit=u.m) q2 = q1.copy() assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value q3 = q1.copy(order='F') assert q3.flags['F_CONTIGUOUS'] assert np.all(q1.value == q3.value) assert q1.unit == q3.unit assert q1.dtype == q3.dtype assert q1.value is not q3.value q4 = q1.copy(order='C') assert q4.flags['C_CONTIGUOUS'] assert np.all(q1.value == q4.value) assert q1.unit == q4.unit assert q1.dtype == q4.dtype assert q1.value is not q4.value def test_deepcopy(): q1 = u.Quantity(np.array([1., 2., 3.]), unit=u.m) q2 = copy.deepcopy(q1) assert isinstance(q2, u.Quantity) assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value def test_equality_numpy_scalar(): """ A regression test to ensure that numpy scalars are correctly compared (which originally failed due to the lack of ``__array_priority__``). """ assert 10 != 10. * u.m assert np.int64(10) != 10 * u.m assert 10 * u.m != np.int64(10) def test_quantity_pickelability(): """ Testing pickleability of quantity """ q1 = np.arange(10) * u.m q2 = pickle.loads(pickle.dumps(q1)) assert np.all(q1.value == q2.value) assert q1.unit.is_equivalent(q2.unit) assert q1.unit == q2.unit def test_quantity_initialisation_from_string(): q = u.Quantity('1') assert q.unit == u.dimensionless_unscaled assert q.value == 1. q = u.Quantity('1.5 m/s') assert q.unit == u.m/u.s assert q.value == 1.5 assert u.Unit(q) == u.Unit('1.5 m/s') q = u.Quantity('.5 m') assert q == u.Quantity(0.5, u.m) q = u.Quantity('-1e1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('-1e+1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('+.5km') assert q == u.Quantity(.5, u.km) q = u.Quantity('+5e-1km') assert q == u.Quantity(.5, u.km) q = u.Quantity('5', u.m) assert q == u.Quantity(5., u.m) q = u.Quantity('5 km', u.m) assert q.value == 5000. assert q.unit == u.m q = u.Quantity('5Em') assert q == u.Quantity(5., u.Em) with pytest.raises(TypeError): u.Quantity('') with pytest.raises(TypeError): u.Quantity('m') with pytest.raises(TypeError): u.Quantity('1.2.3 deg') with pytest.raises(TypeError): u.Quantity('1+deg') with pytest.raises(TypeError): u.Quantity('1-2deg') with pytest.raises(TypeError): u.Quantity('1.2e-13.3m') with pytest.raises(TypeError): u.Quantity(['5']) with pytest.raises(TypeError): u.Quantity(np.array(['5'])) with pytest.raises(ValueError): u.Quantity('5E') with pytest.raises(ValueError): u.Quantity('5 foo') def test_unsupported(): q1 = np.arange(10) * u.m with pytest.raises(TypeError): np.bitwise_and(q1, q1) def test_unit_identity(): q = 1.0 * u.hour assert q.unit is u.hour def test_quantity_to_view(): q1 = np.array([1000, 2000]) * u.m q2 = q1.to(u.km) assert q1.value[0] == 1000 assert q2.value[0] == 1 def test_quantity_tuple_power(): with pytest.raises(ValueError): (5.0 * u.m) ** (1, 2) def test_quantity_fraction_power(): q = (25.0 * u.m**2) ** Fraction(1, 2) assert q.value == 5. assert q.unit == u.m # Regression check to ensure we didn't create an object type by raising # the value of the quantity to a Fraction. [#3922] assert q.dtype.kind == 'f' def test_quantity_from_table(): """ Checks that units from tables are respected when converted to a Quantity. This also generically checks the use of *anything* with a `unit` attribute passed into Quantity """ from astropy.table import Table t = Table(data=[np.arange(5), np.arange(5)], names=['a', 'b']) t['a'].unit = u.kpc qa = u.Quantity(t['a']) assert qa.unit == u.kpc assert_array_equal(qa.value, t['a']) qb = u.Quantity(t['b']) assert qb.unit == u.dimensionless_unscaled assert_array_equal(qb.value, t['b']) # This does *not* auto-convert, because it's not necessarily obvious that's # desired. Instead we revert to standard `Quantity` behavior qap = u.Quantity(t['a'], u.pc) assert qap.unit == u.pc assert_array_equal(qap.value, t['a'] * 1000) qbp = u.Quantity(t['b'], u.pc) assert qbp.unit == u.pc assert_array_equal(qbp.value, t['b']) # Also check with a function unit (regression test for gh-8430) t['a'].unit = u.dex(u.cm/u.s**2) fq = u.Dex(t['a']) assert fq.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq.value, t['a']) fq2 = u.Quantity(t['a'], subok=True) assert isinstance(fq2, u.Dex) assert fq2.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq2.value, t['a']) with pytest.raises(u.UnitTypeError): u.Quantity(t['a']) def test_assign_slice_with_quantity_like(): # Regression tests for gh-5961 from astropy.table import Table, Column # first check directly that we can use a Column to assign to a slice. c = Column(np.arange(10.), unit=u.mm) q = u.Quantity(c) q[:2] = c[:2] # next check that we do not fail the original problem. t = Table() t['x'] = np.arange(10) * u.mm t['y'] = np.ones(10) * u.mm assert type(t['x']) is Column xy = np.vstack([t['x'], t['y']]).T * u.mm ii = [0, 2, 4] assert xy[ii, 0].unit == t['x'][ii].unit # should not raise anything xy[ii, 0] = t['x'][ii] def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]]) def test_repr_array_of_quantity(): """ Test print/repr of object arrays of Quantity objects with different units. Regression test for the issue first reported in https://github.com/astropy/astropy/issues/3777 """ a = np.array([1 * u.m, 2 * u.s], dtype=object) assert repr(a) == 'array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)' assert str(a) == '[<Quantity 1. m> <Quantity 2. s>]' class TestSpecificTypeQuantity: def setup(self): class Length(u.SpecificTypeQuantity): _equivalent_unit = u.m class Length2(Length): _default_unit = u.m class Length3(Length): _unit = u.m self.Length = Length self.Length2 = Length2 self.Length3 = Length3 def test_creation(self): l = self.Length(np.arange(10.)*u.km) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.) * u.hour) with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.)) l2 = self.Length2(np.arange(5.)) assert type(l2) is self.Length2 assert l2._default_unit is self.Length2._default_unit with pytest.raises(u.UnitTypeError): self.Length3(np.arange(10.)) def test_view(self): l = (np.arange(5.) * u.km).view(self.Length) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): (np.arange(5.) * u.s).view(self.Length) v = np.arange(5.).view(self.Length) assert type(v) is self.Length assert v._unit is None l3 = np.ones((2, 2)).view(self.Length3) assert type(l3) is self.Length3 assert l3.unit is self.Length3._unit def test_operation_precedence_and_fallback(self): l = self.Length(np.arange(5.)*u.cm) sum1 = l + 1.*u.m assert type(sum1) is self.Length sum2 = 1.*u.km + l assert type(sum2) is self.Length sum3 = l + l assert type(sum3) is self.Length res1 = l * (1.*u.m) assert type(res1) is u.Quantity res2 = l * l assert type(res2) is u.Quantity def test_unit_class_override(): class MyQuantity(u.Quantity): pass my_unit = u.Unit("my_deg", u.deg) my_unit._quantity_class = MyQuantity q1 = u.Quantity(1., my_unit) assert type(q1) is u.Quantity q2 = u.Quantity(1., my_unit, subok=True) assert type(q2) is MyQuantity class QuantityMimic: def __init__(self, value, unit): self.value = value self.unit = unit def __array__(self): return np.array(self.value) class QuantityMimic2(QuantityMimic): def to(self, unit): return u.Quantity(self.value, self.unit).to(unit) def to_value(self, unit): return u.Quantity(self.value, self.unit).to_value(unit) class TestQuantityMimics: """Test Quantity Mimics that are not ndarray subclasses.""" @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_input(self, Mimic): value = np.arange(10.) mimic = Mimic(value, u.m) q = u.Quantity(mimic) assert q.unit == u.m assert np.all(q.value == value) q2 = u.Quantity(mimic, u.cm) assert q2.unit == u.cm assert np.all(q2.value == 100 * value) @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_setting(self, Mimic): mimic = Mimic([1., 2.], u.m) q = u.Quantity(np.arange(10.), u.cm) q[8:] = mimic assert np.all(q[:8].value == np.arange(8.)) assert np.all(q[8:].value == [100., 200.]) def test_mimic_function_unit(self): mimic = QuantityMimic([1., 2.], u.dex(u.cm/u.s**2)) d = u.Dex(mimic) assert isinstance(d, u.Dex) assert d.unit == u.dex(u.cm/u.s**2) assert np.all(d.value == [1., 2.]) q = u.Quantity(mimic, subok=True) assert isinstance(q, u.Dex) assert q.unit == u.dex(u.cm/u.s**2) assert np.all(q.value == [1., 2.]) with pytest.raises(u.UnitTypeError): u.Quantity(mimic) def test_masked_quantity_str_repr(): """Ensure we don't break masked Quantity representation.""" # Really, masked quantities do not work well, but at least let the # basics work. masked_quantity = np.ma.array([1, 2, 3, 4] * u.kg, mask=[True, False, True, False]) str(masked_quantity) repr(masked_quantity) class TestQuantitySubclassAboveAndBelow: @classmethod def setup_class(self): class MyArray(np.ndarray): def __array_finalize__(self, obj): super_array_finalize = super().__array_finalize__ if super_array_finalize is not None: super_array_finalize(obj) if hasattr(obj, 'my_attr'): self.my_attr = obj.my_attr self.MyArray = MyArray self.MyQuantity1 = type('MyQuantity1', (u.Quantity, MyArray), dict(my_attr='1')) self.MyQuantity2 = type('MyQuantity2', (MyArray, u.Quantity), dict(my_attr='2')) def test_setup(self): mq1 = self.MyQuantity1(10, u.m) assert isinstance(mq1, self.MyQuantity1) assert mq1.my_attr == '1' assert mq1.unit is u.m mq2 = self.MyQuantity2(10, u.m) assert isinstance(mq2, self.MyQuantity2) assert mq2.my_attr == '2' assert mq2.unit is u.m def test_attr_propagation(self): mq1 = self.MyQuantity1(10, u.m) mq12 = self.MyQuantity2(mq1) assert isinstance(mq12, self.MyQuantity2) assert not isinstance(mq12, self.MyQuantity1) assert mq12.my_attr == '1' assert mq12.unit is u.m mq2 = self.MyQuantity2(10, u.m) mq21 = self.MyQuantity1(mq2) assert isinstance(mq21, self.MyQuantity1) assert not isinstance(mq21, self.MyQuantity2) assert mq21.my_attr == '2' assert mq21.unit is u.m
dhomeier/astropy
astropy/units/tests/test_quantity.py
astropy/wcs/setup_package.py
import pytest import warnings # autouse makes this an all-coordinates-tests fixture # this can be eliminated if/when warnings in pytest are all turned to errors (gh issue #7928) @pytest.fixture(autouse=True) def representation_deprecation_to_error(): warnings.filterwarnings('error', 'The `representation` keyword/property name is deprecated in favor of `representation_type`') filt = warnings.filters[0] yield try: warnings.filters.remove(filt) except ValueError: pass # already removed
# coding: utf-8 # Licensed under a 3-clause BSD style license - see LICENSE.rst """Test the Quantity class and related.""" import copy import pickle import decimal import numbers from fractions import Fraction import pytest import numpy as np from numpy.testing import (assert_allclose, assert_array_equal, assert_array_almost_equal) from astropy.utils import isiterable, minversion from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning from astropy import units as u from astropy.units.quantity import _UNIT_NOT_INITIALISED """ The Quantity class will represent a number + unit + uncertainty """ class TestQuantityCreation: def test_1(self): # create objects through operations with Unit objects: quantity = 11.42 * u.meter # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = u.meter * 11.42 # returns a Quantity object assert isinstance(quantity, u.Quantity) quantity = 11.42 / u.meter assert isinstance(quantity, u.Quantity) quantity = u.meter / 11.42 assert isinstance(quantity, u.Quantity) quantity = 11.42 * u.meter / u.second assert isinstance(quantity, u.Quantity) with pytest.raises(TypeError): quantity = 182.234 + u.meter with pytest.raises(TypeError): quantity = 182.234 - u.meter with pytest.raises(TypeError): quantity = 182.234 % u.meter def test_2(self): # create objects using the Quantity constructor: _ = u.Quantity(11.412, unit=u.meter) _ = u.Quantity(21.52, "cm") q3 = u.Quantity(11.412) # By default quantities that don't specify a unit are unscaled # dimensionless assert q3.unit == u.Unit(1) with pytest.raises(TypeError): u.Quantity(object(), unit=u.m) def test_3(self): # with pytest.raises(u.UnitsError): with pytest.raises(ValueError): # Until @mdboom fixes the errors in units u.Quantity(11.412, unit="testingggg") def test_nan_inf(self): # Not-a-number q = u.Quantity('nan', unit='cm') assert np.isnan(q.value) q = u.Quantity('NaN', unit='cm') assert np.isnan(q.value) q = u.Quantity('-nan', unit='cm') # float() allows this assert np.isnan(q.value) q = u.Quantity('nan cm') assert np.isnan(q.value) assert q.unit == u.cm # Infinity q = u.Quantity('inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('-inf', unit='cm') assert np.isinf(q.value) q = u.Quantity('inf cm') assert np.isinf(q.value) assert q.unit == u.cm q = u.Quantity('Infinity', unit='cm') # float() allows this assert np.isinf(q.value) # make sure these strings don't parse... with pytest.raises(TypeError): q = u.Quantity('', unit='cm') with pytest.raises(TypeError): q = u.Quantity('spam', unit='cm') def test_unit_property(self): # test getting and setting 'unit' attribute q1 = u.Quantity(11.4, unit=u.meter) with pytest.raises(AttributeError): q1.unit = u.cm def test_preserve_dtype(self): """Test that if an explicit dtype is given, it is used, while if not, numbers are converted to float (including decimal.Decimal, which numpy converts to an object; closes #1419) """ # If dtype is specified, use it, but if not, convert int, bool to float q1 = u.Quantity(12, unit=u.m / u.s, dtype=int) assert q1.dtype == int q2 = u.Quantity(q1) assert q2.dtype == float assert q2.value == float(q1.value) assert q2.unit == q1.unit # but we should preserve any float32 or even float16 a3_32 = np.array([1., 2.], dtype=np.float32) q3_32 = u.Quantity(a3_32, u.yr) assert q3_32.dtype == a3_32.dtype a3_16 = np.array([1., 2.], dtype=np.float16) q3_16 = u.Quantity(a3_16, u.yr) assert q3_16.dtype == a3_16.dtype # items stored as objects by numpy should be converted to float # by default q4 = u.Quantity(decimal.Decimal('10.25'), u.m) assert q4.dtype == float q5 = u.Quantity(decimal.Decimal('10.25'), u.m, dtype=object) assert q5.dtype == object def test_copy(self): # By default, a new quantity is constructed, but not if copy=False a = np.arange(10.) q0 = u.Quantity(a, unit=u.m / u.s) assert q0.base is not a q1 = u.Quantity(a, unit=u.m / u.s, copy=False) assert q1.base is a q2 = u.Quantity(q0) assert q2 is not q0 assert q2.base is not q0.base q2 = u.Quantity(q0, copy=False) assert q2 is q0 assert q2.base is q0.base q3 = u.Quantity(q0, q0.unit, copy=False) assert q3 is q0 assert q3.base is q0.base q4 = u.Quantity(q0, u.cm / u.s, copy=False) assert q4 is not q0 assert q4.base is not q0.base def test_subok(self): """Test subok can be used to keep class, or to insist on Quantity""" class MyQuantitySubclass(u.Quantity): pass myq = MyQuantitySubclass(np.arange(10.), u.m) # try both with and without changing the unit assert type(u.Quantity(myq)) is u.Quantity assert type(u.Quantity(myq, subok=True)) is MyQuantitySubclass assert type(u.Quantity(myq, u.km)) is u.Quantity assert type(u.Quantity(myq, u.km, subok=True)) is MyQuantitySubclass def test_order(self): """Test that order is correctly propagated to np.array""" ac = np.array(np.arange(10.), order='C') qcc = u.Quantity(ac, u.m, order='C') assert qcc.flags['C_CONTIGUOUS'] qcf = u.Quantity(ac, u.m, order='F') assert qcf.flags['F_CONTIGUOUS'] qca = u.Quantity(ac, u.m, order='A') assert qca.flags['C_CONTIGUOUS'] # check it works also when passing in a quantity assert u.Quantity(qcc, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='A').flags['C_CONTIGUOUS'] assert u.Quantity(qcc, order='F').flags['F_CONTIGUOUS'] af = np.array(np.arange(10.), order='F') qfc = u.Quantity(af, u.m, order='C') assert qfc.flags['C_CONTIGUOUS'] qff = u.Quantity(ac, u.m, order='F') assert qff.flags['F_CONTIGUOUS'] qfa = u.Quantity(af, u.m, order='A') assert qfa.flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='C').flags['C_CONTIGUOUS'] assert u.Quantity(qff, order='A').flags['F_CONTIGUOUS'] assert u.Quantity(qff, order='F').flags['F_CONTIGUOUS'] def test_ndmin(self): """Test that ndmin is correctly propagated to np.array""" a = np.arange(10.) q1 = u.Quantity(a, u.m, ndmin=1) assert q1.ndim == 1 and q1.shape == (10,) q2 = u.Quantity(a, u.m, ndmin=2) assert q2.ndim == 2 and q2.shape == (1, 10) # check it works also when passing in a quantity q3 = u.Quantity(q1, u.m, ndmin=3) assert q3.ndim == 3 and q3.shape == (1, 1, 10) # see github issue #10063 assert u.Quantity(u.Quantity(1, 'm'), 'm', ndmin=1).ndim == 1 assert u.Quantity(u.Quantity(1, 'cm'), 'm', ndmin=1).ndim == 1 def test_non_quantity_with_unit(self): """Test that unit attributes in objects get recognized.""" class MyQuantityLookalike(np.ndarray): pass a = np.arange(3.) mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = 'm' q1 = u.Quantity(mylookalike) assert isinstance(q1, u.Quantity) assert q1.unit is u.m assert np.all(q1.value == a) q2 = u.Quantity(mylookalike, u.mm) assert q2.unit is u.mm assert np.all(q2.value == 1000.*a) q3 = u.Quantity(mylookalike, copy=False) assert np.all(q3.value == mylookalike) q3[2] = 0 assert q3[2] == 0. assert mylookalike[2] == 0. mylookalike = a.copy().view(MyQuantityLookalike) mylookalike.unit = u.m q4 = u.Quantity(mylookalike, u.mm, copy=False) q4[2] = 0 assert q4[2] == 0. assert mylookalike[2] == 2. mylookalike.unit = 'nonsense' with pytest.raises(TypeError): u.Quantity(mylookalike) def test_creation_via_view(self): # This works but is no better than 1. * u.m q1 = 1. << u.m assert isinstance(q1, u.Quantity) assert q1.unit == u.m assert q1.value == 1. # With an array, we get an actual view. a2 = np.arange(10.) q2 = a2 << u.m / u.s assert isinstance(q2, u.Quantity) assert q2.unit == u.m / u.s assert np.all(q2.value == a2) a2[9] = 0. assert np.all(q2.value == a2) # But with a unit change we get a copy. q3 = q2 << u.mm / u.s assert isinstance(q3, u.Quantity) assert q3.unit == u.mm / u.s assert np.all(q3.value == a2 * 1000.) a2[8] = 0. assert q3[8].value == 8000. # Without a unit change, we do get a view. q4 = q2 << q2.unit a2[7] = 0. assert np.all(q4.value == a2) with pytest.raises(u.UnitsError): q2 << u.s # But one can do an in-place unit change. a2_copy = a2.copy() q2 <<= u.mm / u.s assert q2.unit == u.mm / u.s # Of course, this changes a2 as well. assert np.all(q2.value == a2) # Sanity check on the values. assert np.all(q2.value == a2_copy * 1000.) a2[8] = -1. # Using quantities, one can also work with strings. q5 = q2 << 'km/hr' assert q5.unit == u.km / u.hr assert np.all(q5 == q2) # Finally, we can use scalar quantities as units. not_quite_a_foot = 30. * u.cm a6 = np.arange(5.) q6 = a6 << not_quite_a_foot assert q6.unit == u.Unit(not_quite_a_foot) assert np.all(q6.to_value(u.cm) == 30. * a6) def test_rshift_warns(self): with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1 >> u.m assert len(warning_lines) == 1 q = 1. * u.km with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >> u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: q >>= u.m assert len(warning_lines) == 1 with pytest.raises(TypeError), \ pytest.warns(AstropyWarning, match='is not implemented') as warning_lines: 1. >> q assert len(warning_lines) == 1 class TestQuantityOperations: q1 = u.Quantity(11.42, u.meter) q2 = u.Quantity(8.0, u.centimeter) def test_addition(self): # Take units from left object, q1 new_quantity = self.q1 + self.q2 assert new_quantity.value == 11.5 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 + self.q1 assert new_quantity.value == 1150.0 assert new_quantity.unit == u.centimeter new_q = u.Quantity(1500.1, u.m) + u.Quantity(13.5, u.km) assert new_q.unit == u.m assert new_q.value == 15000.1 def test_subtraction(self): # Take units from left object, q1 new_quantity = self.q1 - self.q2 assert new_quantity.value == 11.34 assert new_quantity.unit == u.meter # Take units from left object, q2 new_quantity = self.q2 - self.q1 assert new_quantity.value == -1134.0 assert new_quantity.unit == u.centimeter def test_multiplication(self): # Take units from left object, q1 new_quantity = self.q1 * self.q2 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.meter * u.centimeter) # Take units from left object, q2 new_quantity = self.q2 * self.q1 assert new_quantity.value == 91.36 assert new_quantity.unit == (u.centimeter * u.meter) # Multiply with a number new_quantity = 15. * self.q1 assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter # Multiply with a number new_quantity = self.q1 * 15. assert new_quantity.value == 171.3 assert new_quantity.unit == u.meter def test_division(self): # Take units from left object, q1 new_quantity = self.q1 / self.q2 assert_array_almost_equal(new_quantity.value, 1.4275, decimal=5) assert new_quantity.unit == (u.meter / u.centimeter) # Take units from left object, q2 new_quantity = self.q2 / self.q1 assert_array_almost_equal(new_quantity.value, 0.70052539404553416, decimal=16) assert new_quantity.unit == (u.centimeter / u.meter) q1 = u.Quantity(11.4, unit=u.meter) q2 = u.Quantity(10.0, unit=u.second) new_quantity = q1 / q2 assert_array_almost_equal(new_quantity.value, 1.14, decimal=10) assert new_quantity.unit == (u.meter / u.second) # divide with a number new_quantity = self.q1 / 10. assert new_quantity.value == 1.142 assert new_quantity.unit == u.meter # divide with a number new_quantity = 11.42 / self.q1 assert new_quantity.value == 1. assert new_quantity.unit == u.Unit("1/m") def test_commutativity(self): """Regression test for issue #587.""" new_q = u.Quantity(11.42, 'm*s') assert self.q1 * u.s == u.s * self.q1 == new_q assert self.q1 / u.s == u.Quantity(11.42, 'm/s') assert u.s / self.q1 == u.Quantity(1 / 11.42, 's/m') def test_power(self): # raise quantity to a power new_quantity = self.q1 ** 2 assert_array_almost_equal(new_quantity.value, 130.4164, decimal=5) assert new_quantity.unit == u.Unit("m^2") new_quantity = self.q1 ** 3 assert_array_almost_equal(new_quantity.value, 1489.355288, decimal=7) assert new_quantity.unit == u.Unit("m^3") def test_matrix_multiplication(self): a = np.eye(3) q = a * u.m result1 = q @ a assert np.all(result1 == q) result2 = a @ q assert np.all(result2 == q) result3 = q @ q assert np.all(result3 == a * u.m ** 2) # less trivial case. q2 = np.array([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [[0., 1., 0.], [0., 0., 1.], [1., 0., 0.]], [[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]]]) / u.s result4 = q @ q2 assert np.all(result4 == np.matmul(a, q2.value) * q.unit * q2.unit) def test_unary(self): # Test the minus unary operator new_quantity = -self.q1 assert new_quantity.value == -self.q1.value assert new_quantity.unit == self.q1.unit new_quantity = -(-self.q1) assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit # Test the plus unary operator new_quantity = +self.q1 assert new_quantity.value == self.q1.value assert new_quantity.unit == self.q1.unit def test_abs(self): q = 1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == q.value assert new_quantity.unit == q.unit q = -1. * u.m / u.s new_quantity = abs(q) assert new_quantity.value == -q.value assert new_quantity.unit == q.unit def test_incompatible_units(self): """ When trying to add or subtract units that aren't compatible, throw an error """ q1 = u.Quantity(11.412, unit=u.meter) q2 = u.Quantity(21.52, unit=u.second) with pytest.raises(u.UnitsError): q1 + q2 def test_non_number_type(self): q1 = u.Quantity(11.412, unit=u.meter) with pytest.raises(TypeError) as exc: q1 + {'a': 1} assert exc.value.args[0].startswith( "Unsupported operand type(s) for ufunc add:") with pytest.raises(TypeError): q1 + u.meter def test_dimensionless_operations(self): # test conversion to dimensionless dq = 3. * u.m / u.km dq1 = dq + 1. * u.mm / u.km assert dq1.value == 3.001 assert dq1.unit == dq.unit dq2 = dq + 1. assert dq2.value == 1.003 assert dq2.unit == u.dimensionless_unscaled # this test will check that operations with dimensionless Quantities # don't work with pytest.raises(u.UnitsError): self.q1 + u.Quantity(0.1, unit=u.Unit("")) with pytest.raises(u.UnitsError): self.q1 - u.Quantity(0.1, unit=u.Unit("")) # and test that scaling of integers works q = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int) q2 = q + np.array([4, 5, 6]) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, np.array([4.001, 5.002, 6.003])) # but not if doing it inplace with pytest.raises(TypeError): q += np.array([1, 2, 3]) # except if it is actually possible q = np.array([1, 2, 3]) * u.km / u.m q += np.array([4, 5, 6]) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == np.array([1004, 2005, 3006])) def test_complicated_operation(self): """ Perform a more complicated test """ from astropy.units import imperial # Multiple units distance = u.Quantity(15., u.meter) time = u.Quantity(11., u.second) velocity = (distance / time).to(imperial.mile / u.hour) assert_array_almost_equal( velocity.value, 3.05037, decimal=5) G = u.Quantity(6.673E-11, u.m ** 3 / u.kg / u.s ** 2) _ = ((1. / (4. * np.pi * G)).to(u.pc ** -3 / u.s ** -2 * u.kg)) # Area side1 = u.Quantity(11., u.centimeter) side2 = u.Quantity(7., u.centimeter) area = side1 * side2 assert_array_almost_equal(area.value, 77., decimal=15) assert area.unit == u.cm * u.cm def test_comparison(self): # equality/ non-equality is straightforward for quantity objects assert (1 / (u.cm * u.cm)) == 1 * u.cm ** -2 assert 1 * u.m == 100 * u.cm assert 1 * u.m != 1 * u.cm # when one is a unit, Quantity does not know what to do, # but unit is fine with it, so it still works unit = u.cm**3 q = 1. * unit assert q.__eq__(unit) is NotImplemented assert unit.__eq__(q) is True assert q == unit q = 1000. * u.mm**3 assert q == unit # mismatched types should never work assert not 1. * u.cm == 1. assert 1. * u.cm != 1. # comparison with zero should raise a deprecation warning for quantity in (1. * u.cm, 1. * u.dimensionless_unscaled): with pytest.warns(AstropyDeprecationWarning, match='The truth value of ' 'a Quantity is ambiguous. In the future this will ' 'raise a ValueError.'): bool(quantity) def test_numeric_converters(self): # float, int, long, and __index__ should only work for single # quantities, of appropriate type, and only if they are dimensionless. # for index, this should be unscaled as well # (Check on __index__ is also a regression test for #1557) # quantities with units should never convert, or be usable as an index q1 = u.Quantity(1, u.m) converter_err_msg = ("only dimensionless scalar quantities " "can be converted to Python scalars") index_err_msg = ("only integer dimensionless scalar quantities " "can be converted to a Python index") with pytest.raises(TypeError) as exc: float(q1) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q1) assert exc.value.args[0] == converter_err_msg # We used to test `q1 * ['a', 'b', 'c'] here, but that that worked # at all was a really odd confluence of bugs. Since it doesn't work # in numpy >=1.10 any more, just go directly for `__index__` (which # makes the test more similar to the `int`, `long`, etc., tests). with pytest.raises(TypeError) as exc: q1.__index__() assert exc.value.args[0] == index_err_msg # dimensionless but scaled is OK, however q2 = u.Quantity(1.23, u.m / u.km) assert float(q2) == float(q2.to_value(u.dimensionless_unscaled)) assert int(q2) == int(q2.to_value(u.dimensionless_unscaled)) with pytest.raises(TypeError) as exc: q2.__index__() assert exc.value.args[0] == index_err_msg # dimensionless unscaled is OK, though for index needs to be int q3 = u.Quantity(1.23, u.dimensionless_unscaled) assert float(q3) == 1.23 assert int(q3) == 1 with pytest.raises(TypeError) as exc: q3.__index__() assert exc.value.args[0] == index_err_msg # integer dimensionless unscaled is good for all q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert float(q4) == 2. assert int(q4) == 2 assert q4.__index__() == 2 # but arrays are not OK q5 = u.Quantity([1, 2], u.m) with pytest.raises(TypeError) as exc: float(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: int(q5) assert exc.value.args[0] == converter_err_msg with pytest.raises(TypeError) as exc: q5.__index__() assert exc.value.args[0] == index_err_msg # See https://github.com/numpy/numpy/issues/5074 # It seems unlikely this will be resolved, so xfail'ing it. @pytest.mark.xfail(reason="list multiplication only works for numpy <=1.10") def test_numeric_converter_to_index_in_practice(self): """Test that use of __index__ actually works.""" q4 = u.Quantity(2, u.dimensionless_unscaled, dtype=int) assert q4 * ['a', 'b', 'c'] == ['a', 'b', 'c', 'a', 'b', 'c'] def test_array_converters(self): # Scalar quantity q = u.Quantity(1.23, u.m) assert np.all(np.array(q) == np.array([1.23])) # Array quantity q = u.Quantity([1., 2., 3.], u.m) assert np.all(np.array(q) == np.array([1., 2., 3.])) def test_quantity_conversion(): q1 = u.Quantity(0.1, unit=u.meter) value = q1.value assert value == 0.1 value_in_km = q1.to_value(u.kilometer) assert value_in_km == 0.0001 new_quantity = q1.to(u.kilometer) assert new_quantity.value == 0.0001 with pytest.raises(u.UnitsError): q1.to(u.zettastokes) with pytest.raises(u.UnitsError): q1.to_value(u.zettastokes) def test_quantity_value_views(): q1 = u.Quantity([1., 2.], unit=u.meter) # views if the unit is the same. v1 = q1.value v1[0] = 0. assert np.all(q1 == [0., 2.] * u.meter) v2 = q1.to_value() v2[1] = 3. assert np.all(q1 == [0., 3.] * u.meter) v3 = q1.to_value('m') v3[0] = 1. assert np.all(q1 == [1., 3.] * u.meter) q2 = q1.to('m', copy=False) q2[0] = 2 * u.meter assert np.all(q1 == [2., 3.] * u.meter) v4 = q1.to_value('cm') v4[0] = 0. # copy if different unit. assert np.all(q1 == [2., 3.] * u.meter) def test_quantity_conversion_with_equiv(): q1 = u.Quantity(0.1, unit=u.meter) v2 = q1.to_value(u.Hz, equivalencies=u.spectral()) assert_allclose(v2, 2997924580.0) q2 = q1.to(u.Hz, equivalencies=u.spectral()) assert_allclose(q2.value, v2) q1 = u.Quantity(0.4, unit=u.arcsecond) v2 = q1.to_value(u.au, equivalencies=u.parallax()) q2 = q1.to(u.au, equivalencies=u.parallax()) v3 = q2.to_value(u.arcminute, equivalencies=u.parallax()) q3 = q2.to(u.arcminute, equivalencies=u.parallax()) assert_allclose(v2, 515662.015) assert_allclose(q2.value, v2) assert q2.unit == u.au assert_allclose(v3, 0.0066666667) assert_allclose(q3.value, v3) assert q3.unit == u.arcminute def test_quantity_conversion_equivalency_passed_on(): class MySpectral(u.Quantity): _equivalencies = u.spectral() def __quantity_view__(self, obj, unit): return obj.view(MySpectral) def __quantity_instance__(self, *args, **kwargs): return MySpectral(*args, **kwargs) q1 = MySpectral([1000, 2000], unit=u.Hz) q2 = q1.to(u.nm) assert q2.unit == u.nm q3 = q2.to(u.Hz) assert q3.unit == u.Hz assert_allclose(q3.value, q1.value) q4 = MySpectral([1000, 2000], unit=u.nm) q5 = q4.to(u.Hz).to(u.nm) assert q5.unit == u.nm assert_allclose(q4.value, q5.value) # Regression test for issue #2315, divide-by-zero error when examining 0*unit def test_self_equivalency(): assert u.deg.is_equivalent(0*u.radian) assert u.deg.is_equivalent(1*u.radian) def test_si(): q1 = 10. * u.m * u.s ** 2 / (200. * u.ms) ** 2 # 250 meters assert q1.si.value == 250 assert q1.si.unit == u.m q = 10. * u.m # 10 meters assert q.si.value == 10 assert q.si.unit == u.m q = 10. / u.m # 10 1 / meters assert q.si.value == 10 assert q.si.unit == (1 / u.m) def test_cgs(): q1 = 10. * u.cm * u.s ** 2 / (200. * u.ms) ** 2 # 250 centimeters assert q1.cgs.value == 250 assert q1.cgs.unit == u.cm q = 10. * u.m # 10 centimeters assert q.cgs.value == 1000 assert q.cgs.unit == u.cm q = 10. / u.cm # 10 1 / centimeters assert q.cgs.value == 10 assert q.cgs.unit == (1 / u.cm) q = 10. * u.Pa # 10 pascals assert q.cgs.value == 100 assert q.cgs.unit == u.barye class TestQuantityComparison: def test_quantity_equality(self): assert u.Quantity(1000, unit='m') == u.Quantity(1, unit='km') assert not (u.Quantity(1, unit='m') == u.Quantity(1, unit='km')) # for ==, !=, return False, True if units do not match assert (u.Quantity(1100, unit=u.m) != u.Quantity(1, unit=u.s)) is True assert (u.Quantity(1100, unit=u.m) == u.Quantity(1, unit=u.s)) is False assert (u.Quantity(0, unit=u.m) == u.Quantity(0, unit=u.s)) is False # But allow comparison with 0, +/-inf if latter unitless assert u.Quantity(0, u.m) == 0. assert u.Quantity(1, u.m) != 0. assert u.Quantity(1, u.m) != np.inf assert u.Quantity(np.inf, u.m) == np.inf def test_quantity_equality_array(self): a = u.Quantity([0., 1., 1000.], u.m) b = u.Quantity(1., u.km) eq = a == b ne = a != b assert np.all(eq == [False, False, True]) assert np.all(eq != ne) # For mismatched units, we should just get True, False c = u.Quantity(1., u.s) eq = a == c ne = a != c assert eq is False assert ne is True # Constants are treated as dimensionless, so False too. eq = a == 1. ne = a != 1. assert eq is False assert ne is True # But 0 can have any units, so we can compare. eq = a == 0 ne = a != 0 assert np.all(eq == [True, False, False]) assert np.all(eq != ne) # But we do not extend that to arrays; they should have the same unit. d = np.array([0, 1., 1000.]) eq = a == d ne = a != d assert eq is False assert ne is True def test_quantity_comparison(self): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) < u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) > u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) < u.Quantity(1, unit=u.second) assert u.Quantity(1100, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) >= u.Quantity(1, unit=u.kilometer) assert u.Quantity(900, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) assert u.Quantity(1000, unit=u.meter) <= u.Quantity(1, unit=u.kilometer) with pytest.raises(u.UnitsError): assert u.Quantity( 1100, unit=u.meter) >= u.Quantity(1, unit=u.second) with pytest.raises(u.UnitsError): assert u.Quantity(1100, unit=u.meter) <= u.Quantity(1, unit=u.second) assert u.Quantity(1200, unit=u.meter) != u.Quantity(1, unit=u.kilometer) class TestQuantityDisplay: scalarintq = u.Quantity(1, unit='m', dtype=int) scalarfloatq = u.Quantity(1.3, unit='m') arrq = u.Quantity([1, 2.3, 8.9], unit='m') scalar_complex_q = u.Quantity(complex(1.0, 2.0)) scalar_big_complex_q = u.Quantity(complex(1.0, 2.0e27) * 1e25) scalar_big_neg_complex_q = u.Quantity(complex(-1.0, -2.0e27) * 1e36) arr_complex_q = u.Quantity(np.arange(3) * (complex(-1.0, -2.0e27) * 1e36)) big_arr_complex_q = u.Quantity(np.arange(125) * (complex(-1.0, -2.0e27) * 1e36)) def test_dimensionless_quantity_repr(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert repr(self.scalarintq * q2) == "<Quantity 1.>" assert repr(self.arrq * q2) == "<Quantity [1. , 2.3, 8.9]>" assert repr(self.scalarintq * q3) == "<Quantity 1>" def test_dimensionless_quantity_str(self): q2 = u.Quantity(1., unit='m-1') q3 = u.Quantity(1, unit='m-1', dtype=int) assert str(self.scalarintq * q2) == "1.0" assert str(self.scalarintq * q3) == "1" assert str(self.arrq * q2) == "[1. 2.3 8.9]" def test_dimensionless_quantity_format(self): q1 = u.Quantity(3.14) assert format(q1, '.2f') == '3.14' def test_scalar_quantity_str(self): assert str(self.scalarintq) == "1 m" assert str(self.scalarfloatq) == "1.3 m" def test_scalar_quantity_repr(self): assert repr(self.scalarintq) == "<Quantity 1 m>" assert repr(self.scalarfloatq) == "<Quantity 1.3 m>" def test_array_quantity_str(self): assert str(self.arrq) == "[1. 2.3 8.9] m" def test_array_quantity_repr(self): assert repr(self.arrq) == "<Quantity [1. , 2.3, 8.9] m>" def test_scalar_quantity_format(self): assert format(self.scalarintq, '02d') == "01 m" assert format(self.scalarfloatq, '.1f') == "1.3 m" assert format(self.scalarfloatq, '.0f') == "1 m" def test_uninitialized_unit_format(self): bad_quantity = np.arange(10.).view(u.Quantity) assert str(bad_quantity).endswith(_UNIT_NOT_INITIALISED) assert repr(bad_quantity).endswith(_UNIT_NOT_INITIALISED + '>') def test_to_string(self): qscalar = u.Quantity(1.5e14, 'm/s') # __str__ is the default `format` assert str(qscalar) == qscalar.to_string() res = 'Quantity as KMS: 150000000000.0 km / s' assert f"Quantity as KMS: {qscalar.to_string(unit=u.km / u.s)}" == res # With precision set res = 'Quantity as KMS: 1.500e+11 km / s' assert f"Quantity as KMS: {qscalar.to_string(precision=3, unit=u.km / u.s)}" == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex") == res res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="inline") == res res = r'$\displaystyle 1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$' assert qscalar.to_string(format="latex", subfmt="display") == res def test_repr_latex(self): from astropy.units.quantity import conf q2scalar = u.Quantity(1.5e14, 'm/s') assert self.scalarintq._repr_latex_() == r'$1 \; \mathrm{m}$' assert self.scalarfloatq._repr_latex_() == r'$1.3 \; \mathrm{m}$' assert (q2scalar._repr_latex_() == r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$') assert self.arrq._repr_latex_() == r'$[1,~2.3,~8.9] \; \mathrm{m}$' # Complex quantities assert self.scalar_complex_q._repr_latex_() == r'$(1+2i) \; \mathrm{}$' assert (self.scalar_big_complex_q._repr_latex_() == r'$(1 \times 10^{25}+2 \times 10^{52}i) \; \mathrm{}$') assert (self.scalar_big_neg_complex_q._repr_latex_() == r'$(-1 \times 10^{36}-2 \times 10^{63}i) \; \mathrm{}$') assert (self.arr_complex_q._repr_latex_() == (r'$[(0-0i),~(-1 \times 10^{36}-2 \times 10^{63}i),' r'~(-2 \times 10^{36}-4 \times 10^{63}i)] \; \mathrm{}$')) assert r'\dots' in self.big_arr_complex_q._repr_latex_() qmed = np.arange(100)*u.m qbig = np.arange(1000)*u.m qvbig = np.arange(10000)*1e9*u.m pops = np.get_printoptions() oldlat = conf.latex_array_threshold try: # check precision behavior q = u.Quantity(987654321.123456789, 'm/s') qa = np.array([7.89123, 123456789.987654321, 0]) * u.cm np.set_printoptions(precision=8) assert q._repr_latex_() == r'$9.8765432 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.89123,~1.2345679 \times 10^{8},~0] \; \mathrm{cm}$' np.set_printoptions(precision=2) assert q._repr_latex_() == r'$9.9 \times 10^{8} \; \mathrm{\frac{m}{s}}$' assert qa._repr_latex_() == r'$[7.9,~1.2 \times 10^{8},~0] \; \mathrm{cm}$' # check thresholding behavior conf.latex_array_threshold = 100 # should be default lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = 1001 lsmed = qmed._repr_latex_() assert r'\dots' not in lsmed lsbig = qbig._repr_latex_() assert r'\dots' not in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig conf.latex_array_threshold = -1 # means use the numpy threshold np.set_printoptions(threshold=99) lsmed = qmed._repr_latex_() assert r'\dots' in lsmed lsbig = qbig._repr_latex_() assert r'\dots' in lsbig lsvbig = qvbig._repr_latex_() assert r'\dots' in lsvbig finally: # prevent side-effects from influencing other tests np.set_printoptions(**pops) conf.latex_array_threshold = oldlat qinfnan = [np.inf, -np.inf, np.nan] * u.m assert qinfnan._repr_latex_() == r'$[\infty,~-\infty,~{\rm NaN}] \; \mathrm{m}$' def test_decompose(): q1 = 5 * u.N assert q1.decompose() == (5 * u.kg * u.m * u.s ** -2) def test_decompose_regression(): """ Regression test for bug #1163 If decompose was called multiple times on a Quantity with an array and a scale != 1, the result changed every time. This is because the value was being referenced not copied, then modified, which changed the original value. """ q = np.array([1, 2, 3]) * u.m / (2. * u.km) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) assert np.all(q == np.array([1, 2, 3]) * u.m / (2. * u.km)) assert np.all(q.decompose().value == np.array([0.0005, 0.001, 0.0015])) def test_arrays(): """ Test using quantites with array values """ qsec = u.Quantity(np.arange(10), u.second) assert isinstance(qsec.value, np.ndarray) assert not qsec.isscalar # len and indexing should work for arrays assert len(qsec) == len(qsec.value) qsecsub25 = qsec[2:5] assert qsecsub25.unit == qsec.unit assert isinstance(qsecsub25, u.Quantity) assert len(qsecsub25) == 3 # make sure isscalar, len, and indexing behave correcly for non-arrays. qsecnotarray = u.Quantity(10., u.second) assert qsecnotarray.isscalar with pytest.raises(TypeError): len(qsecnotarray) with pytest.raises(TypeError): qsecnotarray[0] qseclen0array = u.Quantity(np.array(10), u.second, dtype=int) # 0d numpy array should act basically like a scalar assert qseclen0array.isscalar with pytest.raises(TypeError): len(qseclen0array) with pytest.raises(TypeError): qseclen0array[0] assert isinstance(qseclen0array.value, numbers.Integral) a = np.array([(1., 2., 3.), (4., 5., 6.), (7., 8., 9.)], dtype=[('x', float), ('y', float), ('z', float)]) qkpc = u.Quantity(a, u.kpc) assert not qkpc.isscalar qkpc0 = qkpc[0] assert qkpc0.value == a[0] assert qkpc0.unit == qkpc.unit assert isinstance(qkpc0, u.Quantity) assert qkpc0.isscalar qkpcx = qkpc['x'] assert np.all(qkpcx.value == a['x']) assert qkpcx.unit == qkpc.unit assert isinstance(qkpcx, u.Quantity) assert not qkpcx.isscalar qkpcx1 = qkpc['x'][1] assert qkpcx1.unit == qkpc.unit assert isinstance(qkpcx1, u.Quantity) assert qkpcx1.isscalar qkpc1x = qkpc[1]['x'] assert qkpc1x.isscalar assert qkpc1x == qkpcx1 # can also create from lists, will auto-convert to arrays qsec = u.Quantity(list(range(10)), u.second) assert isinstance(qsec.value, np.ndarray) # quantity math should work with arrays assert_array_equal((qsec * 2).value, (np.arange(10) * 2)) assert_array_equal((qsec / 2).value, (np.arange(10) / 2)) # quantity addition/subtraction should *not* work with arrays b/c unit # ambiguous with pytest.raises(u.UnitsError): assert_array_equal((qsec + 2).value, (np.arange(10) + 2)) with pytest.raises(u.UnitsError): assert_array_equal((qsec - 2).value, (np.arange(10) + 2)) # should create by unit multiplication, too qsec2 = np.arange(10) * u.second qsec3 = u.second * np.arange(10) assert np.all(qsec == qsec2) assert np.all(qsec2 == qsec3) # make sure numerical-converters fail when arrays are present with pytest.raises(TypeError): float(qsec) with pytest.raises(TypeError): int(qsec) def test_array_indexing_slicing(): q = np.array([1., 2., 3.]) * u.m assert q[0] == 1. * u.m assert np.all(q[0:2] == u.Quantity([1., 2.], u.m)) def test_array_setslice(): q = np.array([1., 2., 3.]) * u.m q[1:2] = np.array([400.]) * u.cm assert np.all(q == np.array([1., 4., 3.]) * u.m) def test_inverse_quantity(): """ Regression test from issue #679 """ q = u.Quantity(4., u.meter / u.second) qot = q / 2 toq = 2 / q npqot = q / np.array(2) assert npqot.value == 2.0 assert npqot.unit == (u.meter / u.second) assert qot.value == 2.0 assert qot.unit == (u.meter / u.second) assert toq.value == 0.5 assert toq.unit == (u.second / u.meter) def test_quantity_mutability(): q = u.Quantity(9.8, u.meter / u.second / u.second) with pytest.raises(AttributeError): q.value = 3 with pytest.raises(AttributeError): q.unit = u.kg def test_quantity_initialized_with_quantity(): q1 = u.Quantity(60, u.second) q2 = u.Quantity(q1, u.minute) assert q2.value == 1 q3 = u.Quantity([q1, q2], u.second) assert q3[0].value == 60 assert q3[1].value == 60 q4 = u.Quantity([q2, q1]) assert q4.unit == q2.unit assert q4[0].value == 1 assert q4[1].value == 1 def test_quantity_string_unit(): q1 = 1. * u.m / 's' assert q1.value == 1 assert q1.unit == (u.m / u.s) q2 = q1 * "m" assert q2.unit == ((u.m * u.m) / u.s) def test_quantity_invalid_unit_string(): with pytest.raises(ValueError): "foo" * u.m def test_implicit_conversion(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True assert_allclose(q.centimeter, 100) assert_allclose(q.cm, 100) assert_allclose(q.parsec, 3.240779289469756e-17) def test_implicit_conversion_autocomplete(): q = u.Quantity(1.0, u.meter) # Manually turn this on to simulate what might happen in a subclass q._include_easy_conversion_members = True q.foo = 42 attrs = dir(q) assert 'centimeter' in attrs assert 'cm' in attrs assert 'parsec' in attrs assert 'foo' in attrs assert 'to' in attrs assert 'value' in attrs # Something from the base class, object assert '__setattr__' in attrs with pytest.raises(AttributeError): q.l def test_quantity_iterability(): """Regressiont est for issue #878. Scalar quantities should not be iterable and should raise a type error on iteration. """ q1 = [15.0, 17.0] * u.m assert isiterable(q1) q2 = next(iter(q1)) assert q2 == 15.0 * u.m assert not isiterable(q2) pytest.raises(TypeError, iter, q2) def test_copy(): q1 = u.Quantity(np.array([[1., 2., 3.], [4., 5., 6.]]), unit=u.m) q2 = q1.copy() assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value q3 = q1.copy(order='F') assert q3.flags['F_CONTIGUOUS'] assert np.all(q1.value == q3.value) assert q1.unit == q3.unit assert q1.dtype == q3.dtype assert q1.value is not q3.value q4 = q1.copy(order='C') assert q4.flags['C_CONTIGUOUS'] assert np.all(q1.value == q4.value) assert q1.unit == q4.unit assert q1.dtype == q4.dtype assert q1.value is not q4.value def test_deepcopy(): q1 = u.Quantity(np.array([1., 2., 3.]), unit=u.m) q2 = copy.deepcopy(q1) assert isinstance(q2, u.Quantity) assert np.all(q1.value == q2.value) assert q1.unit == q2.unit assert q1.dtype == q2.dtype assert q1.value is not q2.value def test_equality_numpy_scalar(): """ A regression test to ensure that numpy scalars are correctly compared (which originally failed due to the lack of ``__array_priority__``). """ assert 10 != 10. * u.m assert np.int64(10) != 10 * u.m assert 10 * u.m != np.int64(10) def test_quantity_pickelability(): """ Testing pickleability of quantity """ q1 = np.arange(10) * u.m q2 = pickle.loads(pickle.dumps(q1)) assert np.all(q1.value == q2.value) assert q1.unit.is_equivalent(q2.unit) assert q1.unit == q2.unit def test_quantity_initialisation_from_string(): q = u.Quantity('1') assert q.unit == u.dimensionless_unscaled assert q.value == 1. q = u.Quantity('1.5 m/s') assert q.unit == u.m/u.s assert q.value == 1.5 assert u.Unit(q) == u.Unit('1.5 m/s') q = u.Quantity('.5 m') assert q == u.Quantity(0.5, u.m) q = u.Quantity('-1e1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('-1e+1km') assert q == u.Quantity(-10, u.km) q = u.Quantity('+.5km') assert q == u.Quantity(.5, u.km) q = u.Quantity('+5e-1km') assert q == u.Quantity(.5, u.km) q = u.Quantity('5', u.m) assert q == u.Quantity(5., u.m) q = u.Quantity('5 km', u.m) assert q.value == 5000. assert q.unit == u.m q = u.Quantity('5Em') assert q == u.Quantity(5., u.Em) with pytest.raises(TypeError): u.Quantity('') with pytest.raises(TypeError): u.Quantity('m') with pytest.raises(TypeError): u.Quantity('1.2.3 deg') with pytest.raises(TypeError): u.Quantity('1+deg') with pytest.raises(TypeError): u.Quantity('1-2deg') with pytest.raises(TypeError): u.Quantity('1.2e-13.3m') with pytest.raises(TypeError): u.Quantity(['5']) with pytest.raises(TypeError): u.Quantity(np.array(['5'])) with pytest.raises(ValueError): u.Quantity('5E') with pytest.raises(ValueError): u.Quantity('5 foo') def test_unsupported(): q1 = np.arange(10) * u.m with pytest.raises(TypeError): np.bitwise_and(q1, q1) def test_unit_identity(): q = 1.0 * u.hour assert q.unit is u.hour def test_quantity_to_view(): q1 = np.array([1000, 2000]) * u.m q2 = q1.to(u.km) assert q1.value[0] == 1000 assert q2.value[0] == 1 def test_quantity_tuple_power(): with pytest.raises(ValueError): (5.0 * u.m) ** (1, 2) def test_quantity_fraction_power(): q = (25.0 * u.m**2) ** Fraction(1, 2) assert q.value == 5. assert q.unit == u.m # Regression check to ensure we didn't create an object type by raising # the value of the quantity to a Fraction. [#3922] assert q.dtype.kind == 'f' def test_quantity_from_table(): """ Checks that units from tables are respected when converted to a Quantity. This also generically checks the use of *anything* with a `unit` attribute passed into Quantity """ from astropy.table import Table t = Table(data=[np.arange(5), np.arange(5)], names=['a', 'b']) t['a'].unit = u.kpc qa = u.Quantity(t['a']) assert qa.unit == u.kpc assert_array_equal(qa.value, t['a']) qb = u.Quantity(t['b']) assert qb.unit == u.dimensionless_unscaled assert_array_equal(qb.value, t['b']) # This does *not* auto-convert, because it's not necessarily obvious that's # desired. Instead we revert to standard `Quantity` behavior qap = u.Quantity(t['a'], u.pc) assert qap.unit == u.pc assert_array_equal(qap.value, t['a'] * 1000) qbp = u.Quantity(t['b'], u.pc) assert qbp.unit == u.pc assert_array_equal(qbp.value, t['b']) # Also check with a function unit (regression test for gh-8430) t['a'].unit = u.dex(u.cm/u.s**2) fq = u.Dex(t['a']) assert fq.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq.value, t['a']) fq2 = u.Quantity(t['a'], subok=True) assert isinstance(fq2, u.Dex) assert fq2.unit == u.dex(u.cm/u.s**2) assert_array_equal(fq2.value, t['a']) with pytest.raises(u.UnitTypeError): u.Quantity(t['a']) def test_assign_slice_with_quantity_like(): # Regression tests for gh-5961 from astropy.table import Table, Column # first check directly that we can use a Column to assign to a slice. c = Column(np.arange(10.), unit=u.mm) q = u.Quantity(c) q[:2] = c[:2] # next check that we do not fail the original problem. t = Table() t['x'] = np.arange(10) * u.mm t['y'] = np.ones(10) * u.mm assert type(t['x']) is Column xy = np.vstack([t['x'], t['y']]).T * u.mm ii = [0, 2, 4] assert xy[ii, 0].unit == t['x'][ii].unit # should not raise anything xy[ii, 0] = t['x'][ii] def test_insert(): """ Test Quantity.insert method. This does not test the full capabilities of the underlying np.insert, but hits the key functionality for Quantity. """ q = [1, 2] * u.m # Insert a compatible float with different units q2 = q.insert(0, 1 * u.km) assert np.all(q2.value == [1000, 1, 2]) assert q2.unit is u.m assert q2.dtype.kind == 'f' if minversion(np, '1.8.0'): q2 = q.insert(1, [1, 2] * u.km) assert np.all(q2.value == [1, 1000, 2000, 2]) assert q2.unit is u.m # Cannot convert 1.5 * u.s to m with pytest.raises(u.UnitsError): q.insert(1, 1.5 * u.s) # Tests with multi-dim quantity q = [[1, 2], [3, 4]] * u.m q2 = q.insert(1, [10, 20] * u.m, axis=0) assert np.all(q2.value == [[1, 2], [10, 20], [3, 4]]) q2 = q.insert(1, [10, 20] * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 20, 4]]) q2 = q.insert(1, 10 * u.m, axis=1) assert np.all(q2.value == [[1, 10, 2], [3, 10, 4]]) def test_repr_array_of_quantity(): """ Test print/repr of object arrays of Quantity objects with different units. Regression test for the issue first reported in https://github.com/astropy/astropy/issues/3777 """ a = np.array([1 * u.m, 2 * u.s], dtype=object) assert repr(a) == 'array([<Quantity 1. m>, <Quantity 2. s>], dtype=object)' assert str(a) == '[<Quantity 1. m> <Quantity 2. s>]' class TestSpecificTypeQuantity: def setup(self): class Length(u.SpecificTypeQuantity): _equivalent_unit = u.m class Length2(Length): _default_unit = u.m class Length3(Length): _unit = u.m self.Length = Length self.Length2 = Length2 self.Length3 = Length3 def test_creation(self): l = self.Length(np.arange(10.)*u.km) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.) * u.hour) with pytest.raises(u.UnitTypeError): self.Length(np.arange(10.)) l2 = self.Length2(np.arange(5.)) assert type(l2) is self.Length2 assert l2._default_unit is self.Length2._default_unit with pytest.raises(u.UnitTypeError): self.Length3(np.arange(10.)) def test_view(self): l = (np.arange(5.) * u.km).view(self.Length) assert type(l) is self.Length with pytest.raises(u.UnitTypeError): (np.arange(5.) * u.s).view(self.Length) v = np.arange(5.).view(self.Length) assert type(v) is self.Length assert v._unit is None l3 = np.ones((2, 2)).view(self.Length3) assert type(l3) is self.Length3 assert l3.unit is self.Length3._unit def test_operation_precedence_and_fallback(self): l = self.Length(np.arange(5.)*u.cm) sum1 = l + 1.*u.m assert type(sum1) is self.Length sum2 = 1.*u.km + l assert type(sum2) is self.Length sum3 = l + l assert type(sum3) is self.Length res1 = l * (1.*u.m) assert type(res1) is u.Quantity res2 = l * l assert type(res2) is u.Quantity def test_unit_class_override(): class MyQuantity(u.Quantity): pass my_unit = u.Unit("my_deg", u.deg) my_unit._quantity_class = MyQuantity q1 = u.Quantity(1., my_unit) assert type(q1) is u.Quantity q2 = u.Quantity(1., my_unit, subok=True) assert type(q2) is MyQuantity class QuantityMimic: def __init__(self, value, unit): self.value = value self.unit = unit def __array__(self): return np.array(self.value) class QuantityMimic2(QuantityMimic): def to(self, unit): return u.Quantity(self.value, self.unit).to(unit) def to_value(self, unit): return u.Quantity(self.value, self.unit).to_value(unit) class TestQuantityMimics: """Test Quantity Mimics that are not ndarray subclasses.""" @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_input(self, Mimic): value = np.arange(10.) mimic = Mimic(value, u.m) q = u.Quantity(mimic) assert q.unit == u.m assert np.all(q.value == value) q2 = u.Quantity(mimic, u.cm) assert q2.unit == u.cm assert np.all(q2.value == 100 * value) @pytest.mark.parametrize('Mimic', (QuantityMimic, QuantityMimic2)) def test_mimic_setting(self, Mimic): mimic = Mimic([1., 2.], u.m) q = u.Quantity(np.arange(10.), u.cm) q[8:] = mimic assert np.all(q[:8].value == np.arange(8.)) assert np.all(q[8:].value == [100., 200.]) def test_mimic_function_unit(self): mimic = QuantityMimic([1., 2.], u.dex(u.cm/u.s**2)) d = u.Dex(mimic) assert isinstance(d, u.Dex) assert d.unit == u.dex(u.cm/u.s**2) assert np.all(d.value == [1., 2.]) q = u.Quantity(mimic, subok=True) assert isinstance(q, u.Dex) assert q.unit == u.dex(u.cm/u.s**2) assert np.all(q.value == [1., 2.]) with pytest.raises(u.UnitTypeError): u.Quantity(mimic) def test_masked_quantity_str_repr(): """Ensure we don't break masked Quantity representation.""" # Really, masked quantities do not work well, but at least let the # basics work. masked_quantity = np.ma.array([1, 2, 3, 4] * u.kg, mask=[True, False, True, False]) str(masked_quantity) repr(masked_quantity) class TestQuantitySubclassAboveAndBelow: @classmethod def setup_class(self): class MyArray(np.ndarray): def __array_finalize__(self, obj): super_array_finalize = super().__array_finalize__ if super_array_finalize is not None: super_array_finalize(obj) if hasattr(obj, 'my_attr'): self.my_attr = obj.my_attr self.MyArray = MyArray self.MyQuantity1 = type('MyQuantity1', (u.Quantity, MyArray), dict(my_attr='1')) self.MyQuantity2 = type('MyQuantity2', (MyArray, u.Quantity), dict(my_attr='2')) def test_setup(self): mq1 = self.MyQuantity1(10, u.m) assert isinstance(mq1, self.MyQuantity1) assert mq1.my_attr == '1' assert mq1.unit is u.m mq2 = self.MyQuantity2(10, u.m) assert isinstance(mq2, self.MyQuantity2) assert mq2.my_attr == '2' assert mq2.unit is u.m def test_attr_propagation(self): mq1 = self.MyQuantity1(10, u.m) mq12 = self.MyQuantity2(mq1) assert isinstance(mq12, self.MyQuantity2) assert not isinstance(mq12, self.MyQuantity1) assert mq12.my_attr == '1' assert mq12.unit is u.m mq2 = self.MyQuantity2(10, u.m) mq21 = self.MyQuantity1(mq2) assert isinstance(mq21, self.MyQuantity1) assert not isinstance(mq21, self.MyQuantity2) assert mq21.my_attr == '2' assert mq21.unit is u.m
dhomeier/astropy
astropy/units/tests/test_quantity.py
astropy/coordinates/tests/conftest.py
""" Main driver class for PypeIt run """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import time #from abc import ABCMeta import os import datetime import numpy as np from collections import OrderedDict from astropy.io import fits from pypeit import msgs from pypeit import calibrations from pypeit import scienceimage from pypeit import specobjs from pypeit import ginga from pypeit import reduce from pypeit.core import paths from pypeit.core import qa from pypeit.core import wave from pypeit.core import save from pypeit.core import load from pypeit.spectrographs.util import load_spectrograph from linetools import utils as ltu from configobj import ConfigObj from pypeit.par.util import parse_pypeit_file from pypeit.par import PypeItPar from pypeit.metadata import PypeItMetaData from pypeit import debugger class PypeIt(object): """ This class runs the primary calibration and extraction in PypeIt Args: pypeit_file (:obj:`str`): PypeIt filename verbosity (:obj:`int`, optional): Verbosity level of system output. Can be:: - 0: No output - 1: Minimal output (default) - 2: All output overwrite (:obj:`bool`, optional): Flag to overwrite any existing files/directories. reuse_masters (bool, optional): Reuse any pre-existing calibration files logname (:obj:`str`, optional): The name of an ascii log file with the details of the reduction. redux_path (:obj:`str`, optional): Over-ride reduction path in PypeIt file (e.g. Notebook usage) show: (:obj:`bool`, optional): Show reduction steps via plots (which will block further execution until clicked on) and outputs to ginga. Requires remote control ginga session via "ginga --modules=RC &" Attributes: pypeit_file (:obj:`str`): Name of the pypeit file to read. PypeIt files have a specific set of valid formats. A description can be found `here`_ (include doc link). fitstbl (:obj:`pypit.metadata.PypeItMetaData`): holds the meta info """ # __metaclass__ = ABCMeta def __init__(self, pypeit_file, verbosity=2, overwrite=True, reuse_masters=False, logname=None, show=False, redux_path=None): # Load cfg_lines, data_files, frametype, usrdata, setups = parse_pypeit_file(pypeit_file, runtime=True) self.pypeit_file = pypeit_file # Spectrograph cfg = ConfigObj(cfg_lines) spectrograph_name = cfg['rdx']['spectrograph'] self.spectrograph = load_spectrograph(spectrograph_name) # Par # Defaults spectrograph_def_par = self.spectrograph.default_pypeit_par() # Grab a science file for configuration specific parameters sci_file = None for idx, row in enumerate(usrdata): if 'science' in row['frametype']: sci_file = data_files[idx] break # Set spectrograph_cfg_lines = self.spectrograph.config_specific_par(spectrograph_def_par, sci_file).to_config() self.par = PypeItPar.from_cfg_lines(cfg_lines=spectrograph_cfg_lines, merge_with=cfg_lines) # Fitstbl self.fitstbl = PypeItMetaData(self.spectrograph, self.par, file_list=data_files, usrdata=usrdata, strict=True) # The following could be put in a prepare_to_run() method in PypeItMetaData if 'setup' not in self.fitstbl.keys(): self.fitstbl['setup'] = setups[0] self.fitstbl.get_frame_types(user=frametype) # This sets them using the user inputs self.fitstbl.set_defaults() # Only does something if values not set in PypeIt file self.fitstbl._set_calib_group_bits() self.fitstbl._check_calib_groups() # Write .calib file (For QA naming amongst other things) calib_file = pypeit_file.replace('.pypeit', '.calib') self.fitstbl.write_calib(calib_file) # Other Internals self.logname = logname self.overwrite = overwrite # Currently the runtime argument determines the behavior for reuse_masters. There is also a reuse_masters # parameter in the parset but it is currently ignored. self.reuse_masters=reuse_masters self.show = show # Make the output directories self.par['rdx']['redux_path'] = os.getcwd() if redux_path is None else redux_path msgs.info("Setting reduction path to {:s}".format(self.par['rdx']['redux_path'])) paths.make_dirs(self.spectrograph.spectrograph, self.par['calibrations']['caldir'], self.par['rdx']['scidir'], self.par['rdx']['qadir'], overwrite=self.overwrite, redux_path=self.par['rdx']['redux_path']) # Instantiate Calibrations class self.caliBrate \ = calibrations.MultiSlitCalibrations(self.fitstbl, self.par['calibrations'], self.spectrograph, redux_path=self.par['rdx']['redux_path'], reuse_masters=self.reuse_masters, save_masters=True, write_qa=True, show=self.show) # Init self.verbosity = verbosity # TODO: I don't think this ever used self.frame = None self.det = None self.tstart = None self.basename = None self.sciI = None self.obstime = None def build_qa(self): """ Generate QA wrappers """ qa.gen_mf_html(self.pypeit_file) qa.gen_exp_html() def outfile_exists(self, frame): """ Check whether the 2D outfile of a given frame already exists Args: frame (int): Frame index from fitstbl Returns: bool: True if the 2d file exists False if it does not exist """ # Check if the 2d output file exists scidir = os.path.join(self.par['rdx']['redux_path'], self.par['rdx']['scidir']) basename = self.fitstbl.construct_basename(frame) outfile = scidir + '/spec2d_{:s}.fits'.format(basename) return os.path.isfile(outfile) def get_std_outfile(self, standard_frames): """ Grab the output filename from an input list of standard_frame indices If more than one index is provided, the first is taken Args: standard_frames (list): List of indices corresponding to standard stars Returns: str: Full path to the standard spec1d output file """ # TODO: Need to decide how to associate standards with # science frames in the case where there is more than one # standard associated with a given science frame. Below, I # just use the first standard std_outfile = None std_frame = None if len(standard_frames) == 0 else standard_frames[0] # Prepare to load up standard? if std_frame is not None: std_outfile = os.path.join(self.par['rdx']['redux_path'], self.par['rdx']['scidir'], 'spec1d_{:s}.fits'.format(self.fitstbl.construct_basename(std_frame))) \ if isinstance(std_frame, (int,np.integer)) else None if std_outfile is not None and not os.path.isfile(std_outfile): msgs.error('Could not find standard file: {0}'.format(std_outfile)) return std_outfile def reduce_all(self): """ Main driver of the entire reduction Calibration and extraction via a series of calls to reduce_exposure() """ # Validate the parameter set required = ['rdx', 'calibrations', 'scienceframe', 'scienceimage', 'flexure', 'fluxcalib'] can_be_None = ['flexure', 'fluxcalib'] self.par.validate_keys(required=required, can_be_None=can_be_None) self.tstart = time.time() # Find the standard frames is_standard = self.fitstbl.find_frames('standard') # Find the science frames is_science = self.fitstbl.find_frames('science') # Frame indices frame_indx = np.arange(len(self.fitstbl)) # Iterate over each calibration group and reduce the standards for i in range(self.fitstbl.n_calib_groups): # Find all the frames in this calibration group in_grp = self.fitstbl.find_calib_group(i) # Find the indices of the standard frames in this calibration group: grp_standards = frame_indx[is_standard & in_grp] # Reduce all the standard frames, loop on unique comb_id u_combid_std= np.unique(self.fitstbl['comb_id'][grp_standards]) for j, comb_id in enumerate(u_combid_std): frames = np.where(self.fitstbl['comb_id'] == comb_id)[0] bg_frames = np.where(self.fitstbl['bkg_id'] == comb_id)[0] if not self.outfile_exists(frames[0]) or self.overwrite: std_dict = self.reduce_exposure(frames, bg_frames=bg_frames) # TODO come up with sensible naming convention for save_exposure for combined files self.save_exposure(frames[0], std_dict, self.basename) else: msgs.info('Output file: {:s} already exists'.format(self.fitstbl.construct_basename(frames[0])) + '. Set overwrite=True to recreate and overwrite.') # Iterate over each calibration group again and reduce the science frames for i in range(self.fitstbl.n_calib_groups): # Find all the frames in this calibration group in_grp = self.fitstbl.find_calib_group(i) # Find the indices of the science frames in this calibration group: grp_science = frame_indx[is_science & in_grp] # Associate standards (previously reduced above) for this setup std_outfile = self.get_std_outfile(frame_indx[is_standard]) # Reduce all the science frames; keep the basenames of the science frames for use in flux calibration science_basename = [None]*len(grp_science) # Loop on unique comb_id u_combid = np.unique(self.fitstbl['comb_id'][grp_science]) for j, comb_id in enumerate(u_combid): frames = np.where(self.fitstbl['comb_id'] == comb_id)[0] bg_frames = np.where(self.fitstbl['bkg_id'] == comb_id)[0] if not self.outfile_exists(frames[0]) or self.overwrite: sci_dict = self.reduce_exposure(frames, bg_frames=bg_frames, std_outfile=std_outfile) science_basename[j] = self.basename # TODO come up with sensible naming convention for save_exposure for combined files self.save_exposure(frames[0], sci_dict, self.basename) else: msgs.warn('Output file: {:s} already exists'.format(self.fitstbl.construct_basename(frames[0])) + '. Set overwrite=True to recreate and overwrite.') msgs.info('Finished calibration group {0}'.format(i)) # Finish self.print_end_time() def select_detectors(self): """ Return the 1-indexed list of detectors to reduce. Returns: list: List of detectors to be reduced """ if self.par['rdx']['detnum'] is None: return np.arange(self.spectrograph.ndet)+1 return [self.par['rdx']['detnum']] if isinstance(self.par['rdx']['detnum'], int) \ else self.par['rdx']['detnum'] def reduce_exposure(self, frames, bg_frames=[], std_outfile=None): """ Reduce a single exposure Args: frame (:obj:`int`): 0-indexed row in :attr:`fitstbl` with the frame to reduce bgframes (:obj:`list`, optional): List of frame indices for the background std_outfile (:obj:`str`, optional): the name of a file with a previously PypeIt-reduced standard spectrum. Returns: dict: The dictionary containing the primary outputs of extraction """ # if show is set, clear the ginga channels at the start of each new sci_ID if self.show: ginga.clear_all() # Save the frame self.frames = frames self.bg_frames = bg_frames # Is this an IR reduction? self.ir_redux = True if len(bg_frames) > 0 else False # JFH Why does this need to be ordered? sci_dict = OrderedDict() # This needs to be ordered sci_dict['meta'] = {} sci_dict['meta']['vel_corr'] = 0. sci_dict['meta']['ir_redux'] = self.ir_redux # Print status message msgs_string = 'Reducing target {:s}'.format(self.fitstbl['target'][self.frames[0]]) + msgs.newline() msgs_string += 'Combining frames:' + msgs.newline() for iframe in self.frames: msgs_string += '{0:s}'.format(self.fitstbl['filename'][iframe]) + msgs.newline() msgs.info(msgs_string) if len(bg_frames) > 0: bg_msgs_string = '' for iframe in self.bg_frames: bg_msgs_string += '{0:s}'.format(self.fitstbl['filename'][iframe]) + msgs.newline() bg_msgs_string = msgs.newline() + 'Using background from frames:' + msgs.newline() + bg_msgs_string msgs.info(bg_msgs_string) # Find the detectors to reduce detectors = self.select_detectors() if len(detectors) != self.spectrograph.ndet: msgs.warn('Not reducing detectors: {0}'.format(' '.join([ str(d) for d in set(np.arange(self.spectrograph.ndet))-set(detectors)]))) # Loop on Detectors for self.det in detectors: msgs.info("Working on detector {0}".format(self.det)) sci_dict[self.det] = {} # Calibrate #TODO Is the right behavior to just use the first frame? self.caliBrate.set_config(self.frames[0], self.det, self.par['calibrations']) self.caliBrate.run_the_steps() # Extract # TODO: pass back the background frame, pass in background # files as an argument. extract one takes a file list as an # argument and instantiates science within sci_dict[self.det]['sciimg'], sci_dict[self.det]['sciivar'], sci_dict[self.det]['skymodel'], \ sci_dict[self.det]['objmodel'], sci_dict[self.det]['ivarmodel'], sci_dict[self.det]['outmask'], \ sci_dict[self.det]['specobjs'], vel_corr \ = self.extract_one(self.frames, self.det, bg_frames = self.bg_frames, std_outfile = std_outfile) if vel_corr is not None: sci_dict['meta']['vel_corr'] = vel_corr # JFH TODO write out the background frame? # Return return sci_dict def flexure_correct(self, sobjs, maskslits): """ Correct for flexure Spectra are modified in place (wavelengths are shifted) Args: sobjs (SpecObjs): maskslits (ndarray): Mask of SpecObjs """ if self.par['flexure']['method'] != 'skip': flex_list = wave.flexure_obj(sobjs, maskslits, self.par['flexure']['method'], self.par['flexure']['spectrum'], mxshft=self.par['flexure']['maxshift']) # QA wave.flexure_qa(sobjs, maskslits, self.basename, self.det, flex_list, out_dir=self.par['rdx']['redux_path']) else: msgs.info('Skipping flexure correction.') def helio_correct(self, sobjs, maskslits, frame, obstime): """ Perform a heliocentric correction on a set of spectra Args: sobjs (pypeit.specobjs.SpecObjs): Spectra maskslits (ndarray): Slits that are masked frame (int): Frame to use for meta info obstime (astropy.time.Time): Returns: astropy.units.Quantity: Velocity correction in km/s """ # Helio, correct Earth's motion if (self.caliBrate.par['wavelengths']['frame'] in ['heliocentric', 'barycentric']) \ and (self.caliBrate.par['wavelengths']['reference'] != 'pixel'): # TODO change this keyword to refframe instead of frame msgs.info("Performing a {0} correction".format(self.caliBrate.par['wavelengths']['frame'])) vel, vel_corr = wave.geomotion_correct(sobjs, maskslits, self.fitstbl, frame, obstime, self.spectrograph.telescope['longitude'], self.spectrograph.telescope['latitude'], self.spectrograph.telescope['elevation'], self.caliBrate.par['wavelengths']['frame']) else: msgs.info('A wavelength reference-frame correction will not be performed.') vel_corr = None return vel_corr def get_sci_metadata(self, frame, det): """ Grab the meta data for a given science frame and specific detector Args: frame (int): Frame index det (int): Detector index Returns: 5 objects are returned:: - str: Object type; science or standard - str: Setup string from master_key() - astropy.time.Time: Time of observation - str: Basename of the frame - str: Binning of the detector """ # Set binning, obstime, basename, and objtype binning = self.fitstbl['binning'][frame] obstime = self.fitstbl.construct_obstime(frame) basename = self.fitstbl.construct_basename(frame, obstime=obstime) objtype = self.fitstbl['frametype'][frame] if 'science' in objtype: objtype_out = 'science' elif 'standard' in objtype: objtype_out = 'standard' else: msgs.error('Unrecognized objtype') setup = self.fitstbl.master_key(frame, det=det) return objtype_out, setup, obstime, basename, binning def get_std_trace(self, std_redux, det, std_outfile): """ Returns the trace of the standard if it is applicable to the current reduction Args: std_redux (bool): If False, proceed det (int): Detector index std_outfile (str): Filename for the standard star spec1d file Returns: ndarray: Trace of the standard star on input detector """ if std_redux is False and std_outfile is not None: sobjs, hdr_std = load.load_specobjs(std_outfile) # Does the detector match? # TODO Instrument specific logic here could be implemented with the parset. For example LRIS-B or LRIS-R we # we would use the standard from another detector this_det = sobjs.det == det if np.any(this_det): sobjs_det = sobjs[this_det] sobjs_std = sobjs_det.get_std() std_trace = sobjs_std.trace_spat # flatten the array if this multislit if 'MultiSlit' in self.spectrograph.pypeline: std_trace = std_trace.flatten() elif 'Echelle' in self.spectrograph.pypeline: std_trace = std_trace.T else: msgs.error('Unrecognized pypeline') else: std_trace = None else: std_trace = None return std_trace def extract_one(self, frames, det, bg_frames=[], std_outfile=None): """ Extract a single exposure/detector pair sci_ID and det need to have been set internally prior to calling this method Args: frames (list): List of frames to extract; stacked if more than one is provided det (int): bg_frames (list, optional): List of frames to use as the background std_outfile (str, optional): Returns: eight objects are returned:: - ndarray: Science image - ndarray: Science inverse variance image - ndarray: Model of the sky - ndarray: Model of the object - ndarray: Model of inverse variance - ndarray: Mask - :obj:`pypeit.specobjs.SpecObjs`: spectra - astropy.units.Quantity: velocity correction """ # Grab some meta-data needed for the reduction from the fitstbl self.objtype, self.setup, self.obstime, self.basename, self.binning = self.get_sci_metadata(frames[0], det) # Is this a standard star? self.std_redux = 'standard' in self.objtype # Get the standard trace if need be std_trace = self.get_std_trace(self.std_redux, det, std_outfile) # Instantiate ScienceImage for the files we will reduce sci_files = self.fitstbl.frame_paths(frames) self.sciI = scienceimage.ScienceImage(self.spectrograph, sci_files, bg_file_list=self.fitstbl.frame_paths(bg_frames), ir_redux = self.ir_redux, par=self.par['scienceframe'], det=det, binning=self.binning) # For QA on crash. msgs.sciexp = self.sciI # Process images (includes inverse variance image, rn2 image, and CR mask) self.sciimg, self.sciivar, self.rn2img, self.mask, self.crmask = \ self.sciI.proc(self.caliBrate.msbias, self.caliBrate.mspixflatnrm.copy(), self.caliBrate.msbpm, illum_flat=self.caliBrate.msillumflat, show=self.show) # Object finding, first pass on frame without sky subtraction self.maskslits = self.caliBrate.maskslits.copy() self.redux = reduce.instantiate_me(self.spectrograph, self.caliBrate.tslits_dict, self.mask, self.par, ir_redux = self.ir_redux, objtype=self.objtype, setup=self.setup, det=det, binning=self.binning) # Prep for manual extraction (if requested) manual_extract_dict = self.fitstbl.get_manual_extract(frames, det) # Do one iteration of object finding, and sky subtract to get initial sky model self.sobjs_obj, self.nobj, skymask_init = \ self.redux.find_objects(self.sciimg, self.sciivar, std=self.std_redux, ir_redux=self.ir_redux, std_trace=std_trace,maskslits=self.maskslits, show=self.show & (not self.std_redux), manual_extract_dict=manual_extract_dict) # Global sky subtraction, first pass. Uses skymask from object finding step above self.initial_sky = \ self.redux.global_skysub(self.sciimg, self.sciivar, self.caliBrate.tilts_dict['tilts'], skymask=skymask_init, std=self.std_redux, maskslits=self.maskslits, show=self.show) if not self.std_redux: # Object finding, second pass on frame *with* sky subtraction. Show here if requested self.sobjs_obj, self.nobj, self.skymask = \ self.redux.find_objects(self.sciimg - self.initial_sky, self.sciivar, std=self.std_redux, ir_redux=self.ir_redux, std_trace=std_trace,maskslits=self.maskslits,show=self.show, manual_extract_dict=manual_extract_dict) # If there are objects, do 2nd round of global_skysub, local_skysub_extract, flexure, geo_motion if self.nobj > 0: # Global sky subtraction second pass. Uses skymask from object finding self.global_sky = self.initial_sky if self.std_redux else \ self.redux.global_skysub(self.sciimg, self.sciivar, self.caliBrate.tilts_dict['tilts'], skymask=self.skymask, maskslits=self.maskslits, show=self.show) self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs = \ self.redux.local_skysub_extract(self.sciimg, self.sciivar, self.caliBrate.tilts_dict['tilts'], self.caliBrate.mswave, self.global_sky, self.rn2img, self.sobjs_obj, model_noise=(not self.ir_redux),std = self.std_redux, maskslits=self.maskslits, show_profile=self.show,show=self.show) # Purge out the negative objects if this was a near-IR reduction. # TODO should we move this purge call to local_skysub_extract?? if self.ir_redux: self.sobjs.purge_neg() # Flexure correction if this is not a standard star if not self.std_redux: self.redux.flexure_correct(self.sobjs, self.basename) # Grab coord radec = ltu.radec_to_coord((self.fitstbl["ra"][frames[0]], self.fitstbl["dec"][frames[0]])) self.vel_corr = self.redux.helio_correct(self.sobjs, radec, self.obstime) else: # Print status message msgs_string = 'No objects to extract for target {:s}'.format(self.fitstbl['target'][frames[0]]) + msgs.newline() msgs_string += 'On frames:' + msgs.newline() for iframe in frames: msgs_string += '{0:s}'.format(self.fitstbl['filename'][iframe]) + msgs.newline() msgs.warn(msgs_string) # set to first pass global sky self.skymodel = self.initial_sky self.objmodel = np.zeros_like(self.sciimg) # Set to sciivar. Could create a model but what is the point? self.ivarmodel = np.copy(self.sciivar) # Set to the initial mask in case no objects were found self.outmask = self.redux.mask # empty specobjs object from object finding if self.ir_redux: self.sobjs_obj.purge_neg() self.sobjs = self.sobjs_obj self.vel_corr = None return self.sciimg, self.sciivar, self.skymodel, self.objmodel, self.ivarmodel, self.outmask, self.sobjs, self.vel_corr # TODO: Why not use self.frame? def save_exposure(self, frame, sci_dict, basename): """ Save the outputs from extraction for a given exposure Args: frame (:obj:`int`): 0-indexed row in the metadata table with the frame that has been reduced. sci_dict (:obj:`dict`): Dictionary containing the primary outputs of extraction basename (:obj:`str`): The root name for the output file. Returns: None or SpecObjs: All of the objects saved to disk """ # TODO: Need some checks here that the exposure has been reduced # Determine the headers head1d = self.fitstbl[frame] # Need raw file header information rawfile = self.fitstbl.frame_paths(frame) head2d = fits.getheader(rawfile, ext=self.spectrograph.primary_hdrext,) refframe = 'pixel' if self.caliBrate.par['wavelengths']['reference'] == 'pixel' else \ self.caliBrate.par['wavelengths']['frame'] # Determine the paths/filenames scipath = os.path.join(self.par['rdx']['redux_path'], self.par['rdx']['scidir']) save.save_all(sci_dict, self.caliBrate.master_key_dict, self.caliBrate.master_dir, self.spectrograph, head1d, head2d, scipath, basename, refframe=refframe, update_det=self.par['rdx']['detnum'], binning=self.fitstbl['binning'][frame]) return def msgs_reset(self): """ Reset the msgs object """ # Reset the global logger msgs.reset(log=self.logname, verbosity=self.verbosity) msgs.pypeit_file = self.pypeit_file def print_end_time(self): """ Print the elapsed time """ # Capture the end time and print it to user tend = time.time() codetime = tend-self.tstart if codetime < 60.0: msgs.info('Execution time: {0:.2f}s'.format(codetime)) elif codetime/60.0 < 60.0: mns = int(codetime/60.0) scs = codetime - 60.0*mns msgs.info('Execution time: {0:d}m {1:.2f}s'.format(mns, scs)) else: hrs = int(codetime/3600.0) mns = int(60.0*(codetime/3600.0 - hrs)) scs = codetime - 60.0*mns - 3600.0*hrs msgs.info('Execution time: {0:d}h {1:d}m {2:.2f}s'.format(hrs, mns, scs)) # TODO: Move this to fitstbl? def show_science(self): """ Simple print of science frames """ indx = self.fitstbl.find_frames('science') print(self.fitstbl[['target','ra','dec','exptime','dispname']][indx]) def __repr__(self): # Generate sets string return '<{:s}: pypeit_file={}>'.format(self.__class__.__name__, self.pypeit_file)
# Module to run tests on FlatField class # Requires files in Development suite and an Environmental variable from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # TEST_UNICODE_LITERALS import os import pytest import glob import numpy as np from pypeit.tests.tstutils import dev_suite_required, load_kast_blue_masters from pypeit import flatfield from pypeit.par import pypeitpar def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'files') return os.path.join(data_dir, filename) # TODO: Bring this test back in some way? #def test_step_by_step(): # if skip_test: # assert True # return # # Masters # spectrograph, TSlits, tilts, datasec_img \ # = load_kast_blue_masters(get_spectrograph=True, tslits=True, tilts=True, # datasec=True) # # Instantiate # flatField = flatfield.FlatField(spectrograph, det=1, tilts=tilts, # tslits_dict=TSlits.tslits_dict.copy()) # # Use mstrace # flatField.mspixelflat = TSlits.mstrace.copy() # # Normalize a slit # slit=0 # flatField._prep_tck() # modvals, nrmvals, msblaze_slit, blazeext_slit, iextrap_slit = flatField.slit_profile(slit) # assert np.isclose(iextrap_slit, 0.) # # Apply # word = np.where(flatField.tslits_dict['slitpix'] == slit + 1) # flatField.mspixelflatnrm = flatField.mspixelflat.copy() # flatField.mspixelflatnrm[word] /= nrmvals # assert np.isclose(np.median(flatField.mspixelflatnrm), 1.0267346) @dev_suite_required def test_run(): # Masters spectrograph, tslits_dict, tilts_dict, datasec_img \ = load_kast_blue_masters(get_spectrograph=True, tslits=True, tilts=True, datasec=True) # Instantiate frametype = 'pixelflat' par = pypeitpar.FrameGroupPar(frametype) flatField = flatfield.FlatField(spectrograph, par, det=1, tilts_dict=tilts_dict, tslits_dict=tslits_dict.copy()) # Use mstrace flatField.rawflatimg = tslits_dict['mstrace'].copy() mspixelflatnrm, msillumflat = flatField.run() assert np.isclose(np.median(mspixelflatnrm), 1.0)
PYPIT/PYPIT
pypeit/tests/test_flatfield.py
pypeit/pypeit.py
import numpy as np from scipy.optimize import linear_sum_assignment from ...utils.validation import check_consistent_length, check_array from ...utils.validation import _deprecate_positional_args __all__ = ["consensus_score"] def _check_rows_and_columns(a, b): """Unpacks the row and column arrays and checks their shape.""" check_consistent_length(*a) check_consistent_length(*b) checks = lambda x: check_array(x, ensure_2d=False) a_rows, a_cols = map(checks, a) b_rows, b_cols = map(checks, b) return a_rows, a_cols, b_rows, b_cols def _jaccard(a_rows, a_cols, b_rows, b_cols): """Jaccard coefficient on the elements of the two biclusters.""" intersection = ((a_rows * b_rows).sum() * (a_cols * b_cols).sum()) a_size = a_rows.sum() * a_cols.sum() b_size = b_rows.sum() * b_cols.sum() return intersection / (a_size + b_size - intersection) def _pairwise_similarity(a, b, similarity): """Computes pairwise similarity matrix. result[i, j] is the Jaccard coefficient of a's bicluster i and b's bicluster j. """ a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b) n_a = a_rows.shape[0] n_b = b_rows.shape[0] result = np.array(list(list(similarity(a_rows[i], a_cols[i], b_rows[j], b_cols[j]) for j in range(n_b)) for i in range(n_a))) return result @_deprecate_positional_args def consensus_score(a, b, *, similarity="jaccard"): """The similarity of two sets of biclusters. Similarity between individual biclusters is computed. Then the best matching between sets is found using the Hungarian algorithm. The final score is the sum of similarities divided by the size of the larger set. Read more in the :ref:`User Guide <biclustering>`. Parameters ---------- a : (rows, columns) Tuple of row and column indicators for a set of biclusters. b : (rows, columns) Another set of biclusters like ``a``. similarity : 'jaccard' or callable, default='jaccard' May be the string "jaccard" to use the Jaccard coefficient, or any function that takes four arguments, each of which is a 1d indicator vector: (a_rows, a_columns, b_rows, b_columns). References ---------- * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis for bicluster acquisition <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__. """ if similarity == "jaccard": similarity = _jaccard matrix = _pairwise_similarity(a, b, similarity) row_indices, col_indices = linear_sum_assignment(1. - matrix) n_a = len(a[0]) n_b = len(b[0]) return matrix[row_indices, col_indices].sum() / max(n_a, n_b)
""" Testing for Isolation Forest algorithm (sklearn.ensemble.iforest). """ # Authors: Nicolas Goix <nicolas.goix@telecom-paristech.fr> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD 3 clause import pytest import numpy as np from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal from sklearn.utils._testing import assert_raises from sklearn.utils._testing import assert_warns_message from sklearn.utils._testing import ignore_warnings from sklearn.utils._testing import assert_allclose from sklearn.model_selection import ParameterGrid from sklearn.ensemble import IsolationForest from sklearn.ensemble._iforest import _average_path_length from sklearn.model_selection import train_test_split from sklearn.datasets import load_diabetes, load_iris from sklearn.utils import check_random_state from sklearn.metrics import roc_auc_score from scipy.sparse import csc_matrix, csr_matrix from unittest.mock import Mock, patch rng = check_random_state(0) # load the iris dataset # and randomly permute it iris = load_iris() perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the diabetes dataset # and randomly permute it diabetes = load_diabetes() perm = rng.permutation(diabetes.target.size) diabetes.data = diabetes.data[perm] diabetes.target = diabetes.target[perm] def test_iforest(): """Check Isolation Forest for various parameter settings.""" X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid({"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]}) with ignore_warnings(): for params in grid: IsolationForest(random_state=rng, **params).fit(X_train).predict(X_test) def test_iforest_sparse(): """Check IForest for various parameter settings on sparse input.""" rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(diabetes.data[:50], diabetes.target[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "bootstrap": [True, False]}) for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in grid: # Trained on sparse format sparse_classifier = IsolationForest( n_estimators=10, random_state=1, **params).fit(X_train_sparse) sparse_results = sparse_classifier.predict(X_test_sparse) # Trained on dense format dense_classifier = IsolationForest( n_estimators=10, random_state=1, **params).fit(X_train) dense_results = dense_classifier.predict(X_test) assert_array_equal(sparse_results, dense_results) def test_iforest_error(): """Test that it gives proper exception on deficient input.""" X = iris.data # Test max_samples assert_raises(ValueError, IsolationForest(max_samples=-1).fit, X) assert_raises(ValueError, IsolationForest(max_samples=0.0).fit, X) assert_raises(ValueError, IsolationForest(max_samples=2.0).fit, X) # The dataset has less than 256 samples, explicitly setting # max_samples > n_samples should result in a warning. If not set # explicitly there should be no warning assert_warns_message(UserWarning, "max_samples will be set to n_samples for estimation", IsolationForest(max_samples=1000).fit, X) # note that assert_no_warnings does not apply since it enables a # PendingDeprecationWarning triggered by scipy.sparse's use of # np.matrix. See issue #11251. with pytest.warns(None) as record: IsolationForest(max_samples='auto').fit(X) user_warnings = [each for each in record if issubclass(each.category, UserWarning)] assert len(user_warnings) == 0 with pytest.warns(None) as record: IsolationForest(max_samples=np.int64(2)).fit(X) user_warnings = [each for each in record if issubclass(each.category, UserWarning)] assert len(user_warnings) == 0 assert_raises(ValueError, IsolationForest(max_samples='foobar').fit, X) assert_raises(ValueError, IsolationForest(max_samples=1.5).fit, X) # test X_test n_features match X_train one: assert_raises(ValueError, IsolationForest().fit(X).predict, X[:, 1:]) def test_recalculate_max_depth(): """Check max_depth recalculation when max_samples is reset to n_samples""" X = iris.data clf = IsolationForest().fit(X) for est in clf.estimators_: assert est.max_depth == int(np.ceil(np.log2(X.shape[0]))) def test_max_samples_attribute(): X = iris.data clf = IsolationForest().fit(X) assert clf.max_samples_ == X.shape[0] clf = IsolationForest(max_samples=500) assert_warns_message(UserWarning, "max_samples will be set to n_samples for estimation", clf.fit, X) assert clf.max_samples_ == X.shape[0] clf = IsolationForest(max_samples=0.4).fit(X) assert clf.max_samples_ == 0.4*X.shape[0] def test_iforest_parallel_regression(): """Check parallel regression.""" rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(diabetes.data, diabetes.target, random_state=rng) ensemble = IsolationForest(n_jobs=3, random_state=0).fit(X_train) ensemble.set_params(n_jobs=1) y1 = ensemble.predict(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict(X_test) assert_array_almost_equal(y1, y2) ensemble = IsolationForest(n_jobs=1, random_state=0).fit(X_train) y3 = ensemble.predict(X_test) assert_array_almost_equal(y1, y3) def test_iforest_performance(): """Test Isolation Forest performs well""" # Generate train/test data rng = check_random_state(2) X = 0.3 * rng.randn(120, 2) X_train = np.r_[X + 2, X - 2] X_train = X[:100] # Generate some abnormal novel observations X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)) X_test = np.r_[X[100:], X_outliers] y_test = np.array([0] * 20 + [1] * 20) # fit the model clf = IsolationForest(max_samples=100, random_state=rng).fit(X_train) # predict scores (the lower, the more normal) y_pred = - clf.decision_function(X_test) # check that there is at most 6 errors (false positive or false negative) assert roc_auc_score(y_test, y_pred) > 0.98 @pytest.mark.parametrize("contamination", [0.25, "auto"]) def test_iforest_works(contamination): # toy sample (the last two samples are outliers) X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [6, 3], [-4, 7]] # Test IsolationForest clf = IsolationForest(random_state=rng, contamination=contamination) clf.fit(X) decision_func = -clf.decision_function(X) pred = clf.predict(X) # assert detect outliers: assert np.min(decision_func[-2:]) > np.max(decision_func[:-2]) assert_array_equal(pred, 6 * [1] + 2 * [-1]) def test_max_samples_consistency(): # Make sure validated max_samples in iforest and BaseBagging are identical X = iris.data clf = IsolationForest().fit(X) assert clf.max_samples_ == clf._max_samples def test_iforest_subsampled_features(): # It tests non-regression for #5732 which failed at predict. rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(diabetes.data[:50], diabetes.target[:50], random_state=rng) clf = IsolationForest(max_features=0.8) clf.fit(X_train, y_train) clf.predict(X_test) def test_iforest_average_path_length(): # It tests non-regression for #8549 which used the wrong formula # for average path length, strictly for the integer case # Updated to check average path length when input is <= 2 (issue #11839) result_one = 2.0 * (np.log(4.0) + np.euler_gamma) - 2.0 * 4.0 / 5.0 result_two = 2.0 * (np.log(998.0) + np.euler_gamma) - 2.0 * 998.0 / 999.0 assert_allclose(_average_path_length([0]), [0.0]) assert_allclose(_average_path_length([1]), [0.0]) assert_allclose(_average_path_length([2]), [1.0]) assert_allclose(_average_path_length([5]), [result_one]) assert_allclose(_average_path_length([999]), [result_two]) assert_allclose( _average_path_length(np.array([1, 2, 5, 999])), [0.0, 1.0, result_one, result_two], ) # _average_path_length is increasing avg_path_length = _average_path_length(np.arange(5)) assert_array_equal(avg_path_length, np.sort(avg_path_length)) def test_score_samples(): X_train = [[1, 1], [1, 2], [2, 1]] clf1 = IsolationForest(contamination=0.1).fit(X_train) clf2 = IsolationForest().fit(X_train) assert_array_equal(clf1.score_samples([[2., 2.]]), clf1.decision_function([[2., 2.]]) + clf1.offset_) assert_array_equal(clf2.score_samples([[2., 2.]]), clf2.decision_function([[2., 2.]]) + clf2.offset_) assert_array_equal(clf1.score_samples([[2., 2.]]), clf2.score_samples([[2., 2.]])) def test_iforest_warm_start(): """Test iterative addition of iTrees to an iForest """ rng = check_random_state(0) X = rng.randn(20, 2) # fit first 10 trees clf = IsolationForest(n_estimators=10, max_samples=20, random_state=rng, warm_start=True) clf.fit(X) # remember the 1st tree tree_1 = clf.estimators_[0] # fit another 10 trees clf.set_params(n_estimators=20) clf.fit(X) # expecting 20 fitted trees and no overwritten trees assert len(clf.estimators_) == 20 assert clf.estimators_[0] is tree_1 # mock get_chunk_n_rows to actually test more than one chunk (here one # chunk = 3 rows: @patch( "sklearn.ensemble._iforest.get_chunk_n_rows", side_effect=Mock(**{"return_value": 3}), ) @pytest.mark.parametrize( "contamination, n_predict_calls", [(0.25, 3), ("auto", 2)] ) def test_iforest_chunks_works1( mocked_get_chunk, contamination, n_predict_calls ): test_iforest_works(contamination) assert mocked_get_chunk.call_count == n_predict_calls # idem with chunk_size = 5 rows @patch( "sklearn.ensemble._iforest.get_chunk_n_rows", side_effect=Mock(**{"return_value": 10}), ) @pytest.mark.parametrize( "contamination, n_predict_calls", [(0.25, 3), ("auto", 2)] ) def test_iforest_chunks_works2( mocked_get_chunk, contamination, n_predict_calls ): test_iforest_works(contamination) assert mocked_get_chunk.call_count == n_predict_calls def test_iforest_with_uniform_data(): """Test whether iforest predicts inliers when using uniform data""" # 2-d array of all 1s X = np.ones((100, 10)) iforest = IsolationForest() iforest.fit(X) rng = np.random.RandomState(0) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(X + 1) == 1) assert all(iforest.predict(X - 1) == 1) # 2-d array where columns contain the same value across rows X = np.repeat(rng.randn(1, 10), 100, 0) iforest = IsolationForest() iforest.fit(X) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(np.ones((100, 10))) == 1) # Single row X = rng.randn(1, 10) iforest = IsolationForest() iforest.fit(X) assert all(iforest.predict(X) == 1) assert all(iforest.predict(rng.randn(100, 10)) == 1) assert all(iforest.predict(np.ones((100, 10))) == 1)
huzq/scikit-learn
sklearn/ensemble/tests/test_iforest.py
sklearn/metrics/cluster/_bicluster.py
# encoding: utf-8 """ Utility functions wrapping the excellent *mock* library. """ from __future__ import absolute_import, print_function import sys if sys.version_info >= (3, 3): from unittest import mock # noqa from unittest.mock import ANY, call, MagicMock # noqa from unittest.mock import ( create_autospec, Mock, mock_open, patch, PropertyMock ) else: import mock # noqa from mock import ANY, call, MagicMock # noqa from mock import create_autospec, Mock, mock_open, patch, PropertyMock def class_mock(request, q_class_name, autospec=True, **kwargs): """ Return a mock patching the class with qualified name *q_class_name*. The mock is autospec'ed based on the patched class unless the optional argument *autospec* is set to False. Any other keyword arguments are passed through to Mock(). Patch is reversed after calling test returns. """ _patch = patch(q_class_name, autospec=autospec, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def cls_attr_mock(request, cls, attr_name, name=None, **kwargs): """ Return a mock for attribute *attr_name* on *cls* where the patch is reversed after pytest uses it. """ name = request.fixturename if name is None else name _patch = patch.object(cls, attr_name, name=name, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def function_mock(request, q_function_name, **kwargs): """ Return a mock patching the function with qualified name *q_function_name*. Patch is reversed after calling test returns. """ _patch = patch(q_function_name, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def initializer_mock(request, cls): """ Return a mock for the __init__ method on *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, '__init__', return_value=None) request.addfinalizer(_patch.stop) return _patch.start() def instance_mock(request, cls, name=None, spec_set=True, **kwargs): """ Return a mock for an instance of *cls* that draws its spec from the class and does not allow new attributes to be set on the instance. If *name* is missing or |None|, the name of the returned |Mock| instance is set to *request.fixturename*. Additional keyword arguments are passed through to the Mock() call that creates the mock. """ name = name if name is not None else request.fixturename return create_autospec( cls, _name=name, spec_set=spec_set, instance=True, **kwargs ) def loose_mock(request, name=None, **kwargs): """ Return a "loose" mock, meaning it has no spec to constrain calls on it. Additional keyword arguments are passed through to Mock(). If called without a name, it is assigned the name of the fixture. """ if name is None: name = request.fixturename return Mock(name=name, **kwargs) def method_mock(request, cls, method_name, **kwargs): """ Return a mock for method *method_name* on *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, method_name, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def open_mock(request, module_name, **kwargs): """ Return a mock for the builtin `open()` method in *module_name*. """ target = '%s.open' % module_name _patch = patch(target, mock_open(), create=True, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def property_mock(request, cls, prop_name, **kwargs): """ Return a mock for property *prop_name* on class *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs) request.addfinalizer(_patch.stop) return _patch.start() def var_mock(request, q_var_name, **kwargs): """ Return a mock patching the variable with qualified name *q_var_name*. Patch is reversed after calling test returns. """ _patch = patch(q_var_name, **kwargs) request.addfinalizer(_patch.stop) return _patch.start()
# encoding: utf-8 """Test suite for pptx.part module.""" from __future__ import absolute_import import pytest from pptx.opc.constants import RELATIONSHIP_TYPE as RT from pptx.opc.oxml import CT_Relationships from pptx.opc.package import Part, _Relationship, RelationshipCollection from pptx.opc.packuri import PackURI from ..unitutil.mock import ( call, class_mock, instance_mock, loose_mock, Mock, patch, PropertyMock ) class Describe_Relationship(object): def it_remembers_construction_values(self): # test data -------------------- rId = 'rId9' reltype = 'reltype' target = Mock(name='target_part') external = False # exercise --------------------- rel = _Relationship(rId, reltype, target, None, external) # verify ----------------------- assert rel.rId == rId assert rel.reltype == reltype assert rel.target_part == target assert rel.is_external == external def it_should_raise_on_target_part_access_on_external_rel(self): rel = _Relationship(None, None, None, None, external=True) with pytest.raises(ValueError): rel.target_part def it_should_have_target_ref_for_external_rel(self): rel = _Relationship(None, None, 'target', None, external=True) assert rel.target_ref == 'target' def it_should_have_relative_ref_for_internal_rel(self): """ Internal relationships (TargetMode == 'Internal' in the XML) should have a relative ref, e.g. '../slideLayouts/slideLayout1.xml', for the target_ref attribute. """ part = Mock(name='part', partname=PackURI('/ppt/media/image1.png')) baseURI = '/ppt/slides' rel = _Relationship(None, None, part, baseURI) # external=False assert rel.target_ref == '../media/image1.png' class DescribeRelationshipCollection(object): def it_also_has_dict_style_get_rel_by_rId(self, rels_with_known_rel): rels, rId, known_rel = rels_with_known_rel assert rels[rId] == known_rel def it_should_raise_on_failed_lookup_by_rId(self, rels): with pytest.raises(KeyError): rels['rId666'] def it_has_a_len(self, rels): assert len(rels) == 0 def it_can_add_a_relationship(self, _Relationship_): baseURI, rId, reltype, target, is_external = ( 'baseURI', 'rId9', 'reltype', 'target', False ) rels = RelationshipCollection(baseURI) rel = rels.add_relationship(reltype, target, rId, is_external) _Relationship_.assert_called_once_with( rId, reltype, target, baseURI, is_external ) assert rels[rId] == rel assert rel == _Relationship_.return_value def it_can_add_a_relationship_if_not_found( self, rels_with_matching_rel_, rels_with_missing_rel_): rels, reltype, part, matching_rel = rels_with_matching_rel_ assert rels.get_or_add(reltype, part) == matching_rel rels, reltype, part, new_rel = rels_with_missing_rel_ assert rels.get_or_add(reltype, part) == new_rel def it_knows_the_next_available_rId(self, rels_with_rId_gap): rels, expected_next_rId = rels_with_rId_gap next_rId = rels._next_rId assert next_rId == expected_next_rId def it_can_find_a_related_part_by_reltype( self, rels_with_target_known_by_reltype): rels, reltype, known_target_part = rels_with_target_known_by_reltype part = rels.part_with_reltype(reltype) assert part is known_target_part def it_can_find_a_related_part_by_rId(self, rels_with_known_target_part): rels, rId, known_target_part = rels_with_known_target_part part = rels.related_parts[rId] assert part is known_target_part def it_raises_KeyError_on_part_with_rId_not_found(self, rels): with pytest.raises(KeyError): rels.related_parts['rId666'] def it_can_compose_rels_xml(self, rels_with_known_rels, rels_elm): rels_with_known_rels.xml rels_elm.assert_has_calls( [ call.add_rel( 'rId1', 'http://rt-hyperlink', 'http://some/link', True ), call.add_rel( 'rId2', 'http://rt-image', '../media/image1.png', False ), call.xml() ], any_order=True ) # def it_raises_on_add_rel_with_duplicate_rId(self, rels, rel): # with pytest.raises(ValueError): # rels.add_rel(rel) # fixtures --------------------------------------------- @pytest.fixture def _Relationship_(self, request): return class_mock(request, 'pptx.opc.package._Relationship') @pytest.fixture def rel(self, _rId, _reltype, _target_part, _baseURI): return _Relationship(_rId, _reltype, _target_part, _baseURI) @pytest.fixture def rels(self, _baseURI): return RelationshipCollection(_baseURI) @pytest.fixture def rels_elm(self, request): """ Return a rels_elm mock that will be returned from CT_Relationships.new() """ # create rels_elm mock with a .xml property rels_elm = Mock(name='rels_elm') xml = PropertyMock(name='xml') type(rels_elm).xml = xml rels_elm.attach_mock(xml, 'xml') rels_elm.reset_mock() # to clear attach_mock call # patch CT_Relationships to return that rels_elm patch_ = patch.object(CT_Relationships, 'new', return_value=rels_elm) patch_.start() request.addfinalizer(patch_.stop) return rels_elm @pytest.fixture def rels_with_known_rel(self, rels, _rId, rel): rels[_rId] = rel return rels, _rId, rel @pytest.fixture def rels_with_known_rels(self): """ Populated RelationshipCollection instance that will exercise the rels.xml property. """ rels = RelationshipCollection('/baseURI') rels.add_relationship( reltype='http://rt-hyperlink', target='http://some/link', rId='rId1', is_external=True ) part = Mock(name='part') part.partname.relative_ref.return_value = '../media/image1.png' rels.add_relationship(reltype='http://rt-image', target=part, rId='rId2') return rels @pytest.fixture def rels_with_known_target_part(self, rels, _rel_with_known_target_part): rel, rId, target_part = _rel_with_known_target_part rels.add_relationship(None, target_part, rId) return rels, rId, target_part @pytest.fixture def rels_with_matching_rel_(self, request, rels): matching_reltype_ = instance_mock( request, str, name='matching_reltype_' ) matching_part_ = instance_mock( request, Part, name='matching_part_' ) matching_rel_ = instance_mock( request, _Relationship, name='matching_rel_', reltype=matching_reltype_, target_part=matching_part_, is_external=False ) rels[1] = matching_rel_ return rels, matching_reltype_, matching_part_, matching_rel_ @pytest.fixture def rels_with_missing_rel_(self, request, rels, _Relationship_): missing_reltype_ = instance_mock( request, str, name='missing_reltype_' ) missing_part_ = instance_mock( request, Part, name='missing_part_' ) new_rel_ = instance_mock( request, _Relationship, name='new_rel_', reltype=missing_reltype_, target_part=missing_part_, is_external=False ) _Relationship_.return_value = new_rel_ return rels, missing_reltype_, missing_part_, new_rel_ @pytest.fixture def rels_with_rId_gap(self, request, rels): rel_with_rId1 = instance_mock( request, _Relationship, name='rel_with_rId1', rId='rId1' ) rel_with_rId3 = instance_mock( request, _Relationship, name='rel_with_rId3', rId='rId3' ) rels['rId1'] = rel_with_rId1 rels['rId3'] = rel_with_rId3 return rels, 'rId2' @pytest.fixture def rels_with_target_known_by_reltype( self, rels, _rel_with_target_known_by_reltype): rel, reltype, target_part = _rel_with_target_known_by_reltype rels[1] = rel return rels, reltype, target_part @pytest.fixture def _baseURI(self): return '/baseURI' @pytest.fixture def _rel_with_known_target_part( self, _rId, _reltype, _target_part, _baseURI): rel = _Relationship(_rId, _reltype, _target_part, _baseURI) return rel, _rId, _target_part @pytest.fixture def _rel_with_target_known_by_reltype( self, _rId, _reltype, _target_part, _baseURI): rel = _Relationship(_rId, _reltype, _target_part, _baseURI) return rel, _reltype, _target_part @pytest.fixture def _reltype(self): return RT.SLIDE @pytest.fixture def _rId(self): return 'rId6' @pytest.fixture def _target_part(self, request): return loose_mock(request)
biggihs/python-pptx
tests/opc/test_rels.py
tests/unitutil/mock.py
"""Config flow to configure the Luftdaten component.""" from collections import OrderedDict from luftdaten import Luftdaten from luftdaten.exceptions import LuftdatenConnectionError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SHOW_ON_MAP, ) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client import homeassistant.helpers.config_validation as cv from .const import CONF_SENSOR_ID, DEFAULT_SCAN_INTERVAL, DOMAIN @callback def configured_sensors(hass): """Return a set of configured Luftdaten sensors.""" return set( entry.data[CONF_SENSOR_ID] for entry in hass.config_entries.async_entries(DOMAIN) ) @callback def duplicate_stations(hass): """Return a set of duplicate configured Luftdaten stations.""" stations = [ int(entry.data[CONF_SENSOR_ID]) for entry in hass.config_entries.async_entries(DOMAIN) ] return {x for x in stations if stations.count(x) > 1} @config_entries.HANDLERS.register(DOMAIN) class LuftDatenFlowHandler(config_entries.ConfigFlow): """Handle a Luftdaten config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @callback def _show_form(self, errors=None): """Show the form to the user.""" data_schema = OrderedDict() data_schema[vol.Required(CONF_SENSOR_ID)] = cv.positive_int data_schema[vol.Optional(CONF_SHOW_ON_MAP, default=False)] = bool return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors or {} ) async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" if not user_input: return self._show_form() sensor_id = user_input[CONF_SENSOR_ID] if sensor_id in configured_sensors(self.hass): return self._show_form({CONF_SENSOR_ID: "sensor_exists"}) session = aiohttp_client.async_get_clientsession(self.hass) luftdaten = Luftdaten(user_input[CONF_SENSOR_ID], self.hass.loop, session) try: await luftdaten.get_data() valid = await luftdaten.validate_sensor() except LuftdatenConnectionError: return self._show_form({CONF_SENSOR_ID: "communication_error"}) if not valid: return self._show_form({CONF_SENSOR_ID: "invalid_sensor"}) available_sensors = [ x for x in luftdaten.values if luftdaten.values[x] is not None ] if available_sensors: user_input.update( {CONF_SENSORS: {CONF_MONITORED_CONDITIONS: available_sensors}} ) scan_interval = user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) user_input.update({CONF_SCAN_INTERVAL: scan_interval.seconds}) return self.async_create_entry(title=str(sensor_id), data=user_input)
"""Define tests for the IQVIA config flow.""" import pytest from homeassistant import data_entry_flow from homeassistant.components.iqvia import CONF_ZIP_CODE, DOMAIN, config_flow from tests.common import MockConfigEntry, MockDependency @pytest.fixture def mock_pyiqvia(): """Mock the pyiqvia library.""" with MockDependency("pyiqvia") as mock_pyiqvia_: yield mock_pyiqvia_ async def test_duplicate_error(hass): """Test that errors are shown when duplicates are added.""" conf = {CONF_ZIP_CODE: "12345"} MockConfigEntry(domain=DOMAIN, data=conf).add_to_hass(hass) flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "identifier_exists"} async def test_invalid_zip_code(hass, mock_pyiqvia): """Test that an invalid ZIP code key throws an error.""" conf = {CONF_ZIP_CODE: "abcde"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "invalid_zip_code"} async def test_show_form(hass): """Test that the form is served with no input.""" flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=None) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" async def test_step_import(hass, mock_pyiqvia): """Test that the import step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_import(import_config=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"} async def test_step_user(hass, mock_pyiqvia): """Test that the user step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"}
qedi-r/home-assistant
tests/components/iqvia/test_config_flow.py
homeassistant/components/luftdaten/config_flow.py
"""Support for Denon AVR receivers using their HTTP interface.""" from collections import namedtuple import logging import denonavr import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice from homeassistant.components.media_player.const import ( MEDIA_TYPE_CHANNEL, MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOUND_MODE, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_TIMEOUT, CONF_ZONE, STATE_OFF, STATE_ON, STATE_PAUSED, STATE_PLAYING, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_SOUND_MODE_RAW = "sound_mode_raw" CONF_INVALID_ZONES_ERR = "Invalid Zone (expected Zone2 or Zone3)" CONF_SHOW_ALL_SOURCES = "show_all_sources" CONF_VALID_ZONES = ["Zone2", "Zone3"] CONF_ZONES = "zones" DEFAULT_SHOW_SOURCES = False DEFAULT_TIMEOUT = 2 KEY_DENON_CACHE = "denonavr_hosts" SUPPORT_DENON = ( SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE | SUPPORT_VOLUME_SET ) SUPPORT_MEDIA_MODES = ( SUPPORT_PLAY_MEDIA | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_VOLUME_SET | SUPPORT_PLAY ) DENON_ZONE_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE): vol.In(CONF_VALID_ZONES, CONF_INVALID_ZONES_ERR), vol.Optional(CONF_NAME): cv.string, } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_SHOW_ALL_SOURCES, default=DEFAULT_SHOW_SOURCES): cv.boolean, vol.Optional(CONF_ZONES): vol.All(cv.ensure_list, [DENON_ZONE_SCHEMA]), vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, } ) NewHost = namedtuple("NewHost", ["host", "name"]) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Denon platform.""" # Initialize list with receivers to be started receivers = [] cache = hass.data.get(KEY_DENON_CACHE) if cache is None: cache = hass.data[KEY_DENON_CACHE] = set() # Get config option for show_all_sources and timeout show_all_sources = config.get(CONF_SHOW_ALL_SOURCES) timeout = config.get(CONF_TIMEOUT) # Get config option for additional zones zones = config.get(CONF_ZONES) if zones is not None: add_zones = {} for entry in zones: add_zones[entry[CONF_ZONE]] = entry.get(CONF_NAME) else: add_zones = None # Start assignment of host and name new_hosts = [] # 1. option: manual setting if config.get(CONF_HOST) is not None: host = config.get(CONF_HOST) name = config.get(CONF_NAME) new_hosts.append(NewHost(host=host, name=name)) # 2. option: discovery using netdisco if discovery_info is not None: host = discovery_info.get("host") name = discovery_info.get("name") new_hosts.append(NewHost(host=host, name=name)) # 3. option: discovery using denonavr library if config.get(CONF_HOST) is None and discovery_info is None: d_receivers = denonavr.discover() # More than one receiver could be discovered by that method for d_receiver in d_receivers: host = d_receiver["host"] name = d_receiver["friendlyName"] new_hosts.append(NewHost(host=host, name=name)) for entry in new_hosts: # Check if host not in cache, append it and save for later # starting if entry.host not in cache: new_device = denonavr.DenonAVR( host=entry.host, name=entry.name, show_all_inputs=show_all_sources, timeout=timeout, add_zones=add_zones, ) for new_zone in new_device.zones.values(): receivers.append(DenonDevice(new_zone)) cache.add(host) _LOGGER.info("Denon receiver at host %s initialized", host) # Add all freshly discovered receivers if receivers: add_entities(receivers) class DenonDevice(MediaPlayerDevice): """Representation of a Denon Media Player Device.""" def __init__(self, receiver): """Initialize the device.""" self._receiver = receiver self._name = self._receiver.name self._muted = self._receiver.muted self._volume = self._receiver.volume self._current_source = self._receiver.input_func self._source_list = self._receiver.input_func_list self._state = self._receiver.state self._power = self._receiver.power self._media_image_url = self._receiver.image_url self._title = self._receiver.title self._artist = self._receiver.artist self._album = self._receiver.album self._band = self._receiver.band self._frequency = self._receiver.frequency self._station = self._receiver.station self._sound_mode_support = self._receiver.support_sound_mode if self._sound_mode_support: self._sound_mode = self._receiver.sound_mode self._sound_mode_raw = self._receiver.sound_mode_raw self._sound_mode_list = self._receiver.sound_mode_list else: self._sound_mode = None self._sound_mode_raw = None self._sound_mode_list = None self._supported_features_base = SUPPORT_DENON self._supported_features_base |= ( self._sound_mode_support and SUPPORT_SELECT_SOUND_MODE ) def update(self): """Get the latest status information from device.""" self._receiver.update() self._name = self._receiver.name self._muted = self._receiver.muted self._volume = self._receiver.volume self._current_source = self._receiver.input_func self._source_list = self._receiver.input_func_list self._state = self._receiver.state self._power = self._receiver.power self._media_image_url = self._receiver.image_url self._title = self._receiver.title self._artist = self._receiver.artist self._album = self._receiver.album self._band = self._receiver.band self._frequency = self._receiver.frequency self._station = self._receiver.station if self._sound_mode_support: self._sound_mode = self._receiver.sound_mode self._sound_mode_raw = self._receiver.sound_mode_raw @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def is_volume_muted(self): """Return boolean if volume is currently muted.""" return self._muted @property def volume_level(self): """Volume level of the media player (0..1).""" # Volume is sent in a format like -50.0. Minimum is -80.0, # maximum is 18.0 return (float(self._volume) + 80) / 100 @property def source(self): """Return the current input source.""" return self._current_source @property def source_list(self): """Return a list of available input sources.""" return self._source_list @property def sound_mode(self): """Return the current matched sound mode.""" return self._sound_mode @property def sound_mode_list(self): """Return a list of available sound modes.""" return self._sound_mode_list @property def supported_features(self): """Flag media player features that are supported.""" if self._current_source in self._receiver.netaudio_func_list: return self._supported_features_base | SUPPORT_MEDIA_MODES return self._supported_features_base @property def media_content_id(self): """Content ID of current playing media.""" return None @property def media_content_type(self): """Content type of current playing media.""" if self._state == STATE_PLAYING or self._state == STATE_PAUSED: return MEDIA_TYPE_MUSIC return MEDIA_TYPE_CHANNEL @property def media_duration(self): """Duration of current playing media in seconds.""" return None @property def media_image_url(self): """Image url of current playing media.""" if self._current_source in self._receiver.playing_func_list: return self._media_image_url return None @property def media_title(self): """Title of current playing media.""" if self._current_source not in self._receiver.playing_func_list: return self._current_source if self._title is not None: return self._title return self._frequency @property def media_artist(self): """Artist of current playing media, music track only.""" if self._artist is not None: return self._artist return self._band @property def media_album_name(self): """Album name of current playing media, music track only.""" if self._album is not None: return self._album return self._station @property def media_album_artist(self): """Album artist of current playing media, music track only.""" return None @property def media_track(self): """Track number of current playing media, music track only.""" return None @property def media_series_title(self): """Title of series of current playing media, TV show only.""" return None @property def media_season(self): """Season of current playing media, TV show only.""" return None @property def media_episode(self): """Episode of current playing media, TV show only.""" return None @property def device_state_attributes(self): """Return device specific state attributes.""" attributes = {} if ( self._sound_mode_raw is not None and self._sound_mode_support and self._power == "ON" ): attributes[ATTR_SOUND_MODE_RAW] = self._sound_mode_raw return attributes def media_play_pause(self): """Simulate play pause media player.""" return self._receiver.toggle_play_pause() def media_previous_track(self): """Send previous track command.""" return self._receiver.previous_track() def media_next_track(self): """Send next track command.""" return self._receiver.next_track() def select_source(self, source): """Select input source.""" return self._receiver.set_input_func(source) def select_sound_mode(self, sound_mode): """Select sound mode.""" return self._receiver.set_sound_mode(sound_mode) def turn_on(self): """Turn on media player.""" if self._receiver.power_on(): self._state = STATE_ON def turn_off(self): """Turn off media player.""" if self._receiver.power_off(): self._state = STATE_OFF def volume_up(self): """Volume up the media player.""" return self._receiver.volume_up() def volume_down(self): """Volume down media player.""" return self._receiver.volume_down() def set_volume_level(self, volume): """Set volume level, range 0..1.""" # Volume has to be sent in a format like -50.0. Minimum is -80.0, # maximum is 18.0 volume_denon = float((volume * 100) - 80) if volume_denon > 18: volume_denon = float(18) try: if self._receiver.set_volume(volume_denon): self._volume = volume_denon except ValueError: pass def mute_volume(self, mute): """Send mute command.""" return self._receiver.mute(mute)
"""Define tests for the IQVIA config flow.""" import pytest from homeassistant import data_entry_flow from homeassistant.components.iqvia import CONF_ZIP_CODE, DOMAIN, config_flow from tests.common import MockConfigEntry, MockDependency @pytest.fixture def mock_pyiqvia(): """Mock the pyiqvia library.""" with MockDependency("pyiqvia") as mock_pyiqvia_: yield mock_pyiqvia_ async def test_duplicate_error(hass): """Test that errors are shown when duplicates are added.""" conf = {CONF_ZIP_CODE: "12345"} MockConfigEntry(domain=DOMAIN, data=conf).add_to_hass(hass) flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "identifier_exists"} async def test_invalid_zip_code(hass, mock_pyiqvia): """Test that an invalid ZIP code key throws an error.""" conf = {CONF_ZIP_CODE: "abcde"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "invalid_zip_code"} async def test_show_form(hass): """Test that the form is served with no input.""" flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=None) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" async def test_step_import(hass, mock_pyiqvia): """Test that the import step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_import(import_config=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"} async def test_step_user(hass, mock_pyiqvia): """Test that the user step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"}
qedi-r/home-assistant
tests/components/iqvia/test_config_flow.py
homeassistant/components/denonavr/media_player.py
"""Provide functionality to interact with Cast devices on the network.""" import asyncio import logging from typing import Optional import pychromecast from pychromecast.socket_client import ( CONNECTION_STATUS_CONNECTED, CONNECTION_STATUS_DISCONNECTED, ) from pychromecast.controllers.multizone import MultizoneManager from pychromecast.controllers.homeassistant import HomeAssistantController import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice from homeassistant.components.media_player.const import ( MEDIA_TYPE_MOVIE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, ) from homeassistant.const import ( CONF_HOST, EVENT_HOMEASSISTANT_STOP, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, ) from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.typing import ConfigType, HomeAssistantType import homeassistant.util.dt as dt_util from homeassistant.util.logging import async_create_catching_coro from .const import ( DOMAIN as CAST_DOMAIN, ADDED_CAST_DEVICES_KEY, SIGNAL_CAST_DISCOVERED, KNOWN_CHROMECAST_INFO_KEY, CAST_MULTIZONE_MANAGER_KEY, DEFAULT_PORT, SIGNAL_CAST_REMOVED, SIGNAL_HASS_CAST_SHOW_VIEW, ) from .helpers import ( ChromecastInfo, CastStatusListener, DynamicGroupCastStatusListener, ChromeCastZeroconf, ) from .discovery import setup_internal_discovery, discover_chromecast _LOGGER = logging.getLogger(__name__) CONF_IGNORE_CEC = "ignore_cec" CAST_SPLASH = "https://home-assistant.io/images/cast/splash.png" SUPPORT_CAST = ( SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_TURN_OFF | SUPPORT_TURN_ON | SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_IGNORE_CEC, default=[]): vol.All(cv.ensure_list, [cv.string]), } ) @callback def _async_create_cast_device(hass: HomeAssistantType, info: ChromecastInfo): """Create a CastDevice Entity from the chromecast object. Returns None if the cast device has already been added. """ _LOGGER.debug("_async_create_cast_device: %s", info) if info.uuid is None: # Found a cast without UUID, we don't store it because we won't be able # to update it anyway. return CastDevice(info) # Found a cast with UUID if info.is_dynamic_group: # This is a dynamic group, do not add it. return None added_casts = hass.data[ADDED_CAST_DEVICES_KEY] if info.uuid in added_casts: # Already added this one, the entity will take care of moved hosts # itself return None # -> New cast device added_casts.add(info.uuid) return CastDevice(info) async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ): """Set up thet Cast platform. Deprecated. """ _LOGGER.warning( "Setting configuration for Cast via platform is deprecated. " "Configure via Cast integration instead." ) await _async_setup_platform(hass, config, async_add_entities, discovery_info) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Cast from a config entry.""" config = hass.data[CAST_DOMAIN].get("media_player", {}) if not isinstance(config, list): config = [config] # no pending task done, _ = await asyncio.wait( [_async_setup_platform(hass, cfg, async_add_entities, None) for cfg in config] ) if any([task.exception() for task in done]): exceptions = [task.exception() for task in done] for exception in exceptions: _LOGGER.debug("Failed to setup chromecast", exc_info=exception) raise PlatformNotReady async def _async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info ): """Set up the cast platform.""" # Import CEC IGNORE attributes pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, []) hass.data.setdefault(ADDED_CAST_DEVICES_KEY, set()) hass.data.setdefault(KNOWN_CHROMECAST_INFO_KEY, set()) info = None if discovery_info is not None: info = ChromecastInfo(host=discovery_info["host"], port=discovery_info["port"]) elif CONF_HOST in config: info = ChromecastInfo(host=config[CONF_HOST], port=DEFAULT_PORT) @callback def async_cast_discovered(discover: ChromecastInfo) -> None: """Handle discovery of a new chromecast.""" if info is not None and info.host_port != discover.host_port: # Not our requested cast device. return cast_device = _async_create_cast_device(hass, discover) if cast_device is not None: async_add_entities([cast_device]) async_dispatcher_connect(hass, SIGNAL_CAST_DISCOVERED, async_cast_discovered) # Re-play the callback for all past chromecasts, store the objects in # a list to avoid concurrent modification resulting in exception. for chromecast in list(hass.data[KNOWN_CHROMECAST_INFO_KEY]): async_cast_discovered(chromecast) if info is None or info.is_audio_group: # If we were a) explicitly told to enable discovery or # b) have an audio group cast device, we need internal discovery. hass.async_add_executor_job(setup_internal_discovery, hass) else: info = await hass.async_add_executor_job(info.fill_out_missing_chromecast_info) if info.friendly_name is None: _LOGGER.debug( "Cannot retrieve detail information for chromecast" " %s, the device may not be online", info, ) hass.async_add_executor_job(discover_chromecast, hass, info) class CastDevice(MediaPlayerDevice): """Representation of a Cast device on the network. This class is the holder of the pychromecast.Chromecast object and its socket client. It therefore handles all reconnects and audio group changing "elected leader" itself. """ def __init__(self, cast_info: ChromecastInfo): """Initialize the cast device.""" self._cast_info = cast_info self.services = None if cast_info.service: self.services = set() self.services.add(cast_info.service) self._chromecast: Optional[pychromecast.Chromecast] = None self.cast_status = None self.media_status = None self.media_status_received = None self._dynamic_group_cast_info: ChromecastInfo = None self._dynamic_group_cast: Optional[pychromecast.Chromecast] = None self.dynamic_group_media_status = None self.dynamic_group_media_status_received = None self.mz_media_status = {} self.mz_media_status_received = {} self.mz_mgr = None self._available = False self._dynamic_group_available = False self._status_listener: Optional[CastStatusListener] = None self._dynamic_group_status_listener: Optional[ DynamicGroupCastStatusListener ] = None self._hass_cast_controller: Optional[HomeAssistantController] = None self._add_remove_handler = None self._del_remove_handler = None self._cast_view_remove_handler = None async def async_added_to_hass(self): """Create chromecast object when added to hass.""" self._add_remove_handler = async_dispatcher_connect( self.hass, SIGNAL_CAST_DISCOVERED, self._async_cast_discovered ) self._del_remove_handler = async_dispatcher_connect( self.hass, SIGNAL_CAST_REMOVED, self._async_cast_removed ) self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_stop) self.hass.async_create_task( async_create_catching_coro(self.async_set_cast_info(self._cast_info)) ) for info in self.hass.data[KNOWN_CHROMECAST_INFO_KEY]: if self._cast_info.same_dynamic_group(info): _LOGGER.debug( "[%s %s (%s:%s)] Found dynamic group: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, info, ) self.hass.async_create_task( async_create_catching_coro(self.async_set_dynamic_group(info)) ) break self._cast_view_remove_handler = async_dispatcher_connect( self.hass, SIGNAL_HASS_CAST_SHOW_VIEW, self._handle_signal_show_view ) async def async_will_remove_from_hass(self) -> None: """Disconnect Chromecast object when removed.""" await self._async_disconnect() if self._cast_info.uuid is not None: # Remove the entity from the added casts so that it can dynamically # be re-added again. self.hass.data[ADDED_CAST_DEVICES_KEY].remove(self._cast_info.uuid) if self._add_remove_handler: self._add_remove_handler() self._add_remove_handler = None if self._del_remove_handler: self._del_remove_handler() self._del_remove_handler = None if self._cast_view_remove_handler: self._cast_view_remove_handler() self._cast_view_remove_handler = None async def async_set_cast_info(self, cast_info): """Set the cast information and set up the chromecast object.""" self._cast_info = cast_info if self.services is not None: if cast_info.service not in self.services: _LOGGER.debug( "[%s %s (%s:%s)] Got new service: %s (%s)", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, cast_info.service, self.services, ) self.services.add(cast_info.service) if self._chromecast is not None: # Only setup the chromecast once, added elements to services # will automatically be picked up. return # pylint: disable=protected-access if self.services is None: _LOGGER.debug( "[%s %s (%s:%s)] Connecting to cast device by host %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, cast_info, ) chromecast = await self.hass.async_add_job( pychromecast._get_chromecast_from_host, ( cast_info.host, cast_info.port, cast_info.uuid, cast_info.model_name, cast_info.friendly_name, ), ) else: _LOGGER.debug( "[%s %s (%s:%s)] Connecting to cast device by service %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, self.services, ) chromecast = await self.hass.async_add_job( pychromecast._get_chromecast_from_service, ( self.services, ChromeCastZeroconf.get_zeroconf(), cast_info.uuid, cast_info.model_name, cast_info.friendly_name, ), ) self._chromecast = chromecast if CAST_MULTIZONE_MANAGER_KEY not in self.hass.data: self.hass.data[CAST_MULTIZONE_MANAGER_KEY] = MultizoneManager() self.mz_mgr = self.hass.data[CAST_MULTIZONE_MANAGER_KEY] self._status_listener = CastStatusListener(self, chromecast, self.mz_mgr) self._available = False self.cast_status = chromecast.status self.media_status = chromecast.media_controller.status self._chromecast.start() self.async_schedule_update_ha_state() async def async_del_cast_info(self, cast_info): """Remove the service.""" self.services.discard(cast_info.service) _LOGGER.debug( "[%s %s (%s:%s)] Remove service: %s (%s)", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, cast_info.service, self.services, ) async def async_set_dynamic_group(self, cast_info): """Set the cast information and set up the chromecast object.""" _LOGGER.debug( "[%s %s (%s:%s)] Connecting to dynamic group by host %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, cast_info, ) await self.async_del_dynamic_group() self._dynamic_group_cast_info = cast_info # pylint: disable=protected-access chromecast = await self.hass.async_add_executor_job( pychromecast._get_chromecast_from_host, ( cast_info.host, cast_info.port, cast_info.uuid, cast_info.model_name, cast_info.friendly_name, ), ) self._dynamic_group_cast = chromecast if CAST_MULTIZONE_MANAGER_KEY not in self.hass.data: self.hass.data[CAST_MULTIZONE_MANAGER_KEY] = MultizoneManager() mz_mgr = self.hass.data[CAST_MULTIZONE_MANAGER_KEY] self._dynamic_group_status_listener = DynamicGroupCastStatusListener( self, chromecast, mz_mgr ) self._dynamic_group_available = False self.dynamic_group_media_status = chromecast.media_controller.status self._dynamic_group_cast.start() self.async_schedule_update_ha_state() async def async_del_dynamic_group(self): """Remove the dynamic group.""" cast_info = self._dynamic_group_cast_info _LOGGER.debug( "[%s %s (%s:%s)] Remove dynamic group: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, cast_info.service if cast_info else None, ) self._dynamic_group_available = False self._dynamic_group_cast_info = None if self._dynamic_group_cast is not None: await self.hass.async_add_executor_job(self._dynamic_group_cast.disconnect) self._dynamic_group_invalidate() self.async_schedule_update_ha_state() async def _async_disconnect(self): """Disconnect Chromecast object if it is set.""" if self._chromecast is None: # Can't disconnect if not connected. return _LOGGER.debug( "[%s %s (%s:%s)] Disconnecting from chromecast socket.", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, ) self._available = False self.async_schedule_update_ha_state() await self.hass.async_add_executor_job(self._chromecast.disconnect) if self._dynamic_group_cast is not None: await self.hass.async_add_executor_job(self._dynamic_group_cast.disconnect) self._invalidate() self.async_schedule_update_ha_state() def _invalidate(self): """Invalidate some attributes.""" self._chromecast = None self.cast_status = None self.media_status = None self.media_status_received = None self.mz_media_status = {} self.mz_media_status_received = {} self.mz_mgr = None self._hass_cast_controller = None if self._status_listener is not None: self._status_listener.invalidate() self._status_listener = None def _dynamic_group_invalidate(self): """Invalidate some attributes.""" self._dynamic_group_cast = None self.dynamic_group_media_status = None self.dynamic_group_media_status_received = None if self._dynamic_group_status_listener is not None: self._dynamic_group_status_listener.invalidate() self._dynamic_group_status_listener = None # ========== Callbacks ========== def new_cast_status(self, cast_status): """Handle updates of the cast status.""" self.cast_status = cast_status self.schedule_update_ha_state() def new_media_status(self, media_status): """Handle updates of the media status.""" self.media_status = media_status self.media_status_received = dt_util.utcnow() self.schedule_update_ha_state() def new_connection_status(self, connection_status): """Handle updates of connection status.""" _LOGGER.debug( "[%s %s (%s:%s)] Received cast device connection status: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, connection_status.status, ) if connection_status.status == CONNECTION_STATUS_DISCONNECTED: self._available = False self._invalidate() self.schedule_update_ha_state() return new_available = connection_status.status == CONNECTION_STATUS_CONNECTED if new_available != self._available: # Connection status callbacks happen often when disconnected. # Only update state when availability changed to put less pressure # on state machine. _LOGGER.debug( "[%s %s (%s:%s)] Cast device availability changed: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, connection_status.status, ) info = self._cast_info if info.friendly_name is None and not info.is_audio_group: # We couldn't find friendly_name when the cast was added, retry self._cast_info = info.fill_out_missing_chromecast_info() self._available = new_available self.schedule_update_ha_state() def new_dynamic_group_media_status(self, media_status): """Handle updates of the media status.""" self.dynamic_group_media_status = media_status self.dynamic_group_media_status_received = dt_util.utcnow() self.schedule_update_ha_state() def new_dynamic_group_connection_status(self, connection_status): """Handle updates of connection status.""" _LOGGER.debug( "[%s %s (%s:%s)] Received dynamic group connection status: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, connection_status.status, ) if connection_status.status == CONNECTION_STATUS_DISCONNECTED: self._dynamic_group_available = False self._dynamic_group_invalidate() self.schedule_update_ha_state() return new_available = connection_status.status == CONNECTION_STATUS_CONNECTED if new_available != self._dynamic_group_available: # Connection status callbacks happen often when disconnected. # Only update state when availability changed to put less pressure # on state machine. _LOGGER.debug( "[%s %s (%s:%s)] Dynamic group availability changed: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, connection_status.status, ) self._dynamic_group_available = new_available self.schedule_update_ha_state() def multizone_new_media_status(self, group_uuid, media_status): """Handle updates of audio group media status.""" _LOGGER.debug( "[%s %s (%s:%s)] Multizone %s media status: %s", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, group_uuid, media_status, ) self.mz_media_status[group_uuid] = media_status self.mz_media_status_received[group_uuid] = dt_util.utcnow() self.schedule_update_ha_state() # ========== Service Calls ========== def _media_controller(self): """ Return media status. First try from our own cast, then dynamic groups and finally groups which our cast is a member in. """ media_status = self.media_status media_controller = self._chromecast.media_controller if ( media_status is None or media_status.player_state == "UNKNOWN" ) and self._dynamic_group_cast is not None: media_status = self.dynamic_group_media_status media_controller = self._dynamic_group_cast.media_controller if media_status is None or media_status.player_state == "UNKNOWN": groups = self.mz_media_status for k, val in groups.items(): if val and val.player_state != "UNKNOWN": media_controller = self.mz_mgr.get_multizone_mediacontroller(k) break return media_controller def turn_on(self): """Turn on the cast device.""" if not self._chromecast.is_idle: # Already turned on return if self._chromecast.app_id is not None: # Quit the previous app before starting splash screen self._chromecast.quit_app() # The only way we can turn the Chromecast is on is by launching an app self._chromecast.play_media(CAST_SPLASH, pychromecast.STREAM_TYPE_BUFFERED) def turn_off(self): """Turn off the cast device.""" self._chromecast.quit_app() def mute_volume(self, mute): """Mute the volume.""" self._chromecast.set_volume_muted(mute) def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._chromecast.set_volume(volume) def media_play(self): """Send play command.""" media_controller = self._media_controller() media_controller.play() def media_pause(self): """Send pause command.""" media_controller = self._media_controller() media_controller.pause() def media_stop(self): """Send stop command.""" media_controller = self._media_controller() media_controller.stop() def media_previous_track(self): """Send previous track command.""" media_controller = self._media_controller() media_controller.queue_prev() def media_next_track(self): """Send next track command.""" media_controller = self._media_controller() media_controller.queue_next() def media_seek(self, position): """Seek the media to a specific location.""" media_controller = self._media_controller() media_controller.seek(position) def play_media(self, media_type, media_id, **kwargs): """Play media from a URL.""" # We do not want this to be forwarded to a group / dynamic group self._chromecast.media_controller.play_media(media_id, media_type) # ========== Properties ========== @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the device.""" return self._cast_info.friendly_name @property def device_info(self): """Return information about the device.""" cast_info = self._cast_info if cast_info.model_name == "Google Cast Group": return None return { "name": cast_info.friendly_name, "identifiers": {(CAST_DOMAIN, cast_info.uuid.replace("-", ""))}, "model": cast_info.model_name, "manufacturer": cast_info.manufacturer, } def _media_status(self): """ Return media status. First try from our own cast, then dynamic groups and finally groups which our cast is a member in. """ media_status = self.media_status media_status_received = self.media_status_received if ( media_status is None or media_status.player_state == "UNKNOWN" ) and self._dynamic_group_cast is not None: media_status = self.dynamic_group_media_status media_status_received = self.dynamic_group_media_status_received if media_status is None or media_status.player_state == "UNKNOWN": groups = self.mz_media_status for k, val in groups.items(): if val and val.player_state != "UNKNOWN": media_status = val media_status_received = self.mz_media_status_received[k] break return (media_status, media_status_received) @property def state(self): """Return the state of the player.""" media_status, _ = self._media_status() if media_status is None: return None if media_status.player_is_playing: return STATE_PLAYING if media_status.player_is_paused: return STATE_PAUSED if media_status.player_is_idle: return STATE_IDLE if self._chromecast is not None and self._chromecast.is_idle: return STATE_OFF return None @property def available(self): """Return True if the cast device is connected.""" return self._available @property def volume_level(self): """Volume level of the media player (0..1).""" return self.cast_status.volume_level if self.cast_status else None @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self.cast_status.volume_muted if self.cast_status else None @property def media_content_id(self): """Content ID of current playing media.""" media_status, _ = self._media_status() return media_status.content_id if media_status else None @property def media_content_type(self): """Content type of current playing media.""" media_status, _ = self._media_status() if media_status is None: return None if media_status.media_is_tvshow: return MEDIA_TYPE_TVSHOW if media_status.media_is_movie: return MEDIA_TYPE_MOVIE if media_status.media_is_musictrack: return MEDIA_TYPE_MUSIC return None @property def media_duration(self): """Duration of current playing media in seconds.""" media_status, _ = self._media_status() return media_status.duration if media_status else None @property def media_image_url(self): """Image url of current playing media.""" media_status, _ = self._media_status() if media_status is None: return None images = media_status.images return images[0].url if images and images[0].url else None @property def media_image_remotely_accessible(self) -> bool: """If the image url is remotely accessible.""" return True @property def media_title(self): """Title of current playing media.""" media_status, _ = self._media_status() return media_status.title if media_status else None @property def media_artist(self): """Artist of current playing media (Music track only).""" media_status, _ = self._media_status() return media_status.artist if media_status else None @property def media_album_name(self): """Album of current playing media (Music track only).""" media_status, _ = self._media_status() return media_status.album_name if media_status else None @property def media_album_artist(self): """Album artist of current playing media (Music track only).""" media_status, _ = self._media_status() return media_status.album_artist if media_status else None @property def media_track(self): """Track number of current playing media (Music track only).""" media_status, _ = self._media_status() return media_status.track if media_status else None @property def media_series_title(self): """Return the title of the series of current playing media.""" media_status, _ = self._media_status() return media_status.series_title if media_status else None @property def media_season(self): """Season of current playing media (TV Show only).""" media_status, _ = self._media_status() return media_status.season if media_status else None @property def media_episode(self): """Episode of current playing media (TV Show only).""" media_status, _ = self._media_status() return media_status.episode if media_status else None @property def app_id(self): """Return the ID of the current running app.""" return self._chromecast.app_id if self._chromecast else None @property def app_name(self): """Name of the current running app.""" return self._chromecast.app_display_name if self._chromecast else None @property def supported_features(self): """Flag media player features that are supported.""" support = SUPPORT_CAST media_status, _ = self._media_status() if media_status: if media_status.supports_queue_next: support |= SUPPORT_PREVIOUS_TRACK if media_status.supports_queue_next: support |= SUPPORT_NEXT_TRACK if media_status.supports_seek: support |= SUPPORT_SEEK return support @property def media_position(self): """Position of current playing media in seconds.""" media_status, _ = self._media_status() if media_status is None or not ( media_status.player_is_playing or media_status.player_is_paused or media_status.player_is_idle ): return None return media_status.current_time @property def media_position_updated_at(self): """When was the position of the current playing media valid. Returns value from homeassistant.util.dt.utcnow(). """ _, media_status_recevied = self._media_status() return media_status_recevied @property def unique_id(self) -> Optional[str]: """Return a unique ID.""" return self._cast_info.uuid async def _async_cast_discovered(self, discover: ChromecastInfo): """Handle discovery of new Chromecast.""" if self._cast_info.uuid is None: # We can't handle empty UUIDs return if self._cast_info.same_dynamic_group(discover): _LOGGER.debug("Discovered matching dynamic group: %s", discover) await self.async_set_dynamic_group(discover) return if self._cast_info.uuid != discover.uuid: # Discovered is not our device. return if self.services is None: _LOGGER.warning( "[%s %s (%s:%s)] Received update for manually added Cast", self.entity_id, self._cast_info.friendly_name, self._cast_info.host, self._cast_info.port, ) return _LOGGER.debug("Discovered chromecast with same UUID: %s", discover) await self.async_set_cast_info(discover) async def _async_cast_removed(self, discover: ChromecastInfo): """Handle removal of Chromecast.""" if self._cast_info.uuid is None: # We can't handle empty UUIDs return if ( self._dynamic_group_cast_info is not None and self._dynamic_group_cast_info.uuid == discover.uuid ): _LOGGER.debug("Removed matching dynamic group: %s", discover) await self.async_del_dynamic_group() return if self._cast_info.uuid != discover.uuid: # Removed is not our device. return _LOGGER.debug("Removed chromecast with same UUID: %s", discover) await self.async_del_cast_info(discover) async def _async_stop(self, event): """Disconnect socket on Home Assistant stop.""" await self._async_disconnect() def _handle_signal_show_view( self, controller: HomeAssistantController, entity_id: str, view_path: str ): """Handle a show view signal.""" if entity_id != self.entity_id: return if self._hass_cast_controller is None: self._hass_cast_controller = controller self._chromecast.register_handler(controller) self._hass_cast_controller.show_lovelace_view(view_path)
"""Define tests for the IQVIA config flow.""" import pytest from homeassistant import data_entry_flow from homeassistant.components.iqvia import CONF_ZIP_CODE, DOMAIN, config_flow from tests.common import MockConfigEntry, MockDependency @pytest.fixture def mock_pyiqvia(): """Mock the pyiqvia library.""" with MockDependency("pyiqvia") as mock_pyiqvia_: yield mock_pyiqvia_ async def test_duplicate_error(hass): """Test that errors are shown when duplicates are added.""" conf = {CONF_ZIP_CODE: "12345"} MockConfigEntry(domain=DOMAIN, data=conf).add_to_hass(hass) flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "identifier_exists"} async def test_invalid_zip_code(hass, mock_pyiqvia): """Test that an invalid ZIP code key throws an error.""" conf = {CONF_ZIP_CODE: "abcde"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_ZIP_CODE: "invalid_zip_code"} async def test_show_form(hass): """Test that the form is served with no input.""" flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=None) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" async def test_step_import(hass, mock_pyiqvia): """Test that the import step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_import(import_config=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"} async def test_step_user(hass, mock_pyiqvia): """Test that the user step works.""" conf = {CONF_ZIP_CODE: "12345"} flow = config_flow.IQVIAFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=conf) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "12345" assert result["data"] == {CONF_ZIP_CODE: "12345"}
qedi-r/home-assistant
tests/components/iqvia/test_config_flow.py
homeassistant/components/cast/media_player.py