input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
"""Pushbullet platform for sensor component.""" import logging import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_MONITORED_CONDITIONS from homeassistant.components.sensor import PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "application_name": ["Application name"], "body": ["Body"], "notification_id": ["Notification ID"], "notification_tag": ["Notification tag"], "package_name": ["Package name"], "receiver_email": ["Receiver email"], "sender_email": ["Sender email"], "source_device_iden": ["Sender device ID"], "title": ["Title"], "type": ["Type"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["title", "body"]): vol.All( cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)] ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Pushbullet Sensor platform.""" from pushbullet import PushBullet from pushbullet import InvalidKeyError try: pushbullet = PushBullet(config.get(CONF_API_KEY)) except InvalidKeyError: _LOGGER.error("Wrong API key for Pushbullet supplied") return False pbprovider = PushBulletNotificationProvider(pushbullet) devices = [] for sensor_type in config[CONF_MONITORED_CONDITIONS]: devices.append(PushBulletNotificationSensor(pbprovider, sensor_type)) add_entities(devices) class PushBulletNotificationSensor(Entity): """Representation of a Pushbullet Sensor.""" def __init__(self, pb, element): """Initialize the Pushbullet sensor.""" self.pushbullet = pb self._element = element self._state = None self._state_attributes = None def update(self): """Fetch the latest data from the sensor. This will fetch the 'sensor reading' into self._state but also all attributes into self._state_attributes. """ try: self._state = self.pushbullet.data[self._element] self._state_attributes = self.pushbullet.data except (KeyError, TypeError): pass @property def name(self): """Return the name of the sensor.""" return "{} {}".format("Pushbullet", self._element) @property def state(self): """Return the current state of the sensor.""" return self._state @property def device_state_attributes(self): """Return all known attributes of the sensor.""" return self._state_attributes class PushBulletNotificationProvider: """Provider for an account, leading to one or more sensors.""" def __init__(self, pb): """Start to retrieve pushes from the given Pushbullet instance.""" import threading self.pushbullet = pb self._data = None self.listener = None self.thread = threading.Thread(target=self.retrieve_pushes) self.thread.daemon = True self.thread.start() def on_push(self, data): """Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events. """ if data["type"] == "push": self._data = data["push"] @property def data(self): """Return the current data stored in the provider.""" return self._data def retrieve_pushes(self): """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug("Getting pushes") try: self.listener.run_forever() finally: self.listener.close()
"""Tests for the iOS init file.""" from unittest.mock import patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.setup import async_setup_component from homeassistant.components import ios from tests.common import mock_component, mock_coro @pytest.fixture(autouse=True) def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json", return_value={}): yield @pytest.fixture(autouse=True) def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker") async def test_creating_entry_sets_up_sensor(hass): """Test setting up iOS loads the sensor component.""" with patch( "homeassistant.components.ios.sensor.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: result = await hass.config_entries.flow.async_init( ios.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_ios_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_not_configuring_ios_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
fbradyirl/home-assistant
tests/components/ios/test_init.py
homeassistant/components/pushbullet/sensor.py
"""Sensor support for Wireless Sensor Tags platform.""" import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_MONITORED_CONDITIONS from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import DOMAIN as WIRELESSTAG_DOMAIN, SIGNAL_TAG_UPDATE, WirelessTagBaseSensor _LOGGER = logging.getLogger(__name__) SENSOR_TEMPERATURE = "temperature" SENSOR_HUMIDITY = "humidity" SENSOR_MOISTURE = "moisture" SENSOR_LIGHT = "light" SENSOR_TYPES = [SENSOR_TEMPERATURE, SENSOR_HUMIDITY, SENSOR_MOISTURE, SENSOR_LIGHT] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ) } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the sensor platform.""" platform = hass.data.get(WIRELESSTAG_DOMAIN) sensors = [] tags = platform.tags for tag in tags.values(): for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type in tag.allowed_sensor_types: sensors.append( WirelessTagSensor(platform, tag, sensor_type, hass.config) ) add_entities(sensors, True) class WirelessTagSensor(WirelessTagBaseSensor): """Representation of a Sensor.""" def __init__(self, api, tag, sensor_type, config): """Initialize a WirelessTag sensor.""" super().__init__(api, tag) self._sensor_type = sensor_type self._name = self._tag.name # I want to see entity_id as: # sensor.wirelesstag_bedroom_temperature # and not as sensor.bedroom for temperature and # sensor.bedroom_2 for humidity self._entity_id = "{}.{}_{}_{}".format( "sensor", WIRELESSTAG_DOMAIN, self.underscored_name, self._sensor_type ) async def async_added_to_hass(self): """Register callbacks.""" async_dispatcher_connect( self.hass, SIGNAL_TAG_UPDATE.format(self.tag_id, self.tag_manager_mac), self._update_tag_info_callback, ) @property def entity_id(self): """Overridden version.""" return self._entity_id @property def underscored_name(self): """Provide name savvy to be used in entity_id name of self.""" return self.name.lower().replace(" ", "_") @property def state(self): """Return the state of the sensor.""" return self._state @property def device_class(self): """Return the class of the sensor.""" return self._sensor_type @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._sensor.unit @property def principal_value(self): """Return sensor current value.""" return self._sensor.value @property def _sensor(self): """Return tag sensor entity.""" return self._tag.sensor[self._sensor_type] @callback def _update_tag_info_callback(self, event): """Handle push notification sent by tag manager.""" _LOGGER.debug("Entity to update state: %s event data: %s", self, event.data) new_value = self._sensor.value_from_update_event(event.data) self._state = self.decorate_value(new_value) self.async_schedule_update_ha_state()
"""Tests for the iOS init file.""" from unittest.mock import patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.setup import async_setup_component from homeassistant.components import ios from tests.common import mock_component, mock_coro @pytest.fixture(autouse=True) def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json", return_value={}): yield @pytest.fixture(autouse=True) def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker") async def test_creating_entry_sets_up_sensor(hass): """Test setting up iOS loads the sensor component.""" with patch( "homeassistant.components.ios.sensor.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: result = await hass.config_entries.flow.async_init( ios.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_ios_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_not_configuring_ios_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
fbradyirl/home-assistant
tests/components/ios/test_init.py
homeassistant/components/wirelesstag/sensor.py
"""Volume conversion util functions.""" import logging from numbers import Number from homeassistant.const import ( VOLUME_LITERS, VOLUME_MILLILITERS, VOLUME_GALLONS, VOLUME_FLUID_OUNCE, VOLUME, UNIT_NOT_RECOGNIZED_TEMPLATE, ) _LOGGER = logging.getLogger(__name__) VALID_UNITS = [VOLUME_LITERS, VOLUME_MILLILITERS, VOLUME_GALLONS, VOLUME_FLUID_OUNCE] def __liter_to_gallon(liter: float) -> float: """Convert a volume measurement in Liter to Gallon.""" return liter * 0.2642 def __gallon_to_liter(gallon: float) -> float: """Convert a volume measurement in Gallon to Liter.""" return gallon * 3.785 def convert(volume: float, from_unit: str, to_unit: str) -> float: """Convert a temperature from one unit to another.""" if from_unit not in VALID_UNITS: raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit, VOLUME)) if to_unit not in VALID_UNITS: raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit, VOLUME)) if not isinstance(volume, Number): raise TypeError("{} is not of numeric type".format(volume)) # type ignore: https://github.com/python/mypy/issues/7207 if from_unit == to_unit: # type: ignore return volume result = volume if from_unit == VOLUME_LITERS and to_unit == VOLUME_GALLONS: result = __liter_to_gallon(volume) elif from_unit == VOLUME_GALLONS and to_unit == VOLUME_LITERS: result = __gallon_to_liter(volume) return result
"""Tests for the iOS init file.""" from unittest.mock import patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.setup import async_setup_component from homeassistant.components import ios from tests.common import mock_component, mock_coro @pytest.fixture(autouse=True) def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json", return_value={}): yield @pytest.fixture(autouse=True) def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker") async def test_creating_entry_sets_up_sensor(hass): """Test setting up iOS loads the sensor component.""" with patch( "homeassistant.components.ios.sensor.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: result = await hass.config_entries.flow.async_init( ios.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_ios_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_not_configuring_ios_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
fbradyirl/home-assistant
tests/components/ios/test_init.py
homeassistant/util/volume.py
"""Support to trigger Maker IFTTT recipes.""" import json import logging import requests 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 _LOGGER = logging.getLogger(__name__) EVENT_RECEIVED = "ifttt_webhook_received" ATTR_EVENT = "event" ATTR_TARGET = "target" ATTR_VALUE1 = "value1" ATTR_VALUE2 = "value2" ATTR_VALUE3 = "value3" CONF_KEY = "key" SERVICE_TRIGGER = "trigger" SERVICE_TRIGGER_SCHEMA = vol.Schema( { vol.Required(ATTR_EVENT): cv.string, vol.Optional(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]), vol.Optional(ATTR_VALUE1): cv.string, vol.Optional(ATTR_VALUE2): cv.string, vol.Optional(ATTR_VALUE3): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { vol.Optional(DOMAIN): vol.Schema( {vol.Required(CONF_KEY): vol.Any({cv.string: cv.string}, cv.string)} ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the IFTTT service component.""" if DOMAIN not in config: return True api_keys = config[DOMAIN][CONF_KEY] if isinstance(api_keys, str): api_keys = {"default": api_keys} def trigger_service(call): """Handle IFTTT trigger service calls.""" event = call.data[ATTR_EVENT] targets = call.data.get(ATTR_TARGET, list(api_keys)) value1 = call.data.get(ATTR_VALUE1) value2 = call.data.get(ATTR_VALUE2) value3 = call.data.get(ATTR_VALUE3) target_keys = dict() for target in targets: if target not in api_keys: _LOGGER.error("No IFTTT api key for %s", target) continue target_keys[target] = api_keys[target] try: import pyfttt for target, key in target_keys.items(): res = pyfttt.send_event(key, event, value1, value2, value3) if res.status_code != 200: _LOGGER.error("IFTTT reported error sending event to %s.", target) except requests.exceptions.RequestException: _LOGGER.exception("Error communicating with IFTTT") hass.services.async_register( DOMAIN, SERVICE_TRIGGER, trigger_service, schema=SERVICE_TRIGGER_SCHEMA ) return True async def handle_webhook(hass, webhook_id, request): """Handle webhook callback.""" body = await request.text() try: data = json.loads(body) if body else {} except ValueError: return None if isinstance(data, dict): data["webhook_id"] = webhook_id hass.bus.async_fire(EVENT_RECEIVED, data) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "IFTTT", 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 # pylint: disable=invalid-name async_remove_entry = config_entry_flow.webhook_async_remove_entry
"""Tests for the iOS init file.""" from unittest.mock import patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.setup import async_setup_component from homeassistant.components import ios from tests.common import mock_component, mock_coro @pytest.fixture(autouse=True) def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json", return_value={}): yield @pytest.fixture(autouse=True) def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker") async def test_creating_entry_sets_up_sensor(hass): """Test setting up iOS loads the sensor component.""" with patch( "homeassistant.components.ios.sensor.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: result = await hass.config_entries.flow.async_init( ios.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_ios_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_not_configuring_ios_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
fbradyirl/home-assistant
tests/components/ios/test_init.py
homeassistant/components/ifttt/__init__.py
"""Support for esphome devices.""" import asyncio import logging import math from typing import Any, Callable, Dict, List, Optional from aioesphomeapi import ( APIClient, APIConnectionError, DeviceInfo, EntityInfo, EntityState, HomeassistantServiceCall, UserService, UserServiceArgType, ) import voluptuous as vol from homeassistant import const from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import Event, State, callback from homeassistant.exceptions import TemplateError from homeassistant.helpers import template import homeassistant.helpers.config_validation as cv import homeassistant.helpers.device_registry as dr from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.storage import Store from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, HomeAssistantType # Import config flow so that it's added to the registry from .config_flow import EsphomeFlowHandler # noqa from .entry_data import ( DATA_KEY, DISPATCHER_ON_DEVICE_UPDATE, DISPATCHER_ON_LIST, DISPATCHER_ON_STATE, DISPATCHER_REMOVE_ENTITY, DISPATCHER_UPDATE_ENTITY, RuntimeEntryData, ) DOMAIN = "esphome" _LOGGER = logging.getLogger(__name__) STORAGE_KEY = "esphome.{}" STORAGE_VERSION = 1 # No config schema - only configuration entry CONFIG_SCHEMA = vol.Schema({}, extra=vol.ALLOW_EXTRA) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Stub to allow setting up this component. Configuration through YAML is not supported at this time. """ return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up the esphome component.""" hass.data.setdefault(DATA_KEY, {}) host = entry.data[CONF_HOST] port = entry.data[CONF_PORT] password = entry.data[CONF_PASSWORD] cli = APIClient( hass.loop, host, port, password, client_info="Home Assistant {}".format(const.__version__), ) # Store client in per-config-entry hass.data store = Store( hass, STORAGE_VERSION, STORAGE_KEY.format(entry.entry_id), encoder=JSONEncoder ) entry_data = hass.data[DATA_KEY][entry.entry_id] = RuntimeEntryData( client=cli, entry_id=entry.entry_id, store=store ) async def on_stop(event: Event) -> None: """Cleanup the socket client on HA stop.""" await _cleanup_instance(hass, entry) entry_data.cleanup_callbacks.append( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_stop) ) @callback def async_on_state(state: EntityState) -> None: """Send dispatcher updates when a new state is received.""" entry_data.async_update_state(hass, state) @callback def async_on_service_call(service: HomeassistantServiceCall) -> None: """Call service when user automation in ESPHome config is triggered.""" domain, service_name = service.service.split(".", 1) service_data = service.data if service.data_template: try: data_template = { key: Template(value) for key, value in service.data_template.items() } template.attach(hass, data_template) service_data.update( template.render_complex(data_template, service.variables) ) except TemplateError as ex: _LOGGER.error("Error rendering data template: %s", ex) return if service.is_event: # ESPHome uses servicecall packet for both events and service calls # Ensure the user can only send events of form 'esphome.xyz' if domain != "esphome": _LOGGER.error("Can only generate events under esphome " "domain!") return hass.bus.async_fire(service.service, service_data) else: hass.async_create_task( hass.services.async_call( domain, service_name, service_data, blocking=True ) ) async def send_home_assistant_state( entity_id: str, _, new_state: Optional[State] ) -> None: """Forward Home Assistant states to ESPHome.""" if new_state is None: return await cli.send_home_assistant_state(entity_id, new_state.state) @callback def async_on_state_subscription(entity_id: str) -> None: """Subscribe and forward states for requested entities.""" unsub = async_track_state_change(hass, entity_id, send_home_assistant_state) entry_data.disconnect_callbacks.append(unsub) # Send initial state hass.async_create_task( send_home_assistant_state(entity_id, None, hass.states.get(entity_id)) ) async def on_login() -> None: """Subscribe to states and list entities on successful API login.""" try: entry_data.device_info = await cli.device_info() entry_data.available = True await _async_setup_device_registry(hass, entry, entry_data.device_info) entry_data.async_update_device_state(hass) entity_infos, services = await cli.list_entities_services() await entry_data.async_update_static_infos(hass, entry, entity_infos) await _setup_services(hass, entry_data, services) await cli.subscribe_states(async_on_state) await cli.subscribe_service_calls(async_on_service_call) await cli.subscribe_home_assistant_states(async_on_state_subscription) hass.async_create_task(entry_data.async_save_to_store()) except APIConnectionError as err: _LOGGER.warning("Error getting initial data: %s", err) # Re-connection logic will trigger after this await cli.disconnect() try_connect = await _setup_auto_reconnect_logic(hass, cli, entry, host, on_login) async def complete_setup() -> None: """Complete the config entry setup.""" infos, services = await entry_data.async_load_from_store() await entry_data.async_update_static_infos(hass, entry, infos) await _setup_services(hass, entry_data, services) # Create connection attempt outside of HA's tracked task in order # not to delay startup. hass.loop.create_task(try_connect(is_disconnect=False)) hass.async_create_task(complete_setup()) return True async def _setup_auto_reconnect_logic( hass: HomeAssistantType, cli: APIClient, entry: ConfigEntry, host: str, on_login ): """Set up the re-connect logic for the API client.""" async def try_connect(tries: int = 0, is_disconnect: bool = True) -> None: """Try connecting to the API client. Will retry if not successful.""" if entry.entry_id not in hass.data[DOMAIN]: # When removing/disconnecting manually return data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData for disconnect_cb in data.disconnect_callbacks: disconnect_cb() data.disconnect_callbacks = [] data.available = False data.async_update_device_state(hass) if is_disconnect: # This can happen often depending on WiFi signal strength. # So therefore all these connection warnings are logged # as infos. The "unavailable" logic will still trigger so the # user knows if the device is not connected. _LOGGER.info("Disconnected from ESPHome API for %s", host) if tries != 0: # If not first re-try, wait and print message # Cap wait time at 1 minute. This is because while working on the # device (e.g. soldering stuff), users don't want to have to wait # a long time for their device to show up in HA again (this was # mentioned a lot in early feedback) # # In the future another API will be set up so that the ESP can # notify HA of connectivity directly, but for new we'll use a # really short reconnect interval. tries = min(tries, 10) # prevent OverflowError wait_time = int(round(min(1.8 ** tries, 60.0))) _LOGGER.info("Trying to reconnect in %s seconds", wait_time) await asyncio.sleep(wait_time) try: await cli.connect(on_stop=try_connect, login=True) except APIConnectionError as error: _LOGGER.info("Can't connect to ESPHome API for %s: %s", host, error) # Schedule re-connect in event loop in order not to delay HA # startup. First connect is scheduled in tracked tasks. data.reconnect_task = hass.loop.create_task( try_connect(tries + 1, is_disconnect=False) ) else: _LOGGER.info("Successfully connected to %s", host) hass.async_create_task(on_login()) return try_connect async def _async_setup_device_registry( hass: HomeAssistantType, entry: ConfigEntry, device_info: DeviceInfo ): """Set up device registry feature for a particular config entry.""" sw_version = device_info.esphome_version if device_info.compilation_time: sw_version += " ({})".format(device_info.compilation_time) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, device_info.mac_address)}, name=device_info.name, manufacturer="espressif", model=device_info.model, sw_version=sw_version, ) async def _register_service( hass: HomeAssistantType, entry_data: RuntimeEntryData, service: UserService ): service_name = "{}_{}".format(entry_data.device_info.name, service.name) schema = {} for arg in service.args: schema[vol.Required(arg.name)] = { UserServiceArgType.BOOL: cv.boolean, UserServiceArgType.INT: vol.Coerce(int), UserServiceArgType.FLOAT: vol.Coerce(float), UserServiceArgType.STRING: cv.string, UserServiceArgType.BOOL_ARRAY: [cv.boolean], UserServiceArgType.INT_ARRAY: [vol.Coerce(int)], UserServiceArgType.FLOAT_ARRAY: [vol.Coerce(float)], UserServiceArgType.STRING_ARRAY: [cv.string], }[arg.type_] async def execute_service(call): await entry_data.client.execute_service(service, call.data) hass.services.async_register( DOMAIN, service_name, execute_service, vol.Schema(schema) ) async def _setup_services( hass: HomeAssistantType, entry_data: RuntimeEntryData, services: List[UserService] ): old_services = entry_data.services.copy() to_unregister = [] to_register = [] for service in services: if service.key in old_services: # Already exists matching = old_services.pop(service.key) if matching != service: # Need to re-register to_unregister.append(matching) to_register.append(service) else: # New service to_register.append(service) for service in old_services.values(): to_unregister.append(service) entry_data.services = {serv.key: serv for serv in services} for service in to_unregister: service_name = "{}_{}".format(entry_data.device_info.name, service.name) hass.services.async_remove(DOMAIN, service_name) for service in to_register: await _register_service(hass, entry_data, service) async def _cleanup_instance( hass: HomeAssistantType, entry: ConfigEntry ) -> RuntimeEntryData: """Cleanup the esphome client if it exists.""" data = hass.data[DATA_KEY].pop(entry.entry_id) # type: RuntimeEntryData if data.reconnect_task is not None: data.reconnect_task.cancel() for disconnect_cb in data.disconnect_callbacks: disconnect_cb() for cleanup_callback in data.cleanup_callbacks: cleanup_callback() await data.client.disconnect() return data async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Unload an esphome config entry.""" entry_data = await _cleanup_instance(hass, entry) tasks = [] for platform in entry_data.loaded_platforms: tasks.append(hass.config_entries.async_forward_entry_unload(entry, platform)) if tasks: await asyncio.wait(tasks) return True async def platform_async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities, *, component_key: str, info_type, entity_type, state_type, ) -> None: """Set up an esphome platform. This method is in charge of receiving, distributing and storing info and state updates. """ entry_data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData entry_data.info[component_key] = {} entry_data.state[component_key] = {} @callback def async_list_entities(infos: List[EntityInfo]): """Update entities of this platform when entities are listed.""" old_infos = entry_data.info[component_key] new_infos = {} add_entities = [] for info in infos: if not isinstance(info, info_type): # Filter out infos that don't belong to this platform. continue if info.key in old_infos: # Update existing entity old_infos.pop(info.key) else: # Create new entity entity = entity_type(entry.entry_id, component_key, info.key) add_entities.append(entity) new_infos[info.key] = info # Remove old entities for info in old_infos.values(): entry_data.async_remove_entity(hass, component_key, info.key) entry_data.info[component_key] = new_infos async_add_entities(add_entities) signal = DISPATCHER_ON_LIST.format(entry_id=entry.entry_id) entry_data.cleanup_callbacks.append( async_dispatcher_connect(hass, signal, async_list_entities) ) @callback def async_entity_state(state: EntityState): """Notify the appropriate entity of an updated state.""" if not isinstance(state, state_type): return entry_data.state[component_key][state.key] = state entry_data.async_update_entity(hass, component_key, state.key) signal = DISPATCHER_ON_STATE.format(entry_id=entry.entry_id) entry_data.cleanup_callbacks.append( async_dispatcher_connect(hass, signal, async_entity_state) ) def esphome_state_property(func): """Wrap a state property of an esphome entity. This checks if the state object in the entity is set, and prevents writing NAN values to the Home Assistant state machine. """ @property def _wrapper(self): # pylint: disable=protected-access if self._state is None: return None val = func(self) if isinstance(val, float) and math.isnan(val): # Home Assistant doesn't use NAN values in state machine # (not JSON serializable) return None return val return _wrapper class EsphomeEnumMapper: """Helper class to convert between hass and esphome enum values.""" def __init__(self, func: Callable[[], Dict[int, str]]): """Construct a EsphomeEnumMapper.""" self._func = func def from_esphome(self, value: int) -> str: """Convert from an esphome int representation to a hass string.""" return self._func()[value] def from_hass(self, value: str) -> int: """Convert from a hass string to a esphome int representation.""" inverse = {v: k for k, v in self._func().items()} return inverse[value] def esphome_map_enum(func: Callable[[], Dict[int, str]]): """Map esphome int enum values to hass string constants. This class has to be used as a decorator. This ensures the aioesphomeapi import is only happening at runtime. """ return EsphomeEnumMapper(func) class EsphomeEntity(Entity): """Define a generic esphome entity.""" def __init__(self, entry_id: str, component_key: str, key: int): """Initialize.""" self._entry_id = entry_id self._component_key = component_key self._key = key self._remove_callbacks = [] # type: List[Callable[[], None]] async def async_added_to_hass(self) -> None: """Register callbacks.""" kwargs = { "entry_id": self._entry_id, "component_key": self._component_key, "key": self._key, } self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_UPDATE_ENTITY.format(**kwargs), self._on_update ) ) self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_REMOVE_ENTITY.format(**kwargs), self.async_remove ) ) self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_ON_DEVICE_UPDATE.format(**kwargs), self.async_schedule_update_ha_state, ) ) async def _on_update(self) -> None: """Update the entity state when state or static info changed.""" self.async_schedule_update_ha_state() async def async_will_remove_from_hass(self) -> None: """Unregister callbacks.""" for remove_callback in self._remove_callbacks: remove_callback() self._remove_callbacks = [] @property def _entry_data(self) -> RuntimeEntryData: return self.hass.data[DATA_KEY][self._entry_id] @property def _static_info(self) -> EntityInfo: return self._entry_data.info[self._component_key][self._key] @property def _device_info(self) -> DeviceInfo: return self._entry_data.device_info @property def _client(self) -> APIClient: return self._entry_data.client @property def _state(self) -> Optional[EntityState]: try: return self._entry_data.state[self._component_key][self._key] except KeyError: return None @property def available(self) -> bool: """Return if the entity is available.""" device = self._device_info if device.has_deep_sleep: # During deep sleep the ESP will not be connectable (by design) # For these cases, show it as available return True return self._entry_data.available @property def unique_id(self) -> Optional[str]: """Return a unique id identifying the entity.""" if not self._static_info.unique_id: return None return self._static_info.unique_id @property def device_info(self) -> Dict[str, Any]: """Return device registry information for this entity.""" return { "connections": {(dr.CONNECTION_NETWORK_MAC, self._device_info.mac_address)} } @property def name(self) -> str: """Return the name of the entity.""" return self._static_info.name @property def should_poll(self) -> bool: """Disable polling.""" return False
"""Tests for the iOS init file.""" from unittest.mock import patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.setup import async_setup_component from homeassistant.components import ios from tests.common import mock_component, mock_coro @pytest.fixture(autouse=True) def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json", return_value={}): yield @pytest.fixture(autouse=True) def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker") async def test_creating_entry_sets_up_sensor(hass): """Test setting up iOS loads the sensor component.""" with patch( "homeassistant.components.ios.sensor.async_setup_entry", return_value=mock_coro(True), ) as mock_setup: result = await hass.config_entries.flow.async_init( ios.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_ios_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 async def test_not_configuring_ios_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) ) as mock_setup: await async_setup_component(hass, ios.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
fbradyirl/home-assistant
tests/components/ios/test_init.py
homeassistant/components/esphome/__init__.py
from blaze.expr import symbol import numpy as np from datashape import dshape, isscalar def test_array_dshape(): x = symbol('x', '5 * 3 * float32') assert x.shape == (5, 3) assert x.schema == dshape('float32') assert len(x) == 5 assert x.ndim == 2 def test_element(): x = symbol('x', '5 * 3 * float32') assert isscalar(x[1, 2].dshape) assert x[1, 2].dshape == dshape('float32') assert str(x[1, 2]) == 'x[1, 2]' x = symbol('x', '5 * float32') assert isscalar(x[3].dshape) def test_slice(): x = symbol('x', '5 * 3 * {name: string, amount: float32}') assert x[2:, 0].dshape == dshape('3 * {name: string, amount: float32}') assert x[2:].dshape == x[2:, :].dshape # Make sure that these are hashable hash(x[:2]) hash(x[0, :2]) assert str(x[1]) == 'x[1]' assert str(x[:2]) == 'x[:2]' assert str(x[0, :2]) == 'x[0, :2]' assert str(x[1:4:2, :2]) == 'x[1:4:2, :2]' def test_negative_slice(): x = symbol('x', '10 * 10 * int32') assert x[:5, -3:].shape == (5, 3) def test_None_slice(): x = symbol('x', '10 * 10 * int32') assert x[:5, None, -3:].shape == (5, 1, 3) def test_list_slice(): x = symbol('x', '10 * 10 * int32') assert x[[1, 2, 3], [4, 5]].shape == (3, 2) def test_list_slice_string(): x = symbol('x', '10 * 10 * int32') assert str(x[[1, 2, 3]]) == "x[[1, 2, 3]]" def test_slice_with_boolean_list(): x = symbol('x', '5 * int32') expr = x[[True, False, False, True, False]] assert expr.index == ([0, 3],) def test_slice_with_numpy_array(): x = symbol('x', '2 * int32') assert x[np.array([True, False])].isidentical(x[[True, False]])
from blaze.expr import Add, USub, Not, Gt, Mult, Concat, Interp, Repeat from blaze import symbol from datashape import dshape import pytest x = symbol('x', '5 * 3 * int32') y = symbol('y', '5 * 3 * int32') w = symbol('w', '5 * 3 * float32') z = symbol('z', '5 * 3 * int64') a = symbol('a', 'int32') b = symbol('b', '5 * 3 * bool') cs = symbol('cs', 'string') def test_arithmetic_dshape_on_collections(): assert Add(x, y).shape == x.shape == y.shape def test_arithmetic_broadcasts_to_scalars(): assert Add(x, a).shape == x.shape assert Add(x, 1).shape == x.shape def test_unary_ops_are_elemwise(): assert USub(x).shape == x.shape assert Not(b).shape == b.shape def test_relations_maintain_shape(): assert Gt(x, y).shape == x.shape def test_relations_are_boolean(): assert Gt(x, y).schema == dshape('bool') def test_names(): assert Add(x, 1)._name == x._name assert Add(1, x)._name == x._name assert Mult(Add(1, x), 2)._name == x._name assert Add(y, x)._name != x._name assert Add(y, x)._name != y._name assert Add(x, x)._name == x._name def test_inputs(): assert (x + y)._inputs == (x, y) assert (x + 1)._inputs == (x,) assert (1 + y)._inputs == (y,) def test_printing(): assert str(-x) == '-x' assert str(-(x + y)) == '-(x + y)' assert str(~b) == '~b' assert str(~(b | (x > y))) == '~(b | (x > y))' def test_dir(): i = symbol('i', '10 * int') d = symbol('d', '10 * datetime') assert isinstance(i + 1, Add) # this works with pytest.raises(Exception): # this doesn't d + 1 def test_arith_ops_promote_dtype(): r = w + z assert r.dshape == dshape('5 * 3 * float64') def test_str_arith(): assert isinstance(cs * 1, Repeat) assert isinstance(cs % cs, Interp) assert isinstance(cs % 'a', Interp) with pytest.raises(Exception): cs / 1 with pytest.raises(Exception): cs // 1
xlhtc007/blaze
blaze/expr/tests/test_arithmetic.py
blaze/expr/tests/test_slicing.py
from blaze.partition import * from blaze.expr import shape import numpy as np x = np.arange(24).reshape(4, 6) def eq(a, b): if isinstance(a == b, bool): return a == b if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return (a == b).all() else: return a == b def test_partition_get(): assert eq(partition_get(x, (0, slice(0, None)), chunksize=(1, 6)), x[0, :]) assert eq(partition_get(x, (slice(0, None), 0), chunksize=(4, 1)), x[:, 0]) assert eq(partition_get(x, (slice(2, 4), slice(0, 2)), chunksize=(2, 2)), x[2:4, 0:2]) def test_partition_set(): x = np.arange(24).reshape(4, 6) partition_set(x, (slice(0, 2), slice(0, 2)), np.array([[1, 1], [1, 1]]), chunksize=(2, 2)) assert (x[:2, :2] == 1).all() def test_partition_set_1d(): x = np.arange(24).reshape(4, 6) partition_set(x, (slice(0, 4), 0), np.array([[1], [1], [1], [1]]), chunksize=(4, 1), keepdims=False) assert (x[:4, 0] == 1).all() def test_partitions(): assert list(partitions(x, chunksize=(1, 6))) == \ [(i, slice(0, 6)) for i in range(4)] assert list(partitions(x, chunksize=(4, 1))) == \ [(slice(0, 4), i) for i in range(6)] assert list(partitions(x, chunksize=(2, 3))) == [ (slice(0, 2), slice(0, 3)), (slice(0, 2), slice(3, 6)), (slice(2, 4), slice(0, 3)), (slice(2, 4), slice(3, 6))] def dont_test_partitions_flat(): assert list(partitions(x, chunksize=(2, 3))) == [ (slice(0, 2), slice(0, 3)), (slice(0, 2), slice(3, 6)), (slice(2, 4), slice(0, 3)), (slice(2, 4), slice(3, 6))] def test_uneven_partitions(): x = np.arange(10*12).reshape(10, 12) parts = list(partitions(x, chunksize=(7, 7))) assert len(parts) == 2 * 2 assert parts == [(slice(0, 7), slice(0, 7)), (slice(0, 7), slice(7, 12)), (slice(7, 10), slice(0, 7)), (slice(7, 10), slice(7, 12))] x = np.arange(20*24).reshape(20, 24) parts = list(partitions(x, chunksize=(7, 7))) def test_3d_partitions(): x = np.arange(4*4*6).reshape(4, 4, 6) parts = list(partitions(x, chunksize=(2, 2, 3))) assert len(parts) == 2 * 2 * 2
from blaze.expr import Add, USub, Not, Gt, Mult, Concat, Interp, Repeat from blaze import symbol from datashape import dshape import pytest x = symbol('x', '5 * 3 * int32') y = symbol('y', '5 * 3 * int32') w = symbol('w', '5 * 3 * float32') z = symbol('z', '5 * 3 * int64') a = symbol('a', 'int32') b = symbol('b', '5 * 3 * bool') cs = symbol('cs', 'string') def test_arithmetic_dshape_on_collections(): assert Add(x, y).shape == x.shape == y.shape def test_arithmetic_broadcasts_to_scalars(): assert Add(x, a).shape == x.shape assert Add(x, 1).shape == x.shape def test_unary_ops_are_elemwise(): assert USub(x).shape == x.shape assert Not(b).shape == b.shape def test_relations_maintain_shape(): assert Gt(x, y).shape == x.shape def test_relations_are_boolean(): assert Gt(x, y).schema == dshape('bool') def test_names(): assert Add(x, 1)._name == x._name assert Add(1, x)._name == x._name assert Mult(Add(1, x), 2)._name == x._name assert Add(y, x)._name != x._name assert Add(y, x)._name != y._name assert Add(x, x)._name == x._name def test_inputs(): assert (x + y)._inputs == (x, y) assert (x + 1)._inputs == (x,) assert (1 + y)._inputs == (y,) def test_printing(): assert str(-x) == '-x' assert str(-(x + y)) == '-(x + y)' assert str(~b) == '~b' assert str(~(b | (x > y))) == '~(b | (x > y))' def test_dir(): i = symbol('i', '10 * int') d = symbol('d', '10 * datetime') assert isinstance(i + 1, Add) # this works with pytest.raises(Exception): # this doesn't d + 1 def test_arith_ops_promote_dtype(): r = w + z assert r.dshape == dshape('5 * 3 * float64') def test_str_arith(): assert isinstance(cs * 1, Repeat) assert isinstance(cs % cs, Interp) assert isinstance(cs % 'a', Interp) with pytest.raises(Exception): cs / 1 with pytest.raises(Exception): cs // 1
xlhtc007/blaze
blaze/expr/tests/test_arithmetic.py
blaze/tests/test_partition.py
from __future__ import absolute_import from __future__ import unicode_literals from compose import timeparse def test_milli(): assert timeparse.timeparse('5ms') == 0.005 def test_milli_float(): assert timeparse.timeparse('50.5ms') == 0.0505 def test_second_milli(): assert timeparse.timeparse('200s5ms') == 200.005 def test_second_milli_micro(): assert timeparse.timeparse('200s5ms10us') == 200.00501 def test_second(): assert timeparse.timeparse('200s') == 200 def test_second_as_float(): assert timeparse.timeparse('20.5s') == 20.5 def test_minute(): assert timeparse.timeparse('32m') == 1920 def test_hour_minute(): assert timeparse.timeparse('2h32m') == 9120 def test_minute_as_float(): assert timeparse.timeparse('1.5m') == 90 def test_hour_minute_second(): assert timeparse.timeparse('5h34m56s') == 20096 def test_invalid_with_space(): assert timeparse.timeparse('5h 34m 56s') is None def test_invalid_with_comma(): assert timeparse.timeparse('5h,34m,56s') is None def test_invalid_with_empty_string(): assert timeparse.timeparse('') is None
from __future__ import absolute_import from __future__ import unicode_literals import os import re import shutil import tempfile from distutils.spawn import find_executable from os import path import pytest from docker.errors import APIError from docker.errors import ImageNotFound from six import StringIO from six import text_type from .. import mock from .testcases import docker_client from .testcases import DockerClientTestCase from .testcases import get_links from .testcases import pull_busybox from .testcases import SWARM_SKIP_CONTAINERS_ALL from .testcases import SWARM_SKIP_CPU_SHARES from compose import __version__ from compose.config.types import MountSpec from compose.config.types import SecurityOpt from compose.config.types import VolumeFromSpec from compose.config.types import VolumeSpec from compose.const import IS_WINDOWS_PLATFORM from compose.const import LABEL_CONFIG_HASH from compose.const import LABEL_CONTAINER_NUMBER from compose.const import LABEL_ONE_OFF from compose.const import LABEL_PROJECT from compose.const import LABEL_SERVICE from compose.const import LABEL_VERSION from compose.container import Container from compose.errors import OperationFailedError from compose.parallel import ParallelStreamWriter from compose.project import OneOffFilter from compose.service import ConvergencePlan from compose.service import ConvergenceStrategy from compose.service import NetworkMode from compose.service import PidMode from compose.service import Service from compose.utils import parse_nanoseconds_int from tests.helpers import create_custom_host_file from tests.integration.testcases import is_cluster from tests.integration.testcases import no_cluster from tests.integration.testcases import v2_1_only from tests.integration.testcases import v2_2_only from tests.integration.testcases import v2_3_only from tests.integration.testcases import v2_only from tests.integration.testcases import v3_only def create_and_start_container(service, **override_options): container = service.create_container(**override_options) return service.start_container(container) class ServiceTest(DockerClientTestCase): def test_containers(self): foo = self.create_service('foo') bar = self.create_service('bar') create_and_start_container(foo) assert len(foo.containers()) == 1 assert foo.containers()[0].name == 'composetest_foo_1' assert len(bar.containers()) == 0 create_and_start_container(bar) create_and_start_container(bar) assert len(foo.containers()) == 1 assert len(bar.containers()) == 2 names = [c.name for c in bar.containers()] assert 'composetest_bar_1' in names assert 'composetest_bar_2' in names def test_containers_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert db.containers(stopped=True) == [] assert db.containers(one_off=OneOffFilter.only, stopped=True) == [container] def test_project_is_added_to_container_name(self): service = self.create_service('web') create_and_start_container(service) assert service.containers()[0].name == 'composetest_web_1' def test_create_container_with_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_one_off_when_existing_container_is_running(self): db = self.create_service('db') db.start() container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_unspecified_volume(self): service = self.create_service('db', volumes=[VolumeSpec.parse('/var/db')]) container = service.create_container() service.start_container(container) assert container.get_mount('/var/db') def test_create_container_with_volume_driver(self): service = self.create_service('db', volume_driver='foodriver') container = service.create_container() service.start_container(container) assert 'foodriver' == container.get('HostConfig.VolumeDriver') @pytest.mark.skipif(SWARM_SKIP_CPU_SHARES, reason='Swarm --cpu-shares bug') def test_create_container_with_cpu_shares(self): service = self.create_service('db', cpu_shares=73) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuShares') == 73 def test_create_container_with_cpu_quota(self): service = self.create_service('db', cpu_quota=40000, cpu_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuQuota') == 40000 assert container.get('HostConfig.CpuPeriod') == 150000 @pytest.mark.xfail(raises=OperationFailedError, reason='not supported by kernel') def test_create_container_with_cpu_rt(self): service = self.create_service('db', cpu_rt_runtime=40000, cpu_rt_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuRealtimeRuntime') == 40000 assert container.get('HostConfig.CpuRealtimePeriod') == 150000 @v2_2_only() def test_create_container_with_cpu_count(self): self.require_api_version('1.25') service = self.create_service('db', cpu_count=2) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuCount') == 2 @v2_2_only() @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='cpu_percent is not supported for Linux') def test_create_container_with_cpu_percent(self): self.require_api_version('1.25') service = self.create_service('db', cpu_percent=12) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuPercent') == 12 @v2_2_only() def test_create_container_with_cpus(self): self.require_api_version('1.25') service = self.create_service('db', cpus=1) container = service.create_container() service.start_container(container) assert container.get('HostConfig.NanoCpus') == 1000000000 def test_create_container_with_shm_size(self): self.require_api_version('1.22') service = self.create_service('db', shm_size=67108864) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ShmSize') == 67108864 def test_create_container_with_init_bool(self): self.require_api_version('1.25') service = self.create_service('db', init=True) container = service.create_container() service.start_container(container) assert container.get('HostConfig.Init') is True @pytest.mark.xfail(True, reason='Option has been removed in Engine 17.06.0') def test_create_container_with_init_path(self): self.require_api_version('1.25') docker_init_path = find_executable('docker-init') service = self.create_service('db', init=docker_init_path) container = service.create_container() service.start_container(container) assert container.get('HostConfig.InitPath') == docker_init_path @pytest.mark.xfail(True, reason='Some kernels/configs do not support pids_limit') def test_create_container_with_pids_limit(self): self.require_api_version('1.23') service = self.create_service('db', pids_limit=10) container = service.create_container() service.start_container(container) assert container.get('HostConfig.PidsLimit') == 10 def test_create_container_with_extra_hosts_list(self): extra_hosts = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts) def test_create_container_with_extra_hosts_dicts(self): extra_hosts = {'somehost': '162.242.195.82', 'otherhost': '50.31.209.229'} extra_hosts_list = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts_list) def test_create_container_with_cpu_set(self): service = self.create_service('db', cpuset='0') container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpusetCpus') == '0' def test_create_container_with_read_only_root_fs(self): read_only = True service = self.create_service('db', read_only=read_only) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ReadonlyRootfs') == read_only def test_create_container_with_blkio_config(self): blkio_config = { 'weight': 300, 'weight_device': [{'path': '/dev/sda', 'weight': 200}], 'device_read_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024 * 100}], 'device_read_iops': [{'path': '/dev/sda', 'rate': 1000}], 'device_write_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024}], 'device_write_iops': [{'path': '/dev/sda', 'rate': 800}] } service = self.create_service('web', blkio_config=blkio_config) container = service.create_container() assert container.get('HostConfig.BlkioWeight') == 300 assert container.get('HostConfig.BlkioWeightDevice') == [{ 'Path': '/dev/sda', 'Weight': 200 }] assert container.get('HostConfig.BlkioDeviceReadBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 * 100 }] assert container.get('HostConfig.BlkioDeviceWriteBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 }] assert container.get('HostConfig.BlkioDeviceReadIOps') == [{ 'Path': '/dev/sda', 'Rate': 1000 }] assert container.get('HostConfig.BlkioDeviceWriteIOps') == [{ 'Path': '/dev/sda', 'Rate': 800 }] def test_create_container_with_security_opt(self): security_opt = [SecurityOpt.parse('label:disable')] service = self.create_service('db', security_opt=security_opt) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.SecurityOpt')) == set([o.repr() for o in security_opt]) @pytest.mark.xfail(True, reason='Not supported on most drivers') def test_create_container_with_storage_opt(self): storage_opt = {'size': '1G'} service = self.create_service('db', storage_opt=storage_opt) container = service.create_container() service.start_container(container) assert container.get('HostConfig.StorageOpt') == storage_opt def test_create_container_with_oom_kill_disable(self): self.require_api_version('1.20') service = self.create_service('db', oom_kill_disable=True) container = service.create_container() assert container.get('HostConfig.OomKillDisable') is True def test_create_container_with_mac_address(self): service = self.create_service('db', mac_address='02:42:ac:11:65:43') container = service.create_container() service.start_container(container) assert container.inspect()['Config']['MacAddress'] == '02:42:ac:11:65:43' def test_create_container_with_device_cgroup_rules(self): service = self.create_service('db', device_cgroup_rules=['c 7:128 rwm']) container = service.create_container() assert container.get('HostConfig.DeviceCgroupRules') == ['c 7:128 rwm'] def test_create_container_with_specified_volume(self): host_path = '/tmp/host-path' container_path = '/container-path' service = self.create_service( 'db', volumes=[VolumeSpec(host_path, container_path, 'rw')]) container = service.create_container() service.start_container(container) assert container.get_mount(container_path) # Match the last component ("host-path"), because boot2docker symlinks /tmp actual_host_path = container.get_mount(container_path)['Source'] assert path.basename(actual_host_path) == path.basename(host_path), ( "Last component differs: %s, %s" % (actual_host_path, host_path) ) @v2_3_only() def test_create_container_with_host_mount(self): host_path = '/tmp/host-path' container_path = '/container-path' create_custom_host_file(self.client, path.join(host_path, 'a.txt'), 'test') service = self.create_service( 'db', volumes=[ MountSpec(type='bind', source=host_path, target=container_path, read_only=True) ] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert path.basename(mount['Source']) == path.basename(host_path) assert mount['RW'] is False @v2_3_only() def test_create_container_with_tmpfs_mount(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Type'] == 'tmpfs' @v2_3_only() def test_create_container_with_tmpfs_mount_tmpfs_size(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path, tmpfs={'size': 5368709})] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount print(container.dictionary) assert mount['Type'] == 'tmpfs' assert container.get('HostConfig.Mounts')[0]['TmpfsOptions'] == { 'SizeBytes': 5368709 } @v2_3_only() def test_create_container_with_volume_mount(self): container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = self.create_service( 'db', volumes=[MountSpec(type='volume', source=volume_name, target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_mount(self): # Ensure mounts are converted to volumes if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = Service('db', client=client, volumes=[ MountSpec(type='volume', source=volume_name, target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_tmpfs_mount(self): # Ensure tmpfs mounts are converted to tmpfs entries if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-tmpfs' service = Service('db', client=client, volumes=[ MountSpec(type='tmpfs', target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount is None assert container_path in container.get('HostConfig.Tmpfs') def test_create_container_with_healthcheck_config(self): one_second = parse_nanoseconds_int('1s') healthcheck = { 'test': ['true'], 'interval': 2 * one_second, 'timeout': 5 * one_second, 'retries': 5, 'start_period': 2 * one_second } service = self.create_service('db', healthcheck=healthcheck) container = service.create_container() remote_healthcheck = container.get('Config.Healthcheck') assert remote_healthcheck['Test'] == healthcheck['test'] assert remote_healthcheck['Interval'] == healthcheck['interval'] assert remote_healthcheck['Timeout'] == healthcheck['timeout'] assert remote_healthcheck['Retries'] == healthcheck['retries'] assert remote_healthcheck['StartPeriod'] == healthcheck['start_period'] def test_recreate_preserves_volume_with_trailing_slash(self): """When the Compose file specifies a trailing slash in the container path, make sure we copy the volume over when recreating. """ service = self.create_service('data', volumes=[VolumeSpec.parse('/data/')]) old_container = create_and_start_container(service) volume_path = old_container.get_mount('/data')['Source'] new_container = service.recreate_container(old_container) assert new_container.get_mount('/data')['Source'] == volume_path def test_duplicate_volume_trailing_slash(self): """ When an image specifies a volume, and the Compose file specifies a host path but adds a trailing slash, make sure that we don't create duplicate binds. """ host_path = '/tmp/data' container_path = '/data' volumes = [VolumeSpec.parse('{}:{}/'.format(host_path, container_path))] tmp_container = self.client.create_container( 'busybox', 'true', volumes={container_path: {}}, labels={'com.docker.compose.test_image': 'true'}, host_config={} ) image = self.client.commit(tmp_container)['Id'] service = self.create_service('db', image=image, volumes=volumes) old_container = create_and_start_container(service) assert old_container.get('Config.Volumes') == {container_path: {}} service = self.create_service('db', image=image, volumes=volumes) new_container = service.recreate_container(old_container) assert new_container.get('Config.Volumes') == {container_path: {}} assert service.containers(stopped=False) == [new_container] def test_create_container_with_volumes_from(self): volume_service = self.create_service('data') volume_container_1 = volume_service.create_container() volume_container_2 = Container.create( self.client, image='busybox:latest', command=["top"], labels={LABEL_PROJECT: 'composetest'}, host_config={}, environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_service = self.create_service( 'host', volumes_from=[ VolumeFromSpec(volume_service, 'rw', 'service'), VolumeFromSpec(volume_container_2, 'rw', 'container') ], environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_container = host_service.create_container() host_service.start_container(host_container) assert volume_container_1.id + ':rw' in host_container.get('HostConfig.VolumesFrom') assert volume_container_2.id + ':rw' in host_container.get('HostConfig.VolumesFrom') def test_execute_convergence_plan_recreate(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1'] ) old_container = service.create_container() assert old_container.get('Config.Entrypoint') == ['top'] assert old_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=1' in old_container.get('Config.Env') assert old_container.name == 'composetest_db_1' service.start_container(old_container) old_container.inspect() # reload volume data volume_path = old_container.get_mount('/etc')['Source'] num_containers_before = len(self.client.containers(all=True)) service.options['environment']['FOO'] = '2' new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert new_container.get('Config.Entrypoint') == ['top'] assert new_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=2' in new_container.get('Config.Env') assert new_container.name == 'composetest_db_1' assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ( 'affinity:container==%s' % old_container.id in new_container.get('Config.Env') ) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert old_container.get('Node.Name') == new_container.get('Node.Name') assert len(self.client.containers(all=True)) == num_containers_before assert old_container.id != new_container.id with pytest.raises(APIError): self.client.inspect_container(old_container.id) def test_execute_convergence_plan_recreate_change_mount_target(self): service = self.create_service( 'db', volumes=[MountSpec(target='/app1', type='volume')], entrypoint=['top'], command=['-d', '1'] ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/app1'] ) service.options['volumes'] = [MountSpec(target='/app2', type='volume')] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/app2'] ) def test_execute_convergence_plan_recreate_twice(self): service = self.create_service( 'db', volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1']) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container])) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container @v2_3_only() def test_execute_convergence_plan_recreate_twice_with_mount(self): service = self.create_service( 'db', volumes=[MountSpec(target='/etc', type='volume')], entrypoint=['top'], command=['-d', '1'] ) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container]) ) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container def test_execute_convergence_plan_when_containers_are_stopped(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/var/db')], entrypoint=['top'], command=['-d', '1'] ) service.create_container() containers = service.containers(stopped=True) assert len(containers) == 1 container, = containers assert not container.is_running service.execute_convergence_plan(ConvergencePlan('start', [container])) containers = service.containers() assert len(containers) == 1 container.inspect() assert container == containers[0] assert container.is_running def test_execute_convergence_plan_with_image_declared_volume(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_with_image_declared_volume_renew(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_when_image_volume_masks_config(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] service.options['volumes'] = [VolumeSpec.parse('/tmp:/data')] with mock.patch('compose.service.log') as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) mock_log.warn.assert_called_once_with(mock.ANY) _, args, kwargs = mock_log.warn.mock_calls[0] assert "Service \"db\" is using volume \"/data\" from the previous container" in args[0] assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_when_host_volume_is_removed(self): host_path = '/tmp/host-path' service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, volumes=[VolumeSpec(host_path, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) service.options['volumes'] = [] with mock.patch('compose.service.log', autospec=True) as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert not mock_log.warn.called assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != host_path def test_execute_convergence_plan_anonymous_volume_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_anonymous_volume_recreate_then_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] mid_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), ) assert ( [mount['Destination'] for mount in mid_container.get('Mounts')] == ['/data'] ) assert mid_container.get_mount('/data')['Source'] == volume_path new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [mid_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_without_start(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) containers = service.execute_convergence_plan(ConvergencePlan('create', []), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running containers = service.execute_convergence_plan( ConvergencePlan('recreate', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running service.execute_convergence_plan(ConvergencePlan('start', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running def test_execute_convergence_plan_image_with_volume_is_removed(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] old_container.stop() self.client.remove_image(service.image(), force=True) service.ensure_image_exists() with pytest.raises(ImageNotFound): service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) old_container.inspect() # retrieve new name from server new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), reset_container_image=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_start_container_passes_through_options(self): db = self.create_service('db') create_and_start_container(db, environment={'FOO': 'BAR'}) assert db.containers()[0].environment['FOO'] == 'BAR' def test_start_container_inherits_options_from_constructor(self): db = self.create_service('db', environment={'FOO': 'BAR'}) create_and_start_container(db) assert db.containers()[0].environment['FOO'] == 'BAR' @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links(self): db = self.create_service('db') web = self.create_service('web', links=[(db, None)]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links_with_names(self): db = self.create_service('db') web = self.create_service('web', links=[(db, 'custom_link_name')]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'custom_link_name' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_with_external_links(self): db = self.create_service('db') web = self.create_service('web', external_links=['composetest_db_1', 'composetest_db_2', 'composetest_db_3:db_3']) for _ in range(3): create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'composetest_db_2', 'db_3' ]) @no_cluster('No legacy links support in Swarm') def test_start_normal_container_does_not_create_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db) assert set(get_links(c)) == set([]) @no_cluster('No legacy links support in Swarm') def test_start_one_off_container_creates_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db, one_off=OneOffFilter.only) assert set(get_links(c)) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) def test_start_container_builds_images(self): service = Service( name='test', client=self.client, build={'context': 'tests/fixtures/simple-dockerfile'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() assert len(self.client.images(name='composetest_test')) >= 1 def test_start_container_uses_tagged_image_if_it_exists(self): self.check_build('tests/fixtures/simple-dockerfile', tag='composetest_test') service = Service( name='test', client=self.client, build={'context': 'this/does/not/exist/and/will/throw/error'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() def test_start_container_creates_ports(self): service = self.create_service('web', ports=[8000]) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/tcp'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] != '8000' def test_build(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('web', build={'context': base_dir}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_non_ascii_filename(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") with open(os.path.join(base_dir.encode('utf8'), b'foo\xE2bar'), 'w') as f: f.write("hello world\n") service = self.create_service('web', build={'context': text_type(base_dir)}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_with_image_name(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") image_name = 'examples/composetest:latest' self.addCleanup(self.client.remove_image, image_name) self.create_service('web', build={'context': base_dir}, image=image_name).build() assert self.client.inspect_image(image_name) def test_build_with_git_url(self): build_url = "https://github.com/dnephin/docker-build-from-url.git" service = self.create_service('buildwithurl', build={'context': build_url}) self.addCleanup(self.client.remove_image, service.image_name) service.build() assert service.image() def test_build_with_build_args(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=1" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_args_override(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build(build_args_override={'build_version': '2'}) self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=2" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_labels(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('buildlabels', build={ 'context': text_type(base_dir), 'labels': {'com.docker.compose.test': 'true'} }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test'] == 'true' @no_cluster('Container networks not on Swarm') def test_build_with_network(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') f.write('RUN ping -c1 google.local\n') net_container = self.client.create_container( 'busybox', 'top', host_config=self.client.create_host_config( extra_hosts={'google.local': '127.0.0.1'} ), name='composetest_build_network' ) self.addCleanup(self.client.remove_container, net_container, force=True) self.client.start(net_container) service = self.create_service('buildwithnet', build={ 'context': text_type(base_dir), 'network': 'container:{}'.format(net_container['Id']) }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @v2_3_only() @no_cluster('Not supported on UCP 2.2.0-beta1') # FIXME: remove once support is added def test_build_with_target(self): self.require_api_version('1.30') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox as one\n') f.write('LABEL com.docker.compose.test=true\n') f.write('LABEL com.docker.compose.test.target=one\n') f.write('FROM busybox as two\n') f.write('LABEL com.docker.compose.test.target=two\n') service = self.create_service('buildtarget', build={ 'context': text_type(base_dir), 'target': 'one' }) service.build() assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test.target'] == 'one' @v2_3_only() def test_build_with_extra_hosts(self): self.require_api_version('1.27') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'RUN ping -c1 foobar', 'RUN ping -c1 baz', ])) service = self.create_service('build_extra_hosts', build={ 'context': text_type(base_dir), 'extra_hosts': { 'foobar': '127.0.0.1', 'baz': '127.0.0.1' } }) service.build() assert service.image() def test_build_with_gzip(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'COPY . /src', 'RUN cat /src/hello.txt' ])) with open(os.path.join(base_dir, 'hello.txt'), 'w') as f: f.write('hello world\n') service = self.create_service('build_gzip', build={ 'context': text_type(base_dir), }) service.build(gzip=True) assert service.image() @v2_1_only() def test_build_with_isolation(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('build_isolation', build={ 'context': text_type(base_dir), 'isolation': 'default', }) service.build() assert service.image() def test_start_container_stays_unprivileged(self): service = self.create_service('web') container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is False def test_start_container_becomes_privileged(self): service = self.create_service('web', privileged=True) container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is True def test_expose_does_not_publish_ports(self): service = self.create_service('web', expose=["8000"]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports'] == {'8000/tcp': None} def test_start_container_creates_port_with_explicit_protocol(self): service = self.create_service('web', ports=['8000/udp']) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/udp'] def test_start_container_creates_fixed_external_ports(self): service = self.create_service('web', ports=['8000:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8000' def test_start_container_creates_fixed_external_ports_when_it_is_different_to_internal_port(self): service = self.create_service('web', ports=['8001:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8001' def test_port_with_explicit_interface(self): service = self.create_service('web', ports=[ '127.0.0.1:8001:8000', '0.0.0.0:9001:9000/udp', ]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports']['8000/tcp'] == [{ 'HostIp': '127.0.0.1', 'HostPort': '8001', }] assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostPort'] == '9001' if not is_cluster(self.client): assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostIp'] == '0.0.0.0' # self.assertEqual(container['NetworkSettings']['Ports'], { # '8000/tcp': [ # { # 'HostIp': '127.0.0.1', # 'HostPort': '8001', # }, # ], # '9000/udp': [ # { # 'HostIp': '0.0.0.0', # 'HostPort': '9001', # }, # ], # }) def test_create_with_image_id(self): # Get image id for the current busybox:latest pull_busybox(self.client) image_id = self.client.inspect_image('busybox:latest')['Id'][:12] service = self.create_service('foo', image=image_id) service.create_container() def test_scale(self): service = self.create_service('web') service.scale(1) assert len(service.containers()) == 1 # Ensure containers don't have stdout or stdin connected container = service.containers()[0] config = container.inspect()['Config'] assert not config['AttachStderr'] assert not config['AttachStdout'] assert not config['AttachStdin'] service.scale(3) assert len(service.containers()) == 3 service.scale(1) assert len(service.containers()) == 1 service.scale(0) assert len(service.containers()) == 0 @pytest.mark.skipif( SWARM_SKIP_CONTAINERS_ALL, reason='Swarm /containers/json bug' ) def test_scale_with_stopped_containers(self): """ Given there are some stopped containers and scale is called with a desired number that is the same as the number of stopped containers, test that those containers are restarted and not removed/recreated. """ service = self.create_service('web') next_number = service._next_container_number() valid_numbers = [next_number, next_number + 1] service.create_container(number=next_number) service.create_container(number=next_number + 1) ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) for container in service.containers(): assert container.is_running assert container.number in valid_numbers captured_output = mock_stderr.getvalue() assert 'Creating' not in captured_output assert 'Starting' in captured_output def test_scale_with_stopped_containers_and_needing_creation(self): """ Given there are some stopped containers and scale is called with a desired number that is greater than the number of stopped containers, test that those containers are restarted and required number are created. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) for container in service.containers(): assert not container.is_running ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) assert len(service.containers()) == 2 for container in service.containers(): assert container.is_running captured_output = mock_stderr.getvalue() assert 'Creating' in captured_output assert 'Starting' in captured_output def test_scale_with_api_error(self): """Test that when scaling if the API returns an error, that error is handled and the remaining threads continue. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=APIError( message="testing", response={}, explanation="Boom")): with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: with pytest.raises(OperationFailedError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running assert ( "ERROR: for composetest_web_2 Cannot create container for service" " web: Boom" in mock_stderr.getvalue() ) def test_scale_with_unexpected_exception(self): """Test that when scaling if the API returns an error, that is not of type APIError, that error is re-raised. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=ValueError("BOOM") ): with pytest.raises(ValueError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running @mock.patch('compose.service.log') def test_scale_with_desired_number_already_achieved(self, mock_log): """ Test that calling scale with a desired number that is equal to the number of containers already running results in no change. """ service = self.create_service('web') next_number = service._next_container_number() container = service.create_container(number=next_number, quiet=True) container.start() container.inspect() assert container.is_running assert len(service.containers()) == 1 service.scale(1) assert len(service.containers()) == 1 container.inspect() assert container.is_running captured_output = mock_log.info.call_args[0] assert 'Desired container number already achieved' in captured_output @mock.patch('compose.service.log') def test_scale_with_custom_container_name_outputs_warning(self, mock_log): """Test that calling scale on a service that has a custom container name results in warning output. """ service = self.create_service('app', container_name='custom-container') assert service.custom_container_name == 'custom-container' with pytest.raises(OperationFailedError): service.scale(3) captured_output = mock_log.warn.call_args[0][0] assert len(service.containers()) == 1 assert "Remove the custom name to scale the service." in captured_output def test_scale_sets_ports(self): service = self.create_service('web', ports=['8000']) service.scale(2) containers = service.containers() assert len(containers) == 2 for container in containers: assert list(container.get('HostConfig.PortBindings')) == ['8000/tcp'] def test_scale_with_immediate_exit(self): service = self.create_service('web', image='busybox', command='true') service.scale(2) assert len(service.containers(stopped=True)) == 2 def test_network_mode_none(self): service = self.create_service('web', network_mode=NetworkMode('none')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'none' def test_network_mode_bridged(self): service = self.create_service('web', network_mode=NetworkMode('bridge')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'bridge' def test_network_mode_host(self): service = self.create_service('web', network_mode=NetworkMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'host' def test_pid_mode_none_defined(self): service = self.create_service('web', pid_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == '' def test_pid_mode_host(self): service = self.create_service('web', pid_mode=PidMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == 'host' @v2_1_only() def test_userns_mode_none_defined(self): service = self.create_service('web', userns_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == '' @v2_1_only() def test_userns_mode_host(self): service = self.create_service('web', userns_mode='host') container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == 'host' def test_dns_no_value(self): service = self.create_service('web') container = create_and_start_container(service) assert container.get('HostConfig.Dns') is None def test_dns_list(self): service = self.create_service('web', dns=['8.8.8.8', '9.9.9.9']) container = create_and_start_container(service) assert container.get('HostConfig.Dns') == ['8.8.8.8', '9.9.9.9'] def test_mem_swappiness(self): service = self.create_service('web', mem_swappiness=11) container = create_and_start_container(service) assert container.get('HostConfig.MemorySwappiness') == 11 def test_mem_reservation(self): service = self.create_service('web', mem_reservation='20m') container = create_and_start_container(service) assert container.get('HostConfig.MemoryReservation') == 20 * 1024 * 1024 def test_restart_always_value(self): service = self.create_service('web', restart={'Name': 'always'}) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'always' def test_oom_score_adj_value(self): service = self.create_service('web', oom_score_adj=500) container = create_and_start_container(service) assert container.get('HostConfig.OomScoreAdj') == 500 def test_group_add_value(self): service = self.create_service('web', group_add=["root", "1"]) container = create_and_start_container(service) host_container_groupadd = container.get('HostConfig.GroupAdd') assert "root" in host_container_groupadd assert "1" in host_container_groupadd def test_dns_opt_value(self): service = self.create_service('web', dns_opt=["use-vc", "no-tld-query"]) container = create_and_start_container(service) dns_opt = container.get('HostConfig.DnsOptions') assert 'use-vc' in dns_opt assert 'no-tld-query' in dns_opt def test_restart_on_failure_value(self): service = self.create_service('web', restart={ 'Name': 'on-failure', 'MaximumRetryCount': 5 }) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'on-failure' assert container.get('HostConfig.RestartPolicy.MaximumRetryCount') == 5 def test_cap_add_list(self): service = self.create_service('web', cap_add=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapAdd') == ['SYS_ADMIN', 'NET_ADMIN'] def test_cap_drop_list(self): service = self.create_service('web', cap_drop=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapDrop') == ['SYS_ADMIN', 'NET_ADMIN'] def test_dns_search(self): service = self.create_service('web', dns_search=['dc1.example.com', 'dc2.example.com']) container = create_and_start_container(service) assert container.get('HostConfig.DnsSearch') == ['dc1.example.com', 'dc2.example.com'] @v2_only() def test_tmpfs(self): service = self.create_service('web', tmpfs=['/run']) container = create_and_start_container(service) assert container.get('HostConfig.Tmpfs') == {'/run': ''} def test_working_dir_param(self): service = self.create_service('container', working_dir='/working/dir/sample') container = service.create_container() assert container.get('Config.WorkingDir') == '/working/dir/sample' def test_split_env(self): service = self.create_service( 'web', environment=['NORMAL=F1', 'CONTAINS_EQUALS=F=2', 'TRAILING_EQUALS=']) env = create_and_start_container(service).environment for k, v in {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''}.items(): assert env[k] == v def test_env_from_file_combined_with_env(self): service = self.create_service( 'web', environment=['ONE=1', 'TWO=2', 'THREE=3'], env_file=['tests/fixtures/env/one.env', 'tests/fixtures/env/two.env']) env = create_and_start_container(service).environment for k, v in { 'ONE': '1', 'TWO': '2', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah' }.items(): assert env[k] == v @v3_only() def test_build_with_cachefrom(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('cache_from', build={'context': base_dir, 'cache_from': ['build1']}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @mock.patch.dict(os.environ) def test_resolve_env(self): os.environ['FILE_DEF'] = 'E1' os.environ['FILE_DEF_EMPTY'] = 'E2' os.environ['ENV_DEF'] = 'E3' service = self.create_service( 'web', environment={ 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': None, 'NO_DEF': None } ) env = create_and_start_container(service).environment for k, v in { 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None }.items(): assert env[k] == v def test_with_high_enough_api_version_we_get_default_network_mode(self): # TODO: remove this test once minimum docker version is 1.8.x with mock.patch.object(self.client, '_version', '1.20'): service = self.create_service('web') service_config = service._get_container_host_config({}) assert service_config['NetworkMode'] == 'default' def test_labels(self): labels_dict = { 'com.example.description': "Accounting webapp", 'com.example.department': "Finance", 'com.example.label-with-empty-value': "", } compose_labels = { LABEL_CONTAINER_NUMBER: '1', LABEL_ONE_OFF: 'False', LABEL_PROJECT: 'composetest', LABEL_SERVICE: 'web', LABEL_VERSION: __version__, } expected = dict(labels_dict, **compose_labels) service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for pair in expected.items(): assert pair in labels def test_empty_labels(self): labels_dict = {'foo': '', 'bar': ''} service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for name in labels_dict: assert (name, '') in labels def test_stop_signal(self): stop_signal = 'SIGINT' service = self.create_service('web', stop_signal=stop_signal) container = create_and_start_container(service) assert container.stop_signal == stop_signal def test_custom_container_name(self): service = self.create_service('web', container_name='my-web-container') assert service.custom_container_name == 'my-web-container' container = create_and_start_container(service) assert container.name == 'my-web-container' one_off_container = service.create_container(one_off=True) assert one_off_container.name != 'my-web-container' @pytest.mark.skipif(True, reason="Broken on 1.11.0 - 17.03.0") def test_log_drive_invalid(self): service = self.create_service('web', logging={'driver': 'xxx'}) expected_error_msg = "logger: no log driver named 'xxx' is registered" with pytest.raises(APIError) as excinfo: create_and_start_container(service) assert re.search(expected_error_msg, excinfo.value) def test_log_drive_empty_default_jsonfile(self): service = self.create_service('web') log_config = create_and_start_container(service).log_config assert 'json-file' == log_config['Type'] assert not log_config['Config'] def test_log_drive_none(self): service = self.create_service('web', logging={'driver': 'none'}) log_config = create_and_start_container(service).log_config assert 'none' == log_config['Type'] assert not log_config['Config'] def test_devices(self): service = self.create_service('web', devices=["/dev/random:/dev/mapped-random"]) device_config = create_and_start_container(service).get('HostConfig.Devices') device_dict = { 'PathOnHost': '/dev/random', 'CgroupPermissions': 'rwm', 'PathInContainer': '/dev/mapped-random' } assert 1 == len(device_config) assert device_dict == device_config[0] def test_duplicate_containers(self): service = self.create_service('web') options = service._get_container_create_options({}, 1) original = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original]) assert set(service.duplicate_containers()) == set() options['name'] = 'temporary_container_name' duplicate = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original, duplicate]) assert set(service.duplicate_containers()) == set([duplicate]) def converge(service, strategy=ConvergenceStrategy.changed): """Create a converge plan from a strategy and execute the plan.""" plan = service.convergence_plan(strategy) return service.execute_convergence_plan(plan, timeout=1) class ConfigHashTest(DockerClientTestCase): def test_no_config_hash_when_one_off(self): web = self.create_service('web') container = web.create_container(one_off=True) assert LABEL_CONFIG_HASH not in container.labels def test_no_config_hash_when_overriding_options(self): web = self.create_service('web') container = web.create_container(environment={'FOO': '1'}) assert LABEL_CONFIG_HASH not in container.labels def test_config_hash_with_custom_labels(self): web = self.create_service('web', labels={'foo': '1'}) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels assert 'foo' in container.labels def test_config_hash_sticks_around(self): web = self.create_service('web', command=["top"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels web = self.create_service('web', command=["top", "-d", "1"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels
shin-/compose
tests/integration/service_test.py
tests/unit/timeparse_test.py
from __future__ import absolute_import from __future__ import unicode_literals import logging from compose.cli import colors from compose.cli.formatter import ConsoleWarningFormatter from tests import unittest MESSAGE = 'this is the message' def make_log_record(level, message=None): return logging.LogRecord('name', level, 'pathame', 0, message or MESSAGE, (), None) class ConsoleWarningFormatterTestCase(unittest.TestCase): def setUp(self): self.formatter = ConsoleWarningFormatter() def test_format_warn(self): output = self.formatter.format(make_log_record(logging.WARN)) expected = colors.yellow('WARNING') + ': ' assert output == expected + MESSAGE def test_format_error(self): output = self.formatter.format(make_log_record(logging.ERROR)) expected = colors.red('ERROR') + ': ' assert output == expected + MESSAGE def test_format_info(self): output = self.formatter.format(make_log_record(logging.INFO)) assert output == MESSAGE def test_format_unicode_info(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.INFO, message)) assert output == message.decode('utf-8') def test_format_unicode_warn(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.WARN, message)) expected = colors.yellow('WARNING') + ': ' assert output == '{0}{1}'.format(expected, message.decode('utf-8')) def test_format_unicode_error(self): message = b'\xec\xa0\x95\xec\x88\x98\xec\xa0\x95' output = self.formatter.format(make_log_record(logging.ERROR, message)) expected = colors.red('ERROR') + ': ' assert output == '{0}{1}'.format(expected, message.decode('utf-8'))
from __future__ import absolute_import from __future__ import unicode_literals import os import re import shutil import tempfile from distutils.spawn import find_executable from os import path import pytest from docker.errors import APIError from docker.errors import ImageNotFound from six import StringIO from six import text_type from .. import mock from .testcases import docker_client from .testcases import DockerClientTestCase from .testcases import get_links from .testcases import pull_busybox from .testcases import SWARM_SKIP_CONTAINERS_ALL from .testcases import SWARM_SKIP_CPU_SHARES from compose import __version__ from compose.config.types import MountSpec from compose.config.types import SecurityOpt from compose.config.types import VolumeFromSpec from compose.config.types import VolumeSpec from compose.const import IS_WINDOWS_PLATFORM from compose.const import LABEL_CONFIG_HASH from compose.const import LABEL_CONTAINER_NUMBER from compose.const import LABEL_ONE_OFF from compose.const import LABEL_PROJECT from compose.const import LABEL_SERVICE from compose.const import LABEL_VERSION from compose.container import Container from compose.errors import OperationFailedError from compose.parallel import ParallelStreamWriter from compose.project import OneOffFilter from compose.service import ConvergencePlan from compose.service import ConvergenceStrategy from compose.service import NetworkMode from compose.service import PidMode from compose.service import Service from compose.utils import parse_nanoseconds_int from tests.helpers import create_custom_host_file from tests.integration.testcases import is_cluster from tests.integration.testcases import no_cluster from tests.integration.testcases import v2_1_only from tests.integration.testcases import v2_2_only from tests.integration.testcases import v2_3_only from tests.integration.testcases import v2_only from tests.integration.testcases import v3_only def create_and_start_container(service, **override_options): container = service.create_container(**override_options) return service.start_container(container) class ServiceTest(DockerClientTestCase): def test_containers(self): foo = self.create_service('foo') bar = self.create_service('bar') create_and_start_container(foo) assert len(foo.containers()) == 1 assert foo.containers()[0].name == 'composetest_foo_1' assert len(bar.containers()) == 0 create_and_start_container(bar) create_and_start_container(bar) assert len(foo.containers()) == 1 assert len(bar.containers()) == 2 names = [c.name for c in bar.containers()] assert 'composetest_bar_1' in names assert 'composetest_bar_2' in names def test_containers_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert db.containers(stopped=True) == [] assert db.containers(one_off=OneOffFilter.only, stopped=True) == [container] def test_project_is_added_to_container_name(self): service = self.create_service('web') create_and_start_container(service) assert service.containers()[0].name == 'composetest_web_1' def test_create_container_with_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_one_off_when_existing_container_is_running(self): db = self.create_service('db') db.start() container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_unspecified_volume(self): service = self.create_service('db', volumes=[VolumeSpec.parse('/var/db')]) container = service.create_container() service.start_container(container) assert container.get_mount('/var/db') def test_create_container_with_volume_driver(self): service = self.create_service('db', volume_driver='foodriver') container = service.create_container() service.start_container(container) assert 'foodriver' == container.get('HostConfig.VolumeDriver') @pytest.mark.skipif(SWARM_SKIP_CPU_SHARES, reason='Swarm --cpu-shares bug') def test_create_container_with_cpu_shares(self): service = self.create_service('db', cpu_shares=73) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuShares') == 73 def test_create_container_with_cpu_quota(self): service = self.create_service('db', cpu_quota=40000, cpu_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuQuota') == 40000 assert container.get('HostConfig.CpuPeriod') == 150000 @pytest.mark.xfail(raises=OperationFailedError, reason='not supported by kernel') def test_create_container_with_cpu_rt(self): service = self.create_service('db', cpu_rt_runtime=40000, cpu_rt_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuRealtimeRuntime') == 40000 assert container.get('HostConfig.CpuRealtimePeriod') == 150000 @v2_2_only() def test_create_container_with_cpu_count(self): self.require_api_version('1.25') service = self.create_service('db', cpu_count=2) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuCount') == 2 @v2_2_only() @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='cpu_percent is not supported for Linux') def test_create_container_with_cpu_percent(self): self.require_api_version('1.25') service = self.create_service('db', cpu_percent=12) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuPercent') == 12 @v2_2_only() def test_create_container_with_cpus(self): self.require_api_version('1.25') service = self.create_service('db', cpus=1) container = service.create_container() service.start_container(container) assert container.get('HostConfig.NanoCpus') == 1000000000 def test_create_container_with_shm_size(self): self.require_api_version('1.22') service = self.create_service('db', shm_size=67108864) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ShmSize') == 67108864 def test_create_container_with_init_bool(self): self.require_api_version('1.25') service = self.create_service('db', init=True) container = service.create_container() service.start_container(container) assert container.get('HostConfig.Init') is True @pytest.mark.xfail(True, reason='Option has been removed in Engine 17.06.0') def test_create_container_with_init_path(self): self.require_api_version('1.25') docker_init_path = find_executable('docker-init') service = self.create_service('db', init=docker_init_path) container = service.create_container() service.start_container(container) assert container.get('HostConfig.InitPath') == docker_init_path @pytest.mark.xfail(True, reason='Some kernels/configs do not support pids_limit') def test_create_container_with_pids_limit(self): self.require_api_version('1.23') service = self.create_service('db', pids_limit=10) container = service.create_container() service.start_container(container) assert container.get('HostConfig.PidsLimit') == 10 def test_create_container_with_extra_hosts_list(self): extra_hosts = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts) def test_create_container_with_extra_hosts_dicts(self): extra_hosts = {'somehost': '162.242.195.82', 'otherhost': '50.31.209.229'} extra_hosts_list = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts_list) def test_create_container_with_cpu_set(self): service = self.create_service('db', cpuset='0') container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpusetCpus') == '0' def test_create_container_with_read_only_root_fs(self): read_only = True service = self.create_service('db', read_only=read_only) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ReadonlyRootfs') == read_only def test_create_container_with_blkio_config(self): blkio_config = { 'weight': 300, 'weight_device': [{'path': '/dev/sda', 'weight': 200}], 'device_read_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024 * 100}], 'device_read_iops': [{'path': '/dev/sda', 'rate': 1000}], 'device_write_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024}], 'device_write_iops': [{'path': '/dev/sda', 'rate': 800}] } service = self.create_service('web', blkio_config=blkio_config) container = service.create_container() assert container.get('HostConfig.BlkioWeight') == 300 assert container.get('HostConfig.BlkioWeightDevice') == [{ 'Path': '/dev/sda', 'Weight': 200 }] assert container.get('HostConfig.BlkioDeviceReadBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 * 100 }] assert container.get('HostConfig.BlkioDeviceWriteBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 }] assert container.get('HostConfig.BlkioDeviceReadIOps') == [{ 'Path': '/dev/sda', 'Rate': 1000 }] assert container.get('HostConfig.BlkioDeviceWriteIOps') == [{ 'Path': '/dev/sda', 'Rate': 800 }] def test_create_container_with_security_opt(self): security_opt = [SecurityOpt.parse('label:disable')] service = self.create_service('db', security_opt=security_opt) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.SecurityOpt')) == set([o.repr() for o in security_opt]) @pytest.mark.xfail(True, reason='Not supported on most drivers') def test_create_container_with_storage_opt(self): storage_opt = {'size': '1G'} service = self.create_service('db', storage_opt=storage_opt) container = service.create_container() service.start_container(container) assert container.get('HostConfig.StorageOpt') == storage_opt def test_create_container_with_oom_kill_disable(self): self.require_api_version('1.20') service = self.create_service('db', oom_kill_disable=True) container = service.create_container() assert container.get('HostConfig.OomKillDisable') is True def test_create_container_with_mac_address(self): service = self.create_service('db', mac_address='02:42:ac:11:65:43') container = service.create_container() service.start_container(container) assert container.inspect()['Config']['MacAddress'] == '02:42:ac:11:65:43' def test_create_container_with_device_cgroup_rules(self): service = self.create_service('db', device_cgroup_rules=['c 7:128 rwm']) container = service.create_container() assert container.get('HostConfig.DeviceCgroupRules') == ['c 7:128 rwm'] def test_create_container_with_specified_volume(self): host_path = '/tmp/host-path' container_path = '/container-path' service = self.create_service( 'db', volumes=[VolumeSpec(host_path, container_path, 'rw')]) container = service.create_container() service.start_container(container) assert container.get_mount(container_path) # Match the last component ("host-path"), because boot2docker symlinks /tmp actual_host_path = container.get_mount(container_path)['Source'] assert path.basename(actual_host_path) == path.basename(host_path), ( "Last component differs: %s, %s" % (actual_host_path, host_path) ) @v2_3_only() def test_create_container_with_host_mount(self): host_path = '/tmp/host-path' container_path = '/container-path' create_custom_host_file(self.client, path.join(host_path, 'a.txt'), 'test') service = self.create_service( 'db', volumes=[ MountSpec(type='bind', source=host_path, target=container_path, read_only=True) ] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert path.basename(mount['Source']) == path.basename(host_path) assert mount['RW'] is False @v2_3_only() def test_create_container_with_tmpfs_mount(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Type'] == 'tmpfs' @v2_3_only() def test_create_container_with_tmpfs_mount_tmpfs_size(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path, tmpfs={'size': 5368709})] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount print(container.dictionary) assert mount['Type'] == 'tmpfs' assert container.get('HostConfig.Mounts')[0]['TmpfsOptions'] == { 'SizeBytes': 5368709 } @v2_3_only() def test_create_container_with_volume_mount(self): container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = self.create_service( 'db', volumes=[MountSpec(type='volume', source=volume_name, target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_mount(self): # Ensure mounts are converted to volumes if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = Service('db', client=client, volumes=[ MountSpec(type='volume', source=volume_name, target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_tmpfs_mount(self): # Ensure tmpfs mounts are converted to tmpfs entries if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-tmpfs' service = Service('db', client=client, volumes=[ MountSpec(type='tmpfs', target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount is None assert container_path in container.get('HostConfig.Tmpfs') def test_create_container_with_healthcheck_config(self): one_second = parse_nanoseconds_int('1s') healthcheck = { 'test': ['true'], 'interval': 2 * one_second, 'timeout': 5 * one_second, 'retries': 5, 'start_period': 2 * one_second } service = self.create_service('db', healthcheck=healthcheck) container = service.create_container() remote_healthcheck = container.get('Config.Healthcheck') assert remote_healthcheck['Test'] == healthcheck['test'] assert remote_healthcheck['Interval'] == healthcheck['interval'] assert remote_healthcheck['Timeout'] == healthcheck['timeout'] assert remote_healthcheck['Retries'] == healthcheck['retries'] assert remote_healthcheck['StartPeriod'] == healthcheck['start_period'] def test_recreate_preserves_volume_with_trailing_slash(self): """When the Compose file specifies a trailing slash in the container path, make sure we copy the volume over when recreating. """ service = self.create_service('data', volumes=[VolumeSpec.parse('/data/')]) old_container = create_and_start_container(service) volume_path = old_container.get_mount('/data')['Source'] new_container = service.recreate_container(old_container) assert new_container.get_mount('/data')['Source'] == volume_path def test_duplicate_volume_trailing_slash(self): """ When an image specifies a volume, and the Compose file specifies a host path but adds a trailing slash, make sure that we don't create duplicate binds. """ host_path = '/tmp/data' container_path = '/data' volumes = [VolumeSpec.parse('{}:{}/'.format(host_path, container_path))] tmp_container = self.client.create_container( 'busybox', 'true', volumes={container_path: {}}, labels={'com.docker.compose.test_image': 'true'}, host_config={} ) image = self.client.commit(tmp_container)['Id'] service = self.create_service('db', image=image, volumes=volumes) old_container = create_and_start_container(service) assert old_container.get('Config.Volumes') == {container_path: {}} service = self.create_service('db', image=image, volumes=volumes) new_container = service.recreate_container(old_container) assert new_container.get('Config.Volumes') == {container_path: {}} assert service.containers(stopped=False) == [new_container] def test_create_container_with_volumes_from(self): volume_service = self.create_service('data') volume_container_1 = volume_service.create_container() volume_container_2 = Container.create( self.client, image='busybox:latest', command=["top"], labels={LABEL_PROJECT: 'composetest'}, host_config={}, environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_service = self.create_service( 'host', volumes_from=[ VolumeFromSpec(volume_service, 'rw', 'service'), VolumeFromSpec(volume_container_2, 'rw', 'container') ], environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_container = host_service.create_container() host_service.start_container(host_container) assert volume_container_1.id + ':rw' in host_container.get('HostConfig.VolumesFrom') assert volume_container_2.id + ':rw' in host_container.get('HostConfig.VolumesFrom') def test_execute_convergence_plan_recreate(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1'] ) old_container = service.create_container() assert old_container.get('Config.Entrypoint') == ['top'] assert old_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=1' in old_container.get('Config.Env') assert old_container.name == 'composetest_db_1' service.start_container(old_container) old_container.inspect() # reload volume data volume_path = old_container.get_mount('/etc')['Source'] num_containers_before = len(self.client.containers(all=True)) service.options['environment']['FOO'] = '2' new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert new_container.get('Config.Entrypoint') == ['top'] assert new_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=2' in new_container.get('Config.Env') assert new_container.name == 'composetest_db_1' assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ( 'affinity:container==%s' % old_container.id in new_container.get('Config.Env') ) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert old_container.get('Node.Name') == new_container.get('Node.Name') assert len(self.client.containers(all=True)) == num_containers_before assert old_container.id != new_container.id with pytest.raises(APIError): self.client.inspect_container(old_container.id) def test_execute_convergence_plan_recreate_change_mount_target(self): service = self.create_service( 'db', volumes=[MountSpec(target='/app1', type='volume')], entrypoint=['top'], command=['-d', '1'] ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/app1'] ) service.options['volumes'] = [MountSpec(target='/app2', type='volume')] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/app2'] ) def test_execute_convergence_plan_recreate_twice(self): service = self.create_service( 'db', volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1']) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container])) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container @v2_3_only() def test_execute_convergence_plan_recreate_twice_with_mount(self): service = self.create_service( 'db', volumes=[MountSpec(target='/etc', type='volume')], entrypoint=['top'], command=['-d', '1'] ) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container]) ) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container def test_execute_convergence_plan_when_containers_are_stopped(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/var/db')], entrypoint=['top'], command=['-d', '1'] ) service.create_container() containers = service.containers(stopped=True) assert len(containers) == 1 container, = containers assert not container.is_running service.execute_convergence_plan(ConvergencePlan('start', [container])) containers = service.containers() assert len(containers) == 1 container.inspect() assert container == containers[0] assert container.is_running def test_execute_convergence_plan_with_image_declared_volume(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_with_image_declared_volume_renew(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_when_image_volume_masks_config(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] service.options['volumes'] = [VolumeSpec.parse('/tmp:/data')] with mock.patch('compose.service.log') as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) mock_log.warn.assert_called_once_with(mock.ANY) _, args, kwargs = mock_log.warn.mock_calls[0] assert "Service \"db\" is using volume \"/data\" from the previous container" in args[0] assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_when_host_volume_is_removed(self): host_path = '/tmp/host-path' service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, volumes=[VolumeSpec(host_path, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) service.options['volumes'] = [] with mock.patch('compose.service.log', autospec=True) as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert not mock_log.warn.called assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != host_path def test_execute_convergence_plan_anonymous_volume_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_anonymous_volume_recreate_then_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] mid_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), ) assert ( [mount['Destination'] for mount in mid_container.get('Mounts')] == ['/data'] ) assert mid_container.get_mount('/data')['Source'] == volume_path new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [mid_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_without_start(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) containers = service.execute_convergence_plan(ConvergencePlan('create', []), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running containers = service.execute_convergence_plan( ConvergencePlan('recreate', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running service.execute_convergence_plan(ConvergencePlan('start', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running def test_execute_convergence_plan_image_with_volume_is_removed(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] old_container.stop() self.client.remove_image(service.image(), force=True) service.ensure_image_exists() with pytest.raises(ImageNotFound): service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) old_container.inspect() # retrieve new name from server new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), reset_container_image=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_start_container_passes_through_options(self): db = self.create_service('db') create_and_start_container(db, environment={'FOO': 'BAR'}) assert db.containers()[0].environment['FOO'] == 'BAR' def test_start_container_inherits_options_from_constructor(self): db = self.create_service('db', environment={'FOO': 'BAR'}) create_and_start_container(db) assert db.containers()[0].environment['FOO'] == 'BAR' @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links(self): db = self.create_service('db') web = self.create_service('web', links=[(db, None)]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links_with_names(self): db = self.create_service('db') web = self.create_service('web', links=[(db, 'custom_link_name')]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'custom_link_name' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_with_external_links(self): db = self.create_service('db') web = self.create_service('web', external_links=['composetest_db_1', 'composetest_db_2', 'composetest_db_3:db_3']) for _ in range(3): create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'composetest_db_2', 'db_3' ]) @no_cluster('No legacy links support in Swarm') def test_start_normal_container_does_not_create_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db) assert set(get_links(c)) == set([]) @no_cluster('No legacy links support in Swarm') def test_start_one_off_container_creates_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db, one_off=OneOffFilter.only) assert set(get_links(c)) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) def test_start_container_builds_images(self): service = Service( name='test', client=self.client, build={'context': 'tests/fixtures/simple-dockerfile'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() assert len(self.client.images(name='composetest_test')) >= 1 def test_start_container_uses_tagged_image_if_it_exists(self): self.check_build('tests/fixtures/simple-dockerfile', tag='composetest_test') service = Service( name='test', client=self.client, build={'context': 'this/does/not/exist/and/will/throw/error'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() def test_start_container_creates_ports(self): service = self.create_service('web', ports=[8000]) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/tcp'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] != '8000' def test_build(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('web', build={'context': base_dir}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_non_ascii_filename(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") with open(os.path.join(base_dir.encode('utf8'), b'foo\xE2bar'), 'w') as f: f.write("hello world\n") service = self.create_service('web', build={'context': text_type(base_dir)}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_with_image_name(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") image_name = 'examples/composetest:latest' self.addCleanup(self.client.remove_image, image_name) self.create_service('web', build={'context': base_dir}, image=image_name).build() assert self.client.inspect_image(image_name) def test_build_with_git_url(self): build_url = "https://github.com/dnephin/docker-build-from-url.git" service = self.create_service('buildwithurl', build={'context': build_url}) self.addCleanup(self.client.remove_image, service.image_name) service.build() assert service.image() def test_build_with_build_args(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=1" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_args_override(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build(build_args_override={'build_version': '2'}) self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=2" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_labels(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('buildlabels', build={ 'context': text_type(base_dir), 'labels': {'com.docker.compose.test': 'true'} }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test'] == 'true' @no_cluster('Container networks not on Swarm') def test_build_with_network(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') f.write('RUN ping -c1 google.local\n') net_container = self.client.create_container( 'busybox', 'top', host_config=self.client.create_host_config( extra_hosts={'google.local': '127.0.0.1'} ), name='composetest_build_network' ) self.addCleanup(self.client.remove_container, net_container, force=True) self.client.start(net_container) service = self.create_service('buildwithnet', build={ 'context': text_type(base_dir), 'network': 'container:{}'.format(net_container['Id']) }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @v2_3_only() @no_cluster('Not supported on UCP 2.2.0-beta1') # FIXME: remove once support is added def test_build_with_target(self): self.require_api_version('1.30') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox as one\n') f.write('LABEL com.docker.compose.test=true\n') f.write('LABEL com.docker.compose.test.target=one\n') f.write('FROM busybox as two\n') f.write('LABEL com.docker.compose.test.target=two\n') service = self.create_service('buildtarget', build={ 'context': text_type(base_dir), 'target': 'one' }) service.build() assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test.target'] == 'one' @v2_3_only() def test_build_with_extra_hosts(self): self.require_api_version('1.27') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'RUN ping -c1 foobar', 'RUN ping -c1 baz', ])) service = self.create_service('build_extra_hosts', build={ 'context': text_type(base_dir), 'extra_hosts': { 'foobar': '127.0.0.1', 'baz': '127.0.0.1' } }) service.build() assert service.image() def test_build_with_gzip(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'COPY . /src', 'RUN cat /src/hello.txt' ])) with open(os.path.join(base_dir, 'hello.txt'), 'w') as f: f.write('hello world\n') service = self.create_service('build_gzip', build={ 'context': text_type(base_dir), }) service.build(gzip=True) assert service.image() @v2_1_only() def test_build_with_isolation(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('build_isolation', build={ 'context': text_type(base_dir), 'isolation': 'default', }) service.build() assert service.image() def test_start_container_stays_unprivileged(self): service = self.create_service('web') container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is False def test_start_container_becomes_privileged(self): service = self.create_service('web', privileged=True) container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is True def test_expose_does_not_publish_ports(self): service = self.create_service('web', expose=["8000"]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports'] == {'8000/tcp': None} def test_start_container_creates_port_with_explicit_protocol(self): service = self.create_service('web', ports=['8000/udp']) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/udp'] def test_start_container_creates_fixed_external_ports(self): service = self.create_service('web', ports=['8000:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8000' def test_start_container_creates_fixed_external_ports_when_it_is_different_to_internal_port(self): service = self.create_service('web', ports=['8001:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8001' def test_port_with_explicit_interface(self): service = self.create_service('web', ports=[ '127.0.0.1:8001:8000', '0.0.0.0:9001:9000/udp', ]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports']['8000/tcp'] == [{ 'HostIp': '127.0.0.1', 'HostPort': '8001', }] assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostPort'] == '9001' if not is_cluster(self.client): assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostIp'] == '0.0.0.0' # self.assertEqual(container['NetworkSettings']['Ports'], { # '8000/tcp': [ # { # 'HostIp': '127.0.0.1', # 'HostPort': '8001', # }, # ], # '9000/udp': [ # { # 'HostIp': '0.0.0.0', # 'HostPort': '9001', # }, # ], # }) def test_create_with_image_id(self): # Get image id for the current busybox:latest pull_busybox(self.client) image_id = self.client.inspect_image('busybox:latest')['Id'][:12] service = self.create_service('foo', image=image_id) service.create_container() def test_scale(self): service = self.create_service('web') service.scale(1) assert len(service.containers()) == 1 # Ensure containers don't have stdout or stdin connected container = service.containers()[0] config = container.inspect()['Config'] assert not config['AttachStderr'] assert not config['AttachStdout'] assert not config['AttachStdin'] service.scale(3) assert len(service.containers()) == 3 service.scale(1) assert len(service.containers()) == 1 service.scale(0) assert len(service.containers()) == 0 @pytest.mark.skipif( SWARM_SKIP_CONTAINERS_ALL, reason='Swarm /containers/json bug' ) def test_scale_with_stopped_containers(self): """ Given there are some stopped containers and scale is called with a desired number that is the same as the number of stopped containers, test that those containers are restarted and not removed/recreated. """ service = self.create_service('web') next_number = service._next_container_number() valid_numbers = [next_number, next_number + 1] service.create_container(number=next_number) service.create_container(number=next_number + 1) ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) for container in service.containers(): assert container.is_running assert container.number in valid_numbers captured_output = mock_stderr.getvalue() assert 'Creating' not in captured_output assert 'Starting' in captured_output def test_scale_with_stopped_containers_and_needing_creation(self): """ Given there are some stopped containers and scale is called with a desired number that is greater than the number of stopped containers, test that those containers are restarted and required number are created. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) for container in service.containers(): assert not container.is_running ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) assert len(service.containers()) == 2 for container in service.containers(): assert container.is_running captured_output = mock_stderr.getvalue() assert 'Creating' in captured_output assert 'Starting' in captured_output def test_scale_with_api_error(self): """Test that when scaling if the API returns an error, that error is handled and the remaining threads continue. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=APIError( message="testing", response={}, explanation="Boom")): with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: with pytest.raises(OperationFailedError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running assert ( "ERROR: for composetest_web_2 Cannot create container for service" " web: Boom" in mock_stderr.getvalue() ) def test_scale_with_unexpected_exception(self): """Test that when scaling if the API returns an error, that is not of type APIError, that error is re-raised. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=ValueError("BOOM") ): with pytest.raises(ValueError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running @mock.patch('compose.service.log') def test_scale_with_desired_number_already_achieved(self, mock_log): """ Test that calling scale with a desired number that is equal to the number of containers already running results in no change. """ service = self.create_service('web') next_number = service._next_container_number() container = service.create_container(number=next_number, quiet=True) container.start() container.inspect() assert container.is_running assert len(service.containers()) == 1 service.scale(1) assert len(service.containers()) == 1 container.inspect() assert container.is_running captured_output = mock_log.info.call_args[0] assert 'Desired container number already achieved' in captured_output @mock.patch('compose.service.log') def test_scale_with_custom_container_name_outputs_warning(self, mock_log): """Test that calling scale on a service that has a custom container name results in warning output. """ service = self.create_service('app', container_name='custom-container') assert service.custom_container_name == 'custom-container' with pytest.raises(OperationFailedError): service.scale(3) captured_output = mock_log.warn.call_args[0][0] assert len(service.containers()) == 1 assert "Remove the custom name to scale the service." in captured_output def test_scale_sets_ports(self): service = self.create_service('web', ports=['8000']) service.scale(2) containers = service.containers() assert len(containers) == 2 for container in containers: assert list(container.get('HostConfig.PortBindings')) == ['8000/tcp'] def test_scale_with_immediate_exit(self): service = self.create_service('web', image='busybox', command='true') service.scale(2) assert len(service.containers(stopped=True)) == 2 def test_network_mode_none(self): service = self.create_service('web', network_mode=NetworkMode('none')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'none' def test_network_mode_bridged(self): service = self.create_service('web', network_mode=NetworkMode('bridge')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'bridge' def test_network_mode_host(self): service = self.create_service('web', network_mode=NetworkMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'host' def test_pid_mode_none_defined(self): service = self.create_service('web', pid_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == '' def test_pid_mode_host(self): service = self.create_service('web', pid_mode=PidMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == 'host' @v2_1_only() def test_userns_mode_none_defined(self): service = self.create_service('web', userns_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == '' @v2_1_only() def test_userns_mode_host(self): service = self.create_service('web', userns_mode='host') container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == 'host' def test_dns_no_value(self): service = self.create_service('web') container = create_and_start_container(service) assert container.get('HostConfig.Dns') is None def test_dns_list(self): service = self.create_service('web', dns=['8.8.8.8', '9.9.9.9']) container = create_and_start_container(service) assert container.get('HostConfig.Dns') == ['8.8.8.8', '9.9.9.9'] def test_mem_swappiness(self): service = self.create_service('web', mem_swappiness=11) container = create_and_start_container(service) assert container.get('HostConfig.MemorySwappiness') == 11 def test_mem_reservation(self): service = self.create_service('web', mem_reservation='20m') container = create_and_start_container(service) assert container.get('HostConfig.MemoryReservation') == 20 * 1024 * 1024 def test_restart_always_value(self): service = self.create_service('web', restart={'Name': 'always'}) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'always' def test_oom_score_adj_value(self): service = self.create_service('web', oom_score_adj=500) container = create_and_start_container(service) assert container.get('HostConfig.OomScoreAdj') == 500 def test_group_add_value(self): service = self.create_service('web', group_add=["root", "1"]) container = create_and_start_container(service) host_container_groupadd = container.get('HostConfig.GroupAdd') assert "root" in host_container_groupadd assert "1" in host_container_groupadd def test_dns_opt_value(self): service = self.create_service('web', dns_opt=["use-vc", "no-tld-query"]) container = create_and_start_container(service) dns_opt = container.get('HostConfig.DnsOptions') assert 'use-vc' in dns_opt assert 'no-tld-query' in dns_opt def test_restart_on_failure_value(self): service = self.create_service('web', restart={ 'Name': 'on-failure', 'MaximumRetryCount': 5 }) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'on-failure' assert container.get('HostConfig.RestartPolicy.MaximumRetryCount') == 5 def test_cap_add_list(self): service = self.create_service('web', cap_add=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapAdd') == ['SYS_ADMIN', 'NET_ADMIN'] def test_cap_drop_list(self): service = self.create_service('web', cap_drop=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapDrop') == ['SYS_ADMIN', 'NET_ADMIN'] def test_dns_search(self): service = self.create_service('web', dns_search=['dc1.example.com', 'dc2.example.com']) container = create_and_start_container(service) assert container.get('HostConfig.DnsSearch') == ['dc1.example.com', 'dc2.example.com'] @v2_only() def test_tmpfs(self): service = self.create_service('web', tmpfs=['/run']) container = create_and_start_container(service) assert container.get('HostConfig.Tmpfs') == {'/run': ''} def test_working_dir_param(self): service = self.create_service('container', working_dir='/working/dir/sample') container = service.create_container() assert container.get('Config.WorkingDir') == '/working/dir/sample' def test_split_env(self): service = self.create_service( 'web', environment=['NORMAL=F1', 'CONTAINS_EQUALS=F=2', 'TRAILING_EQUALS=']) env = create_and_start_container(service).environment for k, v in {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''}.items(): assert env[k] == v def test_env_from_file_combined_with_env(self): service = self.create_service( 'web', environment=['ONE=1', 'TWO=2', 'THREE=3'], env_file=['tests/fixtures/env/one.env', 'tests/fixtures/env/two.env']) env = create_and_start_container(service).environment for k, v in { 'ONE': '1', 'TWO': '2', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah' }.items(): assert env[k] == v @v3_only() def test_build_with_cachefrom(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('cache_from', build={'context': base_dir, 'cache_from': ['build1']}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @mock.patch.dict(os.environ) def test_resolve_env(self): os.environ['FILE_DEF'] = 'E1' os.environ['FILE_DEF_EMPTY'] = 'E2' os.environ['ENV_DEF'] = 'E3' service = self.create_service( 'web', environment={ 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': None, 'NO_DEF': None } ) env = create_and_start_container(service).environment for k, v in { 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None }.items(): assert env[k] == v def test_with_high_enough_api_version_we_get_default_network_mode(self): # TODO: remove this test once minimum docker version is 1.8.x with mock.patch.object(self.client, '_version', '1.20'): service = self.create_service('web') service_config = service._get_container_host_config({}) assert service_config['NetworkMode'] == 'default' def test_labels(self): labels_dict = { 'com.example.description': "Accounting webapp", 'com.example.department': "Finance", 'com.example.label-with-empty-value': "", } compose_labels = { LABEL_CONTAINER_NUMBER: '1', LABEL_ONE_OFF: 'False', LABEL_PROJECT: 'composetest', LABEL_SERVICE: 'web', LABEL_VERSION: __version__, } expected = dict(labels_dict, **compose_labels) service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for pair in expected.items(): assert pair in labels def test_empty_labels(self): labels_dict = {'foo': '', 'bar': ''} service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for name in labels_dict: assert (name, '') in labels def test_stop_signal(self): stop_signal = 'SIGINT' service = self.create_service('web', stop_signal=stop_signal) container = create_and_start_container(service) assert container.stop_signal == stop_signal def test_custom_container_name(self): service = self.create_service('web', container_name='my-web-container') assert service.custom_container_name == 'my-web-container' container = create_and_start_container(service) assert container.name == 'my-web-container' one_off_container = service.create_container(one_off=True) assert one_off_container.name != 'my-web-container' @pytest.mark.skipif(True, reason="Broken on 1.11.0 - 17.03.0") def test_log_drive_invalid(self): service = self.create_service('web', logging={'driver': 'xxx'}) expected_error_msg = "logger: no log driver named 'xxx' is registered" with pytest.raises(APIError) as excinfo: create_and_start_container(service) assert re.search(expected_error_msg, excinfo.value) def test_log_drive_empty_default_jsonfile(self): service = self.create_service('web') log_config = create_and_start_container(service).log_config assert 'json-file' == log_config['Type'] assert not log_config['Config'] def test_log_drive_none(self): service = self.create_service('web', logging={'driver': 'none'}) log_config = create_and_start_container(service).log_config assert 'none' == log_config['Type'] assert not log_config['Config'] def test_devices(self): service = self.create_service('web', devices=["/dev/random:/dev/mapped-random"]) device_config = create_and_start_container(service).get('HostConfig.Devices') device_dict = { 'PathOnHost': '/dev/random', 'CgroupPermissions': 'rwm', 'PathInContainer': '/dev/mapped-random' } assert 1 == len(device_config) assert device_dict == device_config[0] def test_duplicate_containers(self): service = self.create_service('web') options = service._get_container_create_options({}, 1) original = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original]) assert set(service.duplicate_containers()) == set() options['name'] = 'temporary_container_name' duplicate = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original, duplicate]) assert set(service.duplicate_containers()) == set([duplicate]) def converge(service, strategy=ConvergenceStrategy.changed): """Create a converge plan from a strategy and execute the plan.""" plan = service.convergence_plan(strategy) return service.execute_convergence_plan(plan, timeout=1) class ConfigHashTest(DockerClientTestCase): def test_no_config_hash_when_one_off(self): web = self.create_service('web') container = web.create_container(one_off=True) assert LABEL_CONFIG_HASH not in container.labels def test_no_config_hash_when_overriding_options(self): web = self.create_service('web') container = web.create_container(environment={'FOO': '1'}) assert LABEL_CONFIG_HASH not in container.labels def test_config_hash_with_custom_labels(self): web = self.create_service('web', labels={'foo': '1'}) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels assert 'foo' in container.labels def test_config_hash_sticks_around(self): web = self.create_service('web', command=["top"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels web = self.create_service('web', command=["top", "-d", "1"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels
shin-/compose
tests/integration/service_test.py
tests/unit/cli/formatter_test.py
from __future__ import absolute_import from __future__ import unicode_literals from compose import utils class StreamOutputError(Exception): pass def write_to_stream(s, stream): try: stream.write(s) except UnicodeEncodeError: encoding = getattr(stream, 'encoding', 'ascii') stream.write(s.encode(encoding, errors='replace').decode(encoding)) def stream_output(output, stream): is_terminal = hasattr(stream, 'isatty') and stream.isatty() stream = utils.get_output_stream(stream) all_events = [] lines = {} diff = 0 for event in utils.json_stream(output): all_events.append(event) is_progress_event = 'progress' in event or 'progressDetail' in event if not is_progress_event: print_output_event(event, stream, is_terminal) stream.flush() continue if not is_terminal: continue # if it's a progress event and we have a terminal, then display the progress bars image_id = event.get('id') if not image_id: continue if image_id not in lines: lines[image_id] = len(lines) write_to_stream("\n", stream) diff = len(lines) - lines[image_id] # move cursor up `diff` rows write_to_stream("%c[%dA" % (27, diff), stream) print_output_event(event, stream, is_terminal) if 'id' in event: # move cursor back down write_to_stream("%c[%dB" % (27, diff), stream) stream.flush() return all_events def print_output_event(event, stream, is_terminal): if 'errorDetail' in event: raise StreamOutputError(event['errorDetail']['message']) terminator = '' if is_terminal and 'stream' not in event: # erase current line write_to_stream("%c[2K\r" % 27, stream) terminator = "\r" elif 'progressDetail' in event: return if 'time' in event: write_to_stream("[%s] " % event['time'], stream) if 'id' in event: write_to_stream("%s: " % event['id'], stream) if 'from' in event: write_to_stream("(from %s) " % event['from'], stream) status = event.get('status', '') if 'progress' in event: write_to_stream("%s %s%s" % (status, event['progress'], terminator), stream) elif 'progressDetail' in event: detail = event['progressDetail'] total = detail.get('total') if 'current' in detail and total: percentage = float(detail['current']) / float(total) * 100 write_to_stream('%s (%.1f%%)%s' % (status, percentage, terminator), stream) else: write_to_stream('%s%s' % (status, terminator), stream) elif 'stream' in event: write_to_stream("%s%s" % (event['stream'], terminator), stream) else: write_to_stream("%s%s\n" % (status, terminator), stream) def get_digest_from_pull(events): for event in events: status = event.get('status') if not status or 'Digest' not in status: continue _, digest = status.split(':', 1) return digest.strip() return None def get_digest_from_push(events): for event in events: digest = event.get('aux', {}).get('Digest') if digest: return digest return None
from __future__ import absolute_import from __future__ import unicode_literals import os import re import shutil import tempfile from distutils.spawn import find_executable from os import path import pytest from docker.errors import APIError from docker.errors import ImageNotFound from six import StringIO from six import text_type from .. import mock from .testcases import docker_client from .testcases import DockerClientTestCase from .testcases import get_links from .testcases import pull_busybox from .testcases import SWARM_SKIP_CONTAINERS_ALL from .testcases import SWARM_SKIP_CPU_SHARES from compose import __version__ from compose.config.types import MountSpec from compose.config.types import SecurityOpt from compose.config.types import VolumeFromSpec from compose.config.types import VolumeSpec from compose.const import IS_WINDOWS_PLATFORM from compose.const import LABEL_CONFIG_HASH from compose.const import LABEL_CONTAINER_NUMBER from compose.const import LABEL_ONE_OFF from compose.const import LABEL_PROJECT from compose.const import LABEL_SERVICE from compose.const import LABEL_VERSION from compose.container import Container from compose.errors import OperationFailedError from compose.parallel import ParallelStreamWriter from compose.project import OneOffFilter from compose.service import ConvergencePlan from compose.service import ConvergenceStrategy from compose.service import NetworkMode from compose.service import PidMode from compose.service import Service from compose.utils import parse_nanoseconds_int from tests.helpers import create_custom_host_file from tests.integration.testcases import is_cluster from tests.integration.testcases import no_cluster from tests.integration.testcases import v2_1_only from tests.integration.testcases import v2_2_only from tests.integration.testcases import v2_3_only from tests.integration.testcases import v2_only from tests.integration.testcases import v3_only def create_and_start_container(service, **override_options): container = service.create_container(**override_options) return service.start_container(container) class ServiceTest(DockerClientTestCase): def test_containers(self): foo = self.create_service('foo') bar = self.create_service('bar') create_and_start_container(foo) assert len(foo.containers()) == 1 assert foo.containers()[0].name == 'composetest_foo_1' assert len(bar.containers()) == 0 create_and_start_container(bar) create_and_start_container(bar) assert len(foo.containers()) == 1 assert len(bar.containers()) == 2 names = [c.name for c in bar.containers()] assert 'composetest_bar_1' in names assert 'composetest_bar_2' in names def test_containers_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert db.containers(stopped=True) == [] assert db.containers(one_off=OneOffFilter.only, stopped=True) == [container] def test_project_is_added_to_container_name(self): service = self.create_service('web') create_and_start_container(service) assert service.containers()[0].name == 'composetest_web_1' def test_create_container_with_one_off(self): db = self.create_service('db') container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_one_off_when_existing_container_is_running(self): db = self.create_service('db') db.start() container = db.create_container(one_off=True) assert container.name == 'composetest_db_run_1' def test_create_container_with_unspecified_volume(self): service = self.create_service('db', volumes=[VolumeSpec.parse('/var/db')]) container = service.create_container() service.start_container(container) assert container.get_mount('/var/db') def test_create_container_with_volume_driver(self): service = self.create_service('db', volume_driver='foodriver') container = service.create_container() service.start_container(container) assert 'foodriver' == container.get('HostConfig.VolumeDriver') @pytest.mark.skipif(SWARM_SKIP_CPU_SHARES, reason='Swarm --cpu-shares bug') def test_create_container_with_cpu_shares(self): service = self.create_service('db', cpu_shares=73) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuShares') == 73 def test_create_container_with_cpu_quota(self): service = self.create_service('db', cpu_quota=40000, cpu_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuQuota') == 40000 assert container.get('HostConfig.CpuPeriod') == 150000 @pytest.mark.xfail(raises=OperationFailedError, reason='not supported by kernel') def test_create_container_with_cpu_rt(self): service = self.create_service('db', cpu_rt_runtime=40000, cpu_rt_period=150000) container = service.create_container() container.start() assert container.get('HostConfig.CpuRealtimeRuntime') == 40000 assert container.get('HostConfig.CpuRealtimePeriod') == 150000 @v2_2_only() def test_create_container_with_cpu_count(self): self.require_api_version('1.25') service = self.create_service('db', cpu_count=2) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuCount') == 2 @v2_2_only() @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='cpu_percent is not supported for Linux') def test_create_container_with_cpu_percent(self): self.require_api_version('1.25') service = self.create_service('db', cpu_percent=12) container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpuPercent') == 12 @v2_2_only() def test_create_container_with_cpus(self): self.require_api_version('1.25') service = self.create_service('db', cpus=1) container = service.create_container() service.start_container(container) assert container.get('HostConfig.NanoCpus') == 1000000000 def test_create_container_with_shm_size(self): self.require_api_version('1.22') service = self.create_service('db', shm_size=67108864) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ShmSize') == 67108864 def test_create_container_with_init_bool(self): self.require_api_version('1.25') service = self.create_service('db', init=True) container = service.create_container() service.start_container(container) assert container.get('HostConfig.Init') is True @pytest.mark.xfail(True, reason='Option has been removed in Engine 17.06.0') def test_create_container_with_init_path(self): self.require_api_version('1.25') docker_init_path = find_executable('docker-init') service = self.create_service('db', init=docker_init_path) container = service.create_container() service.start_container(container) assert container.get('HostConfig.InitPath') == docker_init_path @pytest.mark.xfail(True, reason='Some kernels/configs do not support pids_limit') def test_create_container_with_pids_limit(self): self.require_api_version('1.23') service = self.create_service('db', pids_limit=10) container = service.create_container() service.start_container(container) assert container.get('HostConfig.PidsLimit') == 10 def test_create_container_with_extra_hosts_list(self): extra_hosts = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts) def test_create_container_with_extra_hosts_dicts(self): extra_hosts = {'somehost': '162.242.195.82', 'otherhost': '50.31.209.229'} extra_hosts_list = ['somehost:162.242.195.82', 'otherhost:50.31.209.229'] service = self.create_service('db', extra_hosts=extra_hosts) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts_list) def test_create_container_with_cpu_set(self): service = self.create_service('db', cpuset='0') container = service.create_container() service.start_container(container) assert container.get('HostConfig.CpusetCpus') == '0' def test_create_container_with_read_only_root_fs(self): read_only = True service = self.create_service('db', read_only=read_only) container = service.create_container() service.start_container(container) assert container.get('HostConfig.ReadonlyRootfs') == read_only def test_create_container_with_blkio_config(self): blkio_config = { 'weight': 300, 'weight_device': [{'path': '/dev/sda', 'weight': 200}], 'device_read_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024 * 100}], 'device_read_iops': [{'path': '/dev/sda', 'rate': 1000}], 'device_write_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024}], 'device_write_iops': [{'path': '/dev/sda', 'rate': 800}] } service = self.create_service('web', blkio_config=blkio_config) container = service.create_container() assert container.get('HostConfig.BlkioWeight') == 300 assert container.get('HostConfig.BlkioWeightDevice') == [{ 'Path': '/dev/sda', 'Weight': 200 }] assert container.get('HostConfig.BlkioDeviceReadBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 * 100 }] assert container.get('HostConfig.BlkioDeviceWriteBps') == [{ 'Path': '/dev/sda', 'Rate': 1024 * 1024 }] assert container.get('HostConfig.BlkioDeviceReadIOps') == [{ 'Path': '/dev/sda', 'Rate': 1000 }] assert container.get('HostConfig.BlkioDeviceWriteIOps') == [{ 'Path': '/dev/sda', 'Rate': 800 }] def test_create_container_with_security_opt(self): security_opt = [SecurityOpt.parse('label:disable')] service = self.create_service('db', security_opt=security_opt) container = service.create_container() service.start_container(container) assert set(container.get('HostConfig.SecurityOpt')) == set([o.repr() for o in security_opt]) @pytest.mark.xfail(True, reason='Not supported on most drivers') def test_create_container_with_storage_opt(self): storage_opt = {'size': '1G'} service = self.create_service('db', storage_opt=storage_opt) container = service.create_container() service.start_container(container) assert container.get('HostConfig.StorageOpt') == storage_opt def test_create_container_with_oom_kill_disable(self): self.require_api_version('1.20') service = self.create_service('db', oom_kill_disable=True) container = service.create_container() assert container.get('HostConfig.OomKillDisable') is True def test_create_container_with_mac_address(self): service = self.create_service('db', mac_address='02:42:ac:11:65:43') container = service.create_container() service.start_container(container) assert container.inspect()['Config']['MacAddress'] == '02:42:ac:11:65:43' def test_create_container_with_device_cgroup_rules(self): service = self.create_service('db', device_cgroup_rules=['c 7:128 rwm']) container = service.create_container() assert container.get('HostConfig.DeviceCgroupRules') == ['c 7:128 rwm'] def test_create_container_with_specified_volume(self): host_path = '/tmp/host-path' container_path = '/container-path' service = self.create_service( 'db', volumes=[VolumeSpec(host_path, container_path, 'rw')]) container = service.create_container() service.start_container(container) assert container.get_mount(container_path) # Match the last component ("host-path"), because boot2docker symlinks /tmp actual_host_path = container.get_mount(container_path)['Source'] assert path.basename(actual_host_path) == path.basename(host_path), ( "Last component differs: %s, %s" % (actual_host_path, host_path) ) @v2_3_only() def test_create_container_with_host_mount(self): host_path = '/tmp/host-path' container_path = '/container-path' create_custom_host_file(self.client, path.join(host_path, 'a.txt'), 'test') service = self.create_service( 'db', volumes=[ MountSpec(type='bind', source=host_path, target=container_path, read_only=True) ] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert path.basename(mount['Source']) == path.basename(host_path) assert mount['RW'] is False @v2_3_only() def test_create_container_with_tmpfs_mount(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Type'] == 'tmpfs' @v2_3_only() def test_create_container_with_tmpfs_mount_tmpfs_size(self): container_path = '/container-tmpfs' service = self.create_service( 'db', volumes=[MountSpec(type='tmpfs', target=container_path, tmpfs={'size': 5368709})] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount print(container.dictionary) assert mount['Type'] == 'tmpfs' assert container.get('HostConfig.Mounts')[0]['TmpfsOptions'] == { 'SizeBytes': 5368709 } @v2_3_only() def test_create_container_with_volume_mount(self): container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = self.create_service( 'db', volumes=[MountSpec(type='volume', source=volume_name, target=container_path)] ) container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_mount(self): # Ensure mounts are converted to volumes if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-volume' volume_name = 'composetest_abcde' self.client.create_volume(volume_name) service = Service('db', client=client, volumes=[ MountSpec(type='volume', source=volume_name, target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount assert mount['Name'] == volume_name @v3_only() def test_create_container_with_legacy_tmpfs_mount(self): # Ensure tmpfs mounts are converted to tmpfs entries if API version < 1.30 # Needed to support long syntax in the 3.2 format client = docker_client({}, version='1.25') container_path = '/container-tmpfs' service = Service('db', client=client, volumes=[ MountSpec(type='tmpfs', target=container_path) ], image='busybox:latest', command=['top'], project='composetest') container = service.create_container() service.start_container(container) mount = container.get_mount(container_path) assert mount is None assert container_path in container.get('HostConfig.Tmpfs') def test_create_container_with_healthcheck_config(self): one_second = parse_nanoseconds_int('1s') healthcheck = { 'test': ['true'], 'interval': 2 * one_second, 'timeout': 5 * one_second, 'retries': 5, 'start_period': 2 * one_second } service = self.create_service('db', healthcheck=healthcheck) container = service.create_container() remote_healthcheck = container.get('Config.Healthcheck') assert remote_healthcheck['Test'] == healthcheck['test'] assert remote_healthcheck['Interval'] == healthcheck['interval'] assert remote_healthcheck['Timeout'] == healthcheck['timeout'] assert remote_healthcheck['Retries'] == healthcheck['retries'] assert remote_healthcheck['StartPeriod'] == healthcheck['start_period'] def test_recreate_preserves_volume_with_trailing_slash(self): """When the Compose file specifies a trailing slash in the container path, make sure we copy the volume over when recreating. """ service = self.create_service('data', volumes=[VolumeSpec.parse('/data/')]) old_container = create_and_start_container(service) volume_path = old_container.get_mount('/data')['Source'] new_container = service.recreate_container(old_container) assert new_container.get_mount('/data')['Source'] == volume_path def test_duplicate_volume_trailing_slash(self): """ When an image specifies a volume, and the Compose file specifies a host path but adds a trailing slash, make sure that we don't create duplicate binds. """ host_path = '/tmp/data' container_path = '/data' volumes = [VolumeSpec.parse('{}:{}/'.format(host_path, container_path))] tmp_container = self.client.create_container( 'busybox', 'true', volumes={container_path: {}}, labels={'com.docker.compose.test_image': 'true'}, host_config={} ) image = self.client.commit(tmp_container)['Id'] service = self.create_service('db', image=image, volumes=volumes) old_container = create_and_start_container(service) assert old_container.get('Config.Volumes') == {container_path: {}} service = self.create_service('db', image=image, volumes=volumes) new_container = service.recreate_container(old_container) assert new_container.get('Config.Volumes') == {container_path: {}} assert service.containers(stopped=False) == [new_container] def test_create_container_with_volumes_from(self): volume_service = self.create_service('data') volume_container_1 = volume_service.create_container() volume_container_2 = Container.create( self.client, image='busybox:latest', command=["top"], labels={LABEL_PROJECT: 'composetest'}, host_config={}, environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_service = self.create_service( 'host', volumes_from=[ VolumeFromSpec(volume_service, 'rw', 'service'), VolumeFromSpec(volume_container_2, 'rw', 'container') ], environment=['affinity:container=={}'.format(volume_container_1.id)], ) host_container = host_service.create_container() host_service.start_container(host_container) assert volume_container_1.id + ':rw' in host_container.get('HostConfig.VolumesFrom') assert volume_container_2.id + ':rw' in host_container.get('HostConfig.VolumesFrom') def test_execute_convergence_plan_recreate(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1'] ) old_container = service.create_container() assert old_container.get('Config.Entrypoint') == ['top'] assert old_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=1' in old_container.get('Config.Env') assert old_container.name == 'composetest_db_1' service.start_container(old_container) old_container.inspect() # reload volume data volume_path = old_container.get_mount('/etc')['Source'] num_containers_before = len(self.client.containers(all=True)) service.options['environment']['FOO'] = '2' new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert new_container.get('Config.Entrypoint') == ['top'] assert new_container.get('Config.Cmd') == ['-d', '1'] assert 'FOO=2' in new_container.get('Config.Env') assert new_container.name == 'composetest_db_1' assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ( 'affinity:container==%s' % old_container.id in new_container.get('Config.Env') ) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert old_container.get('Node.Name') == new_container.get('Node.Name') assert len(self.client.containers(all=True)) == num_containers_before assert old_container.id != new_container.id with pytest.raises(APIError): self.client.inspect_container(old_container.id) def test_execute_convergence_plan_recreate_change_mount_target(self): service = self.create_service( 'db', volumes=[MountSpec(target='/app1', type='volume')], entrypoint=['top'], command=['-d', '1'] ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/app1'] ) service.options['volumes'] = [MountSpec(target='/app2', type='volume')] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/app2'] ) def test_execute_convergence_plan_recreate_twice(self): service = self.create_service( 'db', volumes=[VolumeSpec.parse('/etc')], entrypoint=['top'], command=['-d', '1']) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container])) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container @v2_3_only() def test_execute_convergence_plan_recreate_twice_with_mount(self): service = self.create_service( 'db', volumes=[MountSpec(target='/etc', type='volume')], entrypoint=['top'], command=['-d', '1'] ) orig_container = service.create_container() service.start_container(orig_container) orig_container.inspect() # reload volume data volume_path = orig_container.get_mount('/etc')['Source'] # Do this twice to reproduce the bug for _ in range(2): new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [orig_container]) ) assert new_container.get_mount('/etc')['Source'] == volume_path if not is_cluster(self.client): assert ('affinity:container==%s' % orig_container.id in new_container.get('Config.Env')) else: # In Swarm, the env marker is consumed and the container should be deployed # on the same node. assert orig_container.get('Node.Name') == new_container.get('Node.Name') orig_container = new_container def test_execute_convergence_plan_when_containers_are_stopped(self): service = self.create_service( 'db', environment={'FOO': '1'}, volumes=[VolumeSpec.parse('/var/db')], entrypoint=['top'], command=['-d', '1'] ) service.create_container() containers = service.containers(stopped=True) assert len(containers) == 1 container, = containers assert not container.is_running service.execute_convergence_plan(ConvergencePlan('start', [container])) containers = service.containers() assert len(containers) == 1 container.inspect() assert container == containers[0] assert container.is_running def test_execute_convergence_plan_with_image_declared_volume(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_with_image_declared_volume_renew(self): service = Service( project='composetest', name='db', client=self.client, build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_when_image_volume_masks_config(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, ) old_container = create_and_start_container(service) assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] volume_path = old_container.get_mount('/data')['Source'] service.options['volumes'] = [VolumeSpec.parse('/tmp:/data')] with mock.patch('compose.service.log') as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) mock_log.warn.assert_called_once_with(mock.ANY) _, args, kwargs = mock_log.warn.mock_calls[0] assert "Service \"db\" is using volume \"/data\" from the previous container" in args[0] assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_execute_convergence_plan_when_host_volume_is_removed(self): host_path = '/tmp/host-path' service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}, volumes=[VolumeSpec(host_path, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) service.options['volumes'] = [] with mock.patch('compose.service.log', autospec=True) as mock_log: new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container])) assert not mock_log.warn.called assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != host_path def test_execute_convergence_plan_anonymous_volume_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_anonymous_volume_recreate_then_renew(self): service = self.create_service( 'db', image='busybox', volumes=[VolumeSpec(None, '/data', 'rw')]) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] mid_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), ) assert ( [mount['Destination'] for mount in mid_container.get('Mounts')] == ['/data'] ) assert mid_container.get_mount('/data')['Source'] == volume_path new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [mid_container]), renew_anonymous_volumes=True ) assert ( [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] ) assert new_container.get_mount('/data')['Source'] != volume_path def test_execute_convergence_plan_without_start(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) containers = service.execute_convergence_plan(ConvergencePlan('create', []), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running containers = service.execute_convergence_plan( ConvergencePlan('recreate', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running service.execute_convergence_plan(ConvergencePlan('start', containers), start=False) service_containers = service.containers(stopped=True) assert len(service_containers) == 1 assert not service_containers[0].is_running def test_execute_convergence_plan_image_with_volume_is_removed(self): service = self.create_service( 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'} ) old_container = create_and_start_container(service) assert ( [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data'] ) volume_path = old_container.get_mount('/data')['Source'] old_container.stop() self.client.remove_image(service.image(), force=True) service.ensure_image_exists() with pytest.raises(ImageNotFound): service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]) ) old_container.inspect() # retrieve new name from server new_container, = service.execute_convergence_plan( ConvergencePlan('recreate', [old_container]), reset_container_image=True ) assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data'] assert new_container.get_mount('/data')['Source'] == volume_path def test_start_container_passes_through_options(self): db = self.create_service('db') create_and_start_container(db, environment={'FOO': 'BAR'}) assert db.containers()[0].environment['FOO'] == 'BAR' def test_start_container_inherits_options_from_constructor(self): db = self.create_service('db', environment={'FOO': 'BAR'}) create_and_start_container(db) assert db.containers()[0].environment['FOO'] == 'BAR' @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links(self): db = self.create_service('db') web = self.create_service('web', links=[(db, None)]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_creates_links_with_names(self): db = self.create_service('db') web = self.create_service('web', links=[(db, 'custom_link_name')]) create_and_start_container(db) create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'custom_link_name' ]) @no_cluster('No legacy links support in Swarm') def test_start_container_with_external_links(self): db = self.create_service('db') web = self.create_service('web', external_links=['composetest_db_1', 'composetest_db_2', 'composetest_db_3:db_3']) for _ in range(3): create_and_start_container(db) create_and_start_container(web) assert set(get_links(web.containers()[0])) == set([ 'composetest_db_1', 'composetest_db_2', 'db_3' ]) @no_cluster('No legacy links support in Swarm') def test_start_normal_container_does_not_create_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db) assert set(get_links(c)) == set([]) @no_cluster('No legacy links support in Swarm') def test_start_one_off_container_creates_links_to_its_own_service(self): db = self.create_service('db') create_and_start_container(db) create_and_start_container(db) c = create_and_start_container(db, one_off=OneOffFilter.only) assert set(get_links(c)) == set([ 'composetest_db_1', 'db_1', 'composetest_db_2', 'db_2', 'db' ]) def test_start_container_builds_images(self): service = Service( name='test', client=self.client, build={'context': 'tests/fixtures/simple-dockerfile'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() assert len(self.client.images(name='composetest_test')) >= 1 def test_start_container_uses_tagged_image_if_it_exists(self): self.check_build('tests/fixtures/simple-dockerfile', tag='composetest_test') service = Service( name='test', client=self.client, build={'context': 'this/does/not/exist/and/will/throw/error'}, project='composetest', ) container = create_and_start_container(service) container.wait() assert b'success' in container.logs() def test_start_container_creates_ports(self): service = self.create_service('web', ports=[8000]) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/tcp'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] != '8000' def test_build(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('web', build={'context': base_dir}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_non_ascii_filename(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") with open(os.path.join(base_dir.encode('utf8'), b'foo\xE2bar'), 'w') as f: f.write("hello world\n") service = self.create_service('web', build={'context': text_type(base_dir)}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert self.client.inspect_image('composetest_web') def test_build_with_image_name(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") image_name = 'examples/composetest:latest' self.addCleanup(self.client.remove_image, image_name) self.create_service('web', build={'context': base_dir}, image=image_name).build() assert self.client.inspect_image(image_name) def test_build_with_git_url(self): build_url = "https://github.com/dnephin/docker-build-from-url.git" service = self.create_service('buildwithurl', build={'context': build_url}) self.addCleanup(self.client.remove_image, service.image_name) service.build() assert service.image() def test_build_with_build_args(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=1" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_args_override(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") f.write("ARG build_version\n") f.write("RUN echo ${build_version}\n") service = self.create_service('buildwithargs', build={'context': text_type(base_dir), 'args': {"build_version": "1"}}) service.build(build_args_override={'build_version': '2'}) self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert "build_version=2" in service.image()['ContainerConfig']['Cmd'] def test_build_with_build_labels(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('buildlabels', build={ 'context': text_type(base_dir), 'labels': {'com.docker.compose.test': 'true'} }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test'] == 'true' @no_cluster('Container networks not on Swarm') def test_build_with_network(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') f.write('RUN ping -c1 google.local\n') net_container = self.client.create_container( 'busybox', 'top', host_config=self.client.create_host_config( extra_hosts={'google.local': '127.0.0.1'} ), name='composetest_build_network' ) self.addCleanup(self.client.remove_container, net_container, force=True) self.client.start(net_container) service = self.create_service('buildwithnet', build={ 'context': text_type(base_dir), 'network': 'container:{}'.format(net_container['Id']) }) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @v2_3_only() @no_cluster('Not supported on UCP 2.2.0-beta1') # FIXME: remove once support is added def test_build_with_target(self): self.require_api_version('1.30') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox as one\n') f.write('LABEL com.docker.compose.test=true\n') f.write('LABEL com.docker.compose.test.target=one\n') f.write('FROM busybox as two\n') f.write('LABEL com.docker.compose.test.target=two\n') service = self.create_service('buildtarget', build={ 'context': text_type(base_dir), 'target': 'one' }) service.build() assert service.image() assert service.image()['Config']['Labels']['com.docker.compose.test.target'] == 'one' @v2_3_only() def test_build_with_extra_hosts(self): self.require_api_version('1.27') base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'RUN ping -c1 foobar', 'RUN ping -c1 baz', ])) service = self.create_service('build_extra_hosts', build={ 'context': text_type(base_dir), 'extra_hosts': { 'foobar': '127.0.0.1', 'baz': '127.0.0.1' } }) service.build() assert service.image() def test_build_with_gzip(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('\n'.join([ 'FROM busybox', 'COPY . /src', 'RUN cat /src/hello.txt' ])) with open(os.path.join(base_dir, 'hello.txt'), 'w') as f: f.write('hello world\n') service = self.create_service('build_gzip', build={ 'context': text_type(base_dir), }) service.build(gzip=True) assert service.image() @v2_1_only() def test_build_with_isolation(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write('FROM busybox\n') service = self.create_service('build_isolation', build={ 'context': text_type(base_dir), 'isolation': 'default', }) service.build() assert service.image() def test_start_container_stays_unprivileged(self): service = self.create_service('web') container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is False def test_start_container_becomes_privileged(self): service = self.create_service('web', privileged=True) container = create_and_start_container(service).inspect() assert container['HostConfig']['Privileged'] is True def test_expose_does_not_publish_ports(self): service = self.create_service('web', expose=["8000"]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports'] == {'8000/tcp': None} def test_start_container_creates_port_with_explicit_protocol(self): service = self.create_service('web', ports=['8000/udp']) container = create_and_start_container(service).inspect() assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/udp'] def test_start_container_creates_fixed_external_ports(self): service = self.create_service('web', ports=['8000:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8000' def test_start_container_creates_fixed_external_ports_when_it_is_different_to_internal_port(self): service = self.create_service('web', ports=['8001:8000']) container = create_and_start_container(service).inspect() assert '8000/tcp' in container['NetworkSettings']['Ports'] assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8001' def test_port_with_explicit_interface(self): service = self.create_service('web', ports=[ '127.0.0.1:8001:8000', '0.0.0.0:9001:9000/udp', ]) container = create_and_start_container(service).inspect() assert container['NetworkSettings']['Ports']['8000/tcp'] == [{ 'HostIp': '127.0.0.1', 'HostPort': '8001', }] assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostPort'] == '9001' if not is_cluster(self.client): assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostIp'] == '0.0.0.0' # self.assertEqual(container['NetworkSettings']['Ports'], { # '8000/tcp': [ # { # 'HostIp': '127.0.0.1', # 'HostPort': '8001', # }, # ], # '9000/udp': [ # { # 'HostIp': '0.0.0.0', # 'HostPort': '9001', # }, # ], # }) def test_create_with_image_id(self): # Get image id for the current busybox:latest pull_busybox(self.client) image_id = self.client.inspect_image('busybox:latest')['Id'][:12] service = self.create_service('foo', image=image_id) service.create_container() def test_scale(self): service = self.create_service('web') service.scale(1) assert len(service.containers()) == 1 # Ensure containers don't have stdout or stdin connected container = service.containers()[0] config = container.inspect()['Config'] assert not config['AttachStderr'] assert not config['AttachStdout'] assert not config['AttachStdin'] service.scale(3) assert len(service.containers()) == 3 service.scale(1) assert len(service.containers()) == 1 service.scale(0) assert len(service.containers()) == 0 @pytest.mark.skipif( SWARM_SKIP_CONTAINERS_ALL, reason='Swarm /containers/json bug' ) def test_scale_with_stopped_containers(self): """ Given there are some stopped containers and scale is called with a desired number that is the same as the number of stopped containers, test that those containers are restarted and not removed/recreated. """ service = self.create_service('web') next_number = service._next_container_number() valid_numbers = [next_number, next_number + 1] service.create_container(number=next_number) service.create_container(number=next_number + 1) ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) for container in service.containers(): assert container.is_running assert container.number in valid_numbers captured_output = mock_stderr.getvalue() assert 'Creating' not in captured_output assert 'Starting' in captured_output def test_scale_with_stopped_containers_and_needing_creation(self): """ Given there are some stopped containers and scale is called with a desired number that is greater than the number of stopped containers, test that those containers are restarted and required number are created. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) for container in service.containers(): assert not container.is_running ParallelStreamWriter.instance = None with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: service.scale(2) assert len(service.containers()) == 2 for container in service.containers(): assert container.is_running captured_output = mock_stderr.getvalue() assert 'Creating' in captured_output assert 'Starting' in captured_output def test_scale_with_api_error(self): """Test that when scaling if the API returns an error, that error is handled and the remaining threads continue. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=APIError( message="testing", response={}, explanation="Boom")): with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr: with pytest.raises(OperationFailedError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running assert ( "ERROR: for composetest_web_2 Cannot create container for service" " web: Boom" in mock_stderr.getvalue() ) def test_scale_with_unexpected_exception(self): """Test that when scaling if the API returns an error, that is not of type APIError, that error is re-raised. """ service = self.create_service('web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch( 'compose.container.Container.create', side_effect=ValueError("BOOM") ): with pytest.raises(ValueError): service.scale(3) assert len(service.containers()) == 1 assert service.containers()[0].is_running @mock.patch('compose.service.log') def test_scale_with_desired_number_already_achieved(self, mock_log): """ Test that calling scale with a desired number that is equal to the number of containers already running results in no change. """ service = self.create_service('web') next_number = service._next_container_number() container = service.create_container(number=next_number, quiet=True) container.start() container.inspect() assert container.is_running assert len(service.containers()) == 1 service.scale(1) assert len(service.containers()) == 1 container.inspect() assert container.is_running captured_output = mock_log.info.call_args[0] assert 'Desired container number already achieved' in captured_output @mock.patch('compose.service.log') def test_scale_with_custom_container_name_outputs_warning(self, mock_log): """Test that calling scale on a service that has a custom container name results in warning output. """ service = self.create_service('app', container_name='custom-container') assert service.custom_container_name == 'custom-container' with pytest.raises(OperationFailedError): service.scale(3) captured_output = mock_log.warn.call_args[0][0] assert len(service.containers()) == 1 assert "Remove the custom name to scale the service." in captured_output def test_scale_sets_ports(self): service = self.create_service('web', ports=['8000']) service.scale(2) containers = service.containers() assert len(containers) == 2 for container in containers: assert list(container.get('HostConfig.PortBindings')) == ['8000/tcp'] def test_scale_with_immediate_exit(self): service = self.create_service('web', image='busybox', command='true') service.scale(2) assert len(service.containers(stopped=True)) == 2 def test_network_mode_none(self): service = self.create_service('web', network_mode=NetworkMode('none')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'none' def test_network_mode_bridged(self): service = self.create_service('web', network_mode=NetworkMode('bridge')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'bridge' def test_network_mode_host(self): service = self.create_service('web', network_mode=NetworkMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.NetworkMode') == 'host' def test_pid_mode_none_defined(self): service = self.create_service('web', pid_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == '' def test_pid_mode_host(self): service = self.create_service('web', pid_mode=PidMode('host')) container = create_and_start_container(service) assert container.get('HostConfig.PidMode') == 'host' @v2_1_only() def test_userns_mode_none_defined(self): service = self.create_service('web', userns_mode=None) container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == '' @v2_1_only() def test_userns_mode_host(self): service = self.create_service('web', userns_mode='host') container = create_and_start_container(service) assert container.get('HostConfig.UsernsMode') == 'host' def test_dns_no_value(self): service = self.create_service('web') container = create_and_start_container(service) assert container.get('HostConfig.Dns') is None def test_dns_list(self): service = self.create_service('web', dns=['8.8.8.8', '9.9.9.9']) container = create_and_start_container(service) assert container.get('HostConfig.Dns') == ['8.8.8.8', '9.9.9.9'] def test_mem_swappiness(self): service = self.create_service('web', mem_swappiness=11) container = create_and_start_container(service) assert container.get('HostConfig.MemorySwappiness') == 11 def test_mem_reservation(self): service = self.create_service('web', mem_reservation='20m') container = create_and_start_container(service) assert container.get('HostConfig.MemoryReservation') == 20 * 1024 * 1024 def test_restart_always_value(self): service = self.create_service('web', restart={'Name': 'always'}) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'always' def test_oom_score_adj_value(self): service = self.create_service('web', oom_score_adj=500) container = create_and_start_container(service) assert container.get('HostConfig.OomScoreAdj') == 500 def test_group_add_value(self): service = self.create_service('web', group_add=["root", "1"]) container = create_and_start_container(service) host_container_groupadd = container.get('HostConfig.GroupAdd') assert "root" in host_container_groupadd assert "1" in host_container_groupadd def test_dns_opt_value(self): service = self.create_service('web', dns_opt=["use-vc", "no-tld-query"]) container = create_and_start_container(service) dns_opt = container.get('HostConfig.DnsOptions') assert 'use-vc' in dns_opt assert 'no-tld-query' in dns_opt def test_restart_on_failure_value(self): service = self.create_service('web', restart={ 'Name': 'on-failure', 'MaximumRetryCount': 5 }) container = create_and_start_container(service) assert container.get('HostConfig.RestartPolicy.Name') == 'on-failure' assert container.get('HostConfig.RestartPolicy.MaximumRetryCount') == 5 def test_cap_add_list(self): service = self.create_service('web', cap_add=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapAdd') == ['SYS_ADMIN', 'NET_ADMIN'] def test_cap_drop_list(self): service = self.create_service('web', cap_drop=['SYS_ADMIN', 'NET_ADMIN']) container = create_and_start_container(service) assert container.get('HostConfig.CapDrop') == ['SYS_ADMIN', 'NET_ADMIN'] def test_dns_search(self): service = self.create_service('web', dns_search=['dc1.example.com', 'dc2.example.com']) container = create_and_start_container(service) assert container.get('HostConfig.DnsSearch') == ['dc1.example.com', 'dc2.example.com'] @v2_only() def test_tmpfs(self): service = self.create_service('web', tmpfs=['/run']) container = create_and_start_container(service) assert container.get('HostConfig.Tmpfs') == {'/run': ''} def test_working_dir_param(self): service = self.create_service('container', working_dir='/working/dir/sample') container = service.create_container() assert container.get('Config.WorkingDir') == '/working/dir/sample' def test_split_env(self): service = self.create_service( 'web', environment=['NORMAL=F1', 'CONTAINS_EQUALS=F=2', 'TRAILING_EQUALS=']) env = create_and_start_container(service).environment for k, v in {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''}.items(): assert env[k] == v def test_env_from_file_combined_with_env(self): service = self.create_service( 'web', environment=['ONE=1', 'TWO=2', 'THREE=3'], env_file=['tests/fixtures/env/one.env', 'tests/fixtures/env/two.env']) env = create_and_start_container(service).environment for k, v in { 'ONE': '1', 'TWO': '2', 'THREE': '3', 'FOO': 'baz', 'DOO': 'dah' }.items(): assert env[k] == v @v3_only() def test_build_with_cachefrom(self): base_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base_dir) with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f: f.write("FROM busybox\n") service = self.create_service('cache_from', build={'context': base_dir, 'cache_from': ['build1']}) service.build() self.addCleanup(self.client.remove_image, service.image_name) assert service.image() @mock.patch.dict(os.environ) def test_resolve_env(self): os.environ['FILE_DEF'] = 'E1' os.environ['FILE_DEF_EMPTY'] = 'E2' os.environ['ENV_DEF'] = 'E3' service = self.create_service( 'web', environment={ 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': None, 'NO_DEF': None } ) env = create_and_start_container(service).environment for k, v in { 'FILE_DEF': 'F1', 'FILE_DEF_EMPTY': '', 'ENV_DEF': 'E3', 'NO_DEF': None }.items(): assert env[k] == v def test_with_high_enough_api_version_we_get_default_network_mode(self): # TODO: remove this test once minimum docker version is 1.8.x with mock.patch.object(self.client, '_version', '1.20'): service = self.create_service('web') service_config = service._get_container_host_config({}) assert service_config['NetworkMode'] == 'default' def test_labels(self): labels_dict = { 'com.example.description': "Accounting webapp", 'com.example.department': "Finance", 'com.example.label-with-empty-value': "", } compose_labels = { LABEL_CONTAINER_NUMBER: '1', LABEL_ONE_OFF: 'False', LABEL_PROJECT: 'composetest', LABEL_SERVICE: 'web', LABEL_VERSION: __version__, } expected = dict(labels_dict, **compose_labels) service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for pair in expected.items(): assert pair in labels def test_empty_labels(self): labels_dict = {'foo': '', 'bar': ''} service = self.create_service('web', labels=labels_dict) labels = create_and_start_container(service).labels.items() for name in labels_dict: assert (name, '') in labels def test_stop_signal(self): stop_signal = 'SIGINT' service = self.create_service('web', stop_signal=stop_signal) container = create_and_start_container(service) assert container.stop_signal == stop_signal def test_custom_container_name(self): service = self.create_service('web', container_name='my-web-container') assert service.custom_container_name == 'my-web-container' container = create_and_start_container(service) assert container.name == 'my-web-container' one_off_container = service.create_container(one_off=True) assert one_off_container.name != 'my-web-container' @pytest.mark.skipif(True, reason="Broken on 1.11.0 - 17.03.0") def test_log_drive_invalid(self): service = self.create_service('web', logging={'driver': 'xxx'}) expected_error_msg = "logger: no log driver named 'xxx' is registered" with pytest.raises(APIError) as excinfo: create_and_start_container(service) assert re.search(expected_error_msg, excinfo.value) def test_log_drive_empty_default_jsonfile(self): service = self.create_service('web') log_config = create_and_start_container(service).log_config assert 'json-file' == log_config['Type'] assert not log_config['Config'] def test_log_drive_none(self): service = self.create_service('web', logging={'driver': 'none'}) log_config = create_and_start_container(service).log_config assert 'none' == log_config['Type'] assert not log_config['Config'] def test_devices(self): service = self.create_service('web', devices=["/dev/random:/dev/mapped-random"]) device_config = create_and_start_container(service).get('HostConfig.Devices') device_dict = { 'PathOnHost': '/dev/random', 'CgroupPermissions': 'rwm', 'PathInContainer': '/dev/mapped-random' } assert 1 == len(device_config) assert device_dict == device_config[0] def test_duplicate_containers(self): service = self.create_service('web') options = service._get_container_create_options({}, 1) original = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original]) assert set(service.duplicate_containers()) == set() options['name'] = 'temporary_container_name' duplicate = Container.create(service.client, **options) assert set(service.containers(stopped=True)) == set([original, duplicate]) assert set(service.duplicate_containers()) == set([duplicate]) def converge(service, strategy=ConvergenceStrategy.changed): """Create a converge plan from a strategy and execute the plan.""" plan = service.convergence_plan(strategy) return service.execute_convergence_plan(plan, timeout=1) class ConfigHashTest(DockerClientTestCase): def test_no_config_hash_when_one_off(self): web = self.create_service('web') container = web.create_container(one_off=True) assert LABEL_CONFIG_HASH not in container.labels def test_no_config_hash_when_overriding_options(self): web = self.create_service('web') container = web.create_container(environment={'FOO': '1'}) assert LABEL_CONFIG_HASH not in container.labels def test_config_hash_with_custom_labels(self): web = self.create_service('web', labels={'foo': '1'}) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels assert 'foo' in container.labels def test_config_hash_sticks_around(self): web = self.create_service('web', command=["top"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels web = self.create_service('web', command=["top", "-d", "1"]) container = converge(web)[0] assert LABEL_CONFIG_HASH in container.labels
shin-/compose
tests/integration/service_test.py
compose/progress_stream.py
# -*- coding: utf-8 -*- from datetime import datetime import hashlib import os import re import struct def hash_opensubtitles(video_path): """Compute a hash using OpenSubtitles' algorithm. :param str video_path: path of the video. :return: the hash. :rtype: str """ bytesize = struct.calcsize(b'<q') with open(video_path, 'rb') as f: filesize = os.path.getsize(video_path) filehash = filesize if filesize < 65536 * 2: return for _ in range(65536 // bytesize): filebuffer = f.read(bytesize) (l_value,) = struct.unpack(b'<q', filebuffer) filehash += l_value filehash &= 0xFFFFFFFFFFFFFFFF # to remain as 64bit number f.seek(max(0, filesize - 65536), 0) for _ in range(65536 // bytesize): filebuffer = f.read(bytesize) (l_value,) = struct.unpack(b'<q', filebuffer) filehash += l_value filehash &= 0xFFFFFFFFFFFFFFFF returnedhash = '%016x' % filehash return returnedhash def hash_thesubdb(video_path): """Compute a hash using TheSubDB's algorithm. :param str video_path: path of the video. :return: the hash. :rtype: str """ readsize = 64 * 1024 if os.path.getsize(video_path) < readsize: return with open(video_path, 'rb') as f: data = f.read(readsize) f.seek(-readsize, os.SEEK_END) data += f.read(readsize) return hashlib.md5(data).hexdigest() def hash_napiprojekt(video_path): """Compute a hash using NapiProjekt's algorithm. :param str video_path: path of the video. :return: the hash. :rtype: str """ readsize = 1024 * 1024 * 10 with open(video_path, 'rb') as f: data = f.read(readsize) return hashlib.md5(data).hexdigest() def hash_shooter(video_path): """Compute a hash using Shooter's algorithm :param string video_path: path of the video :return: the hash :rtype: string """ filesize = os.path.getsize(video_path) readsize = 4096 if os.path.getsize(video_path) < readsize * 2: return None offsets = (readsize, filesize // 3 * 2, filesize // 3, filesize - readsize * 2) filehash = [] with open(video_path, 'rb') as f: for offset in offsets: f.seek(offset) filehash.append(hashlib.md5(f.read(readsize)).hexdigest()) return ';'.join(filehash) def sanitize(string, ignore_characters=None): """Sanitize a string to strip special characters. :param str string: the string to sanitize. :param set ignore_characters: characters to ignore. :return: the sanitized string. :rtype: str """ # only deal with strings if string is None: return ignore_characters = ignore_characters or set() # replace some characters with one space characters = {'-', ':', '(', ')', '.'} - ignore_characters if characters: string = re.sub(r'[%s]' % re.escape(''.join(characters)), ' ', string) # remove some characters characters = {'\''} - ignore_characters if characters: string = re.sub(r'[%s]' % re.escape(''.join(characters)), '', string) # replace multiple spaces with one string = re.sub(r'\s+', ' ', string) # strip and lower case return string.strip().lower() def sanitize_release_group(string): """Sanitize a `release_group` string to remove content in square brackets. :param str string: the release group to sanitize. :return: the sanitized release group. :rtype: str """ # only deal with strings if string is None: return # remove content in square brackets string = re.sub(r'\[\w+\]', '', string) # strip and upper case return string.strip().upper() def timestamp(date): """Get the timestamp of the `date`, python2/3 compatible :param datetime.datetime date: the utc date. :return: the timestamp of the date. :rtype: float """ return (date - datetime(1970, 1, 1)).total_seconds()
# -*- coding: utf-8 -*- from datetime import datetime, timedelta import pytest from six import text_type as str try: from unittest.mock import Mock except ImportError: from mock import Mock from subliminal.utils import sanitize, timestamp from subliminal.video import Episode, Movie, Video def test_video_exists_age(movies, tmpdir, monkeypatch): monkeypatch.chdir(str(tmpdir)) video = movies['man_of_steel'] tmpdir.ensure(video.name).setmtime(timestamp(datetime.utcnow() - timedelta(days=3))) assert video.exists assert timedelta(days=3) < video.age < timedelta(days=3, seconds=1) def test_video_age(movies): assert movies['man_of_steel'].age == timedelta() def test_video_fromguess_episode(episodes, monkeypatch): guess = {'type': 'episode'} monkeypatch.setattr(Episode, 'fromguess', Mock()) Video.fromguess(episodes['bbt_s07e05'].name, guess) assert Episode.fromguess.called def test_video_fromguess_movie(movies, monkeypatch): guess = {'type': 'movie'} monkeypatch.setattr(Movie, 'fromguess', Mock()) Video.fromguess(movies['man_of_steel'].name, guess) assert Movie.fromguess.called def test_video_fromguess_wrong_type(episodes): guess = {'type': 'subtitle'} with pytest.raises(ValueError) as excinfo: Video.fromguess(episodes['bbt_s07e05'].name, guess) assert str(excinfo.value) == 'The guess must be an episode or a movie guess' def test_video_fromname_movie(movies): video = Video.fromname(movies['man_of_steel'].name) assert type(video) is Movie assert video.name == movies['man_of_steel'].name assert video.format == movies['man_of_steel'].format assert video.release_group == movies['man_of_steel'].release_group assert video.resolution == movies['man_of_steel'].resolution assert video.video_codec == movies['man_of_steel'].video_codec assert video.audio_codec is None assert video.imdb_id is None assert video.hashes == {} assert video.size is None assert video.subtitle_languages == set() assert video.title == movies['man_of_steel'].title assert video.year == movies['man_of_steel'].year def test_video_fromname_episode(episodes): video = Video.fromname(episodes['bbt_s07e05'].name) assert type(video) is Episode assert video.name == episodes['bbt_s07e05'].name assert video.format == episodes['bbt_s07e05'].format assert video.release_group == episodes['bbt_s07e05'].release_group assert video.resolution == episodes['bbt_s07e05'].resolution assert video.video_codec == episodes['bbt_s07e05'].video_codec assert video.audio_codec is None assert video.imdb_id is None assert video.hashes == {} assert video.size is None assert video.subtitle_languages == set() assert video.series == episodes['bbt_s07e05'].series assert video.season == episodes['bbt_s07e05'].season assert video.episode == episodes['bbt_s07e05'].episode assert video.title is None assert video.year is None assert video.tvdb_id is None def test_video_fromname_episode_no_season(episodes): video = Video.fromname(episodes['the_jinx_e05'].name) assert type(video) is Episode assert video.name == episodes['the_jinx_e05'].name assert video.format == episodes['the_jinx_e05'].format assert video.release_group == episodes['the_jinx_e05'].release_group assert video.resolution == episodes['the_jinx_e05'].resolution assert video.video_codec == episodes['the_jinx_e05'].video_codec assert video.audio_codec is None assert video.imdb_id is None assert video.hashes == {} assert video.size is None assert video.subtitle_languages == set() assert sanitize(video.series) == sanitize(episodes['the_jinx_e05'].series) assert video.season == episodes['the_jinx_e05'].season assert video.episode == episodes['the_jinx_e05'].episode assert video.title is None assert video.year is None assert video.tvdb_id is None def test_video_hash(episodes): video = episodes['bbt_s07e05'] assert hash(video) == hash(video.name) def test_episode_fromguess_wrong_type(episodes): guess = {'type': 'subtitle'} with pytest.raises(ValueError) as excinfo: Episode.fromguess(episodes['bbt_s07e05'].name, guess) assert str(excinfo.value) == 'The guess must be an episode guess' def test_episode_fromguess_insufficient_data(episodes): guess = {'type': 'episode'} with pytest.raises(ValueError) as excinfo: Episode.fromguess(episodes['bbt_s07e05'].name, guess) assert str(excinfo.value) == 'Insufficient data to process the guess' def test_movie_fromguess_wrong_type(movies): guess = {'type': 'subtitle'} with pytest.raises(ValueError) as excinfo: Movie.fromguess(movies['man_of_steel'].name, guess) assert str(excinfo.value) == 'The guess must be a movie guess' def test_movie_fromguess_insufficient_data(movies): guess = {'type': 'movie'} with pytest.raises(ValueError) as excinfo: Movie.fromguess(movies['man_of_steel'].name, guess) assert str(excinfo.value) == 'Insufficient data to process the guess' def test_movie_fromname(movies): video = Movie.fromname(movies['man_of_steel'].name) assert video.name == movies['man_of_steel'].name assert video.format == movies['man_of_steel'].format assert video.release_group == movies['man_of_steel'].release_group assert video.resolution == movies['man_of_steel'].resolution assert video.video_codec == movies['man_of_steel'].video_codec assert video.audio_codec is None assert video.imdb_id is None assert video.hashes == {} assert video.size is None assert video.subtitle_languages == set() assert video.title == movies['man_of_steel'].title assert video.year == movies['man_of_steel'].year def test_episode_fromname(episodes): video = Episode.fromname(episodes['bbt_s07e05'].name) assert video.name == episodes['bbt_s07e05'].name assert video.format == episodes['bbt_s07e05'].format assert video.release_group == episodes['bbt_s07e05'].release_group assert video.resolution == episodes['bbt_s07e05'].resolution assert video.video_codec == episodes['bbt_s07e05'].video_codec assert video.audio_codec is None assert video.imdb_id is None assert video.hashes == {} assert video.size is None assert video.subtitle_languages == set() assert video.series == episodes['bbt_s07e05'].series assert video.season == episodes['bbt_s07e05'].season assert video.episode == episodes['bbt_s07e05'].episode assert video.title is None assert video.year is None assert video.tvdb_id is None
fernandog/subliminal
tests/test_video.py
subliminal/utils.py
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" import factory from factory.django import DjangoModelFactory from osf_tests.factories import UserFactory, ProjectFactory, ExternalAccountFactory from addons.s3.models import ( UserSettings, NodeSettings ) class S3AccountFactory(ExternalAccountFactory): provider = 's3' provider_id = factory.Sequence(lambda n: 'id-{0}'.format(n)) oauth_key = factory.Sequence(lambda n: 'key-{0}'.format(n)) oauth_secret = factory.Sequence(lambda n: 'secret-{0}'.format(n)) display_name = 'S3 Fake User' class S3UserSettingsFactory(DjangoModelFactory): class Meta: model = UserSettings owner = factory.SubFactory(UserFactory) class S3NodeSettingsFactory(DjangoModelFactory): class Meta: model = NodeSettings owner = factory.SubFactory(ProjectFactory) user_settings = factory.SubFactory(S3UserSettingsFactory)
# -*- coding: utf-8 -*- """Serializer tests for the S3 addon.""" import mock import pytest from addons.base.tests.serializers import StorageAddonSerializerTestSuiteMixin from addons.s3.tests.factories import S3AccountFactory from addons.s3.serializer import S3Serializer from tests.base import OsfTestCase pytestmark = pytest.mark.django_db class TestS3Serializer(StorageAddonSerializerTestSuiteMixin, OsfTestCase): addon_short_name = 's3' Serializer = S3Serializer ExternalAccountFactory = S3AccountFactory client = None def set_provider_id(self, pid): self.node_settings.folder_id = pid def setUp(self): self.mock_can_list = mock.patch('addons.s3.serializer.utils.can_list') self.mock_can_list.return_value = True self.mock_can_list.start() super(TestS3Serializer, self).setUp() def tearDown(self): self.mock_can_list.stop() super(TestS3Serializer, self).tearDown()
cslzchen/osf.io
addons/s3/tests/test_serializer.py
addons/s3/tests/factories.py
# -*- coding: utf-8 -*- """ FTP manipulation library @author: Milan Falešník <mfalesni@redhat.com> """ import fauxfactory import ftplib import re from datetime import datetime from time import strptime, mktime try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class FTPException(Exception): pass class FTPDirectory(object): """ FTP FS Directory encapsulation This class represents one directory. Contains pointers to all child directories (self.directories) and also all files in current directory (self.files) """ def __init__(self, client, name, items, parent_dir=None, time=None): """ Constructor Args: client: ftplib.FTP instance name: Name of this directory items: Content of this directory parent_dir: Pointer to a parent directory to maintain hierarchy. None if root time: Time of this object """ self.client = client self.parent_dir = parent_dir self.time = time self.name = name self.files = [] self.directories = [] for item in items: if isinstance(item, dict): # Is a directory self.directories.append(FTPDirectory(self.client, item["dir"], item["content"], parent_dir=self, time=item["time"])) else: self.files.append(FTPFile(self.client, item[0], self, item[1])) @property def path(self): """ Returns: whole path for this directory """ if self.parent_dir: return self.parent_dir.path + self.name + "/" else: return self.name def __repr__(self): return "<FTPDirectory {}>".format(self.path) def cd(self, path): """ Change to a directory Changes directory to a path specified by parameter path. There are three special cases: / - climbs by self.parent_dir up in the hierarchy until it reaches root element. . - does nothing .. - climbs one level up in hierarchy, if present, otherwise does the same as preceeding. Args: path: Path to change """ if path == ".": return self elif path == "..": result = self if result.parent_dir: result = result.parent_dir return result elif path == "/": result = self while result.parent_dir: result = result.parent_dir return result enter = path.strip("/").split("/", 1) remainder = None if len(enter) == 2: enter, remainder = enter for item in self.directories: if item.name == enter: if remainder: return item.cd("/".join(remainder)) else: return item raise FTPException("Directory {}{} does not exist!".format(self.path, enter)) def search(self, by, files=True, directories=True): """ Recursive search by string or regexp. Searches throughout all the filesystem structure from top till the bottom until it finds required files or dirctories. You can specify either plain string or regexp. String search does classic ``in``, regexp matching is done by exact matching (by.match). Args: by: Search string or regexp files: Whether look for files directories: Whether look for directories Returns: List of all objects found in FS """ def _scan(what, in_what): if isinstance(what, re._pattern_type): return what.match(in_what) is not None else: return what in in_what results = [] if files: for f in self.files: if _scan(by, f.name): results.append(f) for d in self.directories: if directories: if _scan(by, d.name): results.append(d) results.extend(d.search(by, files=files, directories=directories)) return results class FTPFile(object): """ FTP FS File encapsulation This class represents one file in the FS hierarchy. It encapsulates mainly its position in FS and adds the possibility of downloading the file. """ def __init__(self, client, name, parent_dir, time): """ Constructor Args: client: ftplib.FTP instance name: File name (without path) parent_dir: Directory in which this file is """ self.client = client self.parent_dir = parent_dir self.name = name self.time = time @property def path(self): """ Returns: whole path for this file """ if self.parent_dir: return self.parent_dir.path + self.name else: return self.name @property def local_time(self): """ Returns: time modified to match local computer's time zone """ return self.client.dt + self.time def __repr__(self): return "<FTPFile {}>".format(self.path) def retr(self, callback): """ Retrieve file Wrapper around ftplib.FTP.retrbinary(). This function cd's to the directory where this file is present, then calls the FTP's retrbinary() function with provided callable and then cd's back where it started to keep it consistent. Args: callback: Any callable that accepts one parameter as the data Raises: AssertionError: When any of the CWD or CDUP commands fail. ftplib.error_perm: When retrbinary call of ftplib fails """ dirs, f = self.path.rsplit("/", 1) dirs = dirs.lstrip("/").split("/") # Dive in for d in dirs: assert self.client.cwd(d), "Could not change into the directory {}!".format(d) self.client.retrbinary(f, callback) # Dive out for d in dirs: assert self.client.cdup(), "Could not get out of directory {}!".format(d) def download(self, target=None): """ Download file into this machine Wrapper around self.retr function. It downloads the file from remote filesystem into local filesystem. Name is either preserved original, or can be changed. Args: target: Target file name (None to preserver the original) """ if target is None: target = self.name with open(target, "wb") as output: self.retr(output.write) class FTPClient(object): """ FTP Client encapsulation This class provides basic encapsulation around ftplib's FTP class. It wraps some methods and allows to easily delete whole directory or walk through the directory tree. Usage: >>> from utils.ftp import FTPClient >>> ftp = FTPClient("host", "user", "password") >>> only_files_with_EVM_in_name = ftp.filesystem.search("EVM", directories=False) >>> only_files_by_regexp = ftp.filesystem.search(re.compile("regexp"), directories=False) >>> some_directory = ftp.filesystem.cd("a/b/c") # cd's to this directory >>> root = some_directory.cd("/") Always going through filesystem property is a bit slow as it parses the structure on each use. If you are sure that the structure will remain intact between uses, you can do as follows to save the time:: >>> fs = ftp.filesystem Let's download some files:: >>> for f in ftp.filesystem.search("IMPORTANT_FILE", directories=False): ... f.download() # To pickup its original name ... f.download("custom_name") We finished the testing, so we don't need the content of the directory:: >>> ftp.recursively_delete() And it's gone. """ def __init__(self, host, login, password, upload_dir="/"): """ Constructor Args: host: FTP server host login: FTP login password: FTP password """ self.host = host self.login = login self.password = password self.ftp = None self.dt = None self.upload_dir = upload_dir self.connect() self.update_time_difference() def connect(self): self.ftp = ftplib.FTP(self.host) self.ftp.login(self.login, self.password) def update_time_difference(self): """ Determine the time difference between the FTP server and this computer. This is done by uploading a fake file, reading its time and deleting it. Then the self.dt variable captures the time you need to ADD to the remote time or SUBTRACT from local time. The FTPFile object carries this automatically as it has .local_time property which adds the client's .dt to its time. """ TIMECHECK_FILE_NAME = fauxfactory.gen_alphanumeric(length=16) void_file = StringIO(fauxfactory.gen_alpha()) self.cwd(self.upload_dir) assert "Transfer complete" in self.storbinary(TIMECHECK_FILE_NAME, void_file),\ "Could not upload a file for time checking with name {}!".format(TIMECHECK_FILE_NAME) void_file.close() now = datetime.now() for d, name, time in self.ls(): if name == TIMECHECK_FILE_NAME: self.dt = now - time self.dele(TIMECHECK_FILE_NAME) self.cwd("/") return True raise FTPException("The timecheck file was not found in the current FTP directory") def ls(self): """ Lists the content of a directory. Returns: List of all items in current directory Return format is [(is_dir?, "name", remote_time), ...] """ result = [] def _callback(line): is_dir = line.upper().startswith("D") # Max 8, then the final is file which can contain something blank fields = re.split(r"\s+", line, maxsplit=8) # This is because how informations in LIST are presented # Nov 11 12:34 filename (from the end) date = strptime(str(datetime.now().year) + " " + fields[-4] + " " + fields[-3] + " " + fields[-2], "%Y %b %d %H:%M") # convert time.struct_time into datetime date = datetime.fromtimestamp(mktime(date)) result.append((is_dir, fields[-1], date)) self.ftp.dir(_callback) return result def pwd(self): """ Get current directory Returns: Current directory Raises: AssertionError: PWD command fails """ result = self.ftp.sendcmd("PWD") assert "is the current directory" in result, "PWD command failed" x, d, y = result.strip().split("\"") return d.strip() def cdup(self): """ Goes one level up in directory hierarchy (cd ..) """ return self.ftp.sendcmd("CDUP") def mkd(self, d): """ Create a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("MKD {}".format(d)).startswith("250") except ftplib.error_perm: return False def rmd(self, d): """ Remove a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("RMD {}".format(d)).startswith("250") except ftplib.error_perm: return False def dele(self, f): """ Remove a file Args: f: File name Returns: Success of the action """ try: return self.ftp.sendcmd("DELE {}".format(f)).startswith("250") except ftplib.error_perm: return False def cwd(self, d): """ Enter a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("CWD {}".format(d)).startswith("250") except ftplib.error_perm: return False def close(self): """ Finish work and close connection """ self.ftp.quit() self.ftp.close() self.ftp = None def retrbinary(self, f, callback): """ Download file You need to specify the callback function, which accepts one parameter (data), to be processed. Args: f: Requested file name callback: Callable with one parameter accepting the data """ return self.ftp.retrbinary("RETR {}".format(f), callback) def storbinary(self, f, file_obj): """ Store file You need to specify the file object. Args: f: Requested file name file_obj: File object to be stored """ return self.ftp.storbinary("STOR {}".format(f), file_obj) def recursively_delete(self, d=None): """ Recursively deletes content of pwd WARNING: Destructive! Args: d: Directory to enter (None for not entering - root directory) d: str or None Raises: AssertionError: When some of the FTP commands fail. """ # Enter the directory if d: assert self.cwd(d), "Could not enter directory {}".format(d) # Work in it for isdir, name, time in self.ls(): if isdir: self.recursively_delete(name) else: assert self.dele(name), "Could not delete {}!".format(name) # Go out of it if d: # Go to parent directory assert self.cdup(), "Could not go to parent directory of {}!".format(d) # And delete it assert self.rmd(d), "Could not remove directory {}!".format(d) def tree(self, d=None): """ Walks the tree recursively and creates a tree Base structure is a list. List contains directory content and the type decides whether it's a directory or a file: - tuple: it's a file, therefore it represents file's name and time - dict: it's a directory. Then the dict structure is as follows:: dir: directory name content: list of directory content (recurse) Args: d: Directory to enter(None for no entering - root directory) Returns: Directory structure in lists nad dicts. Raises: AssertionError: When some of the FTP commands fail. """ # Enter the directory items = [] if d: assert self.cwd(d), "Could not enter directory {}".format(d) # Work in it for isdir, name, time in self.ls(): if isdir: items.append({"dir": name, "content": self.tree(name), "time": time}) else: items.append((name, time)) # Go out of it if d: # Go to parent directory assert self.cdup(), "Could not go to parent directory of {}!".format(d) return items @property def filesystem(self): """ Returns the object structure of the filesystem Returns: Root directory """ return FTPDirectory(self, "/", self.tree()) # Context management methods def __enter__(self): """ Entering the context does nothing, because the client is already connected """ return self def __exit__(self, type, value, traceback): """ Exiting the context means just calling .close() on the client. """ self.close()
# -*- coding: utf-8 -*- from cfme import test_requirements from cfme.configure.tasks import is_datastore_analysis_finished from cfme.fixtures import pytest_selenium as sel from cfme.infrastructure import datastore, host from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.web_ui import toolbar as tb, Quadicon, InfoBlock from utils import conf, testgen from utils.blockers import BZ from utils.wait import wait_for import pytest pytestmark = [test_requirements.smartstate] DATASTORE_TYPES = ('vmfs', 'nfs', 'iscsi') PROVIDER_TYPES = (VMwareProvider, RHEVMProvider) # Rows to check in the datastore detail Content infoblock; after smartstate analysis CONTENT_ROWS_TO_CHECK = ( 'All Files', 'VM Provisioned Disk Files', 'VM Snapshot Files', 'VM Memory Files', 'Other VM Files', 'Non-VM Files' ) def pytest_generate_tests(metafunc): new_idlist = [] new_argvalues = [] argnames, argvalues, idlist = testgen.providers_by_class( metafunc, PROVIDER_TYPES, required_fields=['datastores']) argnames += ['datastore'] for i, argvalue_tuple in enumerate(argvalues): args = dict(zip(argnames, argvalue_tuple)) datastores = args['provider'].data.get('datastores', {}) if not datastores: continue for ds in datastores: if not ds.get('test_fleece', False): continue assert ds.get('type', None) in DATASTORE_TYPES,\ 'datastore type must be set to [{}] for smartstate analysis tests'\ .format('|'.join(DATASTORE_TYPES)) argvs = argvalues[i][:] new_argvalues.append(argvs + [datastore.Datastore(ds['name'], args['provider'].key, ds['type'])]) test_id = '{}-{}'.format(args['provider'].key, ds['type']) new_idlist.append(test_id) testgen.parametrize(metafunc, argnames, new_argvalues, ids=new_idlist, scope="module") def get_host_data_by_name(provider_key, host_name): for host_obj in conf.cfme_data.get('management_systems', {})[provider_key].get('hosts', []): if host_name == host_obj['name']: return host_obj return None # TODO add support for events @pytest.mark.tier(2) @pytest.mark.meta( blockers=[ BZ(1091033, unblock=lambda datastore: datastore.type != 'iscsi'), BZ(1180467, unblock=lambda provider: provider.type != 'rhevm'), BZ(1380707) ] ) def test_run_datastore_analysis(request, setup_provider, provider, datastore, soft_assert): """Tests smarthost analysis Metadata: test_flag: datastore_analysis """ # Check if there is a host with valid credentials host_names = datastore.get_hosts() assert len(host_names) != 0, "No hosts attached to this datastore found" for host_name in host_names: host_qi = Quadicon(host_name, 'host') if 'checkmark' in host_qi.creds: break else: # If not, get credentials for one of the present hosts found_host = False for host_name in host_names: host_data = get_host_data_by_name(provider.key, host_name) if host_data is None: continue found_host = True test_host = host.Host(name=host_name, provider=provider) # Add them to the host wait_for(lambda: test_host.exists, delay=10, num_sec=120, fail_func=sel.refresh) if not test_host.has_valid_credentials: test_host.update( updates={ 'credentials': host.get_credentials_from_config(host_data['credentials'])} ) wait_for( lambda: test_host.has_valid_credentials, delay=10, num_sec=120, fail_func=sel.refresh ) # And remove them again when the test is finished def test_host_remove_creds(): test_host.update( updates={ 'credentials': host.Host.Credential( principal="", secret="", verify_secret="" ) } ) request.addfinalizer(test_host_remove_creds) break assert found_host,\ "No credentials found for any of the hosts attached to datastore {}"\ .format(datastore.name) # TODO add support for events # register_event( # None, # "datastore", # datastore_name, # ["datastore_analysis_request_req", "datastore_analysis_complete_req"] # ) # Initiate analysis datastore.run_smartstate_analysis() wait_for(lambda: is_datastore_analysis_finished(datastore.name), delay=15, timeout="15m", fail_func=lambda: tb.select('Reload the current display')) ds_str = "Datastores Type" c_datastore = datastore.get_detail('Properties', ds_str) # Check results of the analysis and the datastore type soft_assert(c_datastore == datastore.type.upper(), 'Datastore type does not match the type defined in yaml:' + 'expected "{}" but was "{}"'.format(datastore.type.upper(), c_datastore)) for row_name in CONTENT_ROWS_TO_CHECK: value = InfoBlock('Content', row_name).text soft_assert(value != '0', 'Expected value for {} to be non-empty'.format(row_name))
rananda/cfme_tests
cfme/tests/infrastructure/test_datastore_analysis.py
utils/ftp.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from enumfields import Enum, EnumIntegerField from filer.fields.image import FilerImageField from jsonfield import JSONField from parler.models import TranslatedFields from shuup.core.fields import CurrencyField, InternalIdentifierField from shuup.core.pricing import TaxfulPrice, TaxlessPrice from shuup.utils.analog import define_log_model from ._base import ChangeProtected, TranslatableShuupModel from ._orders import Order def _get_default_currency(): return settings.SHUUP_HOME_CURRENCY class ShopStatus(Enum): DISABLED = 0 ENABLED = 1 class Labels: DISABLED = _('disabled') ENABLED = _('enabled') @python_2_unicode_compatible class Shop(ChangeProtected, TranslatableShuupModel): protected_fields = ["currency", "prices_include_tax"] change_protect_message = _("The following fields cannot be changed since there are existing orders for this shop") identifier = InternalIdentifierField(unique=True) domain = models.CharField(max_length=128, blank=True, null=True, unique=True, verbose_name=_("domain"), help_text=_( "Your shop domain name. Use this field to configure the URL that is used to visit your site. " "Note: this requires additional configuration through your internet domain registrar." )) status = EnumIntegerField(ShopStatus, default=ShopStatus.DISABLED, verbose_name=_("status"), help_text=_( "Your shop status. Disable your shop if it is no longer in use." )) owner = models.ForeignKey("Contact", blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("contact")) options = JSONField(blank=True, null=True, verbose_name=_("options")) currency = CurrencyField(default=_get_default_currency, verbose_name=_("currency"), help_text=_( "The primary shop currency. This is the currency used when selling your products." )) prices_include_tax = models.BooleanField(default=True, verbose_name=_("prices include tax"), help_text=_( "This option defines whether product prices entered in admin include taxes. " "Note this behavior can be overridden with contact group pricing." )) logo = FilerImageField(verbose_name=_("logo"), blank=True, null=True, on_delete=models.SET_NULL) maintenance_mode = models.BooleanField(verbose_name=_("maintenance mode"), default=False, help_text=_( "Check this if you would like to make your shop temporarily unavailable while you do some shop maintenance." )) contact_address = models.ForeignKey( "MutableAddress", verbose_name=_("contact address"), blank=True, null=True, on_delete=models.SET_NULL) translations = TranslatedFields( name=models.CharField(max_length=64, verbose_name=_("name"), help_text=_( "The shop name. This name is displayed throughout admin." )), public_name=models.CharField(max_length=64, verbose_name=_("public name"), help_text=_( "The public shop name. This name is displayed in the store front and in any customer email correspondence." )), maintenance_message=models.CharField( max_length=300, blank=True, verbose_name=_("maintenance message"), help_text=_( "The message to display to customers while your shop is in maintenance mode." ) ) ) def __str__(self): return self.safe_translation_getter("name", default="Shop %d" % self.pk) def create_price(self, value): """ Create a price with given value and settings of this shop. Takes the ``prices_include_tax`` and ``currency`` settings of this Shop into account. :type value: decimal.Decimal|int|str :rtype: shuup.core.pricing.Price """ if self.prices_include_tax: return TaxfulPrice(value, self.currency) else: return TaxlessPrice(value, self.currency) def _are_changes_protected(self): return Order.objects.filter(shop=self).exists() ShopLogEntry = define_log_model(Shop)
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/core/models/_shops.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.urlresolvers import reverse from django.db.transaction import atomic from django.http.response import HttpResponseRedirect, JsonResponse from django.utils.functional import cached_property from django.views.generic import TemplateView from shuup import configuration from shuup.admin.form_part import FormPart, TemplatedFormDef from shuup.admin.utils.wizard import load_setup_wizard_panes from shuup.core.models import Shop from shuup.utils.form_group import FormDef, FormGroup from shuup.utils.iterables import first class WizardFormDefMixin(object): def __init__(self, **kwargs): self.context = kwargs.pop("context", {}) self.extra_js = kwargs.pop("extra_js", "") super(WizardFormDefMixin, self).__init__(**kwargs) class WizardFormDef(WizardFormDefMixin, FormDef): pass class TemplatedWizardFormDef(WizardFormDefMixin, TemplatedFormDef): pass class _WizardFormGroup(FormGroup): def __init__(self, identifier, title, text, icon, **kwargs): super(_WizardFormGroup, self).__init__(**kwargs) self.identifier = identifier self.title = title self.text = text self.icon = icon class WizardPane(FormPart): identifier = None title = None text = None icon = None def visible(self): return True class WizardView(TemplateView): template_name = "shuup/admin/wizard/wizard.jinja" @cached_property def panes(self): return load_setup_wizard_panes( shop=Shop.objects.first(), request=self.request, # if the user presses "previous" then "next" again, resubmit the form visible_only=self.request.method == "GET" ) def get_all_pane_forms(self): return [self.get_form_group_for_pane(pane) for pane in self.panes] @cached_property def current_pane(self): pane_id = self.request.POST.get("pane_id") return first(filter(lambda x: x.identifier == pane_id, self.panes), None) def get_final_pane_identifier(self): visible_panes = list(filter(lambda x: x.visible(), self.panes)) if len(visible_panes) > 0: return visible_panes[-1].identifier return 0 def get_context_data(self, **kwargs): context = super(WizardView, self).get_context_data(**kwargs) context["panes"] = self.get_all_pane_forms() context["active_pane_id"] = self.request.GET.get("pane_id", 1) context["final_pane_id"] = self.get_final_pane_identifier() return context def get_form_group_for_pane(self, pane): kwargs = {} if self.request.method == "POST": kwargs.update({ "data": self.request.POST, "files": self.request.FILES }) fg = _WizardFormGroup(pane.identifier, pane.title, pane.text, pane.icon, **kwargs) for form_def in pane.get_form_defs(): fg.form_defs[form_def.name] = form_def return fg def get_form(self): return self.get_form_group_for_pane(self.current_pane) def form_valid(self, form): pane = self.current_pane pane.form_valid(form) return JsonResponse({"success": "true"}, status=200) def form_invalid(self, form): return JsonResponse(form.errors, status=400) @atomic def post(self, request, *args, **kwargs): abort = request.POST.get("abort", False) if self.request.POST.get("pane_id") == self.get_final_pane_identifier(): configuration.set(Shop.objects.first(), "setup_wizard_complete", True) if abort: return JsonResponse({"success": "true"}, status=200) form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) @atomic def get(self, request, *args, **kwargs): if len(self.panes) == 0: if request.shop.maintenance_mode: return HttpResponseRedirect(reverse("shuup_admin:home")) else: return HttpResponseRedirect(reverse("shuup_admin:dashboard")) return super(WizardView, self).get(request, *args, **kwargs)
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/admin/views/wizard.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.utils.translation import ugettext_lazy as _ from shuup.admin.base import Section from shuup.campaigns.models import BasketCampaign, CatalogCampaign from shuup.core.models import Shop, ShopProduct class ProductCampaignsSection(Section): identifier = "product_campaigns" name = _("Active Campaigns") icon = "fa-bullhorn" template = "shuup/campaigns/admin/_product_campaigns.jinja" @staticmethod def visible_for_object(product): return bool(product.pk) @staticmethod def get_context_data(product): ctx = {} for shop in Shop.objects.all(): try: shop_product = product.get_shop_instance(shop) except ShopProduct.DoesNotExist: continue ctx[shop] = { "basket_campaigns": BasketCampaign.get_for_product(shop_product), "catalog_campaigns": CatalogCampaign.get_for_product(shop_product) } return ctx
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/campaigns/admin_module/sections.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from .edit import ScriptEditView from .editor import EditScriptContentView, script_item_editor from .list import ScriptListView __all__ = ( "script_item_editor", "ScriptEditView", "EditScriptContentView", "ScriptListView" )
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/notify/admin_module/views/__init__.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.forms.formsets import BaseFormSet, DELETION_FIELD_NAME class ProductChildBaseFormSet(BaseFormSet): deletion_label = None def __init__(self, **kwargs): kwargs.pop("empty_permitted", None) self.request = kwargs.pop("request", None) super(ProductChildBaseFormSet, self).__init__(**kwargs) def _construct_form(self, i, **kwargs): form = super(ProductChildBaseFormSet, self)._construct_form(i, **kwargs) form.fields[DELETION_FIELD_NAME].label = self.deletion_label return form
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/admin/modules/products/forms/parent_forms.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.urlresolvers import reverse_lazy from django.views.generic import DeleteView from shuup.core.models import ServiceProvider class ServiceProviderDeleteView(DeleteView): model = ServiceProvider success_url = reverse_lazy("shuup_admin:service_provider.list")
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import pytest from django.conf import settings from django.utils.translation import activate from shuup import configuration from shuup.core import cache from shuup.admin.modules.categories.views import CategoryEditView from shuup.admin.modules.shops.views import ShopEditView from shuup.apps.provides import override_provides from shuup.front.utils.sorts_and_filters import get_configuration from shuup.testing.factories import get_default_category, get_default_shop from shuup.testing.utils import apply_request_middleware DEFAULT_FORM_MODIFIERS = [ "shuup.front.forms.product_list_modifiers.SortProductListByName", "shuup.front.forms.product_list_modifiers.SortProductListByPrice", "shuup.front.forms.product_list_modifiers.ManufacturerProductListFilter", ] @pytest.mark.django_db def test_sorts_and_filter_in_shop_edit(rf, admin_user): cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): shop = get_default_shop() view = ShopEditView.as_view() assert get_configuration(shop=shop) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": shop.name, "base-public_name__en": shop.public_name, "base-status": shop.status.value, "base-currency": shop.currency, "base-prices_include_tax": shop.prices_include_tax, "base-languages": "en", "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 11, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": False, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=shop.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 11, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": False, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(shop=shop) == expected_configurations @pytest.mark.django_db def test_sorts_and_filter_in_category_edit(rf, admin_user): get_default_shop() cache.clear() activate("en") with override_provides("front_extend_product_list_form", DEFAULT_FORM_MODIFIERS): category = get_default_category() view = CategoryEditView.as_view() assert get_configuration(category=category) == settings.SHUUP_FRONT_DEFAULT_SORT_CONFIGURATION data = { "base-name__en": category.name, "base-status": category.status.value, "base-visibility": category.visibility.value, "base-ordering": category.ordering, "product_list_facets-sort_products_by_name": True, "product_list_facets-sort_products_by_name_ordering": 6, "product_list_facets-sort_products_by_price": False, "product_list_facets-sort_products_by_price_ordering": 32, "product_list_facets-filter_products_by_manufacturer": True, "product_list_facets-filter_products_by_manufacturer_ordering": 1 } request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=category.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] expected_configurations = { "sort_products_by_name": True, "sort_products_by_name_ordering": 6, "sort_products_by_price": False, "sort_products_by_price_ordering": 32, "filter_products_by_manufacturer": True, "filter_products_by_manufacturer_ordering": 1 } assert get_configuration(category=category) == expected_configurations
suutari/shoop
shuup_tests/functional/test_sorts_and_filters_admin.py
shuup/admin/modules/service_providers/views/_delete.py
import os import pytest from cfme.fixtures.terminalreporter import reporter from cfme.utils.datafile import data_path_for_filename from cfme.utils.datafile import load_data_file from cfme.utils.path import data_path from cfme.utils.path import log_path # Collection for storing unique combinations of data file paths # and filenames for usage reporting after a completed test run seen_data_files = set() @pytest.fixture(scope="module") def datafile(request): """datafile(filename, replacements) datafile fixture, with templating support Args: filename: filename to load from the data dir replacements: template replacements Returns: Path to the loaded datafile Usage: Given a filename, it will attempt to open the given file from the test's corresponding data dir. For example, this: datafile('testfile') # in tests/subdir/test_module_name.py Would return a file object representing this file: /path/to/cfme_tests/data/subdir/test_module_name/testfile Given a filename with a leading slash, it will attempt to load the file relative to the root of the data dir. For example, this: datafile('/common/testfile') # in tests/subdir/test_module_name.py Would return a file object representing this file: /path/to/cfme_tests/data/common/testfile Note that the test module name is not used with the leading slash. .. rubric:: Templates: This fixture can also handle template replacements. If the datafile being loaded is a python template, the dictionary of replacements can be passed as the 'replacements' keyword argument. In this case, the returned data file will be a NamedTemporaryFile prepopulated with the interpolated result from combining the template with the replacements mapping. * http://docs.python.org/2/library/string.html#template-strings * http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile """ return _FixtureDataFile(request) def pytest_addoption(parser): group = parser.getgroup('cfme') group.addoption('--udf-report', action='store_true', default=False, dest='udf_report', help='flag to generate an unused data files report') def pytest_sessionfinish(session, exitstatus): udf_log_file = log_path.join('unused_data_files.log') if udf_log_file.check(): # Clean up old udf log if it exists udf_log_file.remove() if session.config.option.udf_report is False: # Short out here if not making a report return # Output an unused data files log after a test run data_files = set() for dirpath, dirnames, filenames in os.walk(str(data_path)): for filename in filenames: filepath = os.path.join(dirpath, filename) data_files.add(filepath) unused_data_files = data_files - seen_data_files if unused_data_files: # Write the log of unused data files out, minus the data dir prefix udf_log = ''.join( (line[len(str(data_path)):] + '\n' for line in unused_data_files) ) udf_log_file.write(udf_log + '\n') # Throw a notice into the terminal reporter to check the log tr = reporter() tr.write_line('') tr.write_sep( '-', '%d unused data files after test run, check %s' % ( len(unused_data_files), udf_log_file.basename ) ) class _FixtureDataFile(object): def __init__(self, request): self.base_path = str(request.session.fspath) self.testmod_path = str(request.fspath) def __call__(self, filename, replacements=None): if filename.startswith('/'): complete_path = data_path_for_filename( filename.strip('/'), self.base_path) else: complete_path = data_path_for_filename( filename, self.base_path, self.testmod_path) seen_data_files.add(complete_path) return load_data_file(complete_path, replacements)
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/fixtures/datafile.py
import attr from riggerlib import recursive_update from cfme.cloud.instance import Instance from cfme.cloud.instance import InstanceCollection @attr.s class GCEInstance(Instance): # CFME & provider power control options START = "Start" POWER_ON = START # For compatibility with the infra objects. STOP = "Stop" DELETE = "Delete" TERMINATE = 'Delete' # CFME-only power control options SOFT_REBOOT = "Soft Reboot" # Provider-only power control options RESTART = "Restart" # CFME power states STATE_ON = "on" STATE_OFF = "off" STATE_SUSPENDED = "suspended" STATE_TERMINATED = "terminated" STATE_ARCHIVED = "archived" STATE_UNKNOWN = "unknown" @property def ui_powerstates_available(self): return { 'on': [self.STOP, self.SOFT_REBOOT, self.TERMINATE], 'off': [self.START, self.TERMINATE]} @property def ui_powerstates_unavailable(self): return { 'on': [self.START], 'off': [self.STOP, self.SOFT_REBOOT]} @property def vm_default_args(self): """Represents dictionary used for Vm/Instance provision with GCE mandatory default args""" inst_args = super(GCEInstance, self).vm_default_args provisioning = self.provider.data['provisioning'] inst_args['properties']['boot_disk_size'] = provisioning.get('boot_disk_size', '10 GB') return inst_args @property def vm_default_args_rest(self): inst_args = super(GCEInstance, self).vm_default_args_rest provisioning = self.provider.data['provisioning'] recursive_update(inst_args, { 'vm_fields': { 'boot_disk_size': provisioning['boot_disk_size'].replace(' ', '.')}}) return inst_args @attr.s class GCEInstanceCollection(InstanceCollection): ENTITY = GCEInstance
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/cloud/instance/gce.py
"""Module handling report menus contents""" from contextlib import contextmanager import attr from navmazing import NavigateToAttribute from widgetastic.widget import Text from widgetastic_patternfly import Button from cfme.intelligence.reports import CloudIntelReportsView from cfme.intelligence.reports import ReportsMultiBoxSelect from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from widgetastic_manageiq import FolderManager from widgetastic_manageiq import ManageIQTree class AllReportMenusView(CloudIntelReportsView): title = Text("#explorer_title_text") reports_tree = ManageIQTree("menu_roles_treebox") @property def is_displayed(self): return ( self.in_intel_reports and self.title.text == "All EVM Groups" and self.edit_report_menus.is_opened and self.edit_report_menus.tree.currently_selected == ["All EVM Groups"] ) class EditReportMenusView(AllReportMenusView): # Buttons save_button = Button("Save") reset_button = Button("Reset") default_button = Button("Default") cancel_button = Button("Cancel") commit_button = Button("Commit") discard_button = Button("Discard") manager = FolderManager(".//div[@id='folder_lists']/table") report_select = ReportsMultiBoxSelect( move_into="Move selected reports right", move_from="Move selected reports left", available_items="available_reports", chosen_items="selected_reports" ) @property def is_displayed(self): return ( self.in_intel_reports and self.title.text == 'Editing EVM Group "{}"'.format(self.context["object"].group) and self.edit_report_menus.is_opened and self.edit_report_menus.tree.currently_selected == [ "All EVM Groups", self.context["object"].group ] ) @attr.s class ReportMenu(BaseEntity): """ This is a fake class mainly needed for navmazing navigation. """ group = None def go_to_group(self, group_name): self.group = group_name view = navigate_to(self, "Edit") assert view.is_displayed return view def get_folders(self, group): """Returns list of folders for given user group. Args: group: User group to check. """ view = self.go_to_group(group) view.reports_tree.click_path("Top Level") fields = view.manager.fields view.discard_button.click() return fields def get_subfolders(self, group, folder): """Returns list of sub-folders for given user group and folder. Args: group: User group to check. folder: Folder to read. """ view = self.go_to_group(group) view.reports_tree.click_path("Top Level", folder) fields = view.manager.fields view.discard_button.click() return fields def _action(self, action, manager, folder_name): with manager as folder_manager: getattr(folder_manager, action)(folder_name) def add_folder(self, group, folder): """Adds a folder under top-level. Args: group: User group. folder: Name of the new folder. """ self._action("add", self.manage_folder(group), folder) def add_subfolder(self, group, folder, subfolder): """Adds a subfolder under specified folder. Args: group: User group. folder: Name of the folder. subfolder: Name of the new subfolder. """ self._action("add", self.manage_folder(group, folder), subfolder) def remove_folder(self, group, folder): """Removes a folder under top-level. Args: group: User group. folder: Name of the folder. """ self._action("delete", self.manage_folder(group), folder) def remove_subfolder(self, group, folder, subfolder): """Removes a subfolder under specified folder. Args: group: User group. folder: Name of the folder. subfolder: Name of the subfolder. """ self._action("delete", self.manage_folder(group, folder), subfolder) def reset_to_default(self, group): """Clicks the `Default` button. Args: group: Group to set to Default """ view = self.go_to_group(group) view.default_button.click() view.save_button.click() flash_view = self.create_view(AllReportMenusView) assert flash_view.flash.assert_message( 'Report Menu for role "{}" was saved'.format(group) ) @contextmanager def manage_subfolder(self, group, folder, subfolder): """Context manager to use when modifying the subfolder contents. You can use manager's :py:meth:`FolderManager.bail_out` classmethod to end and discard the changes done inside the with block. Args: group: User group. folder: Parent folder name. subfolder: Subfolder name to manage. Returns: Context-managed :py:class: `widgetastic_manageiq.MultiBoxSelect` instance """ view = self.go_to_group(group) view.reports_tree.click_path("Top Level", folder, subfolder) try: yield view.report_select except FolderManager._BailOut: view.discard_button.click() except Exception: # In case of any exception, nothing will be saved view.discard_button.click() raise # And reraise the exception else: # If no exception happens, save! view.commit_button.click() view.save_button.click() flash_view = self.create_view(AllReportMenusView) flash_view.flash.assert_message( 'Report Menu for role "{}" was saved'.format(group) ) @contextmanager def manage_folder(self, group, folder=None): """Context manager to use when modifying the folder contents. You can use manager's :py:meth:`FolderManager.bail_out` classmethod to end and discard the changes done inside the with block. This context manager does not give the manager as a value to the with block so you have to import and use the :py:class:`FolderManager` class manually. Args: group: User group. folder: Which folder to manage. If None, top-level will be managed. Returns: Context-managed :py:class:`widgetastic_manageiq.FolderManager` instance """ view = self.go_to_group(group) if folder is None: view.reports_tree.click_path("Top Level") else: view.reports_tree.click_path("Top Level", folder) try: yield view.manager except FolderManager._BailOut: view.manager.discard() except Exception: # In case of any exception, nothing will be saved view.manager.discard() raise # And reraise the exception else: # If no exception happens, save! view.manager.commit() view.save_button.click() flash_view = self.create_view(AllReportMenusView) flash_view.flash.assert_message( 'Report Menu for role "{}" was saved'.format(group) ) def move_reports(self, group, folder, subfolder, *reports): """ Moves a list of reports to a given menu Args: group: User group folder: Parent of the subfolder where reports are to be moved. subfolder: Subfolder under which the reports are to be moved. reports: List of reports that are to be moved. """ reports = list(reports) cancel_view = "" with self.manage_subfolder(group, folder, subfolder) as selected_menu: selected_options = selected_menu.parent_view.report_select.all_options diff = set(selected_options) & set(reports) if diff and (len(diff) == len(reports)): cancel_view = self.create_view(AllReportMenusView) # If all the reports to be moved are already present, raise an exception to exit. raise FolderManager._BailOut # fill method replaces all the options in all_options with the value passed as argument # We do not want to replace any value, we just want to move the new reports to a given # menu. This is a work-around for that purpose. reports.extend(selected_options) selected_menu.parent_view.report_select.fill(reports) if cancel_view: cancel_view.flash.assert_message( 'Edit of Report Menu for role "{}" was cancelled by the user'.format( group ) ) @attr.s class ReportMenusCollection(BaseCollection): """Collection object for the :py:class:'cfme.intelligence.reports.ReportMenu'.""" ENTITY = ReportMenu @navigator.register(ReportMenu, "Edit") class EditReportMenus(CFMENavigateStep): VIEW = EditReportMenusView prerequisite = NavigateToAttribute( "appliance.collections.intel_report_menus", "All" ) def step(self, *args, **kwargs): self.prerequisite_view.edit_report_menus.tree.click_path( "All EVM Groups", self.obj.group ) @navigator.register(ReportMenusCollection, "All") class ReportMenus(CFMENavigateStep): VIEW = AllReportMenusView prerequisite = NavigateToAttribute("appliance.server", "CloudIntelReports") def step(self, *args, **kwargs): self.prerequisite_view.edit_report_menus.tree.click_path("All EVM Groups")
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/intelligence/reports/menus.py
import attr import importscan import sentaku from cfme.generic_objects.definition.button_groups import GenericObjectButtonGroupsCollection from cfme.generic_objects.definition.button_groups import GenericObjectButtonsCollection from cfme.generic_objects.instance import GenericObjectInstanceCollection from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.update import Updateable @attr.s class GenericObjectDefinition(BaseEntity, Updateable, sentaku.modeling.ElementMixin): """Generic Objects Definition class to context switch between UI and REST. Read/Update/Delete functionality. """ _collections = { 'generic_objects': GenericObjectInstanceCollection, 'generic_object_groups_buttons': GenericObjectButtonGroupsCollection, 'generic_object_buttons': GenericObjectButtonsCollection } update = sentaku.ContextualMethod() delete = sentaku.ContextualMethod() exists = sentaku.ContextualProperty() add_button = sentaku.ContextualMethod() add_button_group = sentaku.ContextualMethod() generic_objects = sentaku.ContextualProperty() generic_object_buttons = sentaku.ContextualProperty() instance_count = sentaku.ContextualProperty() name = attr.ib() description = attr.ib() attributes = attr.ib(default=None) # e.g. {'address': 'string'} associations = attr.ib(default=None) # e.g. {'services': 'Service'} methods = attr.ib(default=None) # e.g. ['method1', 'method2'] custom_image_file_path = attr.ib(default=None) rest_response = attr.ib(default=None, init=False) @attr.s class GenericObjectDefinitionCollection(BaseCollection, sentaku.modeling.ElementMixin): ENTITY = GenericObjectDefinition create = sentaku.ContextualMethod() all = sentaku.ContextualMethod() from cfme.generic_objects.definition import rest, ui # NOQA last for import cycles importscan.scan(rest) importscan.scan(ui)
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/generic_objects/definition/__init__.py
from os import path from urllib.error import URLError import attr from cached_property import cached_property from wrapanapi.systems.container import Openshift from cfme.common import Taggable from cfme.common.provider import DefaultEndpoint from cfme.common.vm_console import ConsoleMixin from cfme.containers.provider import ContainersProvider from cfme.containers.provider import ContainersProviderDefaultEndpoint from cfme.containers.provider import ContainersProviderEndpointsForm from cfme.control.explorer.alert_profiles import NodeAlertProfile from cfme.control.explorer.alert_profiles import ProviderAlertProfile from cfme.utils import ssh from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.log import logger from cfme.utils.ocp_cli import OcpCli from cfme.utils.varmeth import variable from cfme.utils.wait import TimedOutError from cfme.utils.wait import wait_for class CustomAttribute(object): def __init__(self, name, value, field_type=None, href=None): self.name = name self.value = value self.field_type = field_type self.href = href class OpenshiftDefaultEndpoint(ContainersProviderDefaultEndpoint): """Represents Openshift default endpoint""" @staticmethod def get_ca_cert(connection_info): """Getting OpenShift's certificate from the master machine. Args: connection_info (dict): username, password and hostname for OCP returns: certificate's content. """ with ssh.SSHClient(**connection_info) as provider_ssh: _, stdout, _ = provider_ssh.exec_command("cat /etc/origin/master/ca.crt") return str("".join(stdout.readlines())) class ServiceBasedEndpoint(DefaultEndpoint): @property def view_value_mapping(self): out = {'hostname': self.hostname, 'api_port': self.api_port, 'sec_protocol': self.sec_protocol} if out['sec_protocol'] and self.sec_protocol.lower() == 'ssl trusting custom ca': out['trusted_ca_certificates'] = OpenshiftDefaultEndpoint.get_ca_cert( {"username": self.ssh_creds.principal, "password": self.ssh_creds.secret, "hostname": self.master_hostname}) return out class VirtualizationEndpoint(ServiceBasedEndpoint): """Represents virtualization Endpoint""" name = 'virtualization' @property def view_value_mapping(self): # values like host, port are taken from Default endpoint # and not editable in Virtualization endpoint, only token can be added return {'kubevirt_token': self.token} class MetricsEndpoint(ServiceBasedEndpoint): """Represents metrics Endpoint""" name = 'metrics' class AlertsEndpoint(ServiceBasedEndpoint): """Represents Alerts Endpoint""" name = 'alerts' @attr.s(cmp=False) class OpenshiftProvider(ContainersProvider, ConsoleMixin, Taggable): num_route = ['num_route'] STATS_TO_MATCH = ContainersProvider.STATS_TO_MATCH + num_route type_name = "openshift" mgmt_class = Openshift db_types = ["Openshift::ContainerManager"] endpoints_form = ContainersProviderEndpointsForm settings_key = 'ems_openshift' ems_pretty_name = 'OpenShift Container Platform' http_proxy = attr.ib(default=None) adv_http = attr.ib(default=None) adv_https = attr.ib(default=None) no_proxy = attr.ib(default=None) image_repo = attr.ib(default=None) image_reg = attr.ib(default=None) image_tag = attr.ib(default=None) cve_loc = attr.ib(default=None) virt_type = attr.ib(default=None) provider = attr.ib(default=None) def create(self, **kwargs): # Enable alerts collection before adding the provider to avoid missing active # alert after adding the provider # For more info: https://bugzilla.redhat.com/show_bug.cgi?id=1514950 if getattr(self, "alerts_type") == "Prometheus": alert_profiles = self.appliance.collections.alert_profiles provider_profile = alert_profiles.instantiate(ProviderAlertProfile, "Prometheus Provider Profile") node_profile = alert_profiles.instantiate(NodeAlertProfile, "Prometheus node Profile") for profile in [provider_profile, node_profile]: profile.assign_to("The Enterprise") super(OpenshiftProvider, self).create(**kwargs) @cached_property def cli(self): return OcpCli(self) def href(self): return self.appliance.rest_api.collections.providers\ .find_by(name=self.name).resources[0].href @property def view_value_mapping(self): mapping = {'name': self.name, 'zone': self.zone, 'prov_type': ('OpenShift Container Platform' if self.appliance.is_downstream else 'OpenShift')} mapping['metrics_type'] = self.metrics_type mapping['alerts_type'] = self.alerts_type mapping['proxy'] = { 'http_proxy': self.http_proxy } mapping['advanced'] = { 'adv_http': self.adv_http, 'adv_https': self.adv_https, 'no_proxy': self.no_proxy, 'image_repo': self.image_repo, 'image_reg': self.image_reg, 'image_tag': self.image_tag, 'cve_loc': self.cve_loc } mapping['virt_type'] = self.virt_type return mapping @property def is_provider_enabled(self): return self.appliance.rest_api.collections.providers.get(name=self.name).enabled @variable(alias='db') def num_route(self): return self._num_db_generic('container_routes') @num_route.variant('ui') def num_route_ui(self): view = navigate_to(self, "Details") return int(view.entities.summary("Relationships").get_text_of('Container Routes')) @variable(alias='db') def num_template(self): return self._num_db_generic('container_templates') @num_template.variant('ui') def num_template_ui(self): view = navigate_to(self, "Details") return int(view.entities.summary("Relationships").get_text_of("Container Templates")) @classmethod def from_config(cls, prov_config, prov_key, appliance=None): appliance = appliance or cls.appliance endpoints = {} token_creds = cls.process_credential_yaml_key(prov_config['credentials'], cred_type='token') master_hostname = prov_config['endpoints']['default'].hostname ssh_creds = cls.process_credential_yaml_key(prov_config['ssh_creds']) for endp in prov_config['endpoints']: # Add ssh_password for each endpoint, so get_ca_cert # will be able to get SSL cert form OCP for each endpoint setattr(prov_config['endpoints'][endp], "master_hostname", master_hostname) setattr(prov_config['endpoints'][endp], "ssh_creds", ssh_creds) if OpenshiftDefaultEndpoint.name == endp: prov_config['endpoints'][endp]['token'] = token_creds.token endpoints[endp] = OpenshiftDefaultEndpoint(**prov_config['endpoints'][endp]) elif MetricsEndpoint.name == endp: endpoints[endp] = MetricsEndpoint(**prov_config['endpoints'][endp]) elif AlertsEndpoint.name == endp: endpoints[endp] = AlertsEndpoint(**prov_config['endpoints'][endp]) else: raise Exception('Unsupported endpoint type "{}".'.format(endp)) settings = prov_config.get('settings', {}) advanced = settings.get('advanced', {}) http_proxy = settings.get('proxy', {}).get('http_proxy') adv_http, adv_https, no_proxy, image_repo, image_reg, image_tag, cve_loc = [ advanced.get(field) for field in ('adv_http', 'adv_https', 'no_proxy', 'image_repo', 'image_reg', 'image_tag', 'cve_loc') ] return appliance.collections.containers_providers.instantiate( prov_class=cls, name=prov_config.get('name'), key=prov_key, zone=prov_config.get('server_zone'), metrics_type=prov_config.get('metrics_type'), alerts_type=prov_config.get('alerts_type'), endpoints=endpoints, provider_data=prov_config, http_proxy=http_proxy, adv_http=adv_http, adv_https=adv_https, no_proxy=no_proxy, image_repo=image_repo, image_reg=image_reg, image_tag=image_tag, cve_loc=cve_loc, virt_type=prov_config.get('virt_type')) def custom_attributes(self): """returns custom attributes""" response = self.appliance.rest_api.get( path.join(self.href(), 'custom_attributes')) out = [] for attr_dict in response['resources']: attr = self.appliance.rest_api.get(attr_dict['href']) out.append( CustomAttribute( attr['name'], attr['value'], (attr['field_type'] if 'field_type' in attr else None), attr_dict['href'] ) ) return out def add_custom_attributes(self, *custom_attributes): """Adding static custom attributes to provider. Args: custom_attributes: The custom attributes to add. returns: response. """ if not custom_attributes: raise TypeError('{} takes at least 1 argument.' .format(self.add_custom_attributes.__name__)) for c_attr in custom_attributes: if not isinstance(c_attr, CustomAttribute): raise TypeError('All arguments should be of type {}. ({} != {})' .format(CustomAttribute, type(c_attr), CustomAttribute)) payload = { "action": "add", "resources": [{ "name": ca.name, "value": str(ca.value) } for ca in custom_attributes]} for i, fld_tp in enumerate([c_attr.field_type for c_attr in custom_attributes]): if fld_tp: payload['resources'][i]['field_type'] = fld_tp return self.appliance.rest_api.post( path.join(self.href(), 'custom_attributes'), **payload) def edit_custom_attributes(self, *custom_attributes): """Editing static custom attributes in provider. Args: custom_attributes: The custom attributes to edit. returns: response. """ if not custom_attributes: raise TypeError('{} takes at least 1 argument.' .format(self.edit_custom_attributes.__name__)) for c_attr in custom_attributes: if not isinstance(c_attr, CustomAttribute): raise TypeError('All arguments should be of type {}. ({} != {})' .format(CustomAttribute, type(c_attr), CustomAttribute)) attribs = self.custom_attributes() payload = { "action": "edit", "resources": [{ "href": [c_attr for c_attr in attribs if c_attr.name == ca.name][-1].href, "value": ca.value } for ca in custom_attributes]} return self.appliance.rest_api.post( path.join(self.href(), 'custom_attributes'), **payload) def delete_custom_attributes(self, *custom_attributes): """Deleting static custom attributes from provider. Args: custom_attributes: The custom attributes to delete. (Could be also names (str)) Returns: response. """ names = [] for c_attr in custom_attributes: attr_type = type(c_attr) if attr_type in (str, CustomAttribute): names.append(c_attr if attr_type is str else c_attr.name) else: raise TypeError('Type of arguments should be either' 'str or CustomAttribute. ({} not in [str, CustomAttribute])' .format(type(c_attr))) attribs = self.custom_attributes() if not names: names = [attrib.name for attrib in attribs] payload = { "action": "delete", "resources": [{ "href": attrib.href, } for attrib in attribs if attrib.name in names]} return self.appliance.rest_api.post( path.join(self.href(), 'custom_attributes'), **payload) def sync_ssl_certificate(self): """ fixture which sync SSL certificate between CFME and OCP Args: provider (OpenShiftProvider): OCP system to sync cert from appliance (IPAppliance): CFME appliance to sync cert with Returns: None """ def _copy_certificate(): is_succeed = True try: # Copy certificate to the appliance provider_ssh.get_file("/etc/origin/master/ca.crt", "/tmp/ca.crt") appliance_ssh.put_file("/tmp/ca.crt", "/etc/pki/ca-trust/source/anchors/{crt}".format( crt=cert_name)) except URLError: logger.debug("Fail to deploy certificate from Openshift to CFME") is_succeed = False finally: return is_succeed provider_ssh = self.cli.ssh_client appliance_ssh = self.appliance.ssh_client() # Connection to the applince in case of dead connection if not appliance_ssh.connected: appliance_ssh.connect() # Checking if SSL is already configured between appliance and provider, # by send a HTTPS request (using SSL) from the appliance to the provider, # hiding the output and sending back the return code of the action _, stdout, stderr = \ appliance_ssh.exec_command( "curl https://{provider}:8443 -sS > /dev/null;echo $?".format( provider=self.provider_data.hostname)) # Do in case of failure (return code is not 0) if stdout.readline().replace('\n', "") != "0": cert_name = "{provider_name}.ca.crt".format( provider_name=self.provider_data.hostname.split(".")[0]) wait_for(_copy_certificate, num_sec=600, delay=30, message="Copy certificate from OCP to CFME") appliance_ssh.exec_command("update-ca-trust") # restarting evemserverd to apply the new SSL certificate self.appliance.evmserverd.restart() self.appliance.evmserverd.wait_for_running() self.appliance.wait_for_web_ui() def get_system_id(self): mgmt_systems_tbl = self.appliance.db.client['ext_management_systems'] return self.appliance.db.client.session.query(mgmt_systems_tbl).filter( mgmt_systems_tbl.name == self.name).first().id def get_metrics(self, **kwargs): """"Returns all the collected metrics for this provider Args: filters: list of dicts with column name and values e.g [{"resource_type": "Container"}, {"parent_ems_id": "1L"}] metrics_table: Metrics table name, there are few metrics table e.g metrics, metric_rollups, etc Returns: Query object with the relevant records """ filters = kwargs.get("filters", {}) metrics_table = kwargs.get("metrics_table", "metric_rollups") metrics_tbl = self.appliance.db.client[metrics_table] mgmt_system_id = self.get_system_id() logger.info("Getting metrics for {name} (parent_ems_id == {id})".format( name=self.name, id=mgmt_system_id)) if filters: logger.info("Filtering by: {f}".format(f=filters)) filters["parent_ems_id"] = mgmt_system_id return self.appliance.db.client.session.query(metrics_tbl).filter_by(**filters) def wait_for_collected_metrics(self, timeout="50m", table_name="metrics"): """Check the db if gathering collection data Args: timeout: timeout in minutes Return: Bool: is collected metrics count is greater than 0 """ def is_collected(): metrics_count = self.get_metrics(table=table_name).count() logger.info("Current metrics found count is {count}".format(count=metrics_count)) return metrics_count > 0 logger.info("Monitoring DB for metrics collection") result = True try: wait_for(is_collected, timeout=timeout, delay=30) except TimedOutError: logger.error( "Timeout exceeded, No metrics found in MIQ DB for the provider \"{name}\"".format( name=self.name)) result = False finally: return result def pause(self): """ Pause the OCP provider. Returns: API response. """ return self.appliance.rest_api.collections.providers.get(name=self.name).action.pause() def resume(self): """ Resume the OCP provider. Returns: API response. """ return self.appliance.rest_api.collections.providers.get(name=self.name).action.resume()
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/containers/provider/openshift.py
"""An example config:: artifactor: log_dir: /home/test/workspace/cfme_tests/artiout per_run: test #test, run, None reuse_dir: True squash_exceptions: False threaded: False server_address: 127.0.0.1 server_port: 21212 server_enabled: True plugins: ``log_dir`` is the destination for all artifacts ``per_run`` denotes if the test artifacts should be group by run, test, or None ``reuse_dir`` if this is False and Artifactor comes across a dir that has already been used, it will die """ import atexit import os import subprocess from threading import RLock import diaper import pytest from artifactor import ArtifactorClient from cfme.fixtures.pytest_store import store from cfme.fixtures.pytest_store import write_line from cfme.markers.polarion import extract_polarion_ids from cfme.utils.appliance import find_appliance from cfme.utils.blockers import Blocker from cfme.utils.blockers import BZ from cfme.utils.conf import credentials from cfme.utils.conf import env from cfme.utils.log import logger from cfme.utils.net import net_check from cfme.utils.net import random_port from cfme.utils.wait import wait_for UNDER_TEST = False # set to true for artifactor using tests # Create a list of all our passwords for use with the sanitize request later in this module # Filter out all Nones as it will mess the output up. words = [word for word in {v.get('password') for v in credentials.values()} if word is not None] def get_test_idents(item): try: return item.location[2], item.location[0] except AttributeError: try: return item.fspath.strpath, None except AttributeError: return (None, None) def get_name(obj): return (getattr(obj, '_param_name', None) or getattr(obj, 'name', None) or str(obj)) class DummyClient(object): def fire_hook(self, *args, **kwargs): return def terminate(self): return def task_status(self): return def __bool__(self): # DummyClient is always False, # so it's easy to see if we have an artiactor client return False def get_client(art_config, pytest_config): if art_config and not UNDER_TEST: port = getattr(pytest_config.option, 'artifactor_port', None) or \ art_config.get('server_port') or random_port() pytest_config.option.artifactor_port = port art_config['server_port'] = port return ArtifactorClient( art_config['server_address'], art_config['server_port']) else: return DummyClient() def spawn_server(config, art_client): if store.slave_manager or UNDER_TEST: return None import subprocess cmd = ['miq-artifactor-server', '--port', str(art_client.port)] if config.getvalue('run_id'): cmd.append('--run-id') cmd.append(str(config.getvalue('run_id'))) proc = subprocess.Popen(cmd) return proc session_ver = None session_build = None session_stream = None session_fw_version = None def pytest_addoption(parser): parser.addoption("--run-id", action="store", default=None, help="A run id to assist in logging") @pytest.hookimpl(tryfirst=True) def pytest_configure(config): if config.getoption('--help'): return art_client = get_client( art_config=env.get('artifactor', {}), pytest_config=config) # just in case if not store.slave_manager: with diaper: atexit.register(shutdown, config) if art_client: config._art_proc = spawn_server(config, art_client) wait_for( net_check, func_args=[art_client.port, '127.0.0.1'], func_kwargs={'force': True}, num_sec=10, message="wait for artifactor to start") art_client.ready = True else: config._art_proc = None from cfme.utils.log import artifactor_handler artifactor_handler.artifactor = art_client if store.slave_manager: artifactor_handler.slaveid = store.slaveid config._art_client = art_client def fire_art_hook(config, hook, **hook_args): client = getattr(config, '_art_client', None) if client is None: assert UNDER_TEST, 'missing artifactor is only valid for inprocess tests' else: return client.fire_hook(hook, **hook_args) def fire_art_test_hook(node, hook, **hook_args): name, location = get_test_idents(node) return fire_art_hook( node.config, hook, test_name=name, test_location=location, **hook_args) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_protocol(item): global session_ver global session_build global session_stream appliance = find_appliance(item) if not session_ver: session_ver = str(appliance.version) session_build = appliance.build session_stream = appliance.version.stream() if str(session_ver) not in session_build: session_build = "{}-{}".format(str(session_ver), session_build) session_fw_version = None try: proc = subprocess.Popen(['git', 'describe', '--tags'], stdout=subprocess.PIPE) proc.wait() session_fw_version = proc.stdout.read().strip() except Exception: pass # already set session_fw_version to None fire_art_hook( item.config, 'session_info', version=session_ver, build=session_build, stream=session_stream, fw_version=session_fw_version ) tier = item.get_closest_marker('tier') if tier: tier = tier.args[0] requirement = item.get_closest_marker('requirement') if requirement: requirement = requirement.args[0] param_dict = {} try: params = item.callspec.params param_dict = {p: get_name(v) for p, v in params.items()} except Exception: pass # already set param_dict ip = appliance.hostname # This pre_start_test hook is needed so that filedump is able to make get the test # object set up before the logger starts logging. As the logger fires a nested hook # to the filedumper, and we can't specify order inriggerlib. meta = item.get_closest_marker('meta') if meta and 'blockers' in meta.kwargs: blocker_spec = meta.kwargs['blockers'] blockers = [] for blocker in blocker_spec: if isinstance(blocker, int): blockers.append(BZ(blocker).url) else: blockers.append(Blocker.parse(blocker).url) else: blockers = [] fire_art_test_hook( item, 'pre_start_test', slaveid=store.slaveid, ip=ip) fire_art_test_hook( item, 'start_test', slaveid=store.slaveid, ip=ip, tier=tier, requirement=requirement, param_dict=param_dict, issues=blockers) yield def pytest_runtest_teardown(item, nextitem): name, location = get_test_idents(item) app = find_appliance(item) ip = app.hostname fire_art_test_hook( item, 'finish_test', slaveid=store.slaveid, ip=ip, wait_for_task=True) fire_art_test_hook(item, 'sanitize', words=words) jenkins_data = { 'build_url': os.environ.get('BUILD_URL'), 'build_number': os.environ.get('BUILD_NUMBER'), 'git_commit': os.environ.get('GIT_COMMIT'), 'job_name': os.environ.get('JOB_NAME') } param_dict = None try: caps = app.browser.widgetastic.selenium.capabilities param_dict = { 'browserName': caps.get('browserName', 'Unknown'), 'browserPlatform': caps.get('platformName', caps.get('platform', 'Unknown')), 'browserVersion': caps.get('browserVersion', caps.get('version', 'Unknown')) } except Exception: logger.exception("Couldn't grab browser env_vars") pass # already set param_dict fire_art_test_hook( item, 'ostriz_send', env_params=param_dict, slaveid=store.slaveid, polarion_ids=extract_polarion_ids(item), jenkins=jenkins_data) def pytest_runtest_logreport(report): if store.slave_manager: return # each node does its own reporting config = store.config # tech debt name, location = get_test_idents(report) xfail = hasattr(report, 'wasxfail') if hasattr(report, 'skipped'): if report.skipped: fire_art_hook( config, 'filedump', test_location=location, test_name=name, description="Short traceback", contents=report.longreprtext, file_type="short_tb", group_id="skipped") fire_art_hook( config, 'report_test', test_location=location, test_name=name, test_xfail=xfail, test_when=report.when, test_outcome=report.outcome, test_phase_duration=report.duration) fire_art_hook(config, 'build_report') @pytest.hookimpl(hookwrapper=True) def pytest_unconfigure(config): yield shutdown(config) lock = RLock() def shutdown(config): app = find_appliance(config, require=False) if app is not None: with lock: proc = config._art_proc if proc and proc.returncode is None: if not store.slave_manager: write_line('collecting artifacts') fire_art_hook(config, 'finish_session') if not store.slave_manager: config._art_client.terminate() proc.wait()
import pytest from cfme import test_requirements from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.utils.appliance.implementations.ui import navigate_to pytestmark = [ pytest.mark.long_running, pytest.mark.provider(classes=[InfraProvider], selector=ONE_PER_CATEGORY), pytest.mark.usefixtures("setup_provider"), test_requirements.control, ] FILL_DATA = { "event_type": "Datastore Operation", "event_value": "Datastore Analysis Complete", "filter_type": "By Clusters", "filter_value": "Cluster", "submit_button": True } @pytest.mark.tier(1) def test_control_icons_simulation(appliance): """ Bugzilla: 1349147 1690572 Polarion: assignee: jdupuy casecomponent: Control caseimportance: medium initialEstimate: 1/15h testSteps: 1. Have an infrastructure provider 2. Go to Control -> Simulation 3. Select: Type: Datastore Operation Event: Datastore Analysis Complete VM Selection: By Clusters, Default 4. Submit 5. Check for all icons in this page expectedResults: 1. 2. 3. 4. 5. All the icons should be present """ view = navigate_to(appliance.server, "ControlSimulation") view.fill(FILL_DATA) # Now check all the icons assert view.simulation_results.squash_button.is_displayed # Check the tree icons tree = view.simulation_results.tree # Check the root_item assert tree.image_getter(tree.root_item) # Check all the child items for child_item in tree.child_items(tree.root_item): assert tree.image_getter(child_item)
izapolsk/integration_tests
cfme/tests/control/test_control_simulation.py
cfme/fixtures/artifactor_plugin.py
# -*- coding: utf-8 -*- # Mathmaker creates automatically maths exercises sheets # with their answers # Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com> # This file is part of Mathmaker. # Mathmaker is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # Mathmaker is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Mathmaker; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # This module will add a question about the product of two numbers from . import vocabulary_questions class sub_object(vocabulary_questions.structure): def __init__(self, build_data, **options): super().__init__(build_data, result_fct=lambda x, y: x * y, wording=_("How much is the product of {nb1} by " "{nb2}?"), **options)
# -*- coding: utf-8 -*- # Mathmaker creates automatically maths exercises sheets # with their answers # Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com> # This file is part of Mathmaker. # Mathmaker is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # Mathmaker is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Mathmaker; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import pytest from mathmaker.lib.document.content.calculation \ import fraction_of_a_linesegment def test_instanciation_errors(): """Check errors are raised as expected.""" with pytest.raises(ValueError) as excinfo: fraction_of_a_linesegment.sub_object(build_data=[1, 1, 2, 2]) assert str(excinfo.value) == 'Need either 2, or 3 numbers to build this ' \ 'question.' def test_use_cases(): """Check usage cases are correctly handled.""" o = fraction_of_a_linesegment.sub_object(build_data=[2, 3]) assert o.answer_wording == r'$ \dfrac{2}{3} $' o = fraction_of_a_linesegment.sub_object(build_data=[3, 2]) assert o.answer_wording == r'$ \dfrac{2}{3} $' o = fraction_of_a_linesegment.sub_object(build_data=[1, 10]) assert o.answer_wording == r'$ \dfrac{1}{10} $' assert o.transduration == 18 o = fraction_of_a_linesegment.sub_object(build_data=[2, 2, 3]) assert o.answer_wording == r'$ \dfrac{4}{6} $ (or $ \dfrac{2}{3} $)' o = fraction_of_a_linesegment.sub_object(build_data=[36, 56]) assert o.answer_wording == r'$ \dfrac{36}{56} $ (or $ \dfrac{18}{28} $, ' \ r'or $ \dfrac{9}{14} $)' o = fraction_of_a_linesegment.sub_object(build_data=[18, 24]) assert o.answer_wording == r'$ \dfrac{18}{24} $ (or $ \dfrac{9}{12} $, ' \ r'or $ \dfrac{6}{8} $, or $ \dfrac{3}{4} $)' o = fraction_of_a_linesegment.sub_object(build_data=[32, 40]) assert o.answer_wording == r'$ \dfrac{32}{40} $ (or $ \dfrac{16}{20} $, ' \ r'or $ \dfrac{8}{10} $...)' assert o.js_a() == ['4/5', 'any_fraction == 4/5']
nicolashainaux/mathmaker
tests/02_questions/test_fraction_of_a_linesegment.py
mathmaker/lib/document/content/calculation/vocabulary_multi.py
""" pred_type ~~~~~~~~~ Describe the top level prediction required. E.g.: - Produce a prediction for each day in the assessment time range, and score the prediction using the actual events which occurred that day. - Or... same, but on a weekly basis. """ from . import comparitor import logging import tkinter as tk import tkinter.ttk as ttk import open_cp.gui.tk.util as util import open_cp.gui.tk.tooltips as tooltips import open_cp.gui.tk.richtext as richtext import datetime _text = { "main" : ("Prediction Type\n\n" + "Using the selected 'assessment time range' as a base, how often do we want to create predictions, and what time range do we wish to 'score' the prediction on?\n\n" + "Currently supported is making predictions for a whole number of days, and then testing each prediction for a whole number of days." + "You may mix and match, but be aware of 'multiple testing' issues with setting the score interval to be longer than the repeat interval.\n" + "For example, the default setting is 1 day and 1 day. This generates a prediction for every day in the selected assessment time range, and then scores each such prediction by comparing against the actual events for that day.\n" + "Setting to 7 days and 1 day would generate a prediction for every seven days (i.e. once a week) but would score for just the next day. This could be used to test predictions for just one day of the week."), "every" : "Repeat interval:", "everytt" : "How often do we want to create a prediction? Should be a whole number of days.", "score" : "Score time interval:", "scorett" : "How long a period of time should each prediction be compared with reality for? Should be a whole number of days.", "whole_day_warning" : "Currently we only support making predictions for whole days.", "wdw_round" : "Rounded {} to {}", "pp" : "Preview of Prediction ranges", "pp1" : "Predict for {} and score for the next {} day(s)", "dtfmt" : "%a %d %b %Y", } class PredType(comparitor.Comparitor): def __init__(self, model): super().__init__(model) self._every = datetime.timedelta(days=1) self._score = datetime.timedelta(days=1) @staticmethod def describe(): return "Prediction Type required" @staticmethod def order(): return comparitor.TYPE_TOP_LEVEL def make_view(self, parent): self._view = PredTypeView(parent, self) return self._view @property def name(self): return "Predict for every {} days, scoring the next {} days".format( self._every / datetime.timedelta(days=1), self._score / datetime.timedelta(days=1) ) @property def settings_string(self): return None def config(self): return {"resize" : True} def to_dict(self): return { "every_interval" : self.every.total_seconds(), "score_interval" : self.score_length.total_seconds() } def from_dict(self, data): every_seconds = data["every_interval"] self._every = datetime.timedelta(seconds = every_seconds) score_seconds = data["score_interval"] self._score = datetime.timedelta(seconds = score_seconds) @property def every(self): """Period at which to generate predictions.""" return self._every @every.setter def every(self, value): self._every = value @property def score_length(self): """Length of time to score the prediction on.""" return self._score @score_length.setter def score_length(self, value): self._score = value @staticmethod def _just_date(dt): return datetime.datetime(year=dt.year, month=dt.month, day=dt.day) def run(self): """Returns a list of pairs `(start_date, score_duration)`""" _, _, _assess_start, _assess_end = self._model.time_range logger = logging.getLogger(comparitor.COMPARATOR_LOGGER_NAME) assess_start = self._just_date(_assess_start) assess_end = self._just_date(_assess_end) if assess_start != _assess_start or assess_end != _assess_end: logger.warn(_text["whole_day_warning"]) if assess_start != _assess_start: logger.warn(_text["wdw_round"].format(_assess_start, assess_start)) if assess_end != _assess_end: logger.warn(_text["wdw_round"].format(_assess_end, assess_end)) out = [] start = assess_start while True: end = start + self.score_length if end > assess_end: break out.append( (start, self.score_length) ) start += self.every return out class PredTypeView(tk.Frame): def __init__(self, parent, model): super().__init__(parent) self._model = model util.stretchy_rows_cols(self, [0], [0]) self._text = richtext.RichText(self, height=12, scroll="v") self._text.grid(sticky=tk.NSEW, row=0, column=0) self._text.add_text(_text["main"]) frame = ttk.Frame(parent) frame.grid(row=1, column=0, sticky=tk.NSEW) ttk.Label(frame, text=_text["every"]).grid(row=0, column=0, sticky=tk.E, pady=2) self._every_var = tk.StringVar() self._every = ttk.Entry(frame, width=5, textvariable=self._every_var) self._every.grid(row=0, column=1, sticky=tk.W, pady=2) util.IntValidator(self._every, self._every_var, self.change) tooltips.ToolTipYellow(self._every, _text["everytt"]) ttk.Label(frame, text=_text["score"]).grid(row=1, column=0, sticky=tk.E, pady=2) self._score_var = tk.StringVar() self._score = ttk.Entry(frame, width=5, textvariable=self._score_var) self._score.grid(row=1, column=1, sticky=tk.W, pady=2) util.IntValidator(self._score, self._score_var, self.change) tooltips.ToolTipYellow(self._score, _text["scorett"]) self._preview_frame = ttk.LabelFrame(frame, text=_text["pp"]) self._preview_frame.grid(row=2, column=0, columnspan=2, sticky=tk.NSEW, padx=5, pady=5) self._preview_label = ttk.Label(self._preview_frame) self._preview_label.grid(sticky=tk.NSEW) self.update() @staticmethod def _add_time(text, start, length): text.append( _text["pp1"].format(start.strftime(_text["dtfmt"]), length.days) ) def update(self): self._every_var.set( int(self._model.every / datetime.timedelta(days=1)) ) self._score_var.set( int(self._model.score_length / datetime.timedelta(days=1)) ) preds = self._model.run() text = [] for (start, length), _ in zip(preds, range(2)): self._add_time(text, start, length) if len(preds) > 3: text.append("...") if len(preds) > 2: start, length = preds[-1] self._add_time(text, start, length) self._preview_label["text"] = "\n".join(text) def change(self): every = int(self._every_var.get()) if every > 0: self._model.every = datetime.timedelta(days=every) score = int(self._score_var.get()) if score > 0: self._model.score_length = datetime.timedelta(days=score) self.update()
# These are longer tests running on data. import numpy as np import pytest import os import open_cp import open_cp.stscan def read_test_file(basename): coords = [] with open(basename + ".geo") as geofile: for line in geofile: i, x, y = line.split() coords.append( (float(x), float(y)) ) timestamps = [] with open(basename + ".cas") as casefile: for line in casefile: i, count, t = line.split() timestamps.append(np.datetime64(t)) return np.asarray(timestamps), np.asarray(coords).T def test_stscan_slow(): timestamps, points = read_test_file(os.path.join("tests", "sts_test_data")) trainer = open_cp.stscan.STSTrainerSlow() trainer.data = open_cp.TimedPoints.from_coords(timestamps, points[0], points[1]) result = trainer.predict() assert(result.clusters[0].centre[0] == pytest.approx(0.31681704)) assert(result.clusters[0].centre[1] == pytest.approx(0.26506492)) assert(result.clusters[0].radius == pytest.approx(0.1075727)) assert(result.statistics[0] == pytest.approx(1.8503078)) assert(result.time_ranges[0][0] == np.datetime64("2017-01-10")) assert(result.time_ranges[0][1] == np.datetime64("2017-01-10")) assert(result.clusters[1].centre[0] == pytest.approx(0.25221791)) assert(result.clusters[1].centre[1] == pytest.approx(0.9878925)) assert(result.clusters[1].radius == pytest.approx(0.1579045)) assert(result.statistics[1] == pytest.approx(1.2139669)) assert(result.time_ranges[1][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[1][1] == np.datetime64("2017-01-10")) assert(result.clusters[2].centre[0] == pytest.approx(0.77643025)) assert(result.clusters[2].centre[1] == pytest.approx(0.80196054)) assert(result.clusters[2].radius == pytest.approx(0.268662)) assert(result.statistics[2] == pytest.approx(0.81554083)) assert(result.time_ranges[2][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[2][1] == np.datetime64("2017-01-10")) def test_stscan(): timestamps, points = read_test_file(os.path.join("tests", "sts_test_data")) trainer = open_cp.stscan.STSTrainer() trainer.data = open_cp.TimedPoints.from_coords(timestamps, points[0], points[1]) result = trainer.predict() assert(result.statistics[0] == pytest.approx(1.8503078)) # Unfortunately, as long at the statistic stays the same, _which_ cluster # we find is, currently, an implementation detail and not something we can test for. #assert(result.clusters[0].centre[0] == pytest.approx(0.31681704)) #assert(result.clusters[0].centre[1] == pytest.approx(0.26506492)) #assert(result.clusters[0].radius == pytest.approx(0.1075716)) assert(result.clusters[0].centre[0] == pytest.approx(0.31267453)) assert(result.clusters[0].centre[1] == pytest.approx(0.15757309)) assert(result.clusters[0].radius == pytest.approx(0.201690059)) assert(result.time_ranges[0][0] == np.datetime64("2017-01-10")) assert(result.time_ranges[0][1] == np.datetime64("2017-01-10")) assert(result.statistics[1] == pytest.approx(1.2139669)) assert(result.clusters[1].centre[0] == pytest.approx(0.25221791)) assert(result.clusters[1].centre[1] == pytest.approx(0.9878925)) assert(result.clusters[1].radius == pytest.approx(0.1579029)) assert(result.time_ranges[1][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[1][1] == np.datetime64("2017-01-10")) assert(result.statistics[2] == pytest.approx(0.81554083)) #assert(result.clusters[2].centre[0] == pytest.approx(0.77643025)) #assert(result.clusters[2].centre[1] == pytest.approx(0.80196054)) #assert(result.clusters[2].radius == pytest.approx(0.2686593)) assert(result.clusters[2].centre[0] == pytest.approx(0.74277692)) assert(result.clusters[2].centre[1] == pytest.approx(0.79131745)) assert(result.clusters[2].radius == pytest.approx(0.234036572)) assert(result.time_ranges[2][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[2][1] == np.datetime64("2017-01-10"))
QuantCrimAtLeeds/PredictCode
tests/integration_test.py
open_cp/gui/predictors/pred_type.py
""" hierarchical ~~~~~~~~~~~~ An abstract way to view "hierarchical" data. We imagine that we have a spreadsheet of data (or in Python, perhaps a list of tuples). We have columns `0`,...,`n-1` with column `n` storing some data. Each column is associated with finitely many "keys". E.g. A 1 a Bob A 2 a Dave B 1 b Kate B 3 d Amy C 1 c Fred C 1 d Ahmed Column 0 keys are `{A,B,C}` while column 2 keys are `{a,b,c,d}`. We assume that having specified all column keys, we obtain a unique piece of data. However, not all combinations need to valid: in this example, `A,3,c` codes to nothing. We wish to display a drop-down list to select which key to view in each column. If for a given column there is only one key, we should just display this without a widget to choose it. - When the user makes a choice for column 0, all other choices should be refreshed. In our example, if `B` is chosen for column 0, then column 1 should only offer the choices `{1,3}` and column 2 only offers `{b,d}`. - If possible, maintain the current choice. If previously the user had selected `B,3,d` and then choices `C` for column 0, we should fix column 1 as being `1` (this is the only choice) but leave column 2 choice as `d` (with `c` as another choice). For technical reasons (ultimately tied to the usage of `tkinter`) all key values are treated as _strings_ internally. We hide this, a bit, from the user, but you should make sure that: - Any key has a sensibly defined `__str__` method - Calling `str` maintains uniqueness At the level of the model, we work with Python types; but the view and controller convert these to strings internally. The canonical use is in `browse_analysis`. """ from open_cp.gui.tk.hierarchical_view import HierarchicalView class Model(): """(Absract) base class which just defines methods for accessing available keys. :param number_keys: The number of "keys"/"columns" we'll use. """ def __init__(self, number_keys): self._number_keys = number_keys @property def number_keys(self): """The number of keys which defines each entry.""" return self._number_keys @property def current_selection(self): """A tuple giving the current selection.""" return self._selection @current_selection.setter def current_selection(self, key): try: self.get(tuple(key)) self._selection = key except KeyError: raise ValueError("Key not valid") @property def current_item(self): """Return the data item indexed by the current selection.""" return self.get(self.current_selection) def get(self, key): """Obtain the data object corresponding to the key. Should raise :class:`KeyError` on failure to find. :param key: Tuple of length `self.number_keys`, or object which can be converted to a key. """ raise NotImplementedError() def get_key_options(self, partial_key): """Return an iterable of the available keys for the next level, given the partial key. E.g. in our example, - () -> {A,B,C} - (A,) -> {1,2} - (A,1) -> {a} :param partial_key: Tuple, maybe empty, of length less than `self.number_keys` """ raise NotImplementedError() class DictionaryModel(Model): """Implementation of :class:`Model` where the input data is a dictionary, each key of which should be a tuple of a fixed length. We do not assume that the dictionary keys are tuples-- they merely have to be uniquely convertable to a tuple (e.g. have a sensible implementation of `__iter__`). :param dictionary: The input dictionary. We do not make a copy, so it is possible to mutate this, if you are careful... """ def __init__(self, dictionary): super().__init__(self._key_length(dictionary)) self._dict = dictionary @staticmethod def _key_length(dictionary): length = -1 for k in dictionary.keys(): try: k = tuple(k) except: raise ValueError("Keys should be (convertible to) tuples") if length == -1: length = len(k) if len(k) != length: raise ValueError("Keys should be of the same length") return length def get(self, key): try: return self._dict[key] except: key = self._tuple_to_key(key) return self._dict[key] def _tuple_to_key(self, key): key = tuple(key) for k in self._dict.keys(): if tuple(k) == key: return k raise KeyError("Key not valid") def get_key_options(self, partial_key): partial_key = tuple(partial_key) prefix_length = len(partial_key) return { tuple(key)[prefix_length] for key in self._dict.keys() if tuple(key)[:prefix_length] == partial_key } @property def current_selection(self): """A tuple giving the current selection. Will always be a key of the original dictionary, and not necessarily a tuple.""" return self._selection @current_selection.setter def current_selection(self, key): self._selection = self._tuple_to_key(key) class Hierarchical(): """Main class. Pass in the instance of :class:`Model` you wish to use. The "view" can be accessed from the :attr:`view` attribute. Register a callback on a selection change by setting the :attr:`callback` attribute. :param model: Instance of :class:`Model` :param view: View object; typically leave as `None` to use the default :param parent: If you wish to build the default view, pass the `tk` parent widget. """ def __init__(self, model, view=None, parent=None): self._model = model if view is None: view = HierarchicalView(model, self, parent) else: view.controller = self self.view = view self._callback = None self._init() @property def callback(self): """A callable with signature `callback()` which is called when a selection changes. Interrogate the model to see the selection.""" return self._callback @callback.setter def callback(self, v): self._callback = v def _init(self): self._in_fill_choices((), None) def _in_fill_choices(self, partial_selection, old_selection): while len(partial_selection) < self._model.number_keys: index = len(partial_selection) new_choices = list(self._model.get_key_options(partial_selection)) new_choices.sort() self.view.set_choices(index, new_choices) if old_selection is None or old_selection[index] not in new_choices: next_value = new_choices[0] else: next_value = old_selection[index] self.view.set_selection(index, next_value) partial_selection += (next_value,) self._model.current_selection = partial_selection if self.callback is not None: self.callback() def _de_stringify(self, partial_selection, string_value): for k in self._model.get_key_options(partial_selection): if str(k) == string_value: return k raise ValueError() def new_selection(self, level, value): """Notify that the user has selected `value` from column `level`. We should refresh the choices of selections of each subsequent level, aiming to leave the selection unchanged if possible. :param value: Assumed to be the _string representation_ of the key """ if level < 0 or level >= self._model.number_keys: raise ValueError() old_selection = tuple(self._model.current_selection) partial_selection = old_selection[:level] value = self._de_stringify(partial_selection, str(value)) partial_selection += (value,) self._in_fill_choices(partial_selection, old_selection)
# These are longer tests running on data. import numpy as np import pytest import os import open_cp import open_cp.stscan def read_test_file(basename): coords = [] with open(basename + ".geo") as geofile: for line in geofile: i, x, y = line.split() coords.append( (float(x), float(y)) ) timestamps = [] with open(basename + ".cas") as casefile: for line in casefile: i, count, t = line.split() timestamps.append(np.datetime64(t)) return np.asarray(timestamps), np.asarray(coords).T def test_stscan_slow(): timestamps, points = read_test_file(os.path.join("tests", "sts_test_data")) trainer = open_cp.stscan.STSTrainerSlow() trainer.data = open_cp.TimedPoints.from_coords(timestamps, points[0], points[1]) result = trainer.predict() assert(result.clusters[0].centre[0] == pytest.approx(0.31681704)) assert(result.clusters[0].centre[1] == pytest.approx(0.26506492)) assert(result.clusters[0].radius == pytest.approx(0.1075727)) assert(result.statistics[0] == pytest.approx(1.8503078)) assert(result.time_ranges[0][0] == np.datetime64("2017-01-10")) assert(result.time_ranges[0][1] == np.datetime64("2017-01-10")) assert(result.clusters[1].centre[0] == pytest.approx(0.25221791)) assert(result.clusters[1].centre[1] == pytest.approx(0.9878925)) assert(result.clusters[1].radius == pytest.approx(0.1579045)) assert(result.statistics[1] == pytest.approx(1.2139669)) assert(result.time_ranges[1][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[1][1] == np.datetime64("2017-01-10")) assert(result.clusters[2].centre[0] == pytest.approx(0.77643025)) assert(result.clusters[2].centre[1] == pytest.approx(0.80196054)) assert(result.clusters[2].radius == pytest.approx(0.268662)) assert(result.statistics[2] == pytest.approx(0.81554083)) assert(result.time_ranges[2][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[2][1] == np.datetime64("2017-01-10")) def test_stscan(): timestamps, points = read_test_file(os.path.join("tests", "sts_test_data")) trainer = open_cp.stscan.STSTrainer() trainer.data = open_cp.TimedPoints.from_coords(timestamps, points[0], points[1]) result = trainer.predict() assert(result.statistics[0] == pytest.approx(1.8503078)) # Unfortunately, as long at the statistic stays the same, _which_ cluster # we find is, currently, an implementation detail and not something we can test for. #assert(result.clusters[0].centre[0] == pytest.approx(0.31681704)) #assert(result.clusters[0].centre[1] == pytest.approx(0.26506492)) #assert(result.clusters[0].radius == pytest.approx(0.1075716)) assert(result.clusters[0].centre[0] == pytest.approx(0.31267453)) assert(result.clusters[0].centre[1] == pytest.approx(0.15757309)) assert(result.clusters[0].radius == pytest.approx(0.201690059)) assert(result.time_ranges[0][0] == np.datetime64("2017-01-10")) assert(result.time_ranges[0][1] == np.datetime64("2017-01-10")) assert(result.statistics[1] == pytest.approx(1.2139669)) assert(result.clusters[1].centre[0] == pytest.approx(0.25221791)) assert(result.clusters[1].centre[1] == pytest.approx(0.9878925)) assert(result.clusters[1].radius == pytest.approx(0.1579029)) assert(result.time_ranges[1][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[1][1] == np.datetime64("2017-01-10")) assert(result.statistics[2] == pytest.approx(0.81554083)) #assert(result.clusters[2].centre[0] == pytest.approx(0.77643025)) #assert(result.clusters[2].centre[1] == pytest.approx(0.80196054)) #assert(result.clusters[2].radius == pytest.approx(0.2686593)) assert(result.clusters[2].centre[0] == pytest.approx(0.74277692)) assert(result.clusters[2].centre[1] == pytest.approx(0.79131745)) assert(result.clusters[2].radius == pytest.approx(0.234036572)) assert(result.time_ranges[2][0] == np.datetime64("2017-01-09")) assert(result.time_ranges[2][1] == np.datetime64("2017-01-10"))
QuantCrimAtLeeds/PredictCode
tests/integration_test.py
open_cp/gui/hierarchical.py
from threading import Event, Thread, current_thread from time import time from warnings import warn import atexit __all__ = ["TMonitor", "TqdmSynchronisationWarning"] class TqdmSynchronisationWarning(RuntimeWarning): """tqdm multi-thread/-process errors which may cause incorrect nesting but otherwise no adverse effects""" pass class TMonitor(Thread): """ Monitoring thread for tqdm bars. Monitors if tqdm bars are taking too much time to display and readjusts miniters automatically if necessary. Parameters ---------- tqdm_cls : class tqdm class to use (can be core tqdm or a submodule). sleep_interval : fload Time to sleep between monitoring checks. """ # internal vars for unit testing _time = None _event = None def __init__(self, tqdm_cls, sleep_interval): Thread.__init__(self) self.daemon = True # kill thread when main killed (KeyboardInterrupt) self.was_killed = Event() self.woken = 0 # last time woken up, to sync with monitor self.tqdm_cls = tqdm_cls self.sleep_interval = sleep_interval if TMonitor._time is not None: self._time = TMonitor._time else: self._time = time if TMonitor._event is not None: self._event = TMonitor._event else: self._event = Event atexit.register(self.exit) self.start() def exit(self): self.was_killed.set() if self is not current_thread(): self.join() return self.report() def get_instances(self): # returns a copy of started `tqdm_cls` instances return [i for i in self.tqdm_cls._instances.copy() # Avoid race by checking that the instance started if hasattr(i, 'start_t')] def run(self): cur_t = self._time() while True: # After processing and before sleeping, notify that we woke # Need to be done just before sleeping self.woken = cur_t # Sleep some time... self.was_killed.wait(self.sleep_interval) # Quit if killed if self.was_killed.is_set(): return # Then monitor! # Acquire lock (to access _instances) with self.tqdm_cls.get_lock(): cur_t = self._time() # Check tqdm instances are waiting too long to print instances = self.get_instances() for instance in instances: # Check event in loop to reduce blocking time on exit if self.was_killed.is_set(): return # Only if mininterval > 1 (else iterations are just slow) # and last refresh exceeded maxinterval if instance.miniters > 1 and \ (cur_t - instance.last_print_t) >= \ instance.maxinterval: # force bypassing miniters on next iteration # (dynamic_miniters adjusts mininterval automatically) instance.miniters = 1 # Refresh now! (works only for manual tqdm) instance.refresh(nolock=True) if instances != self.get_instances(): # pragma: nocover warn("Set changed size during iteration" + " (see https://github.com/tqdm/tqdm/issues/481)", TqdmSynchronisationWarning, stacklevel=2) def report(self): return not self.was_killed.is_set()
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/externals/tqdm/_tqdm/_monitor.py
# Authors: Joan Massich <mailsik@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from collections import OrderedDict import os.path as op import numpy as np from functools import partial import xml.etree.ElementTree as ElementTree from .montage import make_dig_montage from ..transforms import _sph_to_cart from ..utils import warn, _pl from . import __file__ as _CHANNELS_INIT_FILE MONTAGE_PATH = op.join(op.dirname(_CHANNELS_INIT_FILE), 'data', 'montages') _str = 'U100' # In standard_1020, T9=LPA, T10=RPA, Nasion is the same as Iz with a # sign-flipped Y value def _egi_256(head_size): fname = op.join(MONTAGE_PATH, 'EGI_256.csd') montage = _read_csd(fname, head_size) ch_pos = montage._get_ch_pos() # For this cap, the Nasion is the frontmost electrode, # LPA/RPA we approximate by putting 75% of the way (toward the front) # between the two electrodes that are halfway down the ear holes nasion = ch_pos['E31'] lpa = 0.75 * ch_pos['E67'] + 0.25 * ch_pos['E94'] rpa = 0.75 * ch_pos['E219'] + 0.25 * ch_pos['E190'] fids_montage = make_dig_montage( coord_frame='unknown', nasion=nasion, lpa=lpa, rpa=rpa, ) montage += fids_montage # add fiducials to montage return montage def _easycap(basename, head_size): fname = op.join(MONTAGE_PATH, basename) montage = _read_theta_phi_in_degrees(fname, head_size, add_fiducials=True) return montage def _hydrocel(basename, head_size): fname = op.join(MONTAGE_PATH, basename) return _read_sfp(fname, head_size) def _str_names(ch_names): return [str(ch_name) for ch_name in ch_names] def _safe_np_loadtxt(fname, **kwargs): out = np.genfromtxt(fname, **kwargs) ch_names = _str_names(out['f0']) others = tuple(out['f%d' % ii] for ii in range(1, len(out.dtype.fields))) return (ch_names,) + others def _biosemi(basename, head_size): fname = op.join(MONTAGE_PATH, basename) fid_names = ('Nz', 'LPA', 'RPA') return _read_theta_phi_in_degrees(fname, head_size, fid_names) def _mgh_or_standard(basename, head_size): fid_names = ('Nz', 'LPA', 'RPA') fname = op.join(MONTAGE_PATH, basename) ch_names_, pos = [], [] with open(fname) as fid: # Ignore units as we will scale later using the norms anyway for line in fid: if 'Positions\n' in line: break pos = [] for line in fid: if 'Labels\n' in line: break pos.append(list(map(float, line.split()))) for line in fid: if not line or not set(line) - {' '}: break ch_names_.append(line.strip(' ').strip('\n')) pos = np.array(pos) ch_pos = _check_dupes_odict(ch_names_, pos) nasion, lpa, rpa = [ch_pos.pop(n) for n in fid_names] scale = head_size / np.median(np.linalg.norm(pos, axis=1)) for value in ch_pos.values(): value *= scale nasion *= scale lpa *= scale rpa *= scale return make_dig_montage(ch_pos=ch_pos, coord_frame='unknown', nasion=nasion, lpa=lpa, rpa=rpa) standard_montage_look_up_table = { 'EGI_256': _egi_256, 'easycap-M1': partial(_easycap, basename='easycap-M1.txt'), 'easycap-M10': partial(_easycap, basename='easycap-M10.txt'), 'GSN-HydroCel-128': partial(_hydrocel, basename='GSN-HydroCel-128.sfp'), 'GSN-HydroCel-129': partial(_hydrocel, basename='GSN-HydroCel-129.sfp'), 'GSN-HydroCel-256': partial(_hydrocel, basename='GSN-HydroCel-256.sfp'), 'GSN-HydroCel-257': partial(_hydrocel, basename='GSN-HydroCel-257.sfp'), 'GSN-HydroCel-32': partial(_hydrocel, basename='GSN-HydroCel-32.sfp'), 'GSN-HydroCel-64_1.0': partial(_hydrocel, basename='GSN-HydroCel-64_1.0.sfp'), 'GSN-HydroCel-65_1.0': partial(_hydrocel, basename='GSN-HydroCel-65_1.0.sfp'), 'biosemi128': partial(_biosemi, basename='biosemi128.txt'), 'biosemi16': partial(_biosemi, basename='biosemi16.txt'), 'biosemi160': partial(_biosemi, basename='biosemi160.txt'), 'biosemi256': partial(_biosemi, basename='biosemi256.txt'), 'biosemi32': partial(_biosemi, basename='biosemi32.txt'), 'biosemi64': partial(_biosemi, basename='biosemi64.txt'), 'mgh60': partial(_mgh_or_standard, basename='mgh60.elc'), 'mgh70': partial(_mgh_or_standard, basename='mgh70.elc'), 'standard_1005': partial(_mgh_or_standard, basename='standard_1005.elc'), 'standard_1020': partial(_mgh_or_standard, basename='standard_1020.elc'), 'standard_alphabetic': partial(_mgh_or_standard, basename='standard_alphabetic.elc'), 'standard_postfixed': partial(_mgh_or_standard, basename='standard_postfixed.elc'), 'standard_prefixed': partial(_mgh_or_standard, basename='standard_prefixed.elc'), 'standard_primed': partial(_mgh_or_standard, basename='standard_primed.elc'), } def _read_sfp(fname, head_size): """Read .sfp BESA/EGI files.""" # fname has been already checked fid_names = ('FidNz', 'FidT9', 'FidT10') options = dict(dtype=(_str, 'f4', 'f4', 'f4')) ch_names, xs, ys, zs = _safe_np_loadtxt(fname, **options) # deal with "headshape" mask = np.array([ch_name == 'headshape' for ch_name in ch_names], bool) hsp = np.stack([xs[mask], ys[mask], zs[mask]], axis=-1) mask = ~mask pos = np.stack([xs[mask], ys[mask], zs[mask]], axis=-1) ch_names = [ch_name for ch_name, m in zip(ch_names, mask) if m] ch_pos = _check_dupes_odict(ch_names, pos) del xs, ys, zs, ch_names # no one grants that fid names are there. nasion, lpa, rpa = [ch_pos.pop(n, None) for n in fid_names] if head_size is not None: scale = head_size / np.median(np.linalg.norm(pos, axis=-1)) for value in ch_pos.values(): value *= scale nasion = nasion * scale if nasion is not None else None lpa = lpa * scale if lpa is not None else None rpa = rpa * scale if rpa is not None else None return make_dig_montage(ch_pos=ch_pos, coord_frame='unknown', nasion=nasion, rpa=rpa, lpa=lpa, hsp=hsp) def _read_csd(fname, head_size): # Label, Theta, Phi, Radius, X, Y, Z, off sphere surface options = dict(comments='//', dtype=(_str, 'f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4')) ch_names, _, _, _, xs, ys, zs, _ = _safe_np_loadtxt(fname, **options) pos = np.stack([xs, ys, zs], axis=-1) if head_size is not None: pos *= head_size / np.median(np.linalg.norm(pos, axis=1)) return make_dig_montage(ch_pos=_check_dupes_odict(ch_names, pos)) def _check_dupes_odict(ch_names, pos): """Warn if there are duplicates, then turn to ordered dict.""" ch_names = list(ch_names) dups = OrderedDict((ch_name, ch_names.count(ch_name)) for ch_name in ch_names) dups = OrderedDict((ch_name, count) for ch_name, count in dups.items() if count > 1) n = len(dups) if n: dups = ', '.join( f'{ch_name} ({count})' for ch_name, count in dups.items()) warn(f'Duplicate channel position{_pl(n)} found, the last will be ' f'used for {dups}') return OrderedDict(zip(ch_names, pos)) def _read_elc(fname, head_size): """Read .elc files. Parameters ---------- fname : str File extension is expected to be '.elc'. head_size : float | None The size of the head in [m]. If none, returns the values read from the file with no modification. Returns ------- montage : instance of DigMontage The montage in [m]. """ fid_names = ('Nz', 'LPA', 'RPA') ch_names_, pos = [], [] with open(fname) as fid: # _read_elc does require to detect the units. (see _mgh_or_standard) for line in fid: if 'UnitPosition' in line: units = line.split()[1] scale = dict(m=1., mm=1e-3)[units] break else: raise RuntimeError('Could not detect units in file %s' % fname) for line in fid: if 'Positions\n' in line: break pos = [] for line in fid: if 'Labels\n' in line: break pos.append(list(map(float, line.split()))) for line in fid: if not line or not set(line) - {' '}: break ch_names_.append(line.strip(' ').strip('\n')) pos = np.array(pos) * scale if head_size is not None: pos *= head_size / np.median(np.linalg.norm(pos, axis=1)) ch_pos = _check_dupes_odict(ch_names_, pos) nasion, lpa, rpa = [ch_pos.pop(n, None) for n in fid_names] return make_dig_montage(ch_pos=ch_pos, coord_frame='unknown', nasion=nasion, lpa=lpa, rpa=rpa) def _read_theta_phi_in_degrees(fname, head_size, fid_names=None, add_fiducials=False): ch_names, theta, phi = _safe_np_loadtxt(fname, skip_header=1, dtype=(_str, 'i4', 'i4')) if add_fiducials: # Add fiducials based on 10/20 spherical coordinate definitions # http://chgd.umich.edu/wp-content/uploads/2014/06/ # 10-20_system_positioning.pdf # extrapolated from other sensor coordinates in the Easycap layouts # https://www.easycap.de/wp-content/uploads/2018/02/ # Easycap-Equidistant-Layouts.pdf assert fid_names is None fid_names = ['Nasion', 'LPA', 'RPA'] ch_names.extend(fid_names) theta = np.append(theta, [115, -115, 115]) phi = np.append(phi, [90, 0, 0]) radii = np.full(len(phi), head_size) pos = _sph_to_cart(np.array([radii, np.deg2rad(phi), np.deg2rad(theta)]).T) ch_pos = _check_dupes_odict(ch_names, pos) nasion, lpa, rpa = None, None, None if fid_names is not None: nasion, lpa, rpa = [ch_pos.pop(n, None) for n in fid_names] return make_dig_montage(ch_pos=ch_pos, coord_frame='unknown', nasion=nasion, lpa=lpa, rpa=rpa) def _read_elp_besa(fname, head_size): # This .elp is not the same as polhemus elp. see _read_isotrak_elp_points dtype = np.dtype('S8, S8, f8, f8, f8') try: data = np.loadtxt(fname, dtype=dtype, skip_header=1) except TypeError: data = np.loadtxt(fname, dtype=dtype, skiprows=1) ch_names = data['f1'].astype(str).tolist() az = data['f2'] horiz = data['f3'] radius = np.abs(az / 180.) az = np.deg2rad(np.array([h if a >= 0. else 180 + h for h, a in zip(horiz, az)])) pol = radius * np.pi rad = data['f4'] / 100 pos = _sph_to_cart(np.array([rad, az, pol]).T) if head_size is not None: pos *= head_size / np.median(np.linalg.norm(pos, axis=1)) ch_pos = _check_dupes_odict(ch_names, pos) fid_names = ('Nz', 'LPA', 'RPA') # No one grants that the fid names actually exist. nasion, lpa, rpa = [ch_pos.pop(n, None) for n in fid_names] return make_dig_montage(ch_pos=ch_pos, nasion=nasion, lpa=lpa, rpa=rpa) def _read_brainvision(fname, head_size): # 'BrainVision Electrodes File' format # Based on BrainVision Analyzer coordinate system: Defined between # standard electrode positions: X-axis from T7 to T8, Y-axis from Oz to # Fpz, Z-axis orthogonal from XY-plane through Cz, fit to a sphere if # idealized (when radius=1), specified in millimeters root = ElementTree.parse(fname).getroot() ch_names = [s.text for s in root.findall("./Electrode/Name")] theta = [float(s.text) for s in root.findall("./Electrode/Theta")] pol = np.deg2rad(np.array(theta)) phi = [float(s.text) for s in root.findall("./Electrode/Phi")] az = np.deg2rad(np.array(phi)) rad = [float(s.text) for s in root.findall("./Electrode/Radius")] rad = np.array(rad) # specified in mm pos = _sph_to_cart(np.array([rad, az, pol]).T) if head_size is not None: pos *= head_size / np.median(np.linalg.norm(pos, axis=1)) return make_dig_montage(ch_pos=_check_dupes_odict(ch_names, pos))
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/channels/_standard_montage_utils.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD Style. import os import os.path as op from ..utils import _manifest_check_download, _get_path from ...utils import (verbose, get_subjects_dir, set_config) FSAVERAGE_MANIFEST_PATH = op.dirname(__file__) @verbose def fetch_fsaverage(subjects_dir=None, verbose=None): """Fetch and update fsaverage. Parameters ---------- subjects_dir : str | None The path to use as the subjects directory in the MNE-Python config file. None will use the existing config variable (i.e., will not change anything), and if it does not exist, will use ``~/mne_data/MNE-fsaverage-data``. %(verbose)s Returns ------- fs_dir : str The fsaverage directory. (essentially ``subjects_dir + '/fsaverage'``). Notes ----- This function is designed to provide 1. All modern (Freesurfer 6) fsaverage subject files 2. All MNE fsaverage parcellations 3. fsaverage head surface, fiducials, head<->MRI trans, 1- and 3-layer BEMs (and surfaces) This function will compare the contents of ``subjects_dir/fsaverage`` to the ones provided in the remote zip file. If any are missing, the zip file is downloaded and files are updated. No files will be overwritten. .. versionadded:: 0.18 """ # Code used to create the BEM (other files taken from MNE-sample-data): # # $ mne watershed_bem -s fsaverage -d $PWD --verbose info --copy # $ python # >>> bem = mne.make_bem_model('fsaverage', subjects_dir='.', verbose=True) # >>> mne.write_bem_surfaces( # ... 'fsaverage/bem/fsaverage-5120-5120-5120-bem.fif', bem) # >>> sol = mne.make_bem_solution(bem, verbose=True) # >>> mne.write_bem_solution( # ... 'fsaverage/bem/fsaverage-5120-5120-5120-bem-sol.fif', sol) # >>> import os # >>> import os.path as op # >>> names = sorted(op.join(r, f) # ... for r, d, files in os.walk('fsaverage') # ... for f in files) # with open('fsaverage.txt', 'w') as fid: # fid.write('\n'.join(names)) # subjects_dir = _set_montage_coreg_path(subjects_dir) subjects_dir = op.abspath(subjects_dir) fs_dir = op.join(subjects_dir, 'fsaverage') os.makedirs(fs_dir, exist_ok=True) _manifest_check_download( manifest_path=op.join(FSAVERAGE_MANIFEST_PATH, 'root.txt'), destination=op.join(subjects_dir), url='https://osf.io/3bxqt/download?revision=2', hash_='5133fe92b7b8f03ae19219d5f46e4177', ) _manifest_check_download( manifest_path=op.join(FSAVERAGE_MANIFEST_PATH, 'bem.txt'), destination=op.join(subjects_dir, 'fsaverage'), url='https://osf.io/7ve8g/download?revision=4', hash_='b31509cdcf7908af6a83dc5ee8f49fb1', ) return fs_dir def _get_create_subjects_dir(subjects_dir): subjects_dir = get_subjects_dir(subjects_dir, raise_error=False) if subjects_dir is None: subjects_dir = _get_path(None, 'MNE_DATA', 'montage coregistration') subjects_dir = op.join(subjects_dir, 'MNE-fsaverage-data') os.makedirs(subjects_dir, exist_ok=True) return subjects_dir def _set_montage_coreg_path(subjects_dir=None): """Set a subject directory suitable for montage(-only) coregistration. Parameters ---------- subjects_dir : str | None The path to use as the subjects directory in the MNE-Python config file. None will use the existing config variable (i.e., will not change anything), and if it does not exist, will use ``~/mne_data/MNE-fsaverage-data``. Returns ------- subjects_dir : str The subjects directory that was used. See Also -------- mne.datasets.fetch_fsaverage mne.get_config mne.set_config Notes ----- If you plan to only do EEG-montage based coregistrations with fsaverage without any MRI warping, this function can facilitate the process. Essentially it sets the default value for ``subjects_dir`` in MNE functions to be ``~/mne_data/MNE-fsaverage-data`` (assuming it has not already been set to some other value). .. versionadded:: 0.18 """ subjects_dir = _get_create_subjects_dir(subjects_dir) old_subjects_dir = get_subjects_dir(None, raise_error=False) if old_subjects_dir is None: set_config('SUBJECTS_DIR', subjects_dir) return subjects_dir
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/datasets/_fsaverage/base.py
"""Brainstorm datasets.""" from . import (bst_raw, bst_resting, bst_auditory, bst_phantom_ctf, bst_phantom_elekta)
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/datasets/brainstorm/__init__.py
#!/usr/bin/env python """Compare FIFF files. Examples -------- .. code-block:: console $ mne compare_fiff test_raw.fif test_raw_sss.fif """ # Authors : Eric Larson, PhD import sys import mne def run(): """Run command.""" parser = mne.commands.utils.get_optparser( __file__, usage='mne compare_fiff <file_a> <file_b>') options, args = parser.parse_args() if len(args) != 2: parser.print_help() sys.exit(1) mne.viz.compare_fiff(args[0], args[1]) mne.utils.run_command_if_main()
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/commands/mne_compare_fiff.py
# -*- coding: utf-8 -*- """Coregistration between different coordinate frames.""" # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) import configparser import fnmatch from glob import glob, iglob import os import os.path as op import stat import sys import re import shutil from functools import reduce import numpy as np from .io import read_fiducials, write_fiducials, read_info from .io.constants import FIFF from .label import read_label, Label from .source_space import (add_source_space_distances, read_source_spaces, write_source_spaces, read_talxfm, _read_mri_info) from .surface import read_surface, write_surface, _normalize_vectors from .bem import read_bem_surfaces, write_bem_surfaces from .transforms import (rotation, rotation3d, scaling, translation, Transform, _read_fs_xfm, _write_fs_xfm, invert_transform, combine_transforms, apply_trans, _quat_to_euler, _fit_matched_points) from .utils import (get_config, get_subjects_dir, logger, pformat, verbose, warn, has_nibabel) from .viz._3d import _fiducial_coords # some path templates trans_fname = os.path.join('{raw_dir}', '{subject}-trans.fif') subject_dirname = os.path.join('{subjects_dir}', '{subject}') bem_dirname = os.path.join(subject_dirname, 'bem') mri_dirname = os.path.join(subject_dirname, 'mri') mri_transforms_dirname = os.path.join(subject_dirname, 'mri', 'transforms') surf_dirname = os.path.join(subject_dirname, 'surf') bem_fname = os.path.join(bem_dirname, "{subject}-{name}.fif") head_bem_fname = pformat(bem_fname, name='head') fid_fname = pformat(bem_fname, name='fiducials') fid_fname_general = os.path.join(bem_dirname, "{head}-fiducials.fif") src_fname = os.path.join(bem_dirname, '{subject}-{spacing}-src.fif') _head_fnames = (os.path.join(bem_dirname, 'outer_skin.surf'), head_bem_fname) _high_res_head_fnames = (os.path.join(bem_dirname, '{subject}-head-dense.fif'), os.path.join(surf_dirname, 'lh.seghead'), os.path.join(surf_dirname, 'lh.smseghead')) def _make_writable(fname): """Make a file writable.""" os.chmod(fname, stat.S_IMODE(os.lstat(fname)[stat.ST_MODE]) | 128) # write def _make_writable_recursive(path): """Recursively set writable.""" if sys.platform.startswith('win'): return # can't safely set perms for root, dirs, files in os.walk(path, topdown=False): for f in dirs + files: _make_writable(os.path.join(root, f)) def _find_head_bem(subject, subjects_dir, high_res=False): """Find a high resolution head.""" # XXX this should be refactored with mne.surface.get_head_surf ... fnames = _high_res_head_fnames if high_res else _head_fnames for fname in fnames: path = fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): return path def coregister_fiducials(info, fiducials, tol=0.01): """Create a head-MRI transform by aligning 3 fiducial points. Parameters ---------- info : Info Measurement info object with fiducials in head coordinate space. fiducials : str | list of dict Fiducials in MRI coordinate space (either path to a ``*-fiducials.fif`` file or list of fiducials as returned by :func:`read_fiducials`. Returns ------- trans : Transform The device-MRI transform. """ if isinstance(info, str): info = read_info(info) if isinstance(fiducials, str): fiducials, coord_frame_to = read_fiducials(fiducials) else: coord_frame_to = FIFF.FIFFV_COORD_MRI frames_from = {d['coord_frame'] for d in info['dig']} if len(frames_from) > 1: raise ValueError("info contains fiducials from different coordinate " "frames") else: coord_frame_from = frames_from.pop() coords_from = _fiducial_coords(info['dig']) coords_to = _fiducial_coords(fiducials, coord_frame_to) trans = fit_matched_points(coords_from, coords_to, tol=tol) return Transform(coord_frame_from, coord_frame_to, trans) @verbose def create_default_subject(fs_home=None, update=False, subjects_dir=None, verbose=None): """Create an average brain subject for subjects without structural MRI. Create a copy of fsaverage from the Freesurfer directory in subjects_dir and add auxiliary files from the mne package. Parameters ---------- fs_home : None | str The freesurfer home directory (only needed if FREESURFER_HOME is not specified as environment variable). update : bool In cases where a copy of the fsaverage brain already exists in the subjects_dir, this option allows to only copy files that don't already exist in the fsaverage directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (os.environ['SUBJECTS_DIR']) as destination for the new subject. %(verbose)s Notes ----- When no structural MRI is available for a subject, an average brain can be substituted. Freesurfer comes with such an average brain model, and MNE comes with some auxiliary files which make coregistration easier. :py:func:`create_default_subject` copies the relevant files from Freesurfer into the current subjects_dir, and also adds the auxiliary files provided by MNE. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if fs_home is None: fs_home = get_config('FREESURFER_HOME', fs_home) if fs_home is None: raise ValueError( "FREESURFER_HOME environment variable not found. Please " "specify the fs_home parameter in your call to " "create_default_subject().") # make sure freesurfer files exist fs_src = os.path.join(fs_home, 'subjects', 'fsaverage') if not os.path.exists(fs_src): raise IOError('fsaverage not found at %r. Is fs_home specified ' 'correctly?' % fs_src) for name in ('label', 'mri', 'surf'): dirname = os.path.join(fs_src, name) if not os.path.isdir(dirname): raise IOError("Freesurfer fsaverage seems to be incomplete: No " "directory named %s found in %s" % (name, fs_src)) # make sure destination does not already exist dest = os.path.join(subjects_dir, 'fsaverage') if dest == fs_src: raise IOError( "Your subjects_dir points to the freesurfer subjects_dir (%r). " "The default subject can not be created in the freesurfer " "installation directory; please specify a different " "subjects_dir." % subjects_dir) elif (not update) and os.path.exists(dest): raise IOError( "Can not create fsaverage because %r already exists in " "subjects_dir %r. Delete or rename the existing fsaverage " "subject folder." % ('fsaverage', subjects_dir)) # copy fsaverage from freesurfer logger.info("Copying fsaverage subject from freesurfer directory...") if (not update) or not os.path.exists(dest): shutil.copytree(fs_src, dest) _make_writable_recursive(dest) # copy files from mne source_fname = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage', 'fsaverage-%s.fif') dest_bem = os.path.join(dest, 'bem') if not os.path.exists(dest_bem): os.mkdir(dest_bem) logger.info("Copying auxiliary fsaverage files from mne...") dest_fname = os.path.join(dest_bem, 'fsaverage-%s.fif') _make_writable_recursive(dest_bem) for name in ('fiducials', 'head', 'inner_skull-bem', 'trans'): if not os.path.exists(dest_fname % name): shutil.copy(source_fname % name, dest_bem) def _decimate_points(pts, res=10): """Decimate the number of points using a voxel grid. Create a voxel grid with a specified resolution and retain at most one point per voxel. For each voxel, the point closest to its center is retained. Parameters ---------- pts : array, shape (n_points, 3) The points making up the head shape. res : scalar The resolution of the voxel space (side length of each voxel). Returns ------- pts : array, shape = (n_points, 3) The decimated points. """ from scipy.spatial.distance import cdist pts = np.asarray(pts) # find the bin edges for the voxel space xmin, ymin, zmin = pts.min(0) - res / 2. xmax, ymax, zmax = pts.max(0) + res xax = np.arange(xmin, xmax, res) yax = np.arange(ymin, ymax, res) zax = np.arange(zmin, zmax, res) # find voxels containing one or more point H, _ = np.histogramdd(pts, bins=(xax, yax, zax), normed=False) # for each voxel, select one point X, Y, Z = pts.T out = np.empty((np.sum(H > 0), 3)) for i, (xbin, ybin, zbin) in enumerate(zip(*np.nonzero(H))): x = xax[xbin] y = yax[ybin] z = zax[zbin] xi = np.logical_and(X >= x, X < x + res) yi = np.logical_and(Y >= y, Y < y + res) zi = np.logical_and(Z >= z, Z < z + res) idx = np.logical_and(zi, np.logical_and(yi, xi)) ipts = pts[idx] mid = np.array([x, y, z]) + res / 2. dist = cdist(ipts, [mid]) i_min = np.argmin(dist) ipt = ipts[i_min] out[i] = ipt return out def _trans_from_params(param_info, params): """Convert transformation parameters into a transformation matrix. Parameters ---------- param_info : tuple, len = 3 Tuple describing the parameters in x (do_translate, do_rotate, do_scale). params : tuple The transformation parameters. Returns ------- trans : array, shape = (4, 4) Transformation matrix. """ do_rotate, do_translate, do_scale = param_info i = 0 trans = [] if do_rotate: x, y, z = params[:3] trans.append(rotation(x, y, z)) i += 3 if do_translate: x, y, z = params[i:i + 3] trans.insert(0, translation(x, y, z)) i += 3 if do_scale == 1: s = params[i] trans.append(scaling(s, s, s)) elif do_scale == 3: x, y, z = params[i:i + 3] trans.append(scaling(x, y, z)) trans = reduce(np.dot, trans) return trans _ALLOW_ANALITICAL = True # XXX this function should be moved out of coreg as used elsewhere def fit_matched_points(src_pts, tgt_pts, rotate=True, translate=True, scale=False, tol=None, x0=None, out='trans', weights=None): """Find a transform between matched sets of points. This minimizes the squared distance between two matching sets of points. Uses :func:`scipy.optimize.leastsq` to find a transformation involving a combination of rotation, translation, and scaling (in that order). Parameters ---------- src_pts : array, shape = (n, 3) Points to which the transform should be applied. tgt_pts : array, shape = (n, 3) Points to which src_pts should be fitted. Each point in tgt_pts should correspond to the point in src_pts with the same index. rotate : bool Allow rotation of the ``src_pts``. translate : bool Allow translation of the ``src_pts``. scale : bool Number of scaling parameters. With False, points are not scaled. With True, points are scaled by the same factor along all axes. tol : scalar | None The error tolerance. If the distance between any of the matched points exceeds this value in the solution, a RuntimeError is raised. With None, no error check is performed. x0 : None | tuple Initial values for the fit parameters. out : 'params' | 'trans' In what format to return the estimate: 'params' returns a tuple with the fit parameters; 'trans' returns a transformation matrix of shape (4, 4). Returns ------- trans : array, shape (4, 4) Transformation that, if applied to src_pts, minimizes the squared distance to tgt_pts. Only returned if out=='trans'. params : array, shape (n_params, ) A single tuple containing the rotation, translation, and scaling parameters in that order (as applicable). """ src_pts = np.atleast_2d(src_pts) tgt_pts = np.atleast_2d(tgt_pts) if src_pts.shape != tgt_pts.shape: raise ValueError("src_pts and tgt_pts must have same shape (got " "{}, {})".format(src_pts.shape, tgt_pts.shape)) if weights is not None: weights = np.asarray(weights, src_pts.dtype) if weights.ndim != 1 or weights.size not in (src_pts.shape[0], 1): raise ValueError("weights (shape=%s) must be None or have shape " "(%s,)" % (weights.shape, src_pts.shape[0],)) weights = weights[:, np.newaxis] param_info = (bool(rotate), bool(translate), int(scale)) del rotate, translate, scale # very common use case, rigid transformation (maybe with one scale factor, # with or without weighted errors) if param_info in ((True, True, 0), (True, True, 1)) and _ALLOW_ANALITICAL: src_pts = np.asarray(src_pts, float) tgt_pts = np.asarray(tgt_pts, float) x, s = _fit_matched_points( src_pts, tgt_pts, weights, bool(param_info[2])) x[:3] = _quat_to_euler(x[:3]) x = np.concatenate((x, [s])) if param_info[2] else x else: x = _generic_fit(src_pts, tgt_pts, param_info, weights, x0) # re-create the final transformation matrix if (tol is not None) or (out == 'trans'): trans = _trans_from_params(param_info, x) # assess the error of the solution if tol is not None: src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) est_pts = np.dot(src_pts, trans.T)[:, :3] err = np.sqrt(np.sum((est_pts - tgt_pts) ** 2, axis=1)) if np.any(err > tol): raise RuntimeError("Error exceeds tolerance. Error = %r" % err) if out == 'params': return x elif out == 'trans': return trans else: raise ValueError("Invalid out parameter: %r. Needs to be 'params' or " "'trans'." % out) def _generic_fit(src_pts, tgt_pts, param_info, weights, x0): from scipy.optimize import leastsq if param_info[1]: # translate src_pts = np.hstack((src_pts, np.ones((len(src_pts), 1)))) if param_info == (True, False, 0): def error(x): rx, ry, rz = x trans = rotation3d(rx, ry, rz) est = np.dot(src_pts, trans.T) d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0) elif param_info == (True, True, 0): def error(x): rx, ry, rz, tx, ty, tz = x trans = np.dot(translation(tx, ty, tz), rotation(rx, ry, rz)) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0) elif param_info == (True, True, 1): def error(x): rx, ry, rz, tx, ty, tz, s = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(s, s, s))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1) elif param_info == (True, True, 3): def error(x): rx, ry, rz, tx, ty, tz, sx, sy, sz = x trans = reduce(np.dot, (translation(tx, ty, tz), rotation(rx, ry, rz), scaling(sx, sy, sz))) est = np.dot(src_pts, trans.T)[:, :3] d = tgt_pts - est if weights is not None: d *= weights return d.ravel() if x0 is None: x0 = (0, 0, 0, 0, 0, 0, 1, 1, 1) else: raise NotImplementedError( "The specified parameter combination is not implemented: " "rotate=%r, translate=%r, scale=%r" % param_info) x, _, _, _, _ = leastsq(error, x0, full_output=True) return x def _find_label_paths(subject='fsaverage', pattern=None, subjects_dir=None): """Find paths to label files in a subject's label directory. Parameters ---------- subject : str Name of the mri subject. pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "aparc/*.label" will find all labels in the "subject/label/aparc" directory). With None, find all labels. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : list List of paths relative to the subject's label directory """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_dir = os.path.join(subjects_dir, subject) lbl_dir = os.path.join(subject_dir, 'label') if pattern is None: paths = [] for dirpath, _, filenames in os.walk(lbl_dir): rel_dir = os.path.relpath(dirpath, lbl_dir) for filename in fnmatch.filter(filenames, '*.label'): path = os.path.join(rel_dir, filename) paths.append(path) else: paths = [os.path.relpath(path, lbl_dir) for path in iglob(pattern)] return paths def _find_mri_paths(subject, skip_fiducials, subjects_dir): """Find all files of an mri relevant for source transformation. Parameters ---------- subject : str Name of the mri subject. skip_fiducials : bool Do not scale the MRI fiducials. If False, an IOError will be raised if no fiducials file can be found. subjects_dir : None | str Override the SUBJECTS_DIR environment variable (sys.environ['SUBJECTS_DIR']) Returns ------- paths : dict Dictionary whose keys are relevant file type names (str), and whose values are lists of paths. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = {} # directories to create paths['dirs'] = [bem_dirname, surf_dirname] # surf/ files paths['surf'] = [] surf_fname = os.path.join(surf_dirname, '{name}') surf_names = ('inflated', 'white', 'orig', 'orig_avg', 'inflated_avg', 'inflated_pre', 'pial', 'pial_avg', 'smoothwm', 'white_avg', 'seghead', 'smseghead') if os.getenv('_MNE_FEW_SURFACES', '') == 'true': # for testing surf_names = surf_names[:4] for surf_name in surf_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=name)) surf_fname = os.path.join(bem_dirname, '{name}') surf_names = ('inner_skull.surf', 'outer_skull.surf', 'outer_skin.surf') for surf_name in surf_names: path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=surf_name) if os.path.exists(path): paths['surf'].append(pformat(surf_fname, name=surf_name)) del surf_names, surf_name, path, hemi # BEM files paths['bem'] = bem = [] path = head_bem_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): bem.append('head') bem_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='*-bem') re_pattern = pformat(bem_fname, subjects_dir=subjects_dir, subject=subject, name='(.+)').replace('\\', '\\\\') for path in iglob(bem_pattern): match = re.match(re_pattern, path) name = match.group(1) bem.append(name) del bem, path, bem_pattern, re_pattern # fiducials if skip_fiducials: paths['fid'] = [] else: paths['fid'] = _find_fiducials_files(subject, subjects_dir) # check that we found at least one if len(paths['fid']) == 0: raise IOError("No fiducials file found for %s. The fiducials " "file should be named " "{subject}/bem/{subject}-fiducials.fif. In " "order to scale an MRI without fiducials set " "skip_fiducials=True." % subject) # duplicate files (curvature and some surfaces) paths['duplicate'] = [] path = os.path.join(surf_dirname, '{name}') surf_fname = os.path.join(surf_dirname, '{name}') surf_dup_names = ('curv', 'sphere', 'sphere.reg', 'sphere.reg.avg') for surf_dup_name in surf_dup_names: for hemi in ('lh.', 'rh.'): name = hemi + surf_dup_name path = surf_fname.format(subjects_dir=subjects_dir, subject=subject, name=name) if os.path.exists(path): paths['duplicate'].append(pformat(surf_fname, name=name)) del surf_dup_name, name, path, hemi # transform files (talairach) paths['transforms'] = [] transform_fname = os.path.join(mri_transforms_dirname, 'talairach.xfm') path = transform_fname.format(subjects_dir=subjects_dir, subject=subject) if os.path.exists(path): paths['transforms'].append(transform_fname) del transform_fname, path # find source space files paths['src'] = src = [] bem_dir = bem_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(bem_dir), '*-src.fif') prefix = subject + '-' for fname in fnames: if fname.startswith(prefix): fname = "{subject}-%s" % fname[len(prefix):] path = os.path.join(bem_dirname, fname) src.append(path) # find MRIs mri_dir = mri_dirname.format(subjects_dir=subjects_dir, subject=subject) fnames = fnmatch.filter(os.listdir(mri_dir), '*.mgz') paths['mri'] = [os.path.join(mri_dir, f) for f in fnames] return paths def _find_fiducials_files(subject, subjects_dir): """Find fiducial files.""" fid = [] # standard fiducials if os.path.exists(fid_fname.format(subjects_dir=subjects_dir, subject=subject)): fid.append(fid_fname) # fiducials with subject name pattern = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='*') regex = pformat(fid_fname_general, subjects_dir=subjects_dir, subject=subject, head='(.+)').replace('\\', '\\\\') for path in iglob(pattern): match = re.match(regex, path) head = match.group(1).replace(subject, '{subject}') fid.append(pformat(fid_fname_general, head=head)) return fid def _is_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is an mri subject directory. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_mri_subject : bool Whether ``subject`` is an mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) return bool(_find_head_bem(subject, subjects_dir) or _find_head_bem(subject, subjects_dir, high_res=True)) def _is_scaled_mri_subject(subject, subjects_dir=None): """Check whether a directory in subjects_dir is a scaled mri subject. Parameters ---------- subject : str Name of the potential subject/directory. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- is_scaled_mri_subject : bool Whether ``subject`` is a scaled mri subject. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if not _is_mri_subject(subject, subjects_dir): return False fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') return os.path.exists(fname) def _mri_subject_has_bem(subject, subjects_dir=None): """Check whether an mri subject has a file matching the bem pattern. Parameters ---------- subject : str Name of the subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- has_bem_file : bool Whether ``subject`` has a bem file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) pattern = bem_fname.format(subjects_dir=subjects_dir, subject=subject, name='*-bem') fnames = glob(pattern) return bool(len(fnames)) def read_mri_cfg(subject, subjects_dir=None): """Read information from the cfg file of a scaled MRI brain. Parameters ---------- subject : str Name of the scaled MRI subject. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. Returns ------- cfg : dict Dictionary with entries from the MRI's cfg file. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg') if not os.path.exists(fname): raise IOError("%r does not seem to be a scaled mri subject: %r does " "not exist." % (subject, fname)) logger.info("Reading MRI cfg file %s" % fname) config = configparser.RawConfigParser() config.read(fname) n_params = config.getint("MRI Scaling", 'n_params') if n_params == 1: scale = config.getfloat("MRI Scaling", 'scale') elif n_params == 3: scale_str = config.get("MRI Scaling", 'scale') scale = np.array([float(s) for s in scale_str.split()]) else: raise ValueError("Invalid n_params value in MRI cfg: %i" % n_params) out = {'subject_from': config.get("MRI Scaling", 'subject_from'), 'n_params': n_params, 'scale': scale} return out def _write_mri_config(fname, subject_from, subject_to, scale): """Write the cfg file describing a scaled MRI subject. Parameters ---------- fname : str Target file. subject_from : str Name of the source MRI subject. subject_to : str Name of the scaled MRI subject. scale : float | array_like, shape = (3,) The scaling parameter. """ scale = np.asarray(scale) if np.isscalar(scale) or scale.shape == (): n_params = 1 else: n_params = 3 config = configparser.RawConfigParser() config.add_section("MRI Scaling") config.set("MRI Scaling", 'subject_from', subject_from) config.set("MRI Scaling", 'subject_to', subject_to) config.set("MRI Scaling", 'n_params', str(n_params)) if n_params == 1: config.set("MRI Scaling", 'scale', str(scale)) else: config.set("MRI Scaling", 'scale', ' '.join([str(s) for s in scale])) config.set("MRI Scaling", 'version', '1') with open(fname, 'w') as fid: config.write(fid) def _scale_params(subject_to, subject_from, scale, subjects_dir): """Assemble parameters for scaling. Returns ------- subjects_dir : str Subjects directory. subject_from : str Name of the source subject. scale : array Scaling factor, either shape=() for uniform scaling or shape=(3,) for non-uniform scaling. uniform : bool Whether scaling is uniform. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if (subject_from is None) != (scale is None): raise TypeError("Need to provide either both subject_from and scale " "parameters, or neither.") if subject_from is None: cfg = read_mri_cfg(subject_to, subjects_dir) subject_from = cfg['subject_from'] n_params = cfg['n_params'] assert n_params in (1, 3) scale = cfg['scale'] scale = np.atleast_1d(scale) if scale.ndim != 1 or scale.shape[0] not in (1, 3): raise ValueError("Invalid shape for scale parameer. Need scalar " "or array of length 3. Got shape %s." % (scale.shape,)) n_params = len(scale) return subjects_dir, subject_from, scale, n_params == 1 @verbose def scale_bem(subject_to, bem_name, subject_from=None, scale=None, subjects_dir=None, verbose=None): """Scale a bem file. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). bem_name : str Name of the bem file. For example, to scale ``fsaverage-inner_skull-bem.fif``, the bem_name would be "inner_skull-bem". subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. %(verbose)s """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) src = bem_fname.format(subjects_dir=subjects_dir, subject=subject_from, name=bem_name) dst = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name=bem_name) if os.path.exists(dst): raise IOError("File already exists: %s" % dst) surfs = read_bem_surfaces(src) for surf in surfs: surf['rr'] *= scale if not uniform: assert len(surf['nn']) > 0 surf['nn'] /= scale _normalize_vectors(surf['nn']) write_bem_surfaces(dst, surfs) def scale_labels(subject_to, pattern=None, overwrite=False, subject_from=None, scale=None, subjects_dir=None): r"""Scale labels to match a brain that was previously created by scaling. Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination brain). pattern : str | None Pattern for finding the labels relative to the label directory in the MRI subject directory (e.g., "lh.BA3a.label" will scale "fsaverage/label/lh.BA3a.label"; "aparc/\*.label" will find all labels in the "fsaverage/label/aparc" directory). With None, scale all labels. overwrite : bool Overwrite any label file that already exists for subject_to (otherwise existing labels are skipped). subject_from : None | str Name of the original MRI subject (the brain that was scaled to create subject_to). If None, the value is read from subject_to's cfg file. scale : None | float | array_like, shape = (3,) Scaling parameter. If None, the value is read from subject_to's cfg file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. """ subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # find labels paths = _find_label_paths(subject_from, pattern, subjects_dir) if not paths: return subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) src_root = os.path.join(subjects_dir, subject_from, 'label') dst_root = os.path.join(subjects_dir, subject_to, 'label') # scale labels for fname in paths: dst = os.path.join(dst_root, fname) if not overwrite and os.path.exists(dst): continue dirname = os.path.dirname(dst) if not os.path.exists(dirname): os.makedirs(dirname) src = os.path.join(src_root, fname) l_old = read_label(src) pos = l_old.pos * scale l_new = Label(l_old.vertices, pos, l_old.values, l_old.hemi, l_old.comment, subject=subject_to) l_new.save(dst) @verbose def scale_mri(subject_from, subject_to, scale, overwrite=False, subjects_dir=None, skip_fiducials=False, labels=True, annot=False, verbose=None): """Create a scaled copy of an MRI subject. Parameters ---------- subject_from : str Name of the subject providing the MRI. subject_to : str New subject name for which to save the scaled MRI. scale : float | array_like, shape = (3,) The scaling factor (one or 3 parameters). overwrite : bool If an MRI already exists for subject_to, overwrite it. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. skip_fiducials : bool Do not scale the MRI fiducials. If False (default), an IOError will be raised if no fiducials file can be found. labels : bool Also scale all labels (default True). annot : bool Copy ``*.annot`` files to the new location (default False). %(verbose)s See Also -------- scale_labels : Add labels to a scaled MRI. scale_source_space : Add a source space to a scaled MRI. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) paths = _find_mri_paths(subject_from, skip_fiducials, subjects_dir) scale = np.atleast_1d(scale) if scale.shape == (3,): if np.isclose(scale[1], scale[0]) and np.isclose(scale[2], scale[0]): scale = scale[0] # speed up scaling conditionals using a singleton elif scale.shape != (1,): raise ValueError('scale must have shape (3,) or (1,), got %s' % (scale.shape,)) # make sure we have an empty target directory dest = subject_dirname.format(subject=subject_to, subjects_dir=subjects_dir) if os.path.exists(dest): if not overwrite: raise IOError("Subject directory for %s already exists: %r" % (subject_to, dest)) shutil.rmtree(dest) logger.debug('create empty directory structure') for dirname in paths['dirs']: dir_ = dirname.format(subject=subject_to, subjects_dir=subjects_dir) os.makedirs(dir_) logger.debug('save MRI scaling parameters') fname = os.path.join(dest, 'MRI scaling parameters.cfg') _write_mri_config(fname, subject_from, subject_to, scale) logger.debug('surf files [in mm]') for fname in paths['surf']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) pts, tri = read_surface(src) write_surface(dest, pts * scale, tri) logger.debug('BEM files [in m]') for bem_name in paths['bem']: scale_bem(subject_to, bem_name, subject_from, scale, subjects_dir, verbose=False) logger.debug('fiducials [in m]') for fname in paths['fid']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) src = os.path.realpath(src) pts, cframe = read_fiducials(src, verbose=False) for pt in pts: pt['r'] = pt['r'] * scale dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) write_fiducials(dest, pts, cframe, verbose=False) logger.debug('MRIs [nibabel]') os.mkdir(mri_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['mri']: mri_name = os.path.basename(fname) _scale_mri(subject_to, mri_name, subject_from, scale, subjects_dir) logger.debug('Transforms') for mri_name in paths['mri']: if mri_name.endswith('T1.mgz'): os.mkdir(mri_transforms_dirname.format(subjects_dir=subjects_dir, subject=subject_to)) for fname in paths['transforms']: xfm_name = os.path.basename(fname) _scale_xfm(subject_to, xfm_name, mri_name, subject_from, scale, subjects_dir) break logger.debug('duplicate files') for fname in paths['duplicate']: src = fname.format(subject=subject_from, subjects_dir=subjects_dir) dest = fname.format(subject=subject_to, subjects_dir=subjects_dir) shutil.copyfile(src, dest) logger.debug('source spaces') for fname in paths['src']: src_name = os.path.basename(fname) scale_source_space(subject_to, src_name, subject_from, scale, subjects_dir, verbose=False) logger.debug('labels [in m]') os.mkdir(os.path.join(subjects_dir, subject_to, 'label')) if labels: scale_labels(subject_to, subject_from=subject_from, scale=scale, subjects_dir=subjects_dir) logger.debug('copy *.annot files') # they don't contain scale-dependent information if annot: src_pattern = os.path.join(subjects_dir, subject_from, 'label', '*.annot') dst_dir = os.path.join(subjects_dir, subject_to, 'label') for src_file in iglob(src_pattern): shutil.copy(src_file, dst_dir) @verbose def scale_source_space(subject_to, src_name, subject_from=None, scale=None, subjects_dir=None, n_jobs=1, verbose=None): """Scale a source space for an mri created with scale_mri(). Parameters ---------- subject_to : str Name of the scaled MRI subject (the destination mri subject). src_name : str Source space name. Can be a spacing parameter (e.g., ``'7'``, ``'ico4'``, ``'oct6'``) or a file name of a source space file relative to the bem directory; if the file name contains the subject name, it should be indicated as "{subject}" in ``src_name`` (e.g., ``"{subject}-my_source_space-src.fif"``). subject_from : None | str The subject from which to read the source space. If None, subject_from is read from subject_to's config file. scale : None | float | array, shape = (3,) Scaling factor. Has to be specified if subjects_from is specified, otherwise it is read from subject_to's config file. subjects_dir : None | str Override the SUBJECTS_DIR environment variable. n_jobs : int Number of jobs to run in parallel if recomputing distances (only applies if scale is an array of length 3, and will not use more cores than there are source spaces). %(verbose)s Notes ----- When scaling volume source spaces, the source (vertex) locations are scaled, but the reference to the MRI volume is left unchanged. Transforms are updated so that source estimates can be plotted on the original MRI volume. """ subjects_dir, subject_from, scale, uniform = \ _scale_params(subject_to, subject_from, scale, subjects_dir) # if n_params==1 scale is a scalar; if n_params==3 scale is a (3,) array # find the source space file names if src_name.isdigit(): spacing = src_name # spacing in mm src_pattern = src_fname else: match = re.match(r"(oct|ico|vol)-?(\d+)$", src_name) if match: spacing = '-'.join(match.groups()) src_pattern = src_fname else: spacing = None src_pattern = os.path.join(bem_dirname, src_name) src = src_pattern.format(subjects_dir=subjects_dir, subject=subject_from, spacing=spacing) dst = src_pattern.format(subjects_dir=subjects_dir, subject=subject_to, spacing=spacing) # read and scale the source space [in m] sss = read_source_spaces(src) logger.info("scaling source space %s: %s -> %s", spacing, subject_from, subject_to) logger.info("Scale factor: %s", scale) add_dist = False for ss in sss: ss['subject_his_id'] = subject_to ss['rr'] *= scale # additional tags for volume source spaces for key in ('vox_mri_t', 'src_mri_t'): # maintain transform to original MRI volume ss['mri_volume_name'] if key in ss: ss[key]['trans'][:3] *= scale[:, np.newaxis] # distances and patch info if uniform: if ss['dist'] is not None: ss['dist'] *= scale[0] # Sometimes this is read-only due to how it's read ss['nearest_dist'] = ss['nearest_dist'] * scale ss['dist_limit'] = ss['dist_limit'] * scale else: # non-uniform scaling ss['nn'] /= scale _normalize_vectors(ss['nn']) if ss['dist'] is not None: add_dist = True dist_limit = float(np.abs(sss[0]['dist_limit'])) elif ss['nearest'] is not None: add_dist = True dist_limit = 0 if add_dist: logger.info("Recomputing distances, this might take a while") add_source_space_distances(sss, dist_limit, n_jobs) write_source_spaces(dst, sss) def _scale_mri(subject_to, mri_fname, subject_from, scale, subjects_dir): """Scale an MRI by setting its affine.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) if not has_nibabel(): warn('Skipping MRI scaling for %s, please install nibabel') return import nibabel fname_from = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_from), mri_fname) fname_to = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), mri_fname) img = nibabel.load(fname_from) zooms = np.array(img.header.get_zooms()) zooms[[0, 2, 1]] *= scale img.header.set_zooms(zooms) # Hack to fix nibabel problems, see # https://github.com/nipy/nibabel/issues/619 img._affine = img.header.get_affine() # or could use None nibabel.save(img, fname_to) def _scale_xfm(subject_to, xfm_fname, mri_name, subject_from, scale, subjects_dir): """Scale a transform.""" subjects_dir, subject_from, scale, _ = _scale_params( subject_to, subject_from, scale, subjects_dir) # The nibabel warning should already be there in MRI step, if applicable, # as we only get here if T1.mgz is present (and thus a scaling was # attempted) so we can silently return here. if not has_nibabel(): return fname_from = os.path.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_from), xfm_fname) fname_to = op.join( mri_transforms_dirname.format( subjects_dir=subjects_dir, subject=subject_to), xfm_fname) assert op.isfile(fname_from), fname_from assert op.isdir(op.dirname(fname_to)), op.dirname(fname_to) # The "talairach.xfm" file stores the ras_mni transform. # # For "from" subj F, "to" subj T, F->T scaling S, some equivalent vertex # positions F_x and T_x in MRI (Freesurfer RAS) coords, knowing that # we have T_x = S @ F_x, we want to have the same MNI coords computed # for these vertices: # # T_mri_mni @ T_x = F_mri_mni @ F_x # # We need to find the correct T_ras_mni (talaraich.xfm file) that yields # this. So we derive (where † indicates inversion): # # T_mri_mni @ S @ F_x = F_mri_mni @ F_x # T_mri_mni @ S = F_mri_mni # T_ras_mni @ T_mri_ras @ S = F_ras_mni @ F_mri_ras # T_ras_mni @ T_mri_ras = F_ras_mni @ F_mri_ras @ S⁻¹ # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # prepare the scale (S) transform scale = np.atleast_1d(scale) scale = np.tile(scale, 3) if len(scale) == 1 else scale S = Transform('mri', 'mri', scaling(*scale)) # F_mri->T_mri # # Get the necessary transforms of the "from" subject # xfm, kind = _read_fs_xfm(fname_from) assert kind == 'MNI Transform File', kind _, _, F_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') F_ras_mni = Transform('ras', 'mni_tal', xfm) del xfm # # Get the necessary transforms of the "to" subject # mri_name = op.join(mri_dirname.format( subjects_dir=subjects_dir, subject=subject_to), op.basename(mri_name)) _, _, T_mri_ras, _, _ = _read_mri_info(mri_name, units='mm') T_ras_mri = invert_transform(T_mri_ras) del mri_name, T_mri_ras # Finally we construct as above: # # T_ras_mni = F_ras_mni @ F_mri_ras @ S⁻¹ @ T_ras_mri # # By moving right to left through the equation. T_ras_mni = \ combine_transforms( combine_transforms( combine_transforms( T_ras_mri, invert_transform(S), 'ras', 'mri'), F_mri_ras, 'ras', 'ras'), F_ras_mni, 'ras', 'mni_tal') _write_fs_xfm(fname_to, T_ras_mni['trans'], kind) @verbose def get_mni_fiducials(subject, subjects_dir=None, verbose=None): """Estimate fiducials for a subject. Parameters ---------- %(subject)s %(subjects_dir)s %(verbose)s Returns ------- fids_mri : list List of estimated fiducials (each point in a dict), in the order LPA, nasion, RPA. Notes ----- This takes the ``fsaverage-fiducials.fif`` file included with MNE—which contain the LPA, nasion, and RPA for the ``fsaverage`` subject—and transforms them to the given FreeSurfer subject's MRI space. The MRI of ``fsaverage`` is already in MNI Talairach space, so applying the inverse of the given subject's MNI Talairach affine transformation (``$SUBJECTS_DIR/$SUBJECT/mri/transforms/talairach.xfm``) is used to estimate the subject's fiducial locations. For more details about the coordinate systems and transformations involved, see https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems and :ref:`plot_source_alignment`. """ # Eventually we might want to allow using the MNI Talairach with-skull # transformation rather than the standard brain-based MNI Talaranch # transformation, and/or project the points onto the head surface # (if available). fname_fids_fs = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage', 'fsaverage-fiducials.fif') # Read fsaverage fiducials file and subject Talairach. fids, coord_frame = read_fiducials(fname_fids_fs) assert coord_frame == FIFF.FIFFV_COORD_MRI if subject == 'fsaverage': return fids # special short-circuit for fsaverage mni_mri_t = invert_transform(read_talxfm(subject, subjects_dir)) for f in fids: f['r'] = apply_trans(mni_mri_t, f['r']) return fids
# -*- coding: utf-8 -*- # # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # Oleh Kozynets <ok7mailbox@gmail.com> # # License: Simplified BSD import os import os.path as path import sys import pytest import numpy as np from numpy.testing import assert_allclose, assert_array_equal from mne import (read_source_estimate, read_evokeds, read_cov, read_forward_solution, pick_types_forward, SourceEstimate, MixedSourceEstimate, write_surface, VolSourceEstimate) from mne.minimum_norm import apply_inverse, make_inverse_operator from mne.source_space import (read_source_spaces, vertex_to_mni, setup_volume_source_space) from mne.datasets import testing from mne.utils import check_version, requires_pysurfer from mne.label import read_label from mne.viz._brain import Brain, _LinkViewer, _BrainScraper, _LayeredMesh from mne.viz._brain.colormap import calculate_lut from matplotlib import cm, image from matplotlib.lines import Line2D import matplotlib.pyplot as plt data_path = testing.data_path(download=False) subject_id = 'sample' subjects_dir = path.join(data_path, 'subjects') fname_stc = path.join(data_path, 'MEG/sample/sample_audvis_trunc-meg') fname_label = path.join(data_path, 'MEG/sample/labels/Vis-lh.label') fname_cov = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-cov.fif') fname_evoked = path.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc-ave.fif') fname_fwd = path.join( data_path, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') src_fname = path.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif') class _Collection(object): def __init__(self, actors): self._actors = actors def GetNumberOfItems(self): return len(self._actors) def GetItemAsObject(self, ii): return self._actors[ii] class TstVTKPicker(object): """Class to test cell picking.""" def __init__(self, mesh, cell_id, hemi, brain): self.mesh = mesh self.cell_id = cell_id self.point_id = None self.hemi = hemi self.brain = brain self._actors = () def GetCellId(self): """Return the picked cell.""" return self.cell_id def GetDataSet(self): """Return the picked mesh.""" return self.mesh def GetPickPosition(self): """Return the picked position.""" if self.hemi == 'vol': self.point_id = self.cell_id return self.brain._data['vol']['grid_coords'][self.cell_id] else: vtk_cell = self.mesh.GetCell(self.cell_id) cell = [vtk_cell.GetPointId(point_id) for point_id in range(vtk_cell.GetNumberOfPoints())] self.point_id = cell[0] return self.mesh.points[self.point_id] def GetProp3Ds(self): """Return all picked Prop3Ds.""" return _Collection(self._actors) def GetRenderer(self): """Return the "renderer".""" return self # set this to also be the renderer and active camera GetActiveCamera = GetRenderer def GetPosition(self): """Return the position.""" return np.array(self.GetPickPosition()) - (0, 0, 100) def test_layered_mesh(renderer_interactive_pyvista): """Test management of scalars/colormap overlay.""" mesh = _LayeredMesh( renderer=renderer_interactive_pyvista._get_renderer(size=(300, 300)), vertices=np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]), triangles=np.array([[0, 1, 2], [1, 2, 3]]), normals=np.array([[0, 0, 1]] * 4), ) assert not mesh._is_mapped mesh.map() assert mesh._is_mapped assert mesh._cache is None mesh.update() assert len(mesh._overlays) == 0 mesh.add_overlay( scalars=np.array([0, 1, 1, 0]), colormap=np.array([(1, 1, 1, 1), (0, 0, 0, 0)]), rng=[0, 1], opacity=None, name='test', ) assert mesh._cache is not None assert len(mesh._overlays) == 1 assert 'test' in mesh._overlays mesh.remove_overlay('test') assert len(mesh._overlays) == 0 mesh._clean() @testing.requires_testing_data def test_brain_gc(renderer_pyvista, brain_gc): """Test that a minimal version of Brain gets GC'ed.""" brain = Brain('fsaverage', 'both', 'inflated', subjects_dir=subjects_dir) brain.close() @requires_pysurfer @testing.requires_testing_data def test_brain_routines(renderer, brain_gc): """Test backend agnostic Brain routines.""" brain_klass = renderer.get_brain_class() if renderer.get_3d_backend() == "mayavi": from surfer import Brain else: # PyVista from mne.viz._brain import Brain assert brain_klass == Brain @testing.requires_testing_data def test_brain_init(renderer_pyvista, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer_pyvista.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh',) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = ['aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close() @testing.requires_testing_data @pytest.mark.skipif(os.getenv('CI_OS_NAME', '') == 'osx', reason='Unreliable/segfault on macOS CI') @pytest.mark.parametrize('hemi', ('lh', 'rh')) def test_single_hemi(hemi, renderer_interactive_pyvista, brain_gc): """Test single hemi support.""" stc = read_source_estimate(fname_stc) idx, order = (0, 1) if hemi == 'lh' else (1, -1) stc = SourceEstimate( getattr(stc, f'{hemi}_data'), [stc.vertices[idx], []][::order], 0, 1, 'sample') brain = stc.plot( subjects_dir=subjects_dir, hemi='both', size=300) brain.close() # test skipping when len(vertices) == 0 stc.vertices[1 - idx] = np.array([]) brain = stc.plot( subjects_dir=subjects_dir, hemi=hemi, size=300) brain.close() @testing.requires_testing_data @pytest.mark.slowtest def test_brain_save_movie(tmpdir, renderer, brain_gc): """Test saving a movie of a Brain instance.""" if renderer._get_3d_backend() == "mayavi": pytest.skip('Save movie only supported on PyVista') brain = _create_testing_brain(hemi='lh', time_viewer=False) filename = str(path.join(tmpdir, "brain_test.mov")) for interactive_state in (False, True): # for coverage, we set interactivity if interactive_state: brain._renderer.plotter.enable() else: brain._renderer.plotter.disable() with pytest.raises(TypeError, match='unexpected keyword argument'): brain.save_movie(filename, time_dilation=1, tmin=1, tmax=1.1, bad_name='blah') assert not path.isfile(filename) brain.save_movie(filename, time_dilation=0.1, interpolation='nearest') assert path.isfile(filename) os.remove(filename) brain.close() _TINY_SIZE = (300, 250) def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) tris = np.array([[0, 1, 2], [2, 1, 3]]) curv = rng.randn(len(rr)) with open(surf_dir.join('lh.curv'), 'wb') as fid: fid.write(np.array([255, 255, 255], dtype=np.uint8)) fid.write(np.array([len(rr), 0, 1], dtype='>i4')) fid.write(curv.astype('>f4')) write_surface(surf_dir.join('lh.white'), rr, tris) write_surface(surf_dir.join('rh.white'), rr, tris) # needed for vertex tc vertices = [np.arange(len(rr)), []] data = rng.randn(len(rr), 10) stc = SourceEstimate(data, vertices, 0, 1, subject) brain = stc.plot(subjects_dir=tmpdir, hemi='lh', surface='white', size=_TINY_SIZE) # in principle this should be sufficient: # # ratio = brain.mpl_canvas.canvas.window().devicePixelRatio() # # but in practice VTK can mess up sizes, so let's just calculate it. sz = brain.plotter.size() sz = (sz.width(), sz.height()) sz_ren = brain.plotter.renderer.GetSize() ratio = np.median(np.array(sz_ren) / np.array(sz)) return brain, ratio @pytest.mark.filterwarnings('ignore:.*constrained_layout not applied.*:') def test_brain_screenshot(renderer_interactive_pyvista, tmpdir, brain_gc): """Test time viewer screenshot.""" # XXX disable for sprint because it's too unreliable if sys.platform == 'darwin' and os.getenv('GITHUB_ACTIONS', '') == 'true': pytest.skip('Test is unreliable on GitHub Actions macOS') tiny_brain, ratio = tiny(tmpdir) img_nv = tiny_brain.screenshot(time_viewer=False) want = (_TINY_SIZE[1] * ratio, _TINY_SIZE[0] * ratio, 3) assert img_nv.shape == want img_v = tiny_brain.screenshot(time_viewer=True) assert img_v.shape[1:] == want[1:] assert_allclose(img_v.shape[0], want[0] * 4 / 3, atol=3) # some slop tiny_brain.close() def _assert_brain_range(brain, rng): __tracebackhide__ = True assert brain._cmap_range == rng, 'brain._cmap_range == rng' for hemi, layerer in brain._layered_meshes.items(): for key, mesh in layerer._overlays.items(): if key == 'curv': continue assert mesh._rng == rng, \ f'_layered_meshes[{repr(hemi)}][{repr(key)}]._rng != {rng}' @testing.requires_testing_data @pytest.mark.slowtest def test_brain_time_viewer(renderer_interactive_pyvista, pixel_ratio, brain_gc): """Test time viewer primitives.""" with pytest.raises(ValueError, match="between 0 and 1"): _create_testing_brain(hemi='lh', show_traces=-1.0) with pytest.raises(ValueError, match="got unknown keys"): _create_testing_brain(hemi='lh', surf='white', src='volume', volume_options={'foo': 'bar'}) brain = _create_testing_brain( hemi='both', show_traces=False, brain_kwargs=dict(silhouette=dict(decimate=0.95)) ) # test sub routines when show_traces=False brain._on_pick(None, None) brain._configure_vertex_time_course() brain._configure_label_time_course() brain.setup_time_viewer() # for coverage brain.callbacks["time"](value=0) assert "renderer" not in brain.callbacks brain.callbacks["orientation"]( value='lat', update_widget=True ) brain.callbacks["orientation"]( value='medial', update_widget=True ) brain.callbacks["time"]( value=0.0, time_as_index=False, ) # Need to process events for old Qt brain.callbacks["smoothing"](value=1) _assert_brain_range(brain, [0.1, 0.3]) from mne.utils import use_log_level print('\nCallback fmin\n') with use_log_level('debug'): brain.callbacks["fmin"](value=12.0) assert brain._data["fmin"] == 12.0 brain.callbacks["fmax"](value=4.0) _assert_brain_range(brain, [4.0, 4.0]) brain.callbacks["fmid"](value=6.0) _assert_brain_range(brain, [4.0, 6.0]) brain.callbacks["fmid"](value=4.0) brain.callbacks["fplus"]() brain.callbacks["fminus"]() brain.callbacks["fmin"](value=12.0) brain.callbacks["fmid"](value=4.0) _assert_brain_range(brain, [4.0, 12.0]) brain._shift_time(op=lambda x, y: x + y) brain._shift_time(op=lambda x, y: x - y) brain._rotate_azimuth(15) brain._rotate_elevation(15) brain.toggle_interface() brain.toggle_interface(value=False) brain.callbacks["playback_speed"](value=0.1) brain.toggle_playback() brain.toggle_playback(value=False) brain.apply_auto_scaling() brain.restore_user_scaling() brain.reset() plt.close('all') brain.help() assert len(plt.get_fignums()) == 1 plt.close('all') assert len(plt.get_fignums()) == 0 # screenshot # Need to turn the interface back on otherwise the window is too wide # (it keeps the window size and expands the 3D area when the interface # is toggled off) brain.toggle_interface(value=True) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') want_shape = np.array([300 * pixel_ratio, 300 * pixel_ratio, 3]) assert_allclose(img.shape, want_shape) brain.close() @testing.requires_testing_data @pytest.mark.parametrize('hemi', [ 'lh', pytest.param('rh', marks=pytest.mark.slowtest), pytest.param('split', marks=pytest.mark.slowtest), pytest.param('both', marks=pytest.mark.slowtest), ]) @pytest.mark.parametrize('src', [ 'surface', pytest.param('vector', marks=pytest.mark.slowtest), pytest.param('volume', marks=pytest.mark.slowtest), pytest.param('mixed', marks=pytest.mark.slowtest), ]) @pytest.mark.slowtest def test_brain_traces(renderer_interactive_pyvista, hemi, src, tmpdir, brain_gc): """Test brain traces.""" hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2] @testing.requires_testing_data @pytest.mark.slowtest def test_brain_linkviewer(renderer_interactive_pyvista, brain_gc): """Test _LinkViewer primitives.""" brain1 = _create_testing_brain(hemi='lh', show_traces=False) brain2 = _create_testing_brain(hemi='lh', show_traces='separate') brain1._times = brain1._times * 2 with pytest.warns(RuntimeWarning, match='linking time'): link_viewer = _LinkViewer( [brain1, brain2], time=True, camera=False, colorbar=False, picking=False, ) brain1.close() brain_data = _create_testing_brain(hemi='split', show_traces='vertex') link_viewer = _LinkViewer( [brain2, brain_data], time=True, camera=True, colorbar=True, picking=True, ) link_viewer.leader.set_time_point(0) link_viewer.leader.mpl_canvas.time_func(0) link_viewer.leader.callbacks["fmin"](0) link_viewer.leader.callbacks["fmid"](0.5) link_viewer.leader.callbacks["fmax"](1) link_viewer.leader.set_playback_speed(0.1) link_viewer.leader.toggle_playback() brain2.close() brain_data.close() def test_calculate_lut(): """Test brain's colormap functions.""" colormap = "coolwarm" alpha = 1.0 fmin = 0.0 fmid = 0.5 fmax = 1.0 center = None calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) center = 0.0 colormap = cm.get_cmap(colormap) calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid, fmax=fmax, center=center) cmap = cm.get_cmap(colormap) zero_alpha = np.array([1., 1., 1., 0]) half_alpha = np.array([1., 1., 1., 0.5]) atol = 1.5 / 256. # fmin < fmid < fmax lut = calculate_lut(colormap, alpha, 1, 2, 3) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[63], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[192], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid == fmax lut = calculate_lut(colormap, alpha, 1, 1, 1) zero_alpha = np.array([1., 1., 1., 0]) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 0, 0, 0, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin == fmid < fmax lut = calculate_lut(colormap, alpha, 1, 1, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0.) * zero_alpha, atol=atol) assert_allclose(lut[1], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 1, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[62], cmap(0.245), atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[193], cmap(0.755), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) lut = calculate_lut(colormap, alpha, 0, 0, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[126], cmap(0.25), atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[129], cmap(0.75), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # fmin < fmid == fmax lut = calculate_lut(colormap, alpha, 1, 2, 2) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0) * zero_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.5), atol=atol) assert_allclose(lut[-1], cmap(1.), atol=atol) # divergent lut = calculate_lut(colormap, alpha, 1, 2, 2, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[32], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[64], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[223], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.7475), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=2 * atol) lut = calculate_lut(colormap, alpha, 0, 1, 1, 0) assert lut.shape == (256, 4) assert_allclose(lut[0], cmap(0), atol=atol) assert_allclose(lut[1], cmap(0.25), atol=2 * atol) assert_allclose(lut[64], cmap(0.375) * half_alpha, atol=atol) assert_allclose(lut[127], cmap(0.5) * zero_alpha, atol=atol) assert_allclose(lut[191], cmap(0.625) * half_alpha, atol=atol) assert_allclose(lut[-2], cmap(0.75), atol=2 * atol) assert_allclose(lut[-1], cmap(1.), atol=atol) with pytest.raises(ValueError, match=r'.*fmin \(1\) <= fmid \(0\) <= fma'): calculate_lut(colormap, alpha, 1, 0, 2) def _create_testing_brain(hemi, surf='inflated', src='surface', size=300, n_time=5, diverging=False, **kwargs): assert src in ('surface', 'vector', 'mixed', 'volume') meth = 'plot' if src in ('surface', 'mixed'): sample_src = read_source_spaces(src_fname) klass = MixedSourceEstimate if src == 'mixed' else SourceEstimate if src == 'vector': fwd = read_forward_solution(fname_fwd) fwd = pick_types_forward(fwd, meg=True, eeg=False) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0] noise_cov = read_cov(fname_cov) free = make_inverse_operator( evoked.info, fwd, noise_cov, loose=1.) stc = apply_inverse(evoked, free, pick_ori='vector') return stc.plot( subject=subject_id, hemi=hemi, size=size, subjects_dir=subjects_dir, colormap='auto', **kwargs) if src in ('volume', 'mixed'): vol_src = setup_volume_source_space( subject_id, 7., mri='aseg.mgz', volume_label='Left-Cerebellum-Cortex', subjects_dir=subjects_dir, add_interpolator=False) assert len(vol_src) == 1 assert vol_src[0]['nuse'] == 150 if src == 'mixed': sample_src = sample_src + vol_src else: sample_src = vol_src klass = VolSourceEstimate meth = 'plot_3d' assert sample_src.kind == src # dense version rng = np.random.RandomState(0) vertices = [s['vertno'] for s in sample_src] n_verts = sum(len(v) for v in vertices) stc_data = np.zeros((n_verts * n_time)) stc_size = stc_data.size stc_data[(rng.rand(stc_size // 20) * stc_size).astype(int)] = \ rng.rand(stc_data.size // 20) stc_data.shape = (n_verts, n_time) if diverging: stc_data -= 0.5 stc = klass(stc_data, vertices, 1, 1) clim = dict(kind='value', lims=[0.1, 0.2, 0.3]) if diverging: clim['pos_lims'] = clim.pop('lims') brain_data = getattr(stc, meth)( subject=subject_id, hemi=hemi, surface=surf, size=size, subjects_dir=subjects_dir, colormap='auto', clim=clim, src=sample_src, **kwargs) return brain_data
wmvanvliet/mne-python
mne/viz/_brain/tests/test_brain.py
mne/coreg.py
"""Interfaces with TotalConnect sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities) -> None: """Set up TotalConnect device sensors based on a config entry.""" sensors = [] client_locations = hass.data[DOMAIN][entry.entry_id].locations for location_id, location in client_locations.items(): for zone_id, zone in location.zones.items(): sensors.append(TotalConnectBinarySensor(zone_id, location_id, zone)) async_add_entities(sensors, True) class TotalConnectBinarySensor(BinarySensorEntity): """Represent an TotalConnect zone.""" def __init__(self, zone_id, location_id, zone): """Initialize the TotalConnect status.""" self._zone_id = zone_id self._location_id = location_id self._zone = zone self._name = self._zone.description self._unique_id = f"{location_id} {zone_id}" self._is_on = None self._is_tampered = None self._is_low_battery = None @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the device.""" return self._name def update(self): """Return the state of the device.""" self._is_tampered = self._zone.is_tampered() self._is_low_battery = self._zone.is_low_battery() if self._zone.is_faulted() or self._zone.is_triggered(): self._is_on = True else: self._is_on = False @property def is_on(self): """Return true if the binary sensor is on.""" return self._is_on @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" if self._zone.is_type_security(): return DEVICE_CLASS_DOOR if self._zone.is_type_fire(): return DEVICE_CLASS_SMOKE if self._zone.is_type_carbon_monoxide(): return DEVICE_CLASS_GAS return None @property def device_state_attributes(self): """Return the state attributes.""" attributes = { "zone_id": self._zone_id, "location_id": self._location_id, "low_battery": self._is_low_battery, "tampered": self._is_tampered, } return attributes
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/totalconnect/binary_sensor.py
"""Device tracker for BMW Connected Drive vehicles.""" import logging from homeassistant.util import slugify from . import DOMAIN as BMW_DOMAIN _LOGGER = logging.getLogger(__name__) def setup_scanner(hass, config, see, discovery_info=None): """Set up the BMW tracker.""" accounts = hass.data[BMW_DOMAIN] _LOGGER.debug("Found BMW accounts: %s", ", ".join([a.name for a in accounts])) for account in accounts: for vehicle in account.account.vehicles: tracker = BMWDeviceTracker(see, vehicle) account.add_update_listener(tracker.update) tracker.update() return True class BMWDeviceTracker: """BMW Connected Drive device tracker.""" def __init__(self, see, vehicle): """Initialize the Tracker.""" self._see = see self.vehicle = vehicle def update(self) -> None: """Update the device info. Only update the state in Home Assistant if tracking in the car is enabled. """ dev_id = slugify(self.vehicle.name) if not self.vehicle.state.is_vehicle_tracking_enabled: _LOGGER.debug("Tracking is disabled for vehicle %s", dev_id) return _LOGGER.debug("Updating %s", dev_id) attrs = {"vin": self.vehicle.vin} self._see( dev_id=dev_id, host_name=self.vehicle.name, gps=self.vehicle.state.gps_position, attributes=attrs, icon="mdi:car", )
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/bmw_connected_drive/device_tracker.py
"""Support for HomematicIP Cloud binary sensor.""" import logging from typing import Any, Dict from homematicip.aio.device import ( AsyncAccelerationSensor, AsyncContactInterface, AsyncDevice, AsyncFullFlushContactInterface, AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, AsyncPluggableMainsFailureSurveillance, AsyncPresenceDetectorIndoor, AsyncRotaryHandleSensor, AsyncShutterContact, AsyncShutterContactMagnetic, AsyncSmokeDetector, AsyncTiltVibrationSensor, AsyncWaterSensor, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ) from homematicip.aio.group import AsyncSecurityGroup, AsyncSecurityZoneGroup from homematicip.base.enums import SmokeDetectorAlarmType, WindowState from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_LIGHT, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_MOVING, DEVICE_CLASS_OPENING, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP _LOGGER = logging.getLogger(__name__) ATTR_ACCELERATION_SENSOR_MODE = "acceleration_sensor_mode" ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION = "acceleration_sensor_neutral_position" ATTR_ACCELERATION_SENSOR_SENSITIVITY = "acceleration_sensor_sensitivity" ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE = "acceleration_sensor_trigger_angle" ATTR_INTRUSION_ALARM = "intrusion_alarm" ATTR_MOISTURE_DETECTED = "moisture_detected" ATTR_MOTION_DETECTED = "motion_detected" ATTR_POWER_MAINS_FAILURE = "power_mains_failure" ATTR_PRESENCE_DETECTED = "presence_detected" ATTR_SMOKE_DETECTOR_ALARM = "smoke_detector_alarm" ATTR_TODAY_SUNSHINE_DURATION = "today_sunshine_duration_in_minutes" ATTR_WATER_LEVEL_DETECTED = "water_level_detected" ATTR_WINDOW_STATE = "window_state" GROUP_ATTRIBUTES = { "moistureDetected": ATTR_MOISTURE_DETECTED, "motionDetected": ATTR_MOTION_DETECTED, "powerMainsFailure": ATTR_POWER_MAINS_FAILURE, "presenceDetected": ATTR_PRESENCE_DETECTED, "waterlevelDetected": ATTR_WATER_LEVEL_DETECTED, } SAM_DEVICE_ATTRIBUTES = { "accelerationSensorNeutralPosition": ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION, "accelerationSensorMode": ATTR_ACCELERATION_SENSOR_MODE, "accelerationSensorSensitivity": ATTR_ACCELERATION_SENSOR_SENSITIVITY, "accelerationSensorTriggerAngle": ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE, } async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP Cloud binary sensor from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.devices: if isinstance(device, AsyncAccelerationSensor): entities.append(HomematicipAccelerationSensor(hap, device)) if isinstance(device, AsyncTiltVibrationSensor): entities.append(HomematicipTiltVibrationSensor(hap, device)) if isinstance(device, (AsyncContactInterface, AsyncFullFlushContactInterface)): entities.append(HomematicipContactInterface(hap, device)) if isinstance( device, (AsyncShutterContact, AsyncShutterContactMagnetic), ): entities.append(HomematicipShutterContact(hap, device)) if isinstance(device, AsyncRotaryHandleSensor): entities.append(HomematicipShutterContact(hap, device, True)) if isinstance( device, ( AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, ), ): entities.append(HomematicipMotionDetector(hap, device)) if isinstance(device, AsyncPluggableMainsFailureSurveillance): entities.append( HomematicipPluggableMainsFailureSurveillanceSensor(hap, device) ) if isinstance(device, AsyncPresenceDetectorIndoor): entities.append(HomematicipPresenceDetector(hap, device)) if isinstance(device, AsyncSmokeDetector): entities.append(HomematicipSmokeDetector(hap, device)) if isinstance(device, AsyncWaterSensor): entities.append(HomematicipWaterDetector(hap, device)) if isinstance(device, (AsyncWeatherSensorPlus, AsyncWeatherSensorPro)): entities.append(HomematicipRainSensor(hap, device)) if isinstance( device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) ): entities.append(HomematicipStormSensor(hap, device)) entities.append(HomematicipSunshineSensor(hap, device)) if isinstance(device, AsyncDevice) and device.lowBat is not None: entities.append(HomematicipBatterySensor(hap, device)) for group in hap.home.groups: if isinstance(group, AsyncSecurityGroup): entities.append(HomematicipSecuritySensorGroup(hap, group)) elif isinstance(group, AsyncSecurityZoneGroup): entities.append(HomematicipSecurityZoneSensorGroup(hap, group)) if entities: async_add_entities(entities) class HomematicipBaseActionSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP base action sensor.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOVING @property def is_on(self) -> bool: """Return true if acceleration is detected.""" return self._device.accelerationSensorTriggered @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the acceleration sensor.""" state_attr = super().device_state_attributes for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value return state_attr class HomematicipAccelerationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP acceleration sensor.""" class HomematicipTiltVibrationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP tilt vibration sensor.""" class HomematicipContactInterface(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP contact interface.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_OPENING @property def is_on(self) -> bool: """Return true if the contact interface is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED class HomematicipShutterContact(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP shutter contact.""" def __init__( self, hap: HomematicipHAP, device, has_additional_state: bool = False ) -> None: """Initialize the shutter contact.""" super().__init__(hap, device) self.has_additional_state = has_additional_state @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_DOOR @property def is_on(self) -> bool: """Return true if the shutter contact is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the Shutter Contact.""" state_attr = super().device_state_attributes if self.has_additional_state: window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = window_state return state_attr class HomematicipMotionDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP motion detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOTION @property def is_on(self) -> bool: """Return true if motion is detected.""" return self._device.motionDetected class HomematicipPresenceDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP presence detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_PRESENCE @property def is_on(self) -> bool: """Return true if presence is detected.""" return self._device.presenceDetected class HomematicipSmokeDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP smoke detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SMOKE @property def is_on(self) -> bool: """Return true if smoke is detected.""" if self._device.smokeDetectorAlarmType: return ( self._device.smokeDetectorAlarmType == SmokeDetectorAlarmType.PRIMARY_ALARM ) return False class HomematicipWaterDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP water detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if moisture or waterlevel is detected.""" return self._device.moistureDetected or self._device.waterlevelDetected class HomematicipStormSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP storm sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize storm sensor.""" super().__init__(hap, device, "Storm") @property def icon(self) -> str: """Return the icon.""" return "mdi:weather-windy" if self.is_on else "mdi:pinwheel-outline" @property def is_on(self) -> bool: """Return true, if storm is detected.""" return self._device.storm class HomematicipRainSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP rain sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize rain sensor.""" super().__init__(hap, device, "Raining") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if it is raining.""" return self._device.raining class HomematicipSunshineSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP sunshine sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize sunshine sensor.""" super().__init__(hap, device, "Sunshine") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_LIGHT @property def is_on(self) -> bool: """Return true if sun is shining.""" return self._device.sunshine @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the illuminance sensor.""" state_attr = super().device_state_attributes today_sunshine_duration = getattr(self._device, "todaySunshineDuration", None) if today_sunshine_duration: state_attr[ATTR_TODAY_SUNSHINE_DURATION] = today_sunshine_duration return state_attr class HomematicipBatterySensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP low battery sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize battery sensor.""" super().__init__(hap, device, "Battery") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_BATTERY @property def is_on(self) -> bool: """Return true if battery is low.""" return self._device.lowBat class HomematicipPluggableMainsFailureSurveillanceSensor( HomematicipGenericEntity, BinarySensorEntity ): """Representation of the HomematicIP pluggable mains failure surveillance sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize pluggable mains failure surveillance sensor.""" super().__init__(hap, device) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_POWER @property def is_on(self) -> bool: """Return true if power mains fails.""" return not self._device.powerMainsFailure class HomematicipSecurityZoneSensorGroup(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP security zone sensor group.""" def __init__(self, hap: HomematicipHAP, device, post: str = "SecurityZone") -> None: """Initialize security zone group.""" device.modelType = f"HmIP-{post}" super().__init__(hap, device, post) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SAFETY @property def available(self) -> bool: """Security-Group available.""" # A security-group must be available, and should not be affected by # the individual availability of group members. return True @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security zone group.""" state_attr = super().device_state_attributes for attr, attr_key in GROUP_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = str(window_state) return state_attr @property def is_on(self) -> bool: """Return true if security issue detected.""" if ( self._device.motionDetected or self._device.presenceDetected or self._device.unreach or self._device.sabotage ): return True if ( self._device.windowState is not None and self._device.windowState != WindowState.CLOSED ): return True return False class HomematicipSecuritySensorGroup( HomematicipSecurityZoneSensorGroup, BinarySensorEntity ): """Representation of the HomematicIP security group.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize security group.""" super().__init__(hap, device, "Sensors") @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security group.""" state_attr = super().device_state_attributes smoke_detector_at = getattr(self._device, "smokeDetectorAlarmType", None) if smoke_detector_at: if smoke_detector_at == SmokeDetectorAlarmType.PRIMARY_ALARM: state_attr[ATTR_SMOKE_DETECTOR_ALARM] = str(smoke_detector_at) if smoke_detector_at == SmokeDetectorAlarmType.INTRUSION_ALARM: state_attr[ATTR_INTRUSION_ALARM] = str(smoke_detector_at) return state_attr @property def is_on(self) -> bool: """Return true if safety issue detected.""" parent_is_on = super().is_on if parent_is_on: return True if ( self._device.powerMainsFailure or self._device.moistureDetected or self._device.waterlevelDetected or self._device.lowBat or self._device.dutyCycle ): return True if ( self._device.smokeDetectorAlarmType is not None and self._device.smokeDetectorAlarmType != SmokeDetectorAlarmType.IDLE_OFF ): return True return False
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/homematicip_cloud/binary_sensor.py
"""Support for OVO Energy.""" from datetime import datetime, timedelta import logging from typing import Any, Dict import aiohttp import async_timeout from ovoenergy import OVODailyUsage from ovoenergy.ovoenergy import OVOEnergy from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the OVO Energy components.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up OVO Energy from a config entry.""" client = OVOEnergy() try: await client.authenticate(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception async def async_update_data() -> OVODailyUsage: """Fetch data from OVO Energy.""" now = datetime.utcnow() async with async_timeout.timeout(10): try: await client.authenticate( entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD] ) return await client.get_daily_usage(now.strftime("%Y-%m")) except aiohttp.ClientError as exception: _LOGGER.warning(exception) return None coordinator = DataUpdateCoordinator( hass, _LOGGER, # Name of the data. For logging purposes. name="sensor", update_method=async_update_data, # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(seconds=300), ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_CLIENT: client, DATA_COORDINATOR: coordinator, } # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload OVO Energy config entry.""" # Unload sensors await hass.config_entries.async_forward_entry_unload(entry, "sensor") del hass.data[DOMAIN][entry.entry_id] return True class OVOEnergyEntity(CoordinatorEntity): """Defines a base OVO Energy entity.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, key: str, name: str, icon: str, ) -> None: """Initialize the OVO Energy entity.""" super().__init__(coordinator) self._client = client self._key = key self._name = name self._icon = icon self._available = True @property def unique_id(self) -> str: """Return the unique ID for this sensor.""" return self._key @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self.coordinator.last_update_success and self._available class OVOEnergyDeviceEntity(OVOEnergyEntity): """Defines a OVO Energy device entity.""" @property def device_info(self) -> Dict[str, Any]: """Return device information about this OVO Energy instance.""" return { "identifiers": {(DOMAIN, self._client.account_id)}, "manufacturer": "OVO Energy", "name": self._client.account_id, "entry_type": "service", }
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/ovo_energy/__init__.py
"""Support for turning on and off Pi-hole system.""" import logging from hole.exceptions import HoleError import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv, entity_platform from . import PiHoleEntity from .const import ( DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN, SERVICE_DISABLE, SERVICE_DISABLE_ATTR_DURATION, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up the Pi-hole switch.""" name = entry.data[CONF_NAME] hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id] switches = [ PiHoleSwitch( hole_data[DATA_KEY_API], hole_data[DATA_KEY_COORDINATOR], name, entry.entry_id, ) ] async_add_entities(switches, True) # register service platform = entity_platform.current_platform.get() platform.async_register_entity_service( SERVICE_DISABLE, { vol.Required(SERVICE_DISABLE_ATTR_DURATION): vol.All( cv.time_period_str, cv.positive_timedelta ), }, "async_disable", ) class PiHoleSwitch(PiHoleEntity, SwitchEntity): """Representation of a Pi-hole switch.""" @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of the switch.""" return f"{self._server_unique_id}/Switch" @property def icon(self): """Icon to use in the frontend, if any.""" return "mdi:pi-hole" @property def is_on(self): """Return if the service is on.""" return self.api.data.get("status") == "enabled" async def async_turn_on(self, **kwargs): """Turn on the service.""" try: await self.api.enable() await self.async_update() except HoleError as err: _LOGGER.error("Unable to enable Pi-hole: %s", err) async def async_turn_off(self, **kwargs): """Turn off the service.""" await self.async_disable() async def async_disable(self, duration=None): """Disable the service for a given duration.""" duration_seconds = True # Disable infinitely by default if duration is not None: duration_seconds = duration.total_seconds() _LOGGER.debug( "Disabling Pi-hole '%s' (%s) for %d seconds", self.name, self.api.host, duration_seconds, ) try: await self.api.disable(duration_seconds) await self.async_update() except HoleError as err: _LOGGER.error("Unable to disable Pi-hole: %s", err)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/pi_hole/switch.py
"""Support for Rova garbage calendar.""" from datetime import datetime, timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError from rova.rova import Rova import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, DEVICE_CLASS_TIMESTAMP, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle # Config for rova requests. CONF_ZIP_CODE = "zip_code" CONF_HOUSE_NUMBER = "house_number" CONF_HOUSE_NUMBER_SUFFIX = "house_number_suffix" UPDATE_DELAY = timedelta(hours=12) SCAN_INTERVAL = timedelta(hours=12) # Supported sensor types: # Key: [json_key, name, icon] SENSOR_TYPES = { "bio": ["gft", "Biowaste", "mdi:recycle"], "paper": ["papier", "Paper", "mdi:recycle"], "plastic": ["pmd", "PET", "mdi:recycle"], "residual": ["restafval", "Residual", "mdi:recycle"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ZIP_CODE): cv.string, vol.Required(CONF_HOUSE_NUMBER): cv.string, vol.Optional(CONF_HOUSE_NUMBER_SUFFIX, default=""): cv.string, vol.Optional(CONF_NAME, default="Rova"): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["bio"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Create the Rova data service and sensors.""" zip_code = config[CONF_ZIP_CODE] house_number = config[CONF_HOUSE_NUMBER] house_number_suffix = config[CONF_HOUSE_NUMBER_SUFFIX] platform_name = config[CONF_NAME] # Create new Rova object to retrieve data api = Rova(zip_code, house_number, house_number_suffix) try: if not api.is_rova_area(): _LOGGER.error("ROVA does not collect garbage in this area") return except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve details from ROVA API") return # Create rova data service which will retrieve and update the data. data_service = RovaData(api) # Create a new sensor for each garbage type. entities = [] for sensor_key in config[CONF_MONITORED_CONDITIONS]: sensor = RovaSensor(platform_name, sensor_key, data_service) entities.append(sensor) add_entities(entities, True) class RovaSensor(Entity): """Representation of a Rova sensor.""" def __init__(self, platform_name, sensor_key, data_service): """Initialize the sensor.""" self.sensor_key = sensor_key self.platform_name = platform_name self.data_service = data_service self._state = None self._json_key = SENSOR_TYPES[self.sensor_key][0] @property def name(self): """Return the name.""" return f"{self.platform_name}_{self.sensor_key}" @property def icon(self): """Return the sensor icon.""" return SENSOR_TYPES[self.sensor_key][2] @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Get the latest data from the sensor and update the state.""" self.data_service.update() pickup_date = self.data_service.data.get(self._json_key) if pickup_date is not None: self._state = pickup_date.isoformat() class RovaData: """Get and update the latest data from the Rova API.""" def __init__(self, api): """Initialize the data object.""" self.api = api self.data = {} @Throttle(UPDATE_DELAY) def update(self): """Update the data from the Rova API.""" try: items = self.api.get_calendar_items() except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve data, retry again later") return self.data = {} for item in items: date = datetime.strptime(item["Date"], "%Y-%m-%dT%H:%M:%S") code = item["GarbageTypeCode"].lower() if code not in self.data and date > datetime.now(): self.data[code] = date _LOGGER.debug("Updated Rova calendar: %s", self.data)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/rova/sensor.py
"""Support for Recollect Waste curbside collection pickup.""" from datetime import timedelta import logging import recollect_waste import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) ATTR_PICKUP_TYPES = "pickup_types" ATTR_AREA_NAME = "area_name" CONF_PLACE_ID = "place_id" CONF_SERVICE_ID = "service_id" DEFAULT_NAME = "recollect_waste" ICON = "mdi:trash-can-outline" SCAN_INTERVAL = timedelta(days=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PLACE_ID): cv.string, vol.Required(CONF_SERVICE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Recollect Waste platform.""" client = recollect_waste.RecollectWasteClient( config[CONF_PLACE_ID], config[CONF_SERVICE_ID] ) # Ensure the client can connect to the API successfully # with given place_id and service_id. try: client.get_next_pickup() except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex) return add_entities([RecollectWasteSensor(config.get(CONF_NAME), client)], True) class RecollectWasteSensor(Entity): """Recollect Waste Sensor.""" def __init__(self, name, client): """Initialize the sensor.""" self._attributes = {} self._name = name self._state = None self.client = client @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self.client.place_id}{self.client.service_id}" @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @property def icon(self): """Icon to use in the frontend.""" return ICON def update(self): """Update device state.""" try: pickup_event = self.client.get_next_pickup() self._state = pickup_event.event_date self._attributes.update( { ATTR_PICKUP_TYPES: pickup_event.pickup_types, ATTR_AREA_NAME: pickup_event.area_name, } ) except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/recollect_waste/sensor.py
"""Constants for the Rollease Acmeda Automate integration.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "acmeda" ACMEDA_HUB_UPDATE = "acmeda_hub_update_{}" ACMEDA_ENTITY_REMOVE = "acmeda_entity_remove_{}"
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/acmeda/const.py
"""Allows the creation of a sensor that filters state property.""" from collections import Counter, deque from copy import copy from datetime import timedelta from functools import partial import logging from numbers import Number import statistics from typing import Optional import voluptuous as vol from homeassistant.components import history from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, CONF_ENTITY_ID, CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.util.decorator import Registry import homeassistant.util.dt as dt_util from . import DOMAIN, PLATFORMS _LOGGER = logging.getLogger(__name__) FILTER_NAME_RANGE = "range" FILTER_NAME_LOWPASS = "lowpass" FILTER_NAME_OUTLIER = "outlier" FILTER_NAME_THROTTLE = "throttle" FILTER_NAME_TIME_THROTTLE = "time_throttle" FILTER_NAME_TIME_SMA = "time_simple_moving_average" FILTERS = Registry() CONF_FILTERS = "filters" CONF_FILTER_NAME = "filter" CONF_FILTER_WINDOW_SIZE = "window_size" CONF_FILTER_PRECISION = "precision" CONF_FILTER_RADIUS = "radius" CONF_FILTER_TIME_CONSTANT = "time_constant" CONF_FILTER_LOWER_BOUND = "lower_bound" CONF_FILTER_UPPER_BOUND = "upper_bound" CONF_TIME_SMA_TYPE = "type" TIME_SMA_LAST = "last" WINDOW_SIZE_UNIT_NUMBER_EVENTS = 1 WINDOW_SIZE_UNIT_TIME = 2 DEFAULT_WINDOW_SIZE = 1 DEFAULT_PRECISION = 2 DEFAULT_FILTER_RADIUS = 2.0 DEFAULT_FILTER_TIME_CONSTANT = 10 NAME_TEMPLATE = "{} filter" ICON = "mdi:chart-line-variant" FILTER_SCHEMA = vol.Schema( {vol.Optional(CONF_FILTER_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int)} ) FILTER_OUTLIER_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_OUTLIER, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional(CONF_FILTER_RADIUS, default=DEFAULT_FILTER_RADIUS): vol.Coerce( float ), } ) FILTER_LOWPASS_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_LOWPASS, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional( CONF_FILTER_TIME_CONSTANT, default=DEFAULT_FILTER_TIME_CONSTANT ): vol.Coerce(int), } ) FILTER_RANGE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_RANGE, vol.Optional(CONF_FILTER_LOWER_BOUND): vol.Coerce(float), vol.Optional(CONF_FILTER_UPPER_BOUND): vol.Coerce(float), } ) FILTER_TIME_SMA_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_SMA, vol.Optional(CONF_TIME_SMA_TYPE, default=TIME_SMA_LAST): vol.In( [TIME_SMA_LAST] ), vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) FILTER_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_THROTTLE, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), } ) FILTER_TIME_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_THROTTLE, vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_FILTERS): vol.All( cv.ensure_list, [ vol.Any( FILTER_OUTLIER_SCHEMA, FILTER_LOWPASS_SCHEMA, FILTER_TIME_SMA_SCHEMA, FILTER_THROTTLE_SCHEMA, FILTER_TIME_THROTTLE_SCHEMA, FILTER_RANGE_SCHEMA, ) ], ), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template sensors.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) name = config.get(CONF_NAME) entity_id = config.get(CONF_ENTITY_ID) filters = [ FILTERS[_filter.pop(CONF_FILTER_NAME)](entity=entity_id, **_filter) for _filter in config[CONF_FILTERS] ] async_add_entities([SensorFilter(name, entity_id, filters)]) class SensorFilter(Entity): """Representation of a Filter Sensor.""" def __init__(self, name, entity_id, filters): """Initialize the sensor.""" self._name = name self._entity = entity_id self._unit_of_measurement = None self._state = None self._filters = filters self._icon = None @callback def _update_filter_sensor_state_event(self, event): """Handle device state changes.""" self._update_filter_sensor_state(event.data.get("new_state")) @callback def _update_filter_sensor_state(self, new_state, update_ha=True): """Process device state changes.""" if new_state is None or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]: return temp_state = new_state try: for filt in self._filters: filtered_state = filt.filter_state(copy(temp_state)) _LOGGER.debug( "%s(%s=%s) -> %s", filt.name, self._entity, temp_state.state, "skip" if filt.skip_processing else filtered_state.state, ) if filt.skip_processing: return temp_state = filtered_state except ValueError: _LOGGER.error("Could not convert state: %s to number", self._state) return self._state = temp_state.state if self._icon is None: self._icon = new_state.attributes.get(ATTR_ICON, ICON) if self._unit_of_measurement is None: self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT ) if update_ha: self.async_write_ha_state() async def async_added_to_hass(self): """Register callbacks.""" if "recorder" in self.hass.config.components: history_list = [] largest_window_items = 0 largest_window_time = timedelta(0) # Determine the largest window_size by type for filt in self._filters: if ( filt.window_unit == WINDOW_SIZE_UNIT_NUMBER_EVENTS and largest_window_items < filt.window_size ): largest_window_items = filt.window_size elif ( filt.window_unit == WINDOW_SIZE_UNIT_TIME and largest_window_time < filt.window_size ): largest_window_time = filt.window_size # Retrieve the largest window_size of each type if largest_window_items > 0: filter_history = await self.hass.async_add_job( partial( history.get_last_state_changes, self.hass, largest_window_items, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend(filter_history[self._entity]) if largest_window_time > timedelta(seconds=0): start = dt_util.utcnow() - largest_window_time filter_history = await self.hass.async_add_job( partial( history.state_changes_during_period, self.hass, start, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend( [ state for state in filter_history[self._entity] if state not in history_list ] ) # Sort the window states history_list = sorted(history_list, key=lambda s: s.last_updated) _LOGGER.debug( "Loading from history: %s", [(s.state, s.last_updated) for s in history_list], ) # Replay history through the filter chain for state in history_list: self._update_filter_sensor_state(state, False) self.async_on_remove( async_track_state_change_event( self.hass, [self._entity], self._update_filter_sensor_state_event ) ) @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 icon(self): """Return the icon to use in the frontend, if any.""" return self._icon @property def unit_of_measurement(self): """Return the unit_of_measurement of the device.""" return self._unit_of_measurement @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes of the sensor.""" state_attr = {ATTR_ENTITY_ID: self._entity} return state_attr class FilterState: """State abstraction for filter usage.""" def __init__(self, state): """Initialize with HA State object.""" self.timestamp = state.last_updated try: self.state = float(state.state) except ValueError: self.state = state.state def set_precision(self, precision): """Set precision of Number based states.""" if isinstance(self.state, Number): value = round(float(self.state), precision) self.state = int(value) if precision == 0 else value def __str__(self): """Return state as the string representation of FilterState.""" return str(self.state) def __repr__(self): """Return timestamp and state as the representation of FilterState.""" return f"{self.timestamp} : {self.state}" class Filter: """Filter skeleton.""" def __init__( self, name, window_size: int = 1, precision: Optional[int] = None, entity: Optional[str] = None, ): """Initialize common attributes. :param window_size: size of the sliding window that holds previous values :param precision: round filtered value to precision value :param entity: used for debugging only """ if isinstance(window_size, int): self.states = deque(maxlen=window_size) self.window_unit = WINDOW_SIZE_UNIT_NUMBER_EVENTS else: self.states = deque(maxlen=0) self.window_unit = WINDOW_SIZE_UNIT_TIME self.precision = precision self._name = name self._entity = entity self._skip_processing = False self._window_size = window_size self._store_raw = False self._only_numbers = True @property def window_size(self): """Return window size.""" return self._window_size @property def name(self): """Return filter name.""" return self._name @property def skip_processing(self): """Return whether the current filter_state should be skipped.""" return self._skip_processing def _filter_state(self, new_state): """Implement filter.""" raise NotImplementedError() def filter_state(self, new_state): """Implement a common interface for filters.""" fstate = FilterState(new_state) if self._only_numbers and not isinstance(fstate.state, Number): raise ValueError filtered = self._filter_state(fstate) filtered.set_precision(self.precision) if self._store_raw: self.states.append(copy(FilterState(new_state))) else: self.states.append(copy(filtered)) new_state.state = filtered.state return new_state @FILTERS.register(FILTER_NAME_RANGE) class RangeFilter(Filter): """Range filter. Determines if new state is in the range of upper_bound and lower_bound. If not inside, lower or upper bound is returned instead. """ def __init__( self, entity, precision: Optional[int] = DEFAULT_PRECISION, lower_bound: Optional[float] = None, upper_bound: Optional[float] = None, ): """Initialize Filter. :param upper_bound: band upper bound :param lower_bound: band lower bound """ super().__init__(FILTER_NAME_RANGE, precision=precision, entity=entity) self._lower_bound = lower_bound self._upper_bound = upper_bound self._stats_internal = Counter() def _filter_state(self, new_state): """Implement the range filter.""" if self._upper_bound is not None and new_state.state > self._upper_bound: self._stats_internal["erasures_up"] += 1 _LOGGER.debug( "Upper outlier nr. %s in %s: %s", self._stats_internal["erasures_up"], self._entity, new_state, ) new_state.state = self._upper_bound elif self._lower_bound is not None and new_state.state < self._lower_bound: self._stats_internal["erasures_low"] += 1 _LOGGER.debug( "Lower outlier nr. %s in %s: %s", self._stats_internal["erasures_low"], self._entity, new_state, ) new_state.state = self._lower_bound return new_state @FILTERS.register(FILTER_NAME_OUTLIER) class OutlierFilter(Filter): """BASIC outlier filter. Determines if new state is in a band around the median. """ def __init__(self, window_size, precision, entity, radius: float): """Initialize Filter. :param radius: band radius """ super().__init__(FILTER_NAME_OUTLIER, window_size, precision, entity) self._radius = radius self._stats_internal = Counter() self._store_raw = True def _filter_state(self, new_state): """Implement the outlier filter.""" median = statistics.median([s.state for s in self.states]) if self.states else 0 if ( len(self.states) == self.states.maxlen and abs(new_state.state - median) > self._radius ): self._stats_internal["erasures"] += 1 _LOGGER.debug( "Outlier nr. %s in %s: %s", self._stats_internal["erasures"], self._entity, new_state, ) new_state.state = median return new_state @FILTERS.register(FILTER_NAME_LOWPASS) class LowPassFilter(Filter): """BASIC Low Pass Filter.""" def __init__(self, window_size, precision, entity, time_constant: int): """Initialize Filter.""" super().__init__(FILTER_NAME_LOWPASS, window_size, precision, entity) self._time_constant = time_constant def _filter_state(self, new_state): """Implement the low pass filter.""" if not self.states: return new_state new_weight = 1.0 / self._time_constant prev_weight = 1.0 - new_weight new_state.state = ( prev_weight * self.states[-1].state + new_weight * new_state.state ) return new_state @FILTERS.register(FILTER_NAME_TIME_SMA) class TimeSMAFilter(Filter): """Simple Moving Average (SMA) Filter. The window_size is determined by time, and SMA is time weighted. """ def __init__( self, window_size, precision, entity, type ): # pylint: disable=redefined-builtin """Initialize Filter. :param type: type of algorithm used to connect discrete values """ super().__init__(FILTER_NAME_TIME_SMA, window_size, precision, entity) self._time_window = window_size self.last_leak = None self.queue = deque() def _leak(self, left_boundary): """Remove timeouted elements.""" while self.queue: if self.queue[0].timestamp + self._time_window <= left_boundary: self.last_leak = self.queue.popleft() else: return def _filter_state(self, new_state): """Implement the Simple Moving Average filter.""" self._leak(new_state.timestamp) self.queue.append(copy(new_state)) moving_sum = 0 start = new_state.timestamp - self._time_window prev_state = self.last_leak or self.queue[0] for state in self.queue: moving_sum += (state.timestamp - start).total_seconds() * prev_state.state start = state.timestamp prev_state = state new_state.state = moving_sum / self._time_window.total_seconds() return new_state @FILTERS.register(FILTER_NAME_THROTTLE) class ThrottleFilter(Filter): """Throttle Filter. One sample per window. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_THROTTLE, window_size, precision, entity) self._only_numbers = False def _filter_state(self, new_state): """Implement the throttle filter.""" if not self.states or len(self.states) == self.states.maxlen: self.states.clear() self._skip_processing = False else: self._skip_processing = True return new_state @FILTERS.register(FILTER_NAME_TIME_THROTTLE) class TimeThrottleFilter(Filter): """Time Throttle Filter. One sample per time period. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision, entity) self._time_window = window_size self._last_emitted_at = None self._only_numbers = False def _filter_state(self, new_state): """Implement the filter.""" window_start = new_state.timestamp - self._time_window if not self._last_emitted_at or self._last_emitted_at <= window_start: self._last_emitted_at = new_state.timestamp self._skip_processing = False else: self._skip_processing = True return new_state
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/filter/sensor.py
"""Time-based One Time Password auth module.""" import asyncio from io import BytesIO import logging from typing import Any, Dict, Optional, Tuple import voluptuous as vol from homeassistant.auth.models import User from homeassistant.core import HomeAssistant from . import ( MULTI_FACTOR_AUTH_MODULE_SCHEMA, MULTI_FACTOR_AUTH_MODULES, MultiFactorAuthModule, SetupFlow, ) REQUIREMENTS = ["pyotp==2.3.0", "PyQRCode==1.2.1"] CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend({}, extra=vol.PREVENT_EXTRA) STORAGE_VERSION = 1 STORAGE_KEY = "auth_module.totp" STORAGE_USERS = "users" STORAGE_USER_ID = "user_id" STORAGE_OTA_SECRET = "ota_secret" INPUT_FIELD_CODE = "code" DUMMY_SECRET = "FPPTH34D4E3MI2HG" _LOGGER = logging.getLogger(__name__) def _generate_qr_code(data: str) -> str: """Generate a base64 PNG string represent QR Code image of data.""" import pyqrcode # pylint: disable=import-outside-toplevel qr_code = pyqrcode.create(data) with BytesIO() as buffer: qr_code.svg(file=buffer, scale=4) return str( buffer.getvalue() .decode("ascii") .replace("\n", "") .replace( '<?xml version="1.0" encoding="UTF-8"?>' '<svg xmlns="http://www.w3.org/2000/svg"', "<svg", ) ) def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]: """Generate a secret, url, and QR code.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret = pyotp.random_base32() url = pyotp.totp.TOTP(ota_secret).provisioning_uri( username, issuer_name="Home Assistant" ) image = _generate_qr_code(url) return ota_secret, url, image @MULTI_FACTOR_AUTH_MODULES.register("totp") class TotpAuthModule(MultiFactorAuthModule): """Auth module validate time-based one time password.""" DEFAULT_TITLE = "Time-based One Time Password" MAX_RETRY_TIME = 5 def __init__(self, hass: HomeAssistant, config: Dict[str, Any]) -> None: """Initialize the user data store.""" super().__init__(hass, config) self._users: Optional[Dict[str, str]] = None self._user_store = hass.helpers.storage.Store( STORAGE_VERSION, STORAGE_KEY, private=True ) self._init_lock = asyncio.Lock() @property def input_schema(self) -> vol.Schema: """Validate login flow input data.""" return vol.Schema({INPUT_FIELD_CODE: str}) async def _async_load(self) -> None: """Load stored data.""" async with self._init_lock: if self._users is not None: return data = await self._user_store.async_load() if data is None: data = {STORAGE_USERS: {}} self._users = data.get(STORAGE_USERS, {}) async def _async_save(self) -> None: """Save data.""" await self._user_store.async_save({STORAGE_USERS: self._users}) def _add_ota_secret(self, user_id: str, secret: Optional[str] = None) -> str: """Create a ota_secret for user.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret: str = secret or pyotp.random_base32() self._users[user_id] = ota_secret # type: ignore return ota_secret async def async_setup_flow(self, user_id: str) -> SetupFlow: """Return a data entry flow handler for setup module. Mfa module should extend SetupFlow """ user = await self.hass.auth.async_get_user(user_id) assert user is not None return TotpSetupFlow(self, self.input_schema, user) async def async_setup_user(self, user_id: str, setup_data: Any) -> str: """Set up auth module for user.""" if self._users is None: await self._async_load() result = await self.hass.async_add_executor_job( self._add_ota_secret, user_id, setup_data.get("secret") ) await self._async_save() return result async def async_depose_user(self, user_id: str) -> None: """Depose auth module for user.""" if self._users is None: await self._async_load() if self._users.pop(user_id, None): # type: ignore await self._async_save() async def async_is_user_setup(self, user_id: str) -> bool: """Return whether user is setup.""" if self._users is None: await self._async_load() return user_id in self._users # type: ignore async def async_validate(self, user_id: str, user_input: Dict[str, Any]) -> bool: """Return True if validation passed.""" if self._users is None: await self._async_load() # user_input has been validate in caller # set INPUT_FIELD_CODE as vol.Required is not user friendly return await self.hass.async_add_executor_job( self._validate_2fa, user_id, user_input.get(INPUT_FIELD_CODE, "") ) def _validate_2fa(self, user_id: str, code: str) -> bool: """Validate two factor authentication code.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret = self._users.get(user_id) # type: ignore if ota_secret is None: # even we cannot find user, we still do verify # to make timing the same as if user was found. pyotp.TOTP(DUMMY_SECRET).verify(code, valid_window=1) return False return bool(pyotp.TOTP(ota_secret).verify(code, valid_window=1)) class TotpSetupFlow(SetupFlow): """Handler for the setup flow.""" def __init__( self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User ) -> None: """Initialize the setup flow.""" super().__init__(auth_module, setup_schema, user.id) # to fix typing complaint self._auth_module: TotpAuthModule = auth_module self._user = user self._ota_secret: Optional[str] = None self._url = None # type Optional[str] self._image = None # type Optional[str] async def async_step_init( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Handle the first step of setup flow. Return self.async_show_form(step_id='init') if user_input is None. Return self.async_create_entry(data={'result': result}) if finish. """ import pyotp # pylint: disable=import-outside-toplevel errors: Dict[str, str] = {} if user_input: verified = await self.hass.async_add_executor_job( # type: ignore pyotp.TOTP(self._ota_secret).verify, user_input["code"] ) if verified: result = await self._auth_module.async_setup_user( self._user_id, {"secret": self._ota_secret} ) return self.async_create_entry( title=self._auth_module.name, data={"result": result} ) errors["base"] = "invalid_code" else: hass = self._auth_module.hass ( self._ota_secret, self._url, self._image, ) = await hass.async_add_executor_job( _generate_secret_and_qr_code, # type: ignore str(self._user.name), ) return self.async_show_form( step_id="init", data_schema=self._setup_schema, description_placeholders={ "code": self._ota_secret, "url": self._url, "qr_code": self._image, }, errors=errors, )
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/auth/mfa_modules/totp.py
"""Support for Alexa skill service end point.""" import logging import voluptuous as vol from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_NAME from homeassistant.helpers import config_validation as cv, entityfilter from . import flash_briefings, intent, smart_home_http from .const import ( CONF_AUDIO, CONF_DESCRIPTION, CONF_DISPLAY_CATEGORIES, CONF_DISPLAY_URL, CONF_ENDPOINT, CONF_ENTITY_CONFIG, CONF_FILTER, CONF_LOCALE, CONF_PASSWORD, CONF_SUPPORTED_LOCALES, CONF_TEXT, CONF_TITLE, CONF_UID, DOMAIN, ) _LOGGER = logging.getLogger(__name__) CONF_FLASH_BRIEFINGS = "flash_briefings" CONF_SMART_HOME = "smart_home" DEFAULT_LOCALE = "en-US" ALEXA_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_DESCRIPTION): cv.string, vol.Optional(CONF_DISPLAY_CATEGORIES): cv.string, vol.Optional(CONF_NAME): cv.string, } ) SMART_HOME_SCHEMA = vol.Schema( { vol.Optional(CONF_ENDPOINT): cv.string, vol.Optional(CONF_CLIENT_ID): cv.string, vol.Optional(CONF_CLIENT_SECRET): cv.string, vol.Optional(CONF_LOCALE, default=DEFAULT_LOCALE): vol.In( CONF_SUPPORTED_LOCALES ), vol.Optional(CONF_FILTER, default={}): entityfilter.FILTER_SCHEMA, vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: { CONF_FLASH_BRIEFINGS: { vol.Required(CONF_PASSWORD): cv.string, cv.string: vol.All( cv.ensure_list, [ { vol.Optional(CONF_UID): cv.string, vol.Required(CONF_TITLE): cv.template, vol.Optional(CONF_AUDIO): cv.template, vol.Required(CONF_TEXT, default=""): cv.template, vol.Optional(CONF_DISPLAY_URL): cv.template, } ], ), }, # vol.Optional here would mean we couldn't distinguish between an empty # smart_home: and none at all. CONF_SMART_HOME: vol.Any(SMART_HOME_SCHEMA, None), } }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Activate the Alexa component.""" if DOMAIN not in config: return True config = config[DOMAIN] flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS) intent.async_setup(hass) if flash_briefings_config: flash_briefings.async_setup(hass, flash_briefings_config) try: smart_home_config = config[CONF_SMART_HOME] except KeyError: pass else: smart_home_config = smart_home_config or SMART_HOME_SCHEMA({}) await smart_home_http.async_setup(hass, smart_home_config) return True
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/alexa/__init__.py
"""Support for LCN lights.""" import pypck from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.const import CONF_ADDRESS from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_DIMMABLE, CONF_OUTPUT, CONF_TRANSITION, DATA_LCN, OUTPUT_PORTS, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN light platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) if config[CONF_OUTPUT] in OUTPUT_PORTS: device = LcnOutputLight(config, address_connection) else: # in RELAY_PORTS device = LcnRelayLight(config, address_connection) devices.append(device) async_add_entities(devices) class LcnOutputLight(LcnDevice, LightEntity): """Representation of a LCN light for output ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.OutputPort[config[CONF_OUTPUT]] self._transition = pypck.lcn_defs.time_to_ramp_value(config[CONF_TRANSITION]) self.dimmable = config[CONF_DIMMABLE] self._brightness = 255 self._is_on = None self._is_dimming_to_zero = False async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def supported_features(self): """Flag supported features.""" features = SUPPORT_TRANSITION if self.dimmable: features |= SUPPORT_BRIGHTNESS return features @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True self._is_dimming_to_zero = False if ATTR_BRIGHTNESS in kwargs: percent = int(kwargs[ATTR_BRIGHTNESS] / 255.0 * 100) else: percent = 100 if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self.address_connection.dim_output(self.output.value, percent, transition) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self._is_dimming_to_zero = bool(transition) self.address_connection.dim_output(self.output.value, 0, transition) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if ( not isinstance(input_obj, pypck.inputs.ModStatusOutput) or input_obj.get_output_id() != self.output.value ): return self._brightness = int(input_obj.get_percent() / 100.0 * 255) if self.brightness == 0: self._is_dimming_to_zero = False if not self._is_dimming_to_zero: self._is_on = self.brightness > 0 self.async_write_ha_state() class LcnRelayLight(LcnDevice, LightEntity): """Representation of a LCN light for relay ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.RelayPort[config[CONF_OUTPUT]] self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.ON self.address_connection.control_relays(states) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.OFF self.address_connection.control_relays(states) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusRelays): return self._is_on = input_obj.get_state(self.output.value) self.async_write_ha_state()
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/lcn/light.py
"""Support for AlarmDecoder devices.""" import asyncio from datetime import timedelta import logging from adext import AdExt from alarmdecoder.devices import SerialDevice, SocketDevice from alarmdecoder.util import NoDeviceError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF_PROTOCOL, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util from .const import ( CONF_DEVICE_BAUD, CONF_DEVICE_PATH, DATA_AD, DATA_REMOVE_STOP_LISTENER, DATA_REMOVE_UPDATE_LISTENER, DATA_RESTART, DOMAIN, PROTOCOL_SERIAL, PROTOCOL_SOCKET, SIGNAL_PANEL_MESSAGE, SIGNAL_REL_MESSAGE, SIGNAL_RFX_MESSAGE, SIGNAL_ZONE_FAULT, SIGNAL_ZONE_RESTORE, ) _LOGGER = logging.getLogger(__name__) PLATFORMS = ["alarm_control_panel", "sensor", "binary_sensor"] async def async_setup(hass, config): """Set up for the AlarmDecoder devices.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up AlarmDecoder config flow.""" undo_listener = entry.add_update_listener(_update_listener) ad_connection = entry.data protocol = ad_connection[CONF_PROTOCOL] def stop_alarmdecoder(event): """Handle the shutdown of AlarmDecoder.""" if not hass.data.get(DOMAIN): return _LOGGER.debug("Shutting down alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False controller.close() async def open_connection(now=None): """Open a connection to AlarmDecoder.""" try: await hass.async_add_executor_job(controller.open, baud) except NoDeviceError: _LOGGER.debug("Failed to connect. Retrying in 5 seconds") hass.helpers.event.async_track_point_in_time( open_connection, dt_util.utcnow() + timedelta(seconds=5) ) return _LOGGER.debug("Established a connection with the alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = True def handle_closed_connection(event): """Restart after unexpected loss of connection.""" if not hass.data[DOMAIN][entry.entry_id][DATA_RESTART]: return hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False _LOGGER.warning("AlarmDecoder unexpectedly lost connection") hass.add_job(open_connection) def handle_message(sender, message): """Handle message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_PANEL_MESSAGE, message) def handle_rfx_message(sender, message): """Handle RFX message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_RFX_MESSAGE, message) def zone_fault_callback(sender, zone): """Handle zone fault from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_FAULT, zone) def zone_restore_callback(sender, zone): """Handle zone restore from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_RESTORE, zone) def handle_rel_message(sender, message): """Handle relay or zone expander message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_REL_MESSAGE, message) baud = ad_connection.get(CONF_DEVICE_BAUD) if protocol == PROTOCOL_SOCKET: host = ad_connection[CONF_HOST] port = ad_connection[CONF_PORT] controller = AdExt(SocketDevice(interface=(host, port))) if protocol == PROTOCOL_SERIAL: path = ad_connection[CONF_DEVICE_PATH] controller = AdExt(SerialDevice(interface=path)) controller.on_message += handle_message controller.on_rfx_message += handle_rfx_message controller.on_zone_fault += zone_fault_callback controller.on_zone_restore += zone_restore_callback controller.on_close += handle_closed_connection controller.on_expander_message += handle_rel_message remove_stop_listener = hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_AD: controller, DATA_REMOVE_UPDATE_LISTENER: undo_listener, DATA_REMOVE_STOP_LISTENER: remove_stop_listener, DATA_RESTART: False, } await open_connection() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): """Unload a AlarmDecoder entry.""" hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_UPDATE_LISTENER]() hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_STOP_LISTENER]() await hass.async_add_executor_job(hass.data[DOMAIN][entry.entry_id][DATA_AD].close) if hass.data[DOMAIN][entry.entry_id]: hass.data[DOMAIN].pop(entry.entry_id) if not hass.data[DOMAIN]: hass.data.pop(DOMAIN) return True async def _update_listener(hass: HomeAssistantType, entry: ConfigEntry): """Handle options update.""" _LOGGER.debug("AlarmDecoder options updated: %s", entry.as_dict()["options"]) await hass.config_entries.async_reload(entry.entry_id)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/alarmdecoder/__init__.py
"""Support for Plaato Airlock.""" import logging from aiohttp import web import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR from homeassistant.const import ( CONF_WEBHOOK_ID, HTTP_OK, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLUME_GALLONS, VOLUME_LITERS, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import DOMAIN _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ["webhook"] PLAATO_DEVICE_SENSORS = "sensors" PLAATO_DEVICE_ATTRS = "attrs" ATTR_DEVICE_ID = "device_id" ATTR_DEVICE_NAME = "device_name" ATTR_TEMP_UNIT = "temp_unit" ATTR_VOLUME_UNIT = "volume_unit" ATTR_BPM = "bpm" ATTR_TEMP = "temp" ATTR_SG = "sg" ATTR_OG = "og" ATTR_BUBBLES = "bubbles" ATTR_ABV = "abv" ATTR_CO2_VOLUME = "co2_volume" ATTR_BATCH_VOLUME = "batch_volume" SENSOR_UPDATE = f"{DOMAIN}_sensor_update" SENSOR_DATA_KEY = f"{DOMAIN}.{SENSOR}" WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_NAME): cv.string, vol.Required(ATTR_DEVICE_ID): cv.positive_int, vol.Required(ATTR_TEMP_UNIT): vol.Any(TEMP_CELSIUS, TEMP_FAHRENHEIT), vol.Required(ATTR_VOLUME_UNIT): vol.Any(VOLUME_LITERS, VOLUME_GALLONS), vol.Required(ATTR_BPM): cv.positive_int, vol.Required(ATTR_TEMP): vol.Coerce(float), vol.Required(ATTR_SG): vol.Coerce(float), vol.Required(ATTR_OG): vol.Coerce(float), vol.Required(ATTR_ABV): vol.Coerce(float), vol.Required(ATTR_CO2_VOLUME): vol.Coerce(float), vol.Required(ATTR_BATCH_VOLUME): vol.Coerce(float), vol.Required(ATTR_BUBBLES): cv.positive_int, }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, hass_config): """Set up the Plaato component.""" return True async def async_setup_entry(hass, entry): """Configure based on config entry.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} webhook_id = entry.data[CONF_WEBHOOK_ID] hass.components.webhook.async_register(DOMAIN, "Plaato", webhook_id, handle_webhook) hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, SENSOR)) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[SENSOR_DATA_KEY]() await hass.config_entries.async_forward_entry_unload(entry, SENSOR) return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Plaato.""" try: data = WEBHOOK_SCHEMA(await request.json()) except vol.MultipleInvalid as error: _LOGGER.warning("An error occurred when parsing webhook data <%s>", error) return device_id = _device_id(data) attrs = { ATTR_DEVICE_NAME: data.get(ATTR_DEVICE_NAME), ATTR_DEVICE_ID: data.get(ATTR_DEVICE_ID), ATTR_TEMP_UNIT: data.get(ATTR_TEMP_UNIT), ATTR_VOLUME_UNIT: data.get(ATTR_VOLUME_UNIT), } sensors = { ATTR_TEMP: data.get(ATTR_TEMP), ATTR_BPM: data.get(ATTR_BPM), ATTR_SG: data.get(ATTR_SG), ATTR_OG: data.get(ATTR_OG), ATTR_ABV: data.get(ATTR_ABV), ATTR_CO2_VOLUME: data.get(ATTR_CO2_VOLUME), ATTR_BATCH_VOLUME: data.get(ATTR_BATCH_VOLUME), ATTR_BUBBLES: data.get(ATTR_BUBBLES), } hass.data[DOMAIN][device_id] = { PLAATO_DEVICE_ATTRS: attrs, PLAATO_DEVICE_SENSORS: sensors, } async_dispatcher_send(hass, SENSOR_UPDATE, device_id) return web.Response(text=f"Saving status for {device_id}", status=HTTP_OK) def _device_id(data): """Return name of device sensor.""" return f"{data.get(ATTR_DEVICE_NAME)}_{data.get(ATTR_DEVICE_ID)}"
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/plaato/__init__.py
"""Support for the Pico TTS speech service.""" import logging import os import shutil import subprocess import tempfile import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider _LOGGER = logging.getLogger(__name__) SUPPORT_LANGUAGES = ["en-US", "en-GB", "de-DE", "es-ES", "fr-FR", "it-IT"] DEFAULT_LANG = "en-US" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)} ) def get_engine(hass, config, discovery_info=None): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG]) class PicoProvider(Provider): """The Pico TTS API provider.""" def __init__(self, lang): """Initialize Pico TTS provider.""" self._lang = lang self.name = "PicoTTS" @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS using pico2wave.""" with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpf: fname = tmpf.name cmd = ["pico2wave", "--wave", fname, "-l", language, message] subprocess.call(cmd) data = None try: with open(fname, "rb") as voice: data = voice.read() except OSError: _LOGGER.error("Error trying to read %s", fname) return (None, None) finally: os.remove(fname) if data: return ("wav", data) return (None, None)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/picotts/tts.py
"""Support for Dominos Pizza ordering.""" from datetime import timedelta import logging from pizzapi import Address, Customer, Order from pizzapi.address import StoreException import voluptuous as vol from homeassistant.components import http from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) # The domain of your component. Should be equal to the name of your component. DOMAIN = "dominos" ENTITY_ID_FORMAT = DOMAIN + ".{}" ATTR_COUNTRY = "country_code" ATTR_FIRST_NAME = "first_name" ATTR_LAST_NAME = "last_name" ATTR_EMAIL = "email" ATTR_PHONE = "phone" ATTR_ADDRESS = "address" ATTR_ORDERS = "orders" ATTR_SHOW_MENU = "show_menu" ATTR_ORDER_ENTITY = "order_entity_id" ATTR_ORDER_NAME = "name" ATTR_ORDER_CODES = "codes" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) MIN_TIME_BETWEEN_STORE_UPDATES = timedelta(minutes=3330) _ORDERS_SCHEMA = vol.Schema( { vol.Required(ATTR_ORDER_NAME): cv.string, vol.Required(ATTR_ORDER_CODES): vol.All(cv.ensure_list, [cv.string]), } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(ATTR_COUNTRY): cv.string, vol.Required(ATTR_FIRST_NAME): cv.string, vol.Required(ATTR_LAST_NAME): cv.string, vol.Required(ATTR_EMAIL): cv.string, vol.Required(ATTR_PHONE): cv.string, vol.Required(ATTR_ADDRESS): cv.string, vol.Optional(ATTR_SHOW_MENU): cv.boolean, vol.Optional(ATTR_ORDERS, default=[]): vol.All( cv.ensure_list, [_ORDERS_SCHEMA] ), } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up is called when Home Assistant is loading our component.""" dominos = Dominos(hass, config) component = EntityComponent(_LOGGER, DOMAIN, hass) hass.data[DOMAIN] = {} entities = [] conf = config[DOMAIN] hass.services.register(DOMAIN, "order", dominos.handle_order) if conf.get(ATTR_SHOW_MENU): hass.http.register_view(DominosProductListView(dominos)) for order_info in conf.get(ATTR_ORDERS): order = DominosOrder(order_info, dominos) entities.append(order) if entities: component.add_entities(entities) # Return boolean to indicate that initialization was successfully. return True class Dominos: """Main Dominos service.""" def __init__(self, hass, config): """Set up main service.""" conf = config[DOMAIN] self.hass = hass self.customer = Customer( conf.get(ATTR_FIRST_NAME), conf.get(ATTR_LAST_NAME), conf.get(ATTR_EMAIL), conf.get(ATTR_PHONE), conf.get(ATTR_ADDRESS), ) self.address = Address( *self.customer.address.split(","), country=conf.get(ATTR_COUNTRY) ) self.country = conf.get(ATTR_COUNTRY) try: self.closest_store = self.address.closest_store() except StoreException: self.closest_store = None def handle_order(self, call): """Handle ordering pizza.""" entity_ids = call.data.get(ATTR_ORDER_ENTITY) target_orders = [ order for order in self.hass.data[DOMAIN]["entities"] if order.entity_id in entity_ids ] for order in target_orders: order.place() @Throttle(MIN_TIME_BETWEEN_STORE_UPDATES) def update_closest_store(self): """Update the shared closest store (if open).""" try: self.closest_store = self.address.closest_store() return True except StoreException: self.closest_store = None return False def get_menu(self): """Return the products from the closest stores menu.""" self.update_closest_store() if self.closest_store is None: _LOGGER.warning("Cannot get menu. Store may be closed") return [] menu = self.closest_store.get_menu() product_entries = [] for product in menu.products: item = {} if isinstance(product.menu_data["Variants"], list): variants = ", ".join(product.menu_data["Variants"]) else: variants = product.menu_data["Variants"] item["name"] = product.name item["variants"] = variants product_entries.append(item) return product_entries class DominosProductListView(http.HomeAssistantView): """View to retrieve product list content.""" url = "/api/dominos" name = "api:dominos" def __init__(self, dominos): """Initialize suite view.""" self.dominos = dominos @callback def get(self, request): """Retrieve if API is running.""" return self.json(self.dominos.get_menu()) class DominosOrder(Entity): """Represents a Dominos order entity.""" def __init__(self, order_info, dominos): """Set up the entity.""" self._name = order_info["name"] self._product_codes = order_info["codes"] self._orderable = False self.dominos = dominos @property def name(self): """Return the orders name.""" return self._name @property def product_codes(self): """Return the orders product codes.""" return self._product_codes @property def orderable(self): """Return the true if orderable.""" return self._orderable @property def state(self): """Return the state either closed, orderable or unorderable.""" if self.dominos.closest_store is None: return "closed" return "orderable" if self._orderable else "unorderable" @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the order state and refreshes the store.""" try: self.dominos.update_closest_store() except StoreException: self._orderable = False return try: order = self.order() order.pay_with() self._orderable = True except StoreException: self._orderable = False def order(self): """Create the order object.""" if self.dominos.closest_store is None: raise StoreException order = Order( self.dominos.closest_store, self.dominos.customer, self.dominos.address, self.dominos.country, ) for code in self._product_codes: order.add_item(code) return order def place(self): """Place the order.""" try: order = self.order() order.place() except StoreException: self._orderable = False _LOGGER.warning( "Attempted to order Dominos - Order invalid or store closed" )
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/dominos/__init__.py
"""Support for Vera switches.""" import logging from typing import Any, Callable, List, Optional import pyvera as veraApi from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, SwitchEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import Entity from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraSwitch(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ] ) class VeraSwitch(VeraDevice[veraApi.VeraSwitch], SwitchEntity): """Representation of a Vera Switch.""" def __init__( self, vera_device: veraApi.VeraSwitch, controller_data: ControllerData ): """Initialize the Vera device.""" self._state = False VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) def turn_on(self, **kwargs: Any) -> None: """Turn device on.""" self.vera_device.switch_on() self._state = True self.schedule_update_ha_state() def turn_off(self, **kwargs: Any) -> None: """Turn device off.""" self.vera_device.switch_off() self._state = False self.schedule_update_ha_state() @property def current_power_w(self) -> Optional[float]: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def is_on(self) -> bool: """Return true if device is on.""" return self._state def update(self) -> None: """Update device state.""" self._state = self.vera_device.is_switched_on()
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/vera/switch.py
"""JSON utility functions.""" from collections import deque import json import logging import os import tempfile from typing import Any, Callable, Dict, List, Optional, Type, Union from homeassistant.core import Event, State from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) class SerializationError(HomeAssistantError): """Error serializing the data to JSON.""" class WriteError(HomeAssistantError): """Error writing the data.""" def load_json( filename: str, default: Union[List, Dict, None] = None ) -> Union[List, Dict]: """Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found. """ try: with open(filename, encoding="utf-8") as fdesc: return json.loads(fdesc.read()) # type: ignore except FileNotFoundError: # This is not a fatal error _LOGGER.debug("JSON file not found: %s", filename) except ValueError as error: _LOGGER.exception("Could not parse JSON content: %s", filename) raise HomeAssistantError(error) from error except OSError as error: _LOGGER.exception("JSON file reading failed: %s", filename) raise HomeAssistantError(error) from error return {} if default is None else default def save_json( filename: str, data: Union[List, Dict], private: bool = False, *, encoder: Optional[Type[json.JSONEncoder]] = None, ) -> None: """Save JSON data to a file. Returns True on success. """ try: json_data = json.dumps(data, indent=4, cls=encoder) except TypeError as error: msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}" _LOGGER.error(msg) raise SerializationError(msg) from error tmp_filename = "" tmp_path = os.path.split(filename)[0] try: # Modern versions of Python tempfile create this file with mode 0o600 with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", dir=tmp_path, delete=False ) as fdesc: fdesc.write(json_data) tmp_filename = fdesc.name if not private: os.chmod(tmp_filename, 0o644) os.replace(tmp_filename, filename) except OSError as error: _LOGGER.exception("Saving JSON file failed: %s", filename) raise WriteError(error) from error finally: if os.path.exists(tmp_filename): try: os.remove(tmp_filename) except OSError as err: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("JSON replacement cleanup failed: %s", err) def format_unserializable_data(data: Dict[str, Any]) -> str: """Format output of find_paths in a friendly way. Format is comma separated: <path>=<value>(<type>) """ return ", ".join(f"{path}={value}({type(value)}" for path, value in data.items()) def find_paths_unserializable_data( bad_data: Any, *, dump: Callable[[Any], str] = json.dumps ) -> Dict[str, Any]: """Find the paths to unserializable data. This method is slow! Only use for error handling. """ to_process = deque([(bad_data, "$")]) invalid = {} while to_process: obj, obj_path = to_process.popleft() try: dump(obj) continue except (ValueError, TypeError): pass # We convert states and events to dict so we can find bad data inside it if isinstance(obj, State): obj_path += f"(state: {obj.entity_id})" obj = obj.as_dict() elif isinstance(obj, Event): obj_path += f"(event: {obj.event_type})" obj = obj.as_dict() if isinstance(obj, dict): for key, value in obj.items(): try: # Is key valid? dump({key: None}) except TypeError: invalid[f"{obj_path}<key: {key}>"] = key else: # Process value to_process.append((value, f"{obj_path}.{key}")) elif isinstance(obj, list): for idx, value in enumerate(obj): to_process.append((value, f"{obj_path}[{idx}]")) else: invalid[obj_path] = obj return invalid
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/util/json.py
"""Support for Genius Hub switch/outlet devices.""" from homeassistant.components.switch import DEVICE_CLASS_OUTLET, SwitchEntity from homeassistant.helpers.typing import ConfigType, HomeAssistantType from . import DOMAIN, GeniusZone ATTR_DURATION = "duration" GH_ON_OFF_ZONE = "on / off" async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Set up the Genius Hub switch entities.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] async_add_entities( [ GeniusSwitch(broker, z) for z in broker.client.zone_objs if z.data["type"] == GH_ON_OFF_ZONE ] ) class GeniusSwitch(GeniusZone, SwitchEntity): """Representation of a Genius Hub switch.""" @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_OUTLET @property def is_on(self) -> bool: """Return the current state of the on/off zone. The zone is considered 'on' if & only if it is override/on (e.g. timer/on is 'off'). """ return self._zone.data["mode"] == "override" and self._zone.data["setpoint"] async def async_turn_off(self, **kwargs) -> None: """Send the zone to Timer mode. The zone is deemed 'off' in this mode, although the plugs may actually be on. """ await self._zone.set_mode("timer") async def async_turn_on(self, **kwargs) -> None: """Set the zone to override/on ({'setpoint': true}) for x seconds.""" await self._zone.set_override(1, kwargs.get(ATTR_DURATION, 3600))
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/geniushub/switch.py
"""Provide configuration end points for Groups.""" from homeassistant.components.group import DOMAIN, GROUP_SCHEMA from homeassistant.config import GROUP_CONFIG_PATH from homeassistant.const import SERVICE_RELOAD import homeassistant.helpers.config_validation as cv from . import EditKeyBasedConfigView async def async_setup(hass): """Set up the Group config API.""" async def hook(action, config_key): """post_write_hook for Config View that reloads groups.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) hass.http.register_view( EditKeyBasedConfigView( "group", "config", GROUP_CONFIG_PATH, cv.slug, GROUP_SCHEMA, post_write_hook=hook, ) ) return True
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/config/group.py
"""Support for LCN climate control.""" import pypck from homeassistant.components.climate import ClimateEntity, const from homeassistant.const import ATTR_TEMPERATURE, CONF_ADDRESS, CONF_UNIT_OF_MEASUREMENT from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_LOCKABLE, CONF_MAX_TEMP, CONF_MIN_TEMP, CONF_SETPOINT, CONF_SOURCE, DATA_LCN, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN climate platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) devices.append(LcnClimate(config, address_connection)) async_add_entities(devices) class LcnClimate(LcnDevice, ClimateEntity): """Representation of a LCN climate device.""" def __init__(self, config, address_connection): """Initialize of a LCN climate device.""" super().__init__(config, address_connection) self.variable = pypck.lcn_defs.Var[config[CONF_SOURCE]] self.setpoint = pypck.lcn_defs.Var[config[CONF_SETPOINT]] self.unit = pypck.lcn_defs.VarUnit.parse(config[CONF_UNIT_OF_MEASUREMENT]) self.regulator_id = pypck.lcn_defs.Var.to_set_point_id(self.setpoint) self.is_lockable = config[CONF_LOCKABLE] self._max_temp = config[CONF_MAX_TEMP] self._min_temp = config[CONF_MIN_TEMP] self._current_temperature = None self._target_temperature = None self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.variable) await self.address_connection.activate_status_request_handler(self.setpoint) @property def supported_features(self): """Return the list of supported features.""" return const.SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self): """Return the unit of measurement.""" return self.unit.value @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._is_on: return const.HVAC_MODE_HEAT return const.HVAC_MODE_OFF @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ modes = [const.HVAC_MODE_HEAT] if self.is_lockable: modes.append(const.HVAC_MODE_OFF) return modes @property def max_temp(self): """Return the maximum temperature.""" return self._max_temp @property def min_temp(self): """Return the minimum temperature.""" return self._min_temp async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == const.HVAC_MODE_HEAT: self._is_on = True self.address_connection.lock_regulator(self.regulator_id, False) elif hvac_mode == const.HVAC_MODE_OFF: self._is_on = False self.address_connection.lock_regulator(self.regulator_id, True) self._target_temperature = None self.async_write_ha_state() async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._target_temperature = temperature self.address_connection.var_abs( self.setpoint, self._target_temperature, self.unit ) self.async_write_ha_state() def input_received(self, input_obj): """Set temperature value when LCN input object is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusVar): return if input_obj.get_var() == self.variable: self._current_temperature = input_obj.get_value().to_var_unit(self.unit) elif input_obj.get_var() == self.setpoint: self._is_on = not input_obj.get_value().is_locked_regulator() if self._is_on: self._target_temperature = input_obj.get_value().to_var_unit(self.unit) self.async_write_ha_state()
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/lcn/climate.py
"""Support for HomeMatic binary sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import ATTR_DISCOVER_DEVICES, ATTR_DISCOVERY_TYPE, DISCOVER_BATTERY from .entity import HMDevice _LOGGER = logging.getLogger(__name__) SENSOR_TYPES_CLASS = { "IPShutterContact": DEVICE_CLASS_OPENING, "IPShutterContactSabotage": DEVICE_CLASS_OPENING, "MaxShutterContact": DEVICE_CLASS_OPENING, "Motion": DEVICE_CLASS_MOTION, "MotionV2": DEVICE_CLASS_MOTION, "PresenceIP": DEVICE_CLASS_PRESENCE, "Remote": None, "RemoteMotion": None, "ShutterContact": DEVICE_CLASS_OPENING, "Smoke": DEVICE_CLASS_SMOKE, "SmokeV2": DEVICE_CLASS_SMOKE, "TiltSensor": None, "WeatherSensor": None, "IPContact": DEVICE_CLASS_OPENING, "MotionIPV2": DEVICE_CLASS_MOTION, "IPRemoteMotionV2": DEVICE_CLASS_MOTION, } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the HomeMatic binary sensor platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY: devices.append(HMBatterySensor(conf)) else: devices.append(HMBinarySensor(conf)) add_entities(devices, True) class HMBinarySensor(HMDevice, BinarySensorEntity): """Representation of a binary HomeMatic device.""" @property def is_on(self): """Return true if switch is on.""" if not self.available: return False return bool(self._hm_get_state()) @property def device_class(self): """Return the class of this sensor from DEVICE_CLASSES.""" # If state is MOTION (Only RemoteMotion working) if self._state == "MOTION": return DEVICE_CLASS_MOTION return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None}) class HMBatterySensor(HMDevice, BinarySensorEntity): """Representation of an HomeMatic low battery sensor.""" @property def device_class(self): """Return battery as a device class.""" return DEVICE_CLASS_BATTERY @property def is_on(self): """Return True if battery is low.""" return bool(self._hm_get_state()) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None})
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/homematic/binary_sensor.py
"""Support for an Intergas heater via an InComfort/InTouch Lan2RF gateway.""" from typing import Any, Dict, Optional from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE, PRESSURE_BAR, TEMP_CELSIUS, ) from homeassistant.util import slugify from . import DOMAIN, IncomfortChild INCOMFORT_HEATER_TEMP = "CV Temp" INCOMFORT_PRESSURE = "CV Pressure" INCOMFORT_TAP_TEMP = "Tap Temp" INCOMFORT_MAP_ATTRS = { INCOMFORT_HEATER_TEMP: ["heater_temp", "is_pumping"], INCOMFORT_PRESSURE: ["pressure", None], INCOMFORT_TAP_TEMP: ["tap_temp", "is_tapping"], } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch sensor device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities( [IncomfortPressure(client, h, INCOMFORT_PRESSURE) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_HEATER_TEMP) for h in heaters] + [IncomfortTemperature(client, h, INCOMFORT_TAP_TEMP) for h in heaters] ) class IncomfortSensor(IncomfortChild): """Representation of an InComfort/InTouch sensor device.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__() self._client = client self._heater = heater self._unique_id = f"{heater.serial_no}_{slugify(name)}" self.entity_id = f"{SENSOR_DOMAIN}.{DOMAIN}_{slugify(name)}" self._name = f"Boiler {name}" self._device_class = None self._state_attr = INCOMFORT_MAP_ATTRS[name][0] self._unit_of_measurement = None @property def state(self) -> Optional[str]: """Return the state of the sensor.""" return self._heater.status[self._state_attr] @property def device_class(self) -> Optional[str]: """Return the device class of the sensor.""" return self._device_class @property def unit_of_measurement(self) -> Optional[str]: """Return the unit of measurement of the sensor.""" return self._unit_of_measurement class IncomfortPressure(IncomfortSensor): """Representation of an InTouch CV Pressure sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the sensor.""" super().__init__(client, heater, name) self._device_class = DEVICE_CLASS_PRESSURE self._unit_of_measurement = PRESSURE_BAR class IncomfortTemperature(IncomfortSensor): """Representation of an InTouch Temperature sensor.""" def __init__(self, client, heater, name) -> None: """Initialize the signal strength sensor.""" super().__init__(client, heater, name) self._attr = INCOMFORT_MAP_ATTRS[name][1] self._device_class = DEVICE_CLASS_TEMPERATURE self._unit_of_measurement = TEMP_CELSIUS @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the device state attributes.""" return {self._attr: self._heater.status[self._attr]}
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/incomfort/sensor.py
"""Support for Satel Integra devices.""" import collections import logging from satel_integra.satel_integra import AsyncSatel import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.discovery import async_load_platform from homeassistant.helpers.dispatcher import async_dispatcher_send DEFAULT_ALARM_NAME = "satel_integra" DEFAULT_PORT = 7094 DEFAULT_CONF_ARM_HOME_MODE = 1 DEFAULT_DEVICE_PARTITION = 1 DEFAULT_ZONE_TYPE = "motion" _LOGGER = logging.getLogger(__name__) DOMAIN = "satel_integra" DATA_SATEL = "satel_integra" CONF_DEVICE_CODE = "code" CONF_DEVICE_PARTITIONS = "partitions" CONF_ARM_HOME_MODE = "arm_home_mode" CONF_ZONE_NAME = "name" CONF_ZONE_TYPE = "type" CONF_ZONES = "zones" CONF_OUTPUTS = "outputs" CONF_SWITCHABLE_OUTPUTS = "switchable_outputs" ZONES = "zones" SIGNAL_PANEL_MESSAGE = "satel_integra.panel_message" SIGNAL_PANEL_ARM_AWAY = "satel_integra.panel_arm_away" SIGNAL_PANEL_ARM_HOME = "satel_integra.panel_arm_home" SIGNAL_PANEL_DISARM = "satel_integra.panel_disarm" SIGNAL_ZONES_UPDATED = "satel_integra.zones_updated" SIGNAL_OUTPUTS_UPDATED = "satel_integra.outputs_updated" ZONE_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE_NAME): cv.string, vol.Optional(CONF_ZONE_TYPE, default=DEFAULT_ZONE_TYPE): cv.string, } ) EDITABLE_OUTPUT_SCHEMA = vol.Schema({vol.Required(CONF_ZONE_NAME): cv.string}) PARTITION_SCHEMA = vol.Schema( { vol.Required(CONF_ZONE_NAME): cv.string, vol.Optional(CONF_ARM_HOME_MODE, default=DEFAULT_CONF_ARM_HOME_MODE): vol.In( [1, 2, 3] ), } ) def is_alarm_code_necessary(value): """Check if alarm code must be configured.""" if value.get(CONF_SWITCHABLE_OUTPUTS) and CONF_DEVICE_CODE not in value: raise vol.Invalid("You need to specify alarm code to use switchable_outputs") return value CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_DEVICE_CODE): cv.string, vol.Optional(CONF_DEVICE_PARTITIONS, default={}): { vol.Coerce(int): PARTITION_SCHEMA }, vol.Optional(CONF_ZONES, default={}): {vol.Coerce(int): ZONE_SCHEMA}, vol.Optional(CONF_OUTPUTS, default={}): {vol.Coerce(int): ZONE_SCHEMA}, vol.Optional(CONF_SWITCHABLE_OUTPUTS, default={}): { vol.Coerce(int): EDITABLE_OUTPUT_SCHEMA }, }, is_alarm_code_necessary, ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the Satel Integra component.""" conf = config.get(DOMAIN) zones = conf.get(CONF_ZONES) outputs = conf.get(CONF_OUTPUTS) switchable_outputs = conf.get(CONF_SWITCHABLE_OUTPUTS) host = conf.get(CONF_HOST) port = conf.get(CONF_PORT) partitions = conf.get(CONF_DEVICE_PARTITIONS) monitored_outputs = collections.OrderedDict( list(outputs.items()) + list(switchable_outputs.items()) ) controller = AsyncSatel(host, port, hass.loop, zones, monitored_outputs, partitions) hass.data[DATA_SATEL] = controller result = await controller.connect() if not result: return False async def _close(): controller.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close()) _LOGGER.debug("Arm home config: %s, mode: %s ", conf, conf.get(CONF_ARM_HOME_MODE)) hass.async_create_task( async_load_platform(hass, "alarm_control_panel", DOMAIN, conf, config) ) hass.async_create_task( async_load_platform( hass, "binary_sensor", DOMAIN, {CONF_ZONES: zones, CONF_OUTPUTS: outputs}, config, ) ) hass.async_create_task( async_load_platform( hass, "switch", DOMAIN, { CONF_SWITCHABLE_OUTPUTS: switchable_outputs, CONF_DEVICE_CODE: conf.get(CONF_DEVICE_CODE), }, config, ) ) @callback def alarm_status_update_callback(): """Send status update received from alarm to Home Assistant.""" _LOGGER.debug("Sending request to update panel state") async_dispatcher_send(hass, SIGNAL_PANEL_MESSAGE) @callback def zones_update_callback(status): """Update zone objects as per notification from the alarm.""" _LOGGER.debug("Zones callback, status: %s", status) async_dispatcher_send(hass, SIGNAL_ZONES_UPDATED, status[ZONES]) @callback def outputs_update_callback(status): """Update zone objects as per notification from the alarm.""" _LOGGER.debug("Outputs updated callback , status: %s", status) async_dispatcher_send(hass, SIGNAL_OUTPUTS_UPDATED, status["outputs"]) # Create a task instead of adding a tracking job, since this task will # run until the connection to satel_integra is closed. hass.loop.create_task(controller.keep_alive()) hass.loop.create_task( controller.monitor_status( alarm_status_update_callback, zones_update_callback, outputs_update_callback ) ) return True
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/satel_integra/__init__.py
"""Support for controlling projector via the PJLink protocol.""" import logging from pypjlink import MUTE_AUDIO, Projector from pypjlink.projector import ProjectorError import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, STATE_OFF, STATE_ON, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_ENCODING = "encoding" DEFAULT_PORT = 4352 DEFAULT_ENCODING = "utf-8" DEFAULT_TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) SUPPORT_PJLINK = ( SUPPORT_VOLUME_MUTE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the PJLink platform.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) encoding = config.get(CONF_ENCODING) password = config.get(CONF_PASSWORD) if "pjlink" not in hass.data: hass.data["pjlink"] = {} hass_data = hass.data["pjlink"] device_label = f"{host}:{port}" if device_label in hass_data: return device = PjLinkDevice(host, port, name, encoding, password) hass_data[device_label] = device add_entities([device], True) def format_input_source(input_source_name, input_source_number): """Format input source for display in UI.""" return f"{input_source_name} {input_source_number}" class PjLinkDevice(MediaPlayerEntity): """Representation of a PJLink device.""" def __init__(self, host, port, name, encoding, password): """Iinitialize the PJLink device.""" self._host = host self._port = port self._name = name self._password = password self._encoding = encoding self._muted = False self._pwstate = STATE_OFF self._current_source = None with self.projector() as projector: if not self._name: self._name = projector.get_name() inputs = projector.get_inputs() self._source_name_mapping = {format_input_source(*x): x for x in inputs} self._source_list = sorted(self._source_name_mapping.keys()) def projector(self): """Create PJLink Projector instance.""" projector = Projector.from_address( self._host, self._port, self._encoding, DEFAULT_TIMEOUT ) projector.authenticate(self._password) return projector def update(self): """Get the latest state from the device.""" with self.projector() as projector: try: pwstate = projector.get_power() if pwstate in ("on", "warm-up"): self._pwstate = STATE_ON self._muted = projector.get_mute()[1] self._current_source = format_input_source(*projector.get_input()) else: self._pwstate = STATE_OFF self._muted = False self._current_source = None except KeyError as err: if str(err) == "'OK'": self._pwstate = STATE_OFF self._muted = False self._current_source = None else: raise except ProjectorError as err: if str(err) == "unavailable time": self._pwstate = STATE_OFF self._muted = False self._current_source = None else: raise @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._pwstate @property def is_volume_muted(self): """Return boolean indicating mute status.""" return self._muted @property def source(self): """Return current input source.""" return self._current_source @property def source_list(self): """Return all available input sources.""" return self._source_list @property def supported_features(self): """Return projector supported features.""" return SUPPORT_PJLINK def turn_off(self): """Turn projector off.""" if self._pwstate == STATE_ON: with self.projector() as projector: projector.set_power("off") def turn_on(self): """Turn projector on.""" if self._pwstate == STATE_OFF: with self.projector() as projector: projector.set_power("on") def mute_volume(self, mute): """Mute (true) of unmute (false) media player.""" with self.projector() as projector: projector.set_mute(MUTE_AUDIO, mute) def select_source(self, source): """Set the input source.""" source = self._source_name_mapping[source] with self.projector() as projector: projector.set_input(*source)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/pjlink/media_player.py
"""Support for ADS covers.""" import logging import voluptuous as vol from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_STOP, CoverEntity, ) from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME import homeassistant.helpers.config_validation as cv from . import ( CONF_ADS_VAR, CONF_ADS_VAR_POSITION, DATA_ADS, STATE_KEY_POSITION, STATE_KEY_STATE, AdsEntity, ) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "ADS Cover" CONF_ADS_VAR_SET_POS = "adsvar_set_position" CONF_ADS_VAR_OPEN = "adsvar_open" CONF_ADS_VAR_CLOSE = "adsvar_close" CONF_ADS_VAR_STOP = "adsvar_stop" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_ADS_VAR): cv.string, vol.Optional(CONF_ADS_VAR_POSITION): cv.string, vol.Optional(CONF_ADS_VAR_SET_POS): cv.string, vol.Optional(CONF_ADS_VAR_CLOSE): cv.string, vol.Optional(CONF_ADS_VAR_OPEN): cv.string, vol.Optional(CONF_ADS_VAR_STOP): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the cover platform for ADS.""" ads_hub = hass.data[DATA_ADS] ads_var_is_closed = config.get(CONF_ADS_VAR) ads_var_position = config.get(CONF_ADS_VAR_POSITION) ads_var_pos_set = config.get(CONF_ADS_VAR_SET_POS) ads_var_open = config.get(CONF_ADS_VAR_OPEN) ads_var_close = config.get(CONF_ADS_VAR_CLOSE) ads_var_stop = config.get(CONF_ADS_VAR_STOP) name = config[CONF_NAME] device_class = config.get(CONF_DEVICE_CLASS) add_entities( [ AdsCover( ads_hub, ads_var_is_closed, ads_var_position, ads_var_pos_set, ads_var_open, ads_var_close, ads_var_stop, name, device_class, ) ] ) class AdsCover(AdsEntity, CoverEntity): """Representation of ADS cover.""" def __init__( self, ads_hub, ads_var_is_closed, ads_var_position, ads_var_pos_set, ads_var_open, ads_var_close, ads_var_stop, name, device_class, ): """Initialize AdsCover entity.""" super().__init__(ads_hub, name, ads_var_is_closed) if self._ads_var is None: if ads_var_position is not None: self._unique_id = ads_var_position elif ads_var_pos_set is not None: self._unique_id = ads_var_pos_set elif ads_var_open is not None: self._unique_id = ads_var_open self._state_dict[STATE_KEY_POSITION] = None self._ads_var_position = ads_var_position self._ads_var_pos_set = ads_var_pos_set self._ads_var_open = ads_var_open self._ads_var_close = ads_var_close self._ads_var_stop = ads_var_stop self._device_class = device_class async def async_added_to_hass(self): """Register device notification.""" if self._ads_var is not None: await self.async_initialize_device( self._ads_var, self._ads_hub.PLCTYPE_BOOL ) if self._ads_var_position is not None: await self.async_initialize_device( self._ads_var_position, self._ads_hub.PLCTYPE_BYTE, STATE_KEY_POSITION ) @property def device_class(self): """Return the class of this cover.""" return self._device_class @property def is_closed(self): """Return if the cover is closed.""" if self._ads_var is not None: return self._state_dict[STATE_KEY_STATE] if self._ads_var_position is not None: return self._state_dict[STATE_KEY_POSITION] == 0 return None @property def current_cover_position(self): """Return current position of cover.""" return self._state_dict[STATE_KEY_POSITION] @property def supported_features(self): """Flag supported features.""" supported_features = SUPPORT_OPEN | SUPPORT_CLOSE if self._ads_var_stop is not None: supported_features |= SUPPORT_STOP if self._ads_var_pos_set is not None: supported_features |= SUPPORT_SET_POSITION return supported_features def stop_cover(self, **kwargs): """Fire the stop action.""" if self._ads_var_stop: self._ads_hub.write_by_name( self._ads_var_stop, True, self._ads_hub.PLCTYPE_BOOL ) def set_cover_position(self, **kwargs): """Set cover position.""" position = kwargs[ATTR_POSITION] if self._ads_var_pos_set is not None: self._ads_hub.write_by_name( self._ads_var_pos_set, position, self._ads_hub.PLCTYPE_BYTE ) def open_cover(self, **kwargs): """Move the cover up.""" if self._ads_var_open is not None: self._ads_hub.write_by_name( self._ads_var_open, True, self._ads_hub.PLCTYPE_BOOL ) elif self._ads_var_pos_set is not None: self.set_cover_position(position=100) def close_cover(self, **kwargs): """Move the cover down.""" if self._ads_var_close is not None: self._ads_hub.write_by_name( self._ads_var_close, True, self._ads_hub.PLCTYPE_BOOL ) elif self._ads_var_pos_set is not None: self.set_cover_position(position=0) @property def available(self): """Return False if state has not been updated yet.""" if self._ads_var is not None or self._ads_var_position is not None: return ( self._state_dict[STATE_KEY_STATE] is not None or self._state_dict[STATE_KEY_POSITION] is not None ) return True
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/ads/cover.py
"""Support for ESPHome switches.""" import logging from typing import Optional from aioesphomeapi import SwitchInfo, SwitchState from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome switches based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="switch", info_type=SwitchInfo, entity_type=EsphomeSwitch, state_type=SwitchState, ) class EsphomeSwitch(EsphomeEntity, SwitchEntity): """A switch implementation for ESPHome.""" @property def _static_info(self) -> SwitchInfo: return super()._static_info @property def _state(self) -> Optional[SwitchState]: return super()._state @property def icon(self) -> str: """Return the icon.""" return self._static_info.icon @property def assumed_state(self) -> bool: """Return true if we do optimistic updates.""" return self._static_info.assumed_state # https://github.com/PyCQA/pylint/issues/3150 for @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_on(self) -> Optional[bool]: """Return true if the switch is on.""" return self._state.state async def async_turn_on(self, **kwargs) -> None: """Turn the entity on.""" await self._client.switch_command(self._static_info.key, True) async def async_turn_off(self, **kwargs) -> None: """Turn the entity off.""" await self._client.switch_command(self._static_info.key, False)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/esphome/switch.py
"""Support for IOTA wallets.""" from datetime import timedelta import logging from iota import Iota import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_IRI = "iri" CONF_TESTNET = "testnet" CONF_WALLET_NAME = "name" CONF_WALLET_SEED = "seed" CONF_WALLETS = "wallets" DOMAIN = "iota" IOTA_PLATFORMS = ["sensor"] SCAN_INTERVAL = timedelta(minutes=10) WALLET_CONFIG = vol.Schema( { vol.Required(CONF_WALLET_NAME): cv.string, vol.Required(CONF_WALLET_SEED): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_IRI): cv.string, vol.Optional(CONF_TESTNET, default=False): cv.boolean, vol.Required(CONF_WALLETS): vol.All(cv.ensure_list, [WALLET_CONFIG]), } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up the IOTA component.""" iota_config = config[DOMAIN] for platform in IOTA_PLATFORMS: load_platform(hass, platform, DOMAIN, iota_config, config) return True class IotaDevice(Entity): """Representation of a IOTA device.""" def __init__(self, name, seed, iri, is_testnet=False): """Initialise the IOTA device.""" self._name = name self._seed = seed self.iri = iri self.is_testnet = is_testnet @property def name(self): """Return the default name of the device.""" return self._name @property def device_state_attributes(self): """Return the state attributes of the device.""" attr = {CONF_WALLET_NAME: self._name} return attr @property def api(self): """Construct API object for interaction with the IRI node.""" return Iota(adapter=self.iri, seed=self._seed)
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/iota/__init__.py
"""Provides device automations for Fan.""" from typing import List import voluptuous as vol from homeassistant.components.automation import AutomationActionType from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.homeassistant.triggers import state as state_trigger from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, STATE_OFF, STATE_ON, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_TYPES = {"turned_on", "turned_off"} TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Fan devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue # Add triggers for each entity that belongs to this integration triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_on", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_off", } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "turned_on": from_state = STATE_OFF to_state = STATE_ON else: from_state = STATE_ON to_state = STATE_OFF state_config = { state_trigger.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state_trigger.CONF_FROM: from_state, state_trigger.CONF_TO: to_state, } state_config = state_trigger.TRIGGER_SCHEMA(state_config) return await state_trigger.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
"""Test the Shark IQ config flow.""" import aiohttp import pytest from sharkiqpy import AylaApi, SharkIqAuthError from homeassistant import config_entries, setup from homeassistant.components.sharkiq.const import DOMAIN from homeassistant.core import HomeAssistant from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID from tests.async_mock import patch from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch( "homeassistant.components.sharkiq.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.sharkiq.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "create_entry" assert result2["title"] == f"{TEST_USERNAME:s}" assert result2["data"] == { "username": TEST_USERNAME, "password": TEST_PASSWORD, } await hass.async_block_till_done() mock_setup.assert_called_once() mock_setup_entry.assert_called_once() @pytest.mark.parametrize( "exc,base_error", [ (SharkIqAuthError, "invalid_auth"), (aiohttp.ClientError, "cannot_connect"), (TypeError, "unknown"), ], ) async def test_form_error(hass: HomeAssistant, exc: Exception, base_error: str): """Test form errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch.object(AylaApi, "async_sign_in", side_effect=exc): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG, ) assert result2["type"] == "form" assert result2["errors"].get("base") == base_error async def test_reauth_success(hass: HomeAssistant): """Test reauth flow.""" with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True): mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG) mock_config.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG ) assert result["type"] == "abort" assert result["reason"] == "reauth_successful" @pytest.mark.parametrize( "side_effect,result_type,msg_field,msg", [ (SharkIqAuthError, "form", "errors", "invalid_auth"), (aiohttp.ClientError, "abort", "reason", "cannot_connect"), (TypeError, "abort", "reason", "unknown"), ], ) async def test_reauth( hass: HomeAssistant, side_effect: Exception, result_type: str, msg_field: str, msg: str, ): """Test reauth failures.""" with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=side_effect): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG, ) msg_value = result[msg_field] if msg_field == "errors": msg_value = msg_value.get("base") assert result["type"] == result_type assert msg_value == msg
tchellomello/home-assistant
tests/components/sharkiq/test_config_flow.py
homeassistant/components/fan/device_trigger.py
import numpy as np import scipy.sparse as sps from ._numdiff import approx_derivative, group_columns from ._hessian_update_strategy import HessianUpdateStrategy from scipy.sparse.linalg import LinearOperator FD_METHODS = ('2-point', '3-point', 'cs') class ScalarFunction: """Scalar function and its derivatives. This class defines a scalar function F: R^n->R and methods for computing or approximating its first and second derivatives. Parameters ---------- fun : callable evaluates the scalar function. Must be of the form ``fun(x, *args)``, where ``x`` is the argument in the form of a 1-D array and ``args`` is a tuple of any additional fixed parameters needed to completely specify the function. Should return a scalar. x0 : array-like Provides an initial set of variables for evaluating fun. Array of real elements of size (n,), where 'n' is the number of independent variables. args : tuple, optional Any additional fixed parameters needed to completely specify the scalar function. grad : {callable, '2-point', '3-point', 'cs'} Method for computing the gradient vector. If it is a callable, it should be a function that returns the gradient vector: ``grad(x, *args) -> array_like, shape (n,)`` where ``x`` is an array with shape (n,) and ``args`` is a tuple with the fixed parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used to select a finite difference scheme for numerical estimation of the gradient with a relative step size. These finite difference schemes obey any specified `bounds`. hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy} Method for computing the Hessian matrix. If it is callable, it should return the Hessian matrix: ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)`` where x is a (n,) ndarray and `args` is a tuple with the fixed parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'} select a finite difference scheme for numerical estimation. Or, objects implementing `HessianUpdateStrategy` interface can be used to approximate the Hessian. Whenever the gradient is estimated via finite-differences, the Hessian cannot be estimated with options {'2-point', '3-point', 'cs'} and needs to be estimated using one of the quasi-Newton strategies. finite_diff_rel_step : None or array_like Relative step size to use. The absolute step size is computed as ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly adjusted to fit into the bounds. For ``method='3-point'`` the sign of `h` is ignored. If None then finite_diff_rel_step is selected automatically, finite_diff_bounds : tuple of array_like Lower and upper bounds on independent variables. Defaults to no bounds, (-np.inf, np.inf). Each bound must match the size of `x0` or be a scalar, in the latter case the bound will be the same for all variables. Use it to limit the range of function evaluation. epsilon : None or array_like, optional Absolute step size to use, possibly adjusted to fit into the bounds. For ``method='3-point'`` the sign of `epsilon` is ignored. By default relative steps are used, only if ``epsilon is not None`` are absolute steps used. Notes ----- This class implements a memoization logic. There are methods `fun`, `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following things should be considered: 1. Use only public methods `fun`, `grad` and `hess`. 2. After one of the methods is called, the corresponding attribute will be set. However, a subsequent call with a different argument of *any* of the methods may overwrite the attribute. """ def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step, finite_diff_bounds, epsilon=None): if not callable(grad) and grad not in FD_METHODS: raise ValueError( f"`grad` must be either callable or one of {FD_METHODS}." ) if not (callable(hess) or hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)): raise ValueError( f"`hess` must be either callable, HessianUpdateStrategy" f" or one of {FD_METHODS}." ) if grad in FD_METHODS and hess in FD_METHODS: raise ValueError("Whenever the gradient is estimated via " "finite-differences, we require the Hessian " "to be estimated using one of the " "quasi-Newton strategies.") # the astype call ensures that self.x is a copy of x0 self.x = np.atleast_1d(x0).astype(float) self.n = self.x.size self.nfev = 0 self.ngev = 0 self.nhev = 0 self.f_updated = False self.g_updated = False self.H_updated = False finite_diff_options = {} if grad in FD_METHODS: finite_diff_options["method"] = grad finite_diff_options["rel_step"] = finite_diff_rel_step finite_diff_options["abs_step"] = epsilon finite_diff_options["bounds"] = finite_diff_bounds if hess in FD_METHODS: finite_diff_options["method"] = hess finite_diff_options["rel_step"] = finite_diff_rel_step finite_diff_options["abs_step"] = epsilon finite_diff_options["as_linear_operator"] = True # Function evaluation def fun_wrapped(x): self.nfev += 1 # Send a copy because the user may overwrite it. # Overwriting results in undefined behaviour because # fun(self.x) will change self.x, with the two no longer linked. return fun(np.copy(x), *args) def update_fun(): self.f = fun_wrapped(self.x) self._update_fun_impl = update_fun self._update_fun() # Gradient evaluation if callable(grad): def grad_wrapped(x): self.ngev += 1 return np.atleast_1d(grad(np.copy(x), *args)) def update_grad(): self.g = grad_wrapped(self.x) elif grad in FD_METHODS: def update_grad(): self._update_fun() self.ngev += 1 self.g = approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options) self._update_grad_impl = update_grad self._update_grad() # Hessian Evaluation if callable(hess): self.H = hess(np.copy(x0), *args) self.H_updated = True self.nhev += 1 if sps.issparse(self.H): def hess_wrapped(x): self.nhev += 1 return sps.csr_matrix(hess(np.copy(x), *args)) self.H = sps.csr_matrix(self.H) elif isinstance(self.H, LinearOperator): def hess_wrapped(x): self.nhev += 1 return hess(np.copy(x), *args) else: def hess_wrapped(x): self.nhev += 1 return np.atleast_2d(np.asarray(hess(np.copy(x), *args))) self.H = np.atleast_2d(np.asarray(self.H)) def update_hess(): self.H = hess_wrapped(self.x) elif hess in FD_METHODS: def update_hess(): self._update_grad() self.H = approx_derivative(grad_wrapped, self.x, f0=self.g, **finite_diff_options) return self.H update_hess() self.H_updated = True elif isinstance(hess, HessianUpdateStrategy): self.H = hess self.H.initialize(self.n, 'hess') self.H_updated = True self.x_prev = None self.g_prev = None def update_hess(): self._update_grad() self.H.update(self.x - self.x_prev, self.g - self.g_prev) self._update_hess_impl = update_hess if isinstance(hess, HessianUpdateStrategy): def update_x(x): self._update_grad() self.x_prev = self.x self.g_prev = self.g # ensure that self.x is a copy of x. Don't store a reference # otherwise the memoization doesn't work properly. self.x = np.atleast_1d(x).astype(float) self.f_updated = False self.g_updated = False self.H_updated = False self._update_hess() else: def update_x(x): # ensure that self.x is a copy of x. Don't store a reference # otherwise the memoization doesn't work properly. self.x = np.atleast_1d(x).astype(float) self.f_updated = False self.g_updated = False self.H_updated = False self._update_x_impl = update_x def _update_fun(self): if not self.f_updated: self._update_fun_impl() self.f_updated = True def _update_grad(self): if not self.g_updated: self._update_grad_impl() self.g_updated = True def _update_hess(self): if not self.H_updated: self._update_hess_impl() self.H_updated = True def fun(self, x): if not np.array_equal(x, self.x): self._update_x_impl(x) self._update_fun() return self.f def grad(self, x): if not np.array_equal(x, self.x): self._update_x_impl(x) self._update_grad() return self.g def hess(self, x): if not np.array_equal(x, self.x): self._update_x_impl(x) self._update_hess() return self.H def fun_and_grad(self, x): if not np.array_equal(x, self.x): self._update_x_impl(x) self._update_fun() self._update_grad() return self.f, self.g class VectorFunction: """Vector function and its derivatives. This class defines a vector function F: R^n->R^m and methods for computing or approximating its first and second derivatives. Notes ----- This class implements a memoization logic. There are methods `fun`, `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following things should be considered: 1. Use only public methods `fun`, `jac` and `hess`. 2. After one of the methods is called, the corresponding attribute will be set. However, a subsequent call with a different argument of *any* of the methods may overwrite the attribute. """ def __init__(self, fun, x0, jac, hess, finite_diff_rel_step, finite_diff_jac_sparsity, finite_diff_bounds, sparse_jacobian): if not callable(jac) and jac not in FD_METHODS: raise ValueError("`jac` must be either callable or one of {}." .format(FD_METHODS)) if not (callable(hess) or hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)): raise ValueError("`hess` must be either callable," "HessianUpdateStrategy or one of {}." .format(FD_METHODS)) if jac in FD_METHODS and hess in FD_METHODS: raise ValueError("Whenever the Jacobian is estimated via " "finite-differences, we require the Hessian to " "be estimated using one of the quasi-Newton " "strategies.") self.x = np.atleast_1d(x0).astype(float) self.n = self.x.size self.nfev = 0 self.njev = 0 self.nhev = 0 self.f_updated = False self.J_updated = False self.H_updated = False finite_diff_options = {} if jac in FD_METHODS: finite_diff_options["method"] = jac finite_diff_options["rel_step"] = finite_diff_rel_step if finite_diff_jac_sparsity is not None: sparsity_groups = group_columns(finite_diff_jac_sparsity) finite_diff_options["sparsity"] = (finite_diff_jac_sparsity, sparsity_groups) finite_diff_options["bounds"] = finite_diff_bounds self.x_diff = np.copy(self.x) if hess in FD_METHODS: finite_diff_options["method"] = hess finite_diff_options["rel_step"] = finite_diff_rel_step finite_diff_options["as_linear_operator"] = True self.x_diff = np.copy(self.x) if jac in FD_METHODS and hess in FD_METHODS: raise ValueError("Whenever the Jacobian is estimated via " "finite-differences, we require the Hessian to " "be estimated using one of the quasi-Newton " "strategies.") # Function evaluation def fun_wrapped(x): self.nfev += 1 return np.atleast_1d(fun(x)) def update_fun(): self.f = fun_wrapped(self.x) self._update_fun_impl = update_fun update_fun() self.v = np.zeros_like(self.f) self.m = self.v.size # Jacobian Evaluation if callable(jac): self.J = jac(self.x) self.J_updated = True self.njev += 1 if (sparse_jacobian or sparse_jacobian is None and sps.issparse(self.J)): def jac_wrapped(x): self.njev += 1 return sps.csr_matrix(jac(x)) self.J = sps.csr_matrix(self.J) self.sparse_jacobian = True elif sps.issparse(self.J): def jac_wrapped(x): self.njev += 1 return jac(x).toarray() self.J = self.J.toarray() self.sparse_jacobian = False else: def jac_wrapped(x): self.njev += 1 return np.atleast_2d(jac(x)) self.J = np.atleast_2d(self.J) self.sparse_jacobian = False def update_jac(): self.J = jac_wrapped(self.x) elif jac in FD_METHODS: self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options) self.J_updated = True if (sparse_jacobian or sparse_jacobian is None and sps.issparse(self.J)): def update_jac(): self._update_fun() self.J = sps.csr_matrix( approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options)) self.J = sps.csr_matrix(self.J) self.sparse_jacobian = True elif sps.issparse(self.J): def update_jac(): self._update_fun() self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options).toarray() self.J = self.J.toarray() self.sparse_jacobian = False else: def update_jac(): self._update_fun() self.J = np.atleast_2d( approx_derivative(fun_wrapped, self.x, f0=self.f, **finite_diff_options)) self.J = np.atleast_2d(self.J) self.sparse_jacobian = False self._update_jac_impl = update_jac # Define Hessian if callable(hess): self.H = hess(self.x, self.v) self.H_updated = True self.nhev += 1 if sps.issparse(self.H): def hess_wrapped(x, v): self.nhev += 1 return sps.csr_matrix(hess(x, v)) self.H = sps.csr_matrix(self.H) elif isinstance(self.H, LinearOperator): def hess_wrapped(x, v): self.nhev += 1 return hess(x, v) else: def hess_wrapped(x, v): self.nhev += 1 return np.atleast_2d(np.asarray(hess(x, v))) self.H = np.atleast_2d(np.asarray(self.H)) def update_hess(): self.H = hess_wrapped(self.x, self.v) elif hess in FD_METHODS: def jac_dot_v(x, v): return jac_wrapped(x).T.dot(v) def update_hess(): self._update_jac() self.H = approx_derivative(jac_dot_v, self.x, f0=self.J.T.dot(self.v), args=(self.v,), **finite_diff_options) update_hess() self.H_updated = True elif isinstance(hess, HessianUpdateStrategy): self.H = hess self.H.initialize(self.n, 'hess') self.H_updated = True self.x_prev = None self.J_prev = None def update_hess(): self._update_jac() # When v is updated before x was updated, then x_prev and # J_prev are None and we need this check. if self.x_prev is not None and self.J_prev is not None: delta_x = self.x - self.x_prev delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v) self.H.update(delta_x, delta_g) self._update_hess_impl = update_hess if isinstance(hess, HessianUpdateStrategy): def update_x(x): self._update_jac() self.x_prev = self.x self.J_prev = self.J self.x = np.atleast_1d(x).astype(float) self.f_updated = False self.J_updated = False self.H_updated = False self._update_hess() else: def update_x(x): self.x = np.atleast_1d(x).astype(float) self.f_updated = False self.J_updated = False self.H_updated = False self._update_x_impl = update_x def _update_v(self, v): if not np.array_equal(v, self.v): self.v = v self.H_updated = False def _update_x(self, x): if not np.array_equal(x, self.x): self._update_x_impl(x) def _update_fun(self): if not self.f_updated: self._update_fun_impl() self.f_updated = True def _update_jac(self): if not self.J_updated: self._update_jac_impl() self.J_updated = True def _update_hess(self): if not self.H_updated: self._update_hess_impl() self.H_updated = True def fun(self, x): self._update_x(x) self._update_fun() return self.f def jac(self, x): self._update_x(x) self._update_jac() return self.J def hess(self, x, v): # v should be updated before x. self._update_v(v) self._update_x(x) self._update_hess() return self.H class LinearVectorFunction: """Linear vector function and its derivatives. Defines a linear function F = A x, where x is N-D vector and A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian is identically zero and it is returned as a csr matrix. """ def __init__(self, A, x0, sparse_jacobian): if sparse_jacobian or sparse_jacobian is None and sps.issparse(A): self.J = sps.csr_matrix(A) self.sparse_jacobian = True elif sps.issparse(A): self.J = A.toarray() self.sparse_jacobian = False else: # np.asarray makes sure A is ndarray and not matrix self.J = np.atleast_2d(np.asarray(A)) self.sparse_jacobian = False self.m, self.n = self.J.shape self.x = np.atleast_1d(x0).astype(float) self.f = self.J.dot(self.x) self.f_updated = True self.v = np.zeros(self.m, dtype=float) self.H = sps.csr_matrix((self.n, self.n)) def _update_x(self, x): if not np.array_equal(x, self.x): self.x = np.atleast_1d(x).astype(float) self.f_updated = False def fun(self, x): self._update_x(x) if not self.f_updated: self.f = self.J.dot(x) self.f_updated = True return self.f def jac(self, x): self._update_x(x) return self.J def hess(self, x, v): self._update_x(x) self.v = v return self.H class IdentityVectorFunction(LinearVectorFunction): """Identity vector function and its derivatives. The Jacobian is the identity matrix, returned as a dense array when `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is identically zero and it is returned as a csr matrix. """ def __init__(self, x0, sparse_jacobian): n = len(x0) if sparse_jacobian or sparse_jacobian is None: A = sps.eye(n, format='csr') sparse_jacobian = True else: A = np.eye(n) sparse_jacobian = False super().__init__(A, x0, sparse_jacobian)
""" Unit tests for trust-region optimization routines. To run it in its simplest form:: nosetests test_optimize.py """ import itertools from copy import deepcopy import numpy as np from numpy.testing import assert_, assert_equal, assert_allclose from scipy.optimize import (minimize, rosen, rosen_der, rosen_hess, rosen_hess_prod, BFGS) from scipy.optimize._differentiable_functions import FD_METHODS import pytest class Accumulator: """ This is for testing callbacks.""" def __init__(self): self.count = 0 self.accum = None def __call__(self, x): self.count += 1 if self.accum is None: self.accum = np.array(x) else: self.accum += x class TestTrustRegionSolvers: def setup_method(self): self.x_opt = [1.0, 1.0] self.easy_guess = [2.0, 2.0] self.hard_guess = [-1.2, 1.0] def test_dogleg_accuracy(self): # test the accuracy and the return_all option x0 = self.hard_guess r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='dogleg', options={'return_all': True},) assert_allclose(x0, r['allvecs'][0]) assert_allclose(r['x'], r['allvecs'][-1]) assert_allclose(r['x'], self.x_opt) def test_dogleg_callback(self): # test the callback mechanism and the maxiter and return_all options accumulator = Accumulator() maxiter = 5 r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess, callback=accumulator, method='dogleg', options={'return_all': True, 'maxiter': maxiter},) assert_equal(accumulator.count, maxiter) assert_equal(len(r['allvecs']), maxiter+1) assert_allclose(r['x'], r['allvecs'][-1]) assert_allclose(sum(r['allvecs'][1:]), accumulator.accum) def test_solver_concordance(self): # Assert that dogleg uses fewer iterations than ncg on the Rosenbrock # test function, although this does not necessarily mean # that dogleg is faster or better than ncg even for this function # and especially not for other test functions. f = rosen g = rosen_der h = rosen_hess for x0 in (self.easy_guess, self.hard_guess): r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='dogleg', options={'return_all': True}) r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-ncg', options={'return_all': True}) r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-krylov', options={'return_all': True}) r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='newton-cg', options={'return_all': True}) r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-exact', options={'return_all': True}) assert_allclose(self.x_opt, r_dogleg['x']) assert_allclose(self.x_opt, r_trust_ncg['x']) assert_allclose(self.x_opt, r_trust_krylov['x']) assert_allclose(self.x_opt, r_ncg['x']) assert_allclose(self.x_opt, r_iterative['x']) assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs'])) def test_trust_ncg_hessp(self): for x0 in (self.easy_guess, self.hard_guess, self.x_opt): r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod, tol=1e-8, method='trust-ncg') assert_allclose(self.x_opt, r['x']) def test_trust_ncg_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-ncg') assert_allclose(self.x_opt, r['x']) def test_trust_krylov_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-krylov') assert_allclose(self.x_opt, r['x']) def test_trust_exact_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-exact') assert_allclose(self.x_opt, r['x']) def test_finite_differences(self): # if the Hessian is estimated by finite differences or # a HessianUpdateStrategy (and no hessp is provided) then creation # of a hessp is possible. # GH13754 methods = ["trust-ncg", "trust-krylov", "dogleg"] product = itertools.product( FD_METHODS + (BFGS,), methods ) # a hessian needs to be specified for trustregion for method in methods: with pytest.raises(ValueError): minimize(rosen, x0=self.x_opt, jac=rosen_der, method=method) # estimate hessian by finite differences. In _trustregion.py this # creates a hessp from the LinearOperator/HessianUpdateStrategy # that's returned from ScalarFunction. for fd, method in product: hess = fd if fd == BFGS: # don't want to use the same object over and over hess = deepcopy(fd()) r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=hess, tol=1e-8, method=method) assert_allclose(self.x_opt, r['x'])
WarrenWeckesser/scipy
scipy/optimize/tests/test_trustregion.py
scipy/optimize/_differentiable_functions.py
""" Interface to Constrained Optimization By Linear Approximation Functions --------- .. autosummary:: :toctree: generated/ fmin_cobyla """ import functools from threading import RLock import numpy as np from scipy.optimize import _cobyla from .optimize import OptimizeResult, _check_unknown_options try: from itertools import izip except ImportError: izip = zip __all__ = ['fmin_cobyla'] # Workarund as _cobyla.minimize is not threadsafe # due to an unknown f2py bug and can segfault, # see gh-9658. _module_lock = RLock() def synchronized(func): @functools.wraps(func) def wrapper(*args, **kwargs): with _module_lock: return func(*args, **kwargs) return wrapper @synchronized def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0, rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4): """ Minimize a function using the Constrained Optimization By Linear Approximation (COBYLA) method. This method wraps a FORTRAN implementation of the algorithm. Parameters ---------- func : callable Function to minimize. In the form func(x, \\*args). x0 : ndarray Initial guess. cons : sequence Constraint functions; must all be ``>=0`` (a single function if only 1 constraint). Each function takes the parameters `x` as its first argument, and it can return either a single number or an array or list of numbers. args : tuple, optional Extra arguments to pass to function. consargs : tuple, optional Extra arguments to pass to constraint functions (default of None means use same extra arguments as those passed to func). Use ``()`` for no extra arguments. rhobeg : float, optional Reasonable initial changes to the variables. rhoend : float, optional Final accuracy in the optimization (not precisely guaranteed). This is a lower bound on the size of the trust region. disp : {0, 1, 2, 3}, optional Controls the frequency of output; 0 implies no output. maxfun : int, optional Maximum number of function evaluations. catol : float, optional Absolute tolerance for constraint violations. Returns ------- x : ndarray The argument that minimises `f`. See also -------- minimize: Interface to minimization algorithms for multivariate functions. See the 'COBYLA' `method` in particular. Notes ----- This algorithm is based on linear approximations to the objective function and each constraint. We briefly describe the algorithm. Suppose the function is being minimized over k variables. At the jth iteration the algorithm has k+1 points v_1, ..., v_(k+1), an approximate solution x_j, and a radius RHO_j. (i.e., linear plus a constant) approximations to the objective function and constraint functions such that their function values agree with the linear approximation on the k+1 points v_1,.., v_(k+1). This gives a linear program to solve (where the linear approximations of the constraint functions are constrained to be non-negative). However, the linear approximations are likely only good approximations near the current simplex, so the linear program is given the further requirement that the solution, which will become x_(j+1), must be within RHO_j from x_j. RHO_j only decreases, never increases. The initial RHO_j is rhobeg and the final RHO_j is rhoend. In this way COBYLA's iterations behave like a trust region algorithm. Additionally, the linear program may be inconsistent, or the approximation may give poor improvement. For details about how these issues are resolved, as well as how the points v_i are updated, refer to the source code or the references below. References ---------- Powell M.J.D. (1994), "A direct search optimization method that models the objective and constraint functions by linear interpolation.", in Advances in Optimization and Numerical Analysis, eds. S. Gomez and J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67 Powell M.J.D. (1998), "Direct search algorithms for optimization calculations", Acta Numerica 7, 287-336 Powell M.J.D. (2007), "A view of algorithms for optimization without derivatives", Cambridge University Technical Report DAMTP 2007/NA03 Examples -------- Minimize the objective function f(x,y) = x*y subject to the constraints x**2 + y**2 < 1 and y > 0:: >>> def objective(x): ... return x[0]*x[1] ... >>> def constr1(x): ... return 1 - (x[0]**2 + x[1]**2) ... >>> def constr2(x): ... return x[1] ... >>> from scipy.optimize import fmin_cobyla >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7) array([-0.70710685, 0.70710671]) The exact solution is (-sqrt(2)/2, sqrt(2)/2). """ err = "cons must be a sequence of callable functions or a single"\ " callable function." try: len(cons) except TypeError as e: if callable(cons): cons = [cons] else: raise TypeError(err) from e else: for thisfunc in cons: if not callable(thisfunc): raise TypeError(err) if consargs is None: consargs = args # build constraints con = tuple({'type': 'ineq', 'fun': c, 'args': consargs} for c in cons) # options opts = {'rhobeg': rhobeg, 'tol': rhoend, 'disp': disp, 'maxiter': maxfun, 'catol': catol} sol = _minimize_cobyla(func, x0, args, constraints=con, **opts) if disp and not sol['success']: print("COBYLA failed to find a solution: %s" % (sol.message,)) return sol['x'] @synchronized def _minimize_cobyla(fun, x0, args=(), constraints=(), rhobeg=1.0, tol=1e-4, maxiter=1000, disp=False, catol=2e-4, **unknown_options): """ Minimize a scalar function of one or more variables using the Constrained Optimization BY Linear Approximation (COBYLA) algorithm. Options ------- rhobeg : float Reasonable initial changes to the variables. tol : float Final accuracy in the optimization (not precisely guaranteed). This is a lower bound on the size of the trust region. disp : bool Set to True to print convergence messages. If False, `verbosity` is ignored as set to 0. maxiter : int Maximum number of function evaluations. catol : float Tolerance (absolute) for constraint violations """ _check_unknown_options(unknown_options) maxfun = maxiter rhoend = tol iprint = int(bool(disp)) # check constraints if isinstance(constraints, dict): constraints = (constraints, ) for ic, con in enumerate(constraints): # check type try: ctype = con['type'].lower() except KeyError as e: raise KeyError('Constraint %d has no type defined.' % ic) from e except TypeError as e: raise TypeError('Constraints must be defined using a ' 'dictionary.') from e except AttributeError as e: raise TypeError("Constraint's type must be a string.") from e else: if ctype != 'ineq': raise ValueError("Constraints of type '%s' not handled by " "COBYLA." % con['type']) # check function if 'fun' not in con: raise KeyError('Constraint %d has no function defined.' % ic) # check extra arguments if 'args' not in con: con['args'] = () # m is the total number of constraint values # it takes into account that some constraints may be vector-valued cons_lengths = [] for c in constraints: f = c['fun'](x0, *c['args']) try: cons_length = len(f) except TypeError: cons_length = 1 cons_lengths.append(cons_length) m = sum(cons_lengths) def calcfc(x, con): f = fun(np.copy(x), *args) i = 0 for size, c in izip(cons_lengths, constraints): con[i: i + size] = c['fun'](x, *c['args']) i += size return f info = np.zeros(4, np.float64) xopt, info = _cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg, rhoend=rhoend, iprint=iprint, maxfun=maxfun, dinfo=info) if info[3] > catol: # Check constraint violation info[0] = 4 return OptimizeResult(x=xopt, status=int(info[0]), success=info[0] == 1, message={1: 'Optimization terminated successfully.', 2: 'Maximum number of function evaluations ' 'has been exceeded.', 3: 'Rounding errors are becoming damaging ' 'in COBYLA subroutine.', 4: 'Did not converge to a solution ' 'satisfying the constraints. See ' '`maxcv` for magnitude of violation.', 5: 'NaN result encountered.' }.get(info[0], 'Unknown exit status.'), nfev=int(info[1]), fun=info[2], maxcv=info[3])
""" Unit tests for trust-region optimization routines. To run it in its simplest form:: nosetests test_optimize.py """ import itertools from copy import deepcopy import numpy as np from numpy.testing import assert_, assert_equal, assert_allclose from scipy.optimize import (minimize, rosen, rosen_der, rosen_hess, rosen_hess_prod, BFGS) from scipy.optimize._differentiable_functions import FD_METHODS import pytest class Accumulator: """ This is for testing callbacks.""" def __init__(self): self.count = 0 self.accum = None def __call__(self, x): self.count += 1 if self.accum is None: self.accum = np.array(x) else: self.accum += x class TestTrustRegionSolvers: def setup_method(self): self.x_opt = [1.0, 1.0] self.easy_guess = [2.0, 2.0] self.hard_guess = [-1.2, 1.0] def test_dogleg_accuracy(self): # test the accuracy and the return_all option x0 = self.hard_guess r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='dogleg', options={'return_all': True},) assert_allclose(x0, r['allvecs'][0]) assert_allclose(r['x'], r['allvecs'][-1]) assert_allclose(r['x'], self.x_opt) def test_dogleg_callback(self): # test the callback mechanism and the maxiter and return_all options accumulator = Accumulator() maxiter = 5 r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess, callback=accumulator, method='dogleg', options={'return_all': True, 'maxiter': maxiter},) assert_equal(accumulator.count, maxiter) assert_equal(len(r['allvecs']), maxiter+1) assert_allclose(r['x'], r['allvecs'][-1]) assert_allclose(sum(r['allvecs'][1:]), accumulator.accum) def test_solver_concordance(self): # Assert that dogleg uses fewer iterations than ncg on the Rosenbrock # test function, although this does not necessarily mean # that dogleg is faster or better than ncg even for this function # and especially not for other test functions. f = rosen g = rosen_der h = rosen_hess for x0 in (self.easy_guess, self.hard_guess): r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='dogleg', options={'return_all': True}) r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-ncg', options={'return_all': True}) r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-krylov', options={'return_all': True}) r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='newton-cg', options={'return_all': True}) r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8, method='trust-exact', options={'return_all': True}) assert_allclose(self.x_opt, r_dogleg['x']) assert_allclose(self.x_opt, r_trust_ncg['x']) assert_allclose(self.x_opt, r_trust_krylov['x']) assert_allclose(self.x_opt, r_ncg['x']) assert_allclose(self.x_opt, r_iterative['x']) assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs'])) def test_trust_ncg_hessp(self): for x0 in (self.easy_guess, self.hard_guess, self.x_opt): r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod, tol=1e-8, method='trust-ncg') assert_allclose(self.x_opt, r['x']) def test_trust_ncg_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-ncg') assert_allclose(self.x_opt, r['x']) def test_trust_krylov_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-krylov') assert_allclose(self.x_opt, r['x']) def test_trust_exact_start_in_optimum(self): r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess, tol=1e-8, method='trust-exact') assert_allclose(self.x_opt, r['x']) def test_finite_differences(self): # if the Hessian is estimated by finite differences or # a HessianUpdateStrategy (and no hessp is provided) then creation # of a hessp is possible. # GH13754 methods = ["trust-ncg", "trust-krylov", "dogleg"] product = itertools.product( FD_METHODS + (BFGS,), methods ) # a hessian needs to be specified for trustregion for method in methods: with pytest.raises(ValueError): minimize(rosen, x0=self.x_opt, jac=rosen_der, method=method) # estimate hessian by finite differences. In _trustregion.py this # creates a hessp from the LinearOperator/HessianUpdateStrategy # that's returned from ScalarFunction. for fd, method in product: hess = fd if fd == BFGS: # don't want to use the same object over and over hess = deepcopy(fd()) r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=hess, tol=1e-8, method=method) assert_allclose(self.x_opt, r['x'])
WarrenWeckesser/scipy
scipy/optimize/tests/test_trustregion.py
scipy/optimize/cobyla.py
# Copyright (c) 2016, NECST Laboratory, Politecnico di Milano # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import Arduino from . import ARDUINO_GROVE_I2C __author__ = "Marco Rabozzi, Luca Cerina, Giuseppe Natale" __copyright__ = "Copyright 2016, NECST Laboratory, Politecnico di Milano" ARDUINO_GROVE_DLIGHT_PROGRAM = "arduino_grove_dlight.bin" CONFIG_IOP_SWITCH = 0x1 GET_LIGHT_VALUE = 0x3 GET_LUX_VALUE = 0x5 class Grove_Dlight(object): """This class controls the Grove IIC color sensor. Grove Color sensor based on the TCS3414CS. Hardware version: v1.3. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. """ def __init__(self, mb_info, gr_pin): """Return a new instance of an Grove_Dlight object. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. gr_pin: list A group of pins on arduino-grove shield. """ if gr_pin not in [ARDUINO_GROVE_I2C]: raise ValueError("Group number can only be I2C.") self.microblaze = Arduino(mb_info, ARDUINO_GROVE_DLIGHT_PROGRAM) self.microblaze.write_blocking_command(CONFIG_IOP_SWITCH) def read_raw_light(self): """Read the visible and IR channel values. Read the values from the grove digital light peripheral. Returns ------- tuple A tuple containing 2 integer values ch0 (visible) and ch1 (IR). """ self.microblaze.write_blocking_command(GET_LIGHT_VALUE) ch0, ch1 = self.microblaze.read_mailbox(0, 2) return ch0, ch1 def read_lux(self): """Read the computed lux value of the sensor. Returns ------- int The lux value from the sensor """ self.microblaze.write_blocking_command(GET_LUX_VALUE) lux = self.microblaze.read_mailbox(0x8) return lux
# Copyright (c) 2016, Xilinx, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from random import randint from copy import deepcopy import pytest from pynq import Overlay from pynq.tests.util import user_answer_yes from pynq.lib.logictools import PatternGenerator from pynq.lib.logictools.waveform import wave_to_bitstring from pynq.lib.logictools import ARDUINO from pynq.lib.logictools import PYNQZ1_LOGICTOOLS_SPECIFICATION from pynq.lib.logictools import MAX_NUM_PATTERN_SAMPLES __author__ = "Yun Rock Qu" __copyright__ = "Copyright 2016, Xilinx" __email__ = "pynq_support@xilinx.com" try: ol = Overlay('logictools.bit', download=False) flag0 = True except IOError: flag0 = False flag1 = user_answer_yes("\nTest pattern generator?") if flag1: mb_info = ARDUINO flag = flag0 and flag1 def build_loopback_pattern(num_samples): """Method to construct loopback signal patterns. Each loopback signal channel is simulating a clock signal with a specific frequency. And the number of samples can be specified. Parameters ---------- num_samples : int The number of samples can be looped. Returns ------- dict A waveform dictionary that can be recognized by WaveDrom. """ loopback_pattern = {'signal': [ ['stimulus'], {}, ['analysis']], 'foot': {'tock': 1}, 'head': {'text': 'Loopback Test'}} pin_dict = PYNQZ1_LOGICTOOLS_SPECIFICATION['traceable_outputs'] interface_width = PYNQZ1_LOGICTOOLS_SPECIFICATION['interface_width'] all_pins = [k for k in list(pin_dict.keys())[:interface_width]] for i in range(interface_width): wavelane1 = dict() wavelane2 = dict() wavelane1['name'] = 'clk{}'.format(i) wavelane2['name'] = 'clk{}'.format(i) wavelane1['pin'] = all_pins[i] wavelane2['pin'] = all_pins[i] loopback_pattern['signal'][-1].append(wavelane2) if i % 4 == 0: wavelane1['wave'] = 'lh' * int(num_samples / 2) elif i % 4 == 1: wavelane1['wave'] = 'l.h.' * int(num_samples / 4) elif i % 4 == 2: wavelane1['wave'] = 'l...h...' * int(num_samples / 8) else: wavelane1['wave'] = 'l.......h.......' * int(num_samples / 16) loopback_pattern['signal'][0].append(wavelane1) return loopback_pattern def build_random_pattern(num_samples): """Method to construct random signal patterns. Each random signal channel is a collection of random bits. And the number of samples can be specified. Parameters ---------- num_samples : int The number of samples can be looped. Returns ------- dict A waveform dictionary that can be recognized by WaveDrom. """ random_pattern = {'signal': [ ['stimulus'], {}, ['analysis']], 'foot': {'tock': 1}, 'head': {'text': 'Random Test'}} pin_dict = PYNQZ1_LOGICTOOLS_SPECIFICATION['traceable_outputs'] interface_width = PYNQZ1_LOGICTOOLS_SPECIFICATION['interface_width'] all_pins = [k for k in list(pin_dict.keys())[:interface_width]] for i in range(interface_width): wavelane1 = dict() wavelane2 = dict() wavelane1['name'] = 'signal{}'.format(i) wavelane2['name'] = 'signal{}'.format(i) wavelane1['pin'] = all_pins[i] wavelane2['pin'] = all_pins[i] random_pattern['signal'][-1].append(wavelane2) rand_list = [str(randint(0, 1)) for _ in range(num_samples)] rand_str = ''.join(rand_list) wavelane1['wave'] = rand_str.replace('0', 'l').replace('1', 'h') random_pattern['signal'][0].append(wavelane1) return random_pattern @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_state(): """Test for the PatternGenerator class. This test will test a set of loopback signals. Each lane is simulating a clock of a specific frequency. """ ol.download() print("\nDisconnect all the pins.") input("Hit enter after done ...") num_samples = 128 loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) assert pattern_generator.status == 'RESET' pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') assert pattern_generator.status == 'READY' pattern_generator.run() assert pattern_generator.status == 'RUNNING' loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': list1 = wavelane_group[1:] for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': list2 = wavelane_group[1:] elif wavelane_group and wavelane_group[0] == 'analysis': list3 = wavelane_group[1:] assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() assert pattern_generator.status == 'READY' pattern_generator.reset() assert pattern_generator.status == 'RESET' del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_no_trace(): """Test for the PatternGenerator class. This test will test the case when no analyzer is used. Exception should be raised when users want to show the waveform. """ ol.download() num_samples = 128 loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=False, num_analyzer_samples=num_samples) exception_raised = False try: pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') pattern_generator.run() pattern_generator.show_waveform() except ValueError: exception_raised = True assert exception_raised, 'Should raise exception for show_waveform().' pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_num_samples(): """Test for the PatternGenerator class. This test will examine 0 sample and more than the maximum number of samples. In these cases, exception should be raised. Here the `MAX_NUM_PATTERN_SAMPLE` is used for display purpose. The maximum number of samples that can be captured by the trace analyzer is defined as `MAX_NUM_TRACE_SAMPLES`. """ ol.download() for num_samples in [0, MAX_NUM_PATTERN_SAMPLES+1]: loopback_sent = build_loopback_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) exception_raised = False try: pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis') except ValueError: exception_raised = True assert exception_raised, 'Should raise exception if number of ' \ 'samples is out of range.' pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_random(): """Test for the PatternGenerator class. This test will examine 1 sample, and a maximum number of samples. For theses cases, random signals will be used, and all the pins will be used to build the pattern. """ ol.download() for num_samples in [1, MAX_NUM_PATTERN_SAMPLES]: loopback_sent = build_random_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis', frequency_mhz=100) pattern_generator.run() loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list1.append(temp) for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list2.append(temp) elif wavelane_group and wavelane_group[0] == 'analysis': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list3.append(temp) assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() pattern_generator.reset() del pattern_generator @pytest.mark.skipif(not flag, reason="need correct overlay to run") def test_pattern_step(): """Test for the PatternGenerator class. This test will examine a moderate number of 128 samples (in order to shorten testing time). For theses cases, random signals will be used, and all the pins will be used to build the pattern. Each sample is captured after advancing the `step()`. """ ol.download() num_samples = 128 loopback_sent = build_random_pattern(num_samples) pattern_generator = PatternGenerator(mb_info) pattern_generator.trace(use_analyzer=True, num_analyzer_samples=num_samples) pattern_generator.setup(loopback_sent, stimulus_group_name='stimulus', analysis_group_name='analysis', frequency_mhz=100) for _ in range(num_samples): pattern_generator.step() loopback_recv = pattern_generator.waveform.waveform_dict list1 = list2 = list3 = list() for wavelane_group in loopback_sent['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list1.append(temp) for wavelane_group in loopback_recv['signal']: if wavelane_group and wavelane_group[0] == 'stimulus': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list2.append(temp) elif wavelane_group and wavelane_group[0] == 'analysis': for i in wavelane_group[1:]: temp = deepcopy(i) temp['wave'] = wave_to_bitstring(i['wave']) list3.append(temp) assert list1 == list2, \ 'Stimulus not equal in generated and captured patterns.' assert list2 == list3, \ 'Stimulus not equal to analysis in captured patterns.' pattern_generator.stop() pattern_generator.reset() del pattern_generator
Xilinx/PYNQ
pynq/lib/logictools/tests/test_pattern_generator.py
pynq/lib/arduino/arduino_grove_dlight.py
# -*- coding: utf-8 -*- from django.http import HttpResponse from future.moves.urllib.parse import urlparse import mock from nose.tools import * # noqa: from rest_framework.test import APIRequestFactory from django.test.utils import override_settings from website.util import api_v2_url from api.base import settings from api.base.middleware import CorsMiddleware from tests.base import ApiTestCase from osf_tests import factories class MiddlewareTestCase(ApiTestCase): MIDDLEWARE = None def setUp(self): super(MiddlewareTestCase, self).setUp() self.middleware = self.MIDDLEWARE() self.mock_response = mock.Mock() self.request_factory = APIRequestFactory() class TestCorsMiddleware(MiddlewareTestCase): MIDDLEWARE = CorsMiddleware @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_institutions_added_to_cors_whitelist(self): url = api_v2_url('users/me/') domain = urlparse('https://dinosaurs.sexy') factories.InstitutionFactory( domains=[domain.netloc.lower()], name='Institute for Sexy Lizards' ) settings.load_origins_whitelist() request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl()) response = HttpResponse() self.middleware.process_request(request) self.middleware.process_response(request, response) assert_equal(response['Access-Control-Allow-Origin'], domain.geturl()) @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_preprintproviders_added_to_cors_whitelist(self): url = api_v2_url('users/me/') domain = urlparse('https://dinoprints.sexy') factories.PreprintProviderFactory( domain=domain.geturl().lower(), _id='DinoXiv' ) settings.load_origins_whitelist() request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl()) response = HttpResponse() self.middleware.process_request(request) self.middleware.process_response(request, response) assert_equal(response['Access-Control-Allow-Origin'], domain.geturl()) @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_cross_origin_request_with_cookies_does_not_get_cors_headers(self): url = api_v2_url('users/me/') domain = urlparse('https://dinosaurs.sexy') request = self.request_factory.get(url, HTTP_ORIGIN=domain.geturl()) response = {} with mock.patch.object(request, 'COOKIES', True): self.middleware.process_request(request) self.middleware.process_response(request, response) assert_not_in('Access-Control-Allow-Origin', response) @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_cross_origin_request_with_Authorization_gets_cors_headers(self): url = api_v2_url('users/me/') domain = urlparse('https://dinosaurs.sexy') request = self.request_factory.get( url, HTTP_ORIGIN=domain.geturl(), HTTP_AUTHORIZATION='Bearer aqweqweohuweglbiuwefq' ) response = HttpResponse() self.middleware.process_request(request) self.middleware.process_response(request, response) assert_equal(response['Access-Control-Allow-Origin'], domain.geturl()) @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_cross_origin_request_with_Authorization_and_cookie_does_not_get_cors_headers( self): url = api_v2_url('users/me/') domain = urlparse('https://dinosaurs.sexy') request = self.request_factory.get( url, HTTP_ORIGIN=domain.geturl(), HTTP_AUTHORIZATION='Bearer aqweqweohuweglbiuwefq' ) response = {} with mock.patch.object(request, 'COOKIES', True): self.middleware.process_request(request) self.middleware.process_response(request, response) assert_not_in('Access-Control-Allow-Origin', response) @override_settings(CORS_ORIGIN_ALLOW_ALL=False) def test_non_institution_preflight_request_requesting_authorization_header_gets_cors_headers( self): url = api_v2_url('users/me/') domain = urlparse('https://dinosaurs.sexy') request = self.request_factory.options( url, HTTP_ORIGIN=domain.geturl(), HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET', HTTP_ACCESS_CONTROL_REQUEST_HEADERS='authorization' ) response = HttpResponse() self.middleware.process_request(request) self.middleware.process_response(request, response) assert_equal(response['Access-Control-Allow-Origin'], domain.geturl())
import pytest import uuid from api.base.settings.defaults import API_BASE from api_tests import utils from framework.auth.core import Auth from osf.models import RegistrationSchema from osf_tests.factories import ( AuthUserFactory, NodeFactory, ProjectFactory, RegistrationFactory, InstitutionFactory, CollectionFactory, CollectionProviderFactory, RegistrationProviderFactory, ) from osf_tests.utils import mock_archive from website import settings from website.search import elastic_search from website.search import search SCHEMA_VERSION = 2 @pytest.mark.django_db @pytest.mark.enable_search @pytest.mark.enable_enqueue_task @pytest.mark.enable_quickfiles_creation class ApiSearchTestCase: @pytest.fixture(autouse=True) def index(self): settings.ELASTIC_INDEX = uuid.uuid4().hex elastic_search.INDEX = settings.ELASTIC_INDEX search.create_index(elastic_search.INDEX) yield search.delete_index(elastic_search.INDEX) @pytest.fixture() def user(self): return AuthUserFactory() @pytest.fixture() def institution(self): return InstitutionFactory(name='Social Experiment') @pytest.fixture() def collection_public(self, user): return CollectionFactory(creator=user, provider=CollectionProviderFactory(), is_public=True, status_choices=['', 'asdf', 'lkjh'], collected_type_choices=['', 'asdf', 'lkjh'], issue_choices=['', '0', '1', '2'], volume_choices=['', '0', '1', '2'], program_area_choices=['', 'asdf', 'lkjh']) @pytest.fixture() def registration_collection(self, user): return CollectionFactory(creator=user, provider=RegistrationProviderFactory(), is_public=True, status_choices=['', 'asdf', 'lkjh'], collected_type_choices=['', 'asdf', 'lkjh']) @pytest.fixture() def user_one(self): user_one = AuthUserFactory(fullname='Kanye Omari West') user_one.schools = [{ 'degree': 'English', 'institution': 'Chicago State University' }] user_one.jobs = [{ 'title': 'Producer', 'institution': 'GOOD Music, Inc.' }] user_one.save() return user_one @pytest.fixture() def user_two(self, institution): user_two = AuthUserFactory(fullname='Chance The Rapper') user_two.affiliated_institutions.add(institution) user_two.save() return user_two @pytest.fixture() def project(self, user_one): project = ProjectFactory( title='Graduation', creator=user_one, is_public=True) project.update_search() return project @pytest.fixture() def project_public(self, user_one): project_public = ProjectFactory( title='The Life of Pablo', creator=user_one, is_public=True) project_public.set_description( 'Name one genius who ain\'t crazy', auth=Auth(user_one), save=True) project_public.add_tag('Yeezus', auth=Auth(user_one), save=True) return project_public @pytest.fixture() def project_private(self, user_two): return ProjectFactory(title='Coloring Book', creator=user_two) @pytest.fixture() def component(self, user_one, project_public): return NodeFactory( parent=project_public, title='Highlights', description='', creator=user_one, is_public=True) @pytest.fixture() def component_public(self, user_two, project_public): component_public = NodeFactory( parent=project_public, title='Ultralight Beam', creator=user_two, is_public=True) component_public.set_description( 'This is my part, nobody else speak', auth=Auth(user_two), save=True) component_public.add_tag('trumpets', auth=Auth(user_two), save=True) return component_public @pytest.fixture() def component_private(self, user_one, project_public): return NodeFactory( parent=project_public, description='', title='Wavves', creator=user_one) @pytest.fixture() def file_component(self, component, user_one): return utils.create_test_file( component, user_one, filename='Highlights.mp3') @pytest.fixture() def file_public(self, component_public, user_one): return utils.create_test_file( component_public, user_one, filename='UltralightBeam.mp3') @pytest.fixture() def file_private(self, component_private, user_one): return utils.create_test_file( component_private, user_one, filename='Wavves.mp3') class TestSearch(ApiSearchTestCase): @pytest.fixture() def url_search(self): return '/{}search/'.format(API_BASE) def test_search_results( self, app, url_search, user, user_one, user_two, institution, component, component_private, component_public, file_component, file_private, file_public, project, project_public, project_private): # test_search_no_auth res = app.get(url_search) assert res.status_code == 200 search_fields = res.json['search_fields'] users_found = search_fields['users']['related']['meta']['total'] files_found = search_fields['files']['related']['meta']['total'] projects_found = search_fields['projects']['related']['meta']['total'] components_found = search_fields['components']['related']['meta']['total'] registrations_found = search_fields['registrations']['related']['meta']['total'] assert users_found == 3 assert files_found == 2 assert projects_found == 2 assert components_found == 2 assert registrations_found == 0 # test_search_auth res = app.get(url_search, auth=user.auth) assert res.status_code == 200 search_fields = res.json['search_fields'] users_found = search_fields['users']['related']['meta']['total'] files_found = search_fields['files']['related']['meta']['total'] projects_found = search_fields['projects']['related']['meta']['total'] components_found = search_fields['components']['related']['meta']['total'] registrations_found = search_fields['registrations']['related']['meta']['total'] assert users_found == 3 assert files_found == 2 assert projects_found == 2 assert components_found == 2 assert registrations_found == 0 # test_search_fields_links res = app.get(url_search) assert res.status_code == 200 search_fields = res.json['search_fields'] users_link = search_fields['users']['related']['href'] files_link = search_fields['files']['related']['href'] projects_link = search_fields['projects']['related']['href'] components_link = search_fields['components']['related']['href'] registrations_link = search_fields['registrations']['related']['href'] assert '/{}search/users/?q=%2A'.format(API_BASE) in users_link assert '/{}search/files/?q=%2A'.format(API_BASE) in files_link assert '/{}search/projects/?q=%2A'.format(API_BASE) in projects_link assert '/{}search/components/?q=%2A'.format( API_BASE) in components_link assert '/{}search/registrations/?q=%2A'.format( API_BASE) in registrations_link # test_search_fields_links_with_query url = '{}?q=science'.format(url_search) res = app.get(url) assert res.status_code == 200 search_fields = res.json['search_fields'] users_link = search_fields['users']['related']['href'] files_link = search_fields['files']['related']['href'] projects_link = search_fields['projects']['related']['href'] components_link = search_fields['components']['related']['href'] registrations_link = search_fields['registrations']['related']['href'] assert '/{}search/users/?q=science'.format(API_BASE) in users_link assert '/{}search/files/?q=science'.format(API_BASE) in files_link assert '/{}search/projects/?q=science'.format( API_BASE) in projects_link assert '/{}search/components/?q=science'.format( API_BASE) in components_link assert '/{}search/registrations/?q=science'.format( API_BASE) in registrations_link class TestSearchComponents(ApiSearchTestCase): @pytest.fixture() def url_component_search(self): return '/{}search/components/'.format(API_BASE) def test_search_components( self, app, url_component_search, user, user_one, user_two, component, component_public, component_private): # test_search_public_component_no_auth res = app.get(url_component_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert component_public.title in res assert component.title in res # test_search_public_component_auth res = app.get(url_component_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert component_public.title in res assert component.title in res # test_search_public_component_contributor res = app.get(url_component_search, auth=user_two) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert component_public.title in res assert component.title in res # test_search_private_component_no_auth res = app.get(url_component_search) assert res.status_code == 200 assert component_private.title not in res # test_search_private_component_auth res = app.get(url_component_search, auth=user) assert res.status_code == 200 assert component_private.title not in res # test_search_private_component_contributor res = app.get(url_component_search, auth=user_two) assert res.status_code == 200 assert component_private.title not in res # test_search_component_by_title url = '{}?q={}'.format(url_component_search, 'beam') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert component_public.title == res.json['data'][0]['attributes']['title'] # test_search_component_by_description url = '{}?q={}'.format(url_component_search, 'speak') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert component_public.title == res.json['data'][0]['attributes']['title'] # test_search_component_by_tags url = '{}?q={}'.format(url_component_search, 'trumpets') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert component_public.title == res.json['data'][0]['attributes']['title'] # test_search_component_by_contributor url = '{}?q={}'.format(url_component_search, 'Chance') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert component_public.title == res.json['data'][0]['attributes']['title'] # test_search_component_no_results url = '{}?q={}'.format(url_component_search, 'Ocean') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 0 assert total == 0 # test_search_component_bad_query url = '{}?q={}'.format( url_component_search, 'www.spam.com/help/twitter/') res = app.get(url, expect_errors=True) assert res.status_code == 400 class TestSearchFiles(ApiSearchTestCase): @pytest.fixture() def url_file_search(self): return '/{}search/files/'.format(API_BASE) def test_search_files( self, app, url_file_search, user, user_one, file_public, file_component, file_private): # test_search_public_file_no_auth res = app.get(url_file_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert file_public.name in res assert file_component.name in res # test_search_public_file_auth res = app.get(url_file_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert file_public.name in res assert file_component.name in res # test_search_public_file_contributor res = app.get(url_file_search, auth=user_one) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert file_public.name in res assert file_component.name in res # test_search_private_file_no_auth res = app.get(url_file_search) assert res.status_code == 200 assert file_private.name not in res # test_search_private_file_auth res = app.get(url_file_search, auth=user) assert res.status_code == 200 assert file_private.name not in res # test_search_private_file_contributor res = app.get(url_file_search, auth=user_one) assert res.status_code == 200 assert file_private.name not in res # test_search_file_by_name url = '{}?q={}'.format(url_file_search, 'highlights') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert file_component.name == res.json['data'][0]['attributes']['name'] class TestSearchProjects(ApiSearchTestCase): @pytest.fixture() def url_project_search(self): return '/{}search/projects/'.format(API_BASE) def test_search_projects( self, app, url_project_search, user, user_one, user_two, project, project_public, project_private): # test_search_public_project_no_auth res = app.get(url_project_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert project_public.title in res assert project.title in res # test_search_public_project_auth res = app.get(url_project_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert project_public.title in res assert project.title in res # test_search_public_project_contributor res = app.get(url_project_search, auth=user_one) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert project_public.title in res assert project.title in res # test_search_private_project_no_auth res = app.get(url_project_search) assert res.status_code == 200 assert project_private.title not in res # test_search_private_project_auth res = app.get(url_project_search, auth=user) assert res.status_code == 200 assert project_private.title not in res # test_search_private_project_contributor res = app.get(url_project_search, auth=user_two) assert res.status_code == 200 assert project_private.title not in res # test_search_project_by_title url = '{}?q={}'.format(url_project_search, 'pablo') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert project_public.title == res.json['data'][0]['attributes']['title'] # test_search_project_by_description url = '{}?q={}'.format(url_project_search, 'genius') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert project_public.title == res.json['data'][0]['attributes']['title'] # test_search_project_by_tags url = '{}?q={}'.format(url_project_search, 'Yeezus') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert project_public.title == res.json['data'][0]['attributes']['title'] # test_search_project_by_contributor url = '{}?q={}'.format(url_project_search, 'kanye') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert project_public.title in res assert project.title in res # test_search_project_no_results url = '{}?q={}'.format(url_project_search, 'chicago') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 0 assert total == 0 # test_search_project_bad_query url = '{}?q={}'.format( url_project_search, 'www.spam.com/help/facebook/') res = app.get(url, expect_errors=True) assert res.status_code == 400 @pytest.mark.django_db class TestSearchRegistrations(ApiSearchTestCase): @pytest.fixture() def url_registration_search(self): return '/{}search/registrations/'.format(API_BASE) @pytest.fixture() def schema(self): schema = RegistrationSchema.objects.filter( name='Replication Recipe (Brandt et al., 2013): Post-Completion', schema_version=SCHEMA_VERSION).first() return schema @pytest.fixture() def registration(self, project, schema): with mock_archive(project, autocomplete=True, autoapprove=True, schema=schema) as registration: return registration @pytest.fixture() def registration_public(self, project_public, schema): with mock_archive(project_public, autocomplete=True, autoapprove=True, schema=schema) as registration_public: return registration_public @pytest.fixture() def registration_private(self, project_private, schema): with mock_archive(project_private, autocomplete=True, autoapprove=True, schema=schema) as registration_private: registration_private.is_public = False registration_private.save() # TODO: This shouldn't be necessary, but tests fail if we don't do # this. Investigate further. registration_private.update_search() return registration_private def test_search_registrations( self, app, url_registration_search, user, user_one, user_two, registration, registration_public, registration_private): # test_search_public_registration_no_auth res = app.get(url_registration_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert registration_public.title in res assert registration.title in res # test_search_public_registration_auth res = app.get(url_registration_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert registration_public.title in res assert registration.title in res # test_search_public_registration_contributor res = app.get(url_registration_search, auth=user_one) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert registration_public.title in res assert registration.title in res # test_search_private_registration_no_auth res = app.get(url_registration_search) assert res.status_code == 200 assert registration_private.title not in res # test_search_private_registration_auth res = app.get(url_registration_search, auth=user) assert res.status_code == 200 assert registration_private.title not in res # test_search_private_registration_contributor res = app.get(url_registration_search, auth=user_two) assert res.status_code == 200 assert registration_private.title not in res # test_search_registration_by_title url = '{}?q={}'.format(url_registration_search, 'graduation') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert registration.title == res.json['data'][0]['attributes']['title'] # test_search_registration_by_description url = '{}?q={}'.format(url_registration_search, 'crazy') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert registration_public.title == res.json['data'][0]['attributes']['title'] # test_search_registration_by_tags url = '{}?q={}'.format(url_registration_search, 'yeezus') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert registration_public.title == res.json['data'][0]['attributes']['title'] # test_search_registration_by_contributor url = '{}?q={}'.format(url_registration_search, 'west') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 2 assert total == 2 assert registration_public.title in res assert registration.title in res # test_search_registration_no_results url = '{}?q={}'.format(url_registration_search, '79th') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 0 assert total == 0 # test_search_registration_bad_query url = '{}?q={}'.format( url_registration_search, 'www.spam.com/help/snapchat/') res = app.get(url, expect_errors=True) assert res.status_code == 400 class TestSearchUsers(ApiSearchTestCase): @pytest.fixture() def url_user_search(self): return '/{}search/users/'.format(API_BASE) @pytest.mark.enable_quickfiles_creation def test_search_user(self, app, url_user_search, user, user_one, user_two): # test_search_users_no_auth res = app.get(url_user_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 3 assert total == 3 assert user.fullname in res # test_search_users_auth res = app.get(url_user_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 3 assert total == 3 assert user.fullname in res # test_search_users_by_given_name url = '{}?q={}'.format(url_user_search, 'Kanye') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert user_one.given_name == res.json['data'][0]['attributes']['given_name'] # test_search_users_by_middle_name url = '{}?q={}'.format(url_user_search, 'Omari') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert user_one.middle_names[0] == res.json['data'][0]['attributes']['middle_names'][0] # test_search_users_by_family_name url = '{}?q={}'.format(url_user_search, 'West') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert user_one.family_name == res.json['data'][0]['attributes']['family_name'] # test_search_users_by_job url = '{}?q={}'.format(url_user_search, 'producer') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert user_one.fullname == res.json['data'][0]['attributes']['full_name'] # test_search_users_by_school url = '{}?q={}'.format(url_user_search, 'Chicago') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert user_one.fullname == res.json['data'][0]['attributes']['full_name'] class TestSearchInstitutions(ApiSearchTestCase): @pytest.fixture() def url_institution_search(self): return '/{}search/institutions/'.format(API_BASE) def test_search_institutions( self, app, url_institution_search, user, institution): # test_search_institutions_no_auth res = app.get(url_institution_search) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert institution.name in res # test_search_institutions_auth res = app.get(url_institution_search, auth=user) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert institution.name in res # test_search_institutions_by_name url = '{}?q={}'.format(url_institution_search, 'Social') res = app.get(url) assert res.status_code == 200 num_results = len(res.json['data']) total = res.json['links']['meta']['total'] assert num_results == 1 assert total == 1 assert institution.name == res.json['data'][0]['attributes']['name'] class TestSearchCollections(ApiSearchTestCase): def get_ids(self, data): return [s['id'] for s in data] def post_payload(self, *args, **kwargs): return { 'data': { 'attributes': kwargs }, 'type': 'search' } @pytest.fixture() def url_collection_search(self): return '/{}search/collections/'.format(API_BASE) @pytest.fixture() def node_one(self, user): return NodeFactory(title='Ismael Lo: Tajabone', creator=user, is_public=True) @pytest.fixture() def registration_one(self, node_one): return RegistrationFactory(project=node_one, is_public=True) @pytest.fixture() def node_two(self, user): return NodeFactory(title='Sambolera', creator=user, is_public=True) @pytest.fixture() def registration_two(self, node_two): return RegistrationFactory(project=node_two, is_public=True) @pytest.fixture() def node_private(self, user): return NodeFactory(title='Classified', creator=user) @pytest.fixture() def registration_private(self, node_private): return RegistrationFactory(project=node_private, is_public=False) @pytest.fixture() def node_with_abstract(self, user): node_with_abstract = NodeFactory(title='Sambolera', creator=user, is_public=True) node_with_abstract.set_description( 'Sambolera by Khadja Nin', auth=Auth(user), save=True) return node_with_abstract @pytest.fixture() def reg_with_abstract(self, node_with_abstract): return RegistrationFactory(project=node_with_abstract, is_public=True) def test_search_collections( self, app, url_collection_search, user, node_one, node_two, collection_public, node_with_abstract, node_private, registration_collection, registration_one, registration_two, registration_private, reg_with_abstract): collection_public.collect_object(node_one, user) collection_public.collect_object(node_two, user) collection_public.collect_object(node_private, user) registration_collection.collect_object(registration_one, user) registration_collection.collect_object(registration_two, user) registration_collection.collect_object(registration_private, user) # test_search_collections_no_auth res = app.get(url_collection_search) assert res.status_code == 200 total = res.json['links']['meta']['total'] num_results = len(res.json['data']) assert total == 4 assert num_results == 4 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids # test_search_collections_auth res = app.get(url_collection_search, auth=user) assert res.status_code == 200 total = res.json['links']['meta']['total'] num_results = len(res.json['data']) assert total == 4 assert num_results == 4 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids # test_search_collections_by_submission_title url = '{}?q={}'.format(url_collection_search, 'Ismael') res = app.get(url) assert res.status_code == 200 total = res.json['links']['meta']['total'] num_results = len(res.json['data']) assert node_one.title == registration_one.title == res.json['data'][0]['embeds']['guid']['data']['attributes']['title'] assert total == num_results == 2 # test_search_collections_by_submission_abstract collection_public.collect_object(node_with_abstract, user) registration_collection.collect_object(reg_with_abstract, user) url = '{}?q={}'.format(url_collection_search, 'KHADJA') res = app.get(url) assert res.status_code == 200 total = res.json['links']['meta']['total'] assert node_with_abstract.description == reg_with_abstract.description == res.json['data'][0]['embeds']['guid']['data']['attributes']['description'] assert total == 2 # test_search_collections_no_results: url = '{}?q={}'.format(url_collection_search, 'Wale Watu') res = app.get(url) assert res.status_code == 200 total = res.json['links']['meta']['total'] assert total == 0 def test_POST_search_collections( self, app, url_collection_search, user, node_one, node_two, collection_public, node_with_abstract, node_private, registration_collection, registration_one, registration_two, registration_private, reg_with_abstract): collection_public.collect_object(node_one, user, status='asdf', issue='0', volume='1', program_area='asdf') collection_public.collect_object(node_two, user, collected_type='asdf', status='lkjh') collection_public.collect_object(node_with_abstract, user, status='asdf') collection_public.collect_object(node_private, user, status='asdf', collected_type='asdf') registration_collection.collect_object(registration_one, user, status='asdf') registration_collection.collect_object(registration_two, user, collected_type='asdf', status='lkjh') registration_collection.collect_object(reg_with_abstract, user, status='asdf') registration_collection.collect_object(registration_private, user, status='asdf', collected_type='asdf') # test_search_empty payload = self.post_payload() res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 6 assert len(res.json['data']) == 6 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids # test_search_title_keyword payload = self.post_payload(q='Ismael') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 2 assert len(res.json['data']) == 2 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids # test_search_abstract_keyword payload = self.post_payload(q='Khadja') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 2 assert len(res.json['data']) == 2 actual_ids = self.get_ids(res.json['data']) assert node_with_abstract._id in actual_ids assert reg_with_abstract._id in actual_ids # test_search_filter payload = self.post_payload(status='asdf') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 4 assert len(res.json['data']) == 4 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids payload = self.post_payload(status=['asdf', 'lkjh']) res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 6 assert len(res.json['data']) == 6 actual_ids = self.get_ids(res.json['data']) assert registration_private._id not in actual_ids assert node_private._id not in actual_ids payload = self.post_payload(collectedType='asdf') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 2 assert len(res.json['data']) == 2 actual_ids = self.get_ids(res.json['data']) assert node_two._id in actual_ids assert registration_two._id in actual_ids payload = self.post_payload(status='asdf', issue='0', volume='1', programArea='asdf', collectedType='') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 1 assert len(res.json['data']) == 1 actual_ids = self.get_ids(res.json['data']) assert node_one._id in actual_ids # test_search_abstract_keyword_and_filter payload = self.post_payload(q='Khadja', status='asdf') res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 2 assert len(res.json['data']) == 2 actual_ids = self.get_ids(res.json['data']) assert node_with_abstract._id in actual_ids assert reg_with_abstract._id in actual_ids # test_search_abstract_keyword_and_filter_provider payload = self.post_payload(q='Khadja', status='asdf', provider=collection_public.provider._id) res = app.post_json_api(url_collection_search, payload) assert res.status_code == 200 assert res.json['links']['meta']['total'] == 1 assert len(res.json['data']) == 1 assert res.json['data'][0]['id'] == node_with_abstract._id
CenterForOpenScience/osf.io
api_tests/search/views/test_views.py
api_tests/base/test_middleware.py
#!/usr/bin/python3 import math import hashlib import numpy as np from typing import Any, Optional from ..exceptions import StrandError, ChromosomeError, MissingLocusError from .subloci import SubLoci from .attrs import LocusAttrs __all__ = ["Locus"] class Locus: def __init__( self, chromosome: str, start: int, end: int, source: str = "locuspocus", feature_type: str = "locus", strand: str = "+", frame: int = None, name: str = None, # Extra locus stuff attrs: LocusAttrs = None, subloci: SubLoci = None, ): self.chromosome = str(chromosome) self.start = int(start) self.end = int(end) self.source = str(source) self.feature_type = str(feature_type) self.strand = str(strand) self.frame = frame self.name = name self.attrs = LocusAttrs(attrs) self.subloci = SubLoci(subloci) def __eq__(self, other): return hash(self) == hash(other) if ( self.chromosome == other.chromosome and self.start == other.start and self.end == other.end and self.source == other.source and self.feature_type == other.feature_type and self.strand == other.strand and self.frame == other.frame and self.name == other.name and self.attrs == other.attrs #and self.subloci == other.subloci ): return True else: return False def __hash__(self): """ Convert the locus to a hash, uses md5. The hash is computed using the *core* properties of the Locus, i.e. changing any attrs will not change the hash value. Parameters ---------- None Returns ------- int : md5 hash of locus """ field_list = [ str(x) for x in ( self.chromosome, self.start, self.end, self.feature_type, self.strand, self.frame, ) ] subloci_list = [str(hash(x)) for x in self.subloci] # Create a full string loc_string = "_".join(field_list + subloci_list) # attr_list + subloci_list) digest = hashlib.md5(str.encode(loc_string)).hexdigest() return int(digest, base=16) def __len__(self): return abs(self.end - self.start) + 1 def __lt__(self, locus): if self.chromosome == locus.chromosome: return self.start < locus.start else: return self.chromosome < locus.chromosome def __le__(self, locus): if (self.chromosome, self.coor) == (locus.chromosome, locus.coor): return True else: return self < locus def __ge__(self, locus): if (self.chromosome, self.coor) == (locus.chromosome, locus.coor): return True else: return self > locus def __gt__(self, locus): if self.chromosome == locus.chromosome: return self.start > locus.start else: return self.chromosome > locus.chromosome def __repr__(self): return ( f"Locus(" f"{self.chromosome},{self.start},{self.end},source={self.source}," f"feature_type='{self.feature_type}'," f"strand='{self.strand}'," f"frame='{self.frame}'," f"name='{self.name}'," f"attrs={self.attrs}," f"subloci=[{len(self.subloci)} subloci]" f")" ) @property def stranded_start(self): if self.strand == "+": return min(self.coor) elif self.strand == "-": return max(self.coor) else: raise StrandError @property def stranded_end(self): if self.strand == "+": return max(self.coor) elif self.strand == "-": return min(self.coor) else: raise StrandError def __getitem__(self, item): return self.attrs[item] def __setitem__(self, key, val): self.attrs[key] = val def add_sublocus( self, locus: "Locus", find_parent=False, parent_attr: Optional[str] = "Parent" ): """ Adds a sublocus to the current Locus. The added locus will be added according to its `parent_attr` keyword. """ if not find_parent: self.subloci.add(locus) else: try: if locus[parent_attr] == self.name: self.subloci.add(locus) else: # Find the parent of the sublocus parent = self.subloci.find(locus[parent_attr]) if parent is None: raise MissingLocusError parent.subloci.add(locus) except KeyError: raise KeyError( f"Unable to resolve the key:{parent_attr} to find parent Locus" ) def as_record(self): return ( ( self.chromosome, self.start, self.end, self.source, self.feature_type, self.strand, self.frame, self.name, hash(self), ), self.attrs, ) def default_getitem(self, key, default=None) -> Any: """ Returns the attr value of the Locus based on the key. similar to: Locus['Name'] -> "Locus1". If the attr key (e.g. 'Name') does not exist, a default can be specified. Parameters ---------- key : str The key value of the attr default : Any If the key is not in the Locus attributes, return this value by default. """ try: val = self.attrs[key] except KeyError: val = default finally: return val @property def coor(self): """ Returns a tuple containing the start and end positions of the locus """ return (self.start, self.end) def upstream(self, distance: int) -> int: """ Calculates a base pair position 5' of the locus. Parameters ---------- distance : int The distance upstream of the locus """ if self.strand == "+": return max(0, self.start - distance) elif self.strand == "-": return self.end + distance def downstream(self, distance: int) -> int: """ Calculates a base pair position 3' of the locus Parameters ---------- distance : int The distance downstream of the locus """ if self.strand == "+": return self.end + distance elif self.strand == "-": return max(0, self.start) - distance # return self.end + distance @property def center(self): """ Calculates the center base pair position of the locus. NOTE: If the locus has an odd length, a 'half-bp' will be returned. E.g: Locus('1',100,200).center == Returns ------- The center position """ return self.start + len(self) / 2 def distance(self, locus): """ Return the number of base pairs between two loci. NOTE: this excludes the start/end bases of the loci. Locus A Locus B ==========---------========= 1 10 20 30 There are 9 bases between 10 and 20 (excluding positions 10 and 20 themselves because they are included in the loci). If the loci are on different chromosomes, return np.inf Parameters ---------- locus: Locus Object A second locus object to calculate distance. Returns ------- int: the number of bp between the loci np.inf: if on different chromosomes """ if self.chromosome != locus.chromosome: distance = np.inf else: x, y = sorted([self, locus]) distance = y.start - x.end - 1 return distance def center_distance(self, locus): """ Return the distance between the center of two loci. If the loci are on different chromosomes, return np.inf. Parameters ---------- locus : Locus Object A second locus object used to calculate a distance. Returns ------- int : the distance between the center of two loci. np.inf: if on different chromosomes """ if self.chromosome != locus.chromosome: distance = np.inf else: distance = math.floor(abs(self.center - locus.center)) return distance def combine(self, locus): """ Returns a new Locus with start and stop boundaries that contain both of the input loci. Both input loci are added to the subloci of the new Locus. NOTE: this ignores strand, the resultant Locus is just a container for the input loci. ___________Ascii Example__________________________ Locus A Locus B ------=========-------=============--------------- A.combine(B) ------=============================--------------- subloci=[A,B] """ if self.chromosome != locus.chromosome: raise ChromosomeError("Input Chromosomes do not match") x, y = sorted([self, locus]) start = x.start end = y.end return Locus(self.chromosome, start, end, subloci=[self, locus]) def as_tree(self, parent=None): # pragma: no cover from anytree import Node, RenderTree root = Node(f"{self.feature_type}:{self.name}", parent=parent) for c in self.subloci: node = c.as_tree(parent=root) if parent is None: for pre, _, node in RenderTree(root): print("%s%s" % (pre, node.name)) return root def __str__(self): return repr(self) # -------------------------------- # Factory Methods # -------------------------------- @classmethod def from_gff_line( cls, line, /, ID_attr: str = "ID", parent_attr: str = "Parent", attr_split: str = "=", ) -> "Locus": ( chromosome, source, feature, start, end, score, strand, frame, attributes, ) = line.strip().split("\t", maxsplit=8) # Cast data into appropriate types strand = None if strand == "." else strand frame = None if frame == "." else int(frame) # Get the attributes attributes = dict( [ (field.strip().split(attr_split)) for field in attributes.strip(";").split(";") ] ) # Store the score in the attrs if it exists if score != ".": attributes["score"] = float(score) # Parse out the Identifier if ID_attr in attributes: name = attributes[ID_attr] else: name = None l = cls( chromosome, start, end, source=source, feature_type=feature, strand=strand, frame=frame, name=name, attrs=attributes, ) return l
import pytest import numpy as np from itertools import chain from locuspocus import Locus from locuspocus.exceptions import StrandError, ChromosomeError @pytest.fixture def simple_Locus(): return Locus("1", 100, 200, attrs={"foo": "bar"}) def test_initialization(simple_Locus): # numeric chromosomes assert simple_Locus.chromosome == "1" assert simple_Locus.start == 100 assert simple_Locus.end == 200 assert len(simple_Locus) == 101 def test_getitem(simple_Locus): assert simple_Locus["foo"] == "bar" def test_default_getitem(simple_Locus): assert simple_Locus.default_getitem("name", "default") == "default" def test_start(simple_Locus): assert simple_Locus.start == 100 def test_plus_stranded_start(): l = Locus("1", 1, 100, strand="+") assert l.stranded_start == 1 def test_minus_stranded_start(): l = Locus("1", 1, 100, strand="-") assert l.stranded_start == 100 def test_end(simple_Locus): assert simple_Locus.end == 200 def test_plus_stranded_end(): l = Locus("1", 1, 100, strand="+") assert l.stranded_end == 100 def test_minus_stranded_end(): l = Locus("1", 1, 100, strand="-") assert l.stranded_end == 1 def test_hash(): l = Locus("1", 1, 100, strand="+") assert hash(l) == 530409172339088127 def test_coor(simple_Locus): assert simple_Locus.coor == (100, 200) def test_upstream(simple_Locus): assert simple_Locus.upstream(50) == 50 def test_upstream_minus_strand(simple_Locus): l = Locus("1", 1, 100, strand="-") assert l.upstream(50) == 150 def test_downstream(simple_Locus): assert simple_Locus.downstream(50) == 250 def test_downstream_minus_strand(simple_Locus): l = Locus("1", 100, 200, strand="-") assert l.downstream(50) == 50 def test_center(): l = Locus("1", 100, 200, strand="-") assert l.center == 150.5 def test_name(simple_Locus): assert simple_Locus.name is None def test_eq(simple_Locus): another_Locus = Locus(1, 110, 220) assert simple_Locus == simple_Locus assert simple_Locus != another_Locus def test_ne_diff_attrs(): x = Locus(1, 110, 220, attrs={"foo": "bar"}) y = Locus(1, 110, 220, attrs={"baz": "bat"}) assert x != y def test_empty_subloci_getitem(): a = Locus("1", 10, 20) with pytest.raises(IndexError): a.subloci[1] def test_empty_subloci_repr(): a = Locus("1", 10, 20) b = Locus("1", 20, 30) x = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[a, b]) assert repr(x) def test_ne_diff_subloci(): a = Locus("1", 10, 20) b = Locus("1", 20, 30) c = Locus("1", 30, 40) d = Locus("1", 40, 50) x = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[a, b]) y = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[c, d]) assert x != y def test_loci_lt_by_chrom(): x = Locus("1", 1, 1) y = Locus("2", 1, 1) assert x < y def test_loci_gt_by_chrom(): x = Locus("1", 1, 1) y = Locus("2", 1, 1) assert y > x def test_loci_lt_by_pos(): x = Locus("1", 1, 100) y = Locus("1", 2, 100) assert x < y def test_loci_gt_by_pos(): x = Locus("1", 1, 100) y = Locus("1", 2, 200) assert y > x def test_len(simple_Locus): assert len(simple_Locus) == 101 assert len(Locus(1, 100, 100)) == 1 def test_lt(simple_Locus): same_chrom_Locus = Locus(1, 110, 220) diff_chrom_Locus = Locus(2, 90, 150) assert simple_Locus < same_chrom_Locus assert simple_Locus < diff_chrom_Locus def test_gt(simple_Locus): same_chrom_Locus = Locus(1, 90, 150) diff_chrom_Locus = Locus(2, 90, 150) assert simple_Locus > same_chrom_Locus assert diff_chrom_Locus > simple_Locus def test_repr(simple_Locus): assert repr(simple_Locus) def test_subloci_repr(simple_Locus): assert repr(simple_Locus.subloci) def test_subloci_getitem(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus") x.add_sublocus(y) assert x.subloci[0].name == "sublocus" def test_subloci_iter(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus1") z = Locus("1", 3, 4, name="sublocus2") x.add_sublocus(y) x.add_sublocus(z) for sub in x.subloci: assert sub.chromosome == "1" def test_subloci_len(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus1") z = Locus("1", 3, 4, name="sublocus2") x.add_sublocus(y) x.add_sublocus(z) assert len(x.subloci) == 2 def test_empty_attr(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.keys() == [] def test_empty_attr_cmp(): x = Locus("chr1", 1, 100) y = Locus("chr1", 2, 200) # both are empty assert x.attrs == y.attrs def test_empty_attrs_contains(): x = Locus("chr1", 1, 100) assert "foo" not in x.attrs def test_empty_attr_values(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.values() == [] def test_empty_getitem(): # empty attr x = Locus("chr1", 1, 100) with pytest.raises(KeyError): x["test"] def test_empty_items(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.items() == {} def test_attrs_repr(): x = Locus("chr1", 1, 100, attrs={"foo": "bar"}) assert repr(x) def test_attrs_cmp_with_empty(): x = Locus("chr1", 1, 100, attrs={"foo": "bar"}) y = Locus("chr1", 2, 200) assert x.attrs != y.attrs def test_empty_setitem(): # empty attr x = Locus("chr1", 1, 100) x["test"] = "foo" def test_attrs_keys_method(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert sorted(x.keys()) == ["bar", "foo"] def test_attrs_keys_method_empty(): x = Locus("1", 3, 4, attrs={}) assert len(list(x.attrs.keys())) == 0 def test_attrs_vals_method(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert len(sorted(x.values())) == 2 def test_attrs_vals_method_empty(): x = Locus("1", 3, 4, attrs={}) assert len(list(x.attrs.values())) == 0 def test_attrs_getitem(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" def test_attrs_getitem_missing(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) with pytest.raises(KeyError): x["foobar"] def test_attrs_setitem(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" x["foo"] = "bar" assert x["foo"] == "bar" def test_setitem(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" x["foo"] = "bar" assert x["foo"] == "bar" def test_attrs_items(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert len(sorted(x.items())) == 2 def test_attrs_contains(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) assert "foo" in x.attrs def test_le_equals(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x <= y def test_le_less(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 30, 40) assert x <= y def test_ge_equals(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x >= y def test_ge_greater(): x = Locus("1", 30, 40, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x >= y def test_stranded_start_invalid(): # Strand cannot be '=' x = Locus("1", 3, 4, strand="=") with pytest.raises(StrandError): x.stranded_start def test_stranded_stop_invalid(): # Strand cannot be '=' x = Locus("1", 3, 4, strand="=") with pytest.raises(StrandError): x.stranded_end def test_as_record(): x = Locus("1", 3, 4, strand="+") # This doesn't compare the dictionaries of each ... assert x.as_record()[0] == ( "1", 3, 4, "locuspocus", "locus", "+", None, None, 2039807104618252476, ) def test_center_distance(): x = Locus("1", 1, 100, strand="+") # This needs to be 201 since x starts at 1 y = Locus("1", 201, 300, strand="=") assert x.center_distance(y) == 200 def test_center_distance_different_chroms(): x = Locus("1", 1, 100, strand="+") # This needs to be 201 since x starts at 1 y = Locus("2", 201, 300, strand="+") assert x.center_distance(y) == np.inf def test_str(): x = Locus("1", 1, 100, strand="+") assert str(x) == repr(x) def test_combine(): x = Locus("1", 1, 2) y = Locus("1", 3, 4) z = x.combine(y) assert z.start == 1 assert z.end == 4 assert x in z.subloci assert y in z.subloci def test_combine_chromosome_mismatch(): x = Locus("1", 1, 2) y = Locus("2", 3, 4) with pytest.raises(ChromosomeError): x.combine(y) def test_distance(): x = Locus("1", 1, 100) y = Locus("1", 150, 250) assert x.distance(y) == 49 def test_distance_diff_chroms(): x = Locus("1", 1, 100) y = Locus("2", 150, 250) assert x.distance(y) == np.inf
LinkageIO/LocusPocus
tests/test_Locus.py
locuspocus/locus/__init__.py
import logging import re import reprlib import pprint import numpy as np from minus80 import Freezable from minus80.RawFile import RawFile from collections import defaultdict from functools import lru_cache from .chromosome import Chromosome class Fasta(Freezable): """ A pythonic interface to a FASTA file. This interface allows convenient slicing into contigs (chromosomes). >>> from locuspocus import Fasta >>> x = Fasta.from_file('example.fa') """ log = logging.getLogger(__name__) handler = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") handler.setFormatter(formatter) if not len(log.handlers): log.addHandler(handler) log.setLevel(logging.INFO) def __init__(self, name, rootdir=None): """ Load a Fasta object from the Minus80. Parameters ---------- name : str The name of the frozen object Returns ------- A Fasta object """ super().__init__(name, rootdir=rootdir) # Load up from the database self._initialize_tables() def _initialize_tables(self): """ Initialize the tables for the FASTA class NOTE: internal method """ cur = self.m80.db.cursor() cur.execute( """ CREATE TABLE IF NOT EXISTS added_order ( aorder INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT ); """ ) cur.execute( """ CREATE TABLE IF NOT EXISTS nicknames ( nickname TEXT, chrom TEXT, PRIMARY KEY(nickname,chrom), FOREIGN KEY(chrom) REFERENCES chroms(chrom) ) """ ) cur.execute( """ CREATE TABLE IF NOT EXISTS attributes ( chrom TEXT, attribute TEXT, PRIMARY KEY(chrom,attribute), FOREIGN KEY(chrom) REFERENCES chroms(chrom) ) """ ) def add_chrom(self, chrom, replace=False, cur=None): """ Add a chromosome to the Fasta object. Parameters ---------- chrom : Chromosome object The chromosome object to add. See LocusPocus.Chromosome replace : bool (default: False) By default a chromosome can only be added once. If this is set, the chromosome object will be replaced. """ self.log.info(f"Adding {chrom.name}") # Check for duplicates if chrom.name in self: if not replace: raise ValueError(f"{chrom.name} already in FASTA") else: if cur is None: cur = self.m80.db.cursor() cur.execute( """ INSERT OR REPLACE INTO added_order (name) VALUES (?) """, (chrom.name,), ) for x in chrom._attrs: self._add_attribute(chrom.name, x) seqarray = chrom.seq self.m80.col[chrom.name] = seqarray self.cache_clear() def del_chrom(self, chrom): """ Delete a chromosome from the database """ if isinstance(chrom, Chromosome): name = chrom.name elif isinstance(chrom, str): name = chrom else: raise ValueError(f"input must be a Chromosome object or a string") if name not in self: raise ValueError(f"'{name}' not in the {self.m80.dtype}('{self.m80.name}')") self.m80.db.cursor().execute( """ DELETE FROM added_order WHERE name = ?; DELETE FROM nicknames WHERE chrom = ?; DELETE FROM attributes WHERE chrom = ?; """, (name, name, name), ) self.m80.col.remove(name) def chrom_names(self): """ Returns an iterable of chromosome names Parameters ---------- None Returns ------- An iterable of chromosome names in added order """ return ( x for (x,) in self.m80.db.cursor().execute( """ SELECT name FROM added_order ORDER BY aorder """ ) ) def cache_clear(self): self.__getitem__.cache_clear() @classmethod def from_file(cls, name, fasta_file, replace=False, rootdir=None): """ Create a Fasta object from a file. """ self = cls(name, rootdir=rootdir) with RawFile(fasta_file) as IN, self.m80.db.bulk_transaction() as cur: cur_chrom = None seqs = [] name, attrs = None, None for line in IN: line = line.strip() if line.startswith(">"): # Finish the last chromosome before adding a new one if len(seqs) > 0: cur_chrom = Chromosome(name, seqs, *attrs) self.add_chrom(cur_chrom, cur=cur, replace=replace) seqs = [] name, *attrs = line.lstrip(">").split() else: seqs += line # cur_chrom.seq = np.append(cur_chrom.seq,list(line)) # Add the last chromosome cur_chrom = Chromosome(name, seqs, *attrs) self.add_chrom(cur_chrom, cur=cur, replace=replace) return self def __iter__(self): """ Iterate over chromosome objects """ chroms = self.m80.db.cursor().execute( "SELECT name FROM added_order ORDER BY aorder" ) for (chrom,) in chroms: yield self[chrom] def __len__(self): """ Returns the number of chroms in the Fasta """ return ( self.m80.db.cursor() .execute( """ SELECT COUNT(*) FROM added_order """ ) .fetchone()[0] ) def __contains__(self, obj): """ Returns boolean indicating if a named contig (chromosome) is in the fasta. """ if isinstance(obj, Chromosome): obj = obj.name cur = self.m80.db.cursor() # Check if in chrom names in_added = cur.execute( """ SELECT COUNT(*) FROM added_order WHERE name = ? """, (obj,), ).fetchone()[0] if in_added == 1: return True # Check if in aliases in_alias = cur.execute( """ SELECT COUNT(*) FROM nicknames WHERE nickname = ? """, (obj,), ).fetchone()[0] if in_alias == 1: return True # Otherise its not here return False @lru_cache(maxsize=128) def __getitem__(self, chrom_name): if chrom_name not in self: raise ValueError(f"{chrom_name} not in {self.m80.name}") try: seq_array = self.m80.col[chrom_name] except Exception as e: chrom_name = self._get_nickname(chrom_name) seq_array = self.m80.col[chrom_name] finally: attrs = [ x[0] for x in self.m80.db.cursor().execute( """ SELECT attribute FROM attributes WHERE chrom = ? ORDER BY rowid -- This preserves the ordering of attrs """, (chrom_name,), ) ] return Chromosome(chrom_name, seq_array, *attrs) def to_fasta(self, filename, line_length=70): """ Print the chromosomes to a file in FASTA format Paramaters ---------- filename : str The output filename line_length : int (default: 70) The number of nucleotides per line Returns ------- None """ with open(filename, "w") as OUT: for chrom_name in self.chrom_names(): print(f"Printing out {chrom_name}") chrom = self[chrom_name] # easy_id = ids[chrom_name] start_length = len(chrom) # if easy_id == 'chrUn': # easy_id = easy_id + '_' + chrom_name print(f'>{chrom_name} {"|".join(chrom._attrs)}', file=OUT) printed_length = 0 for i in range(1, len(chrom), 70): sequence = chrom[i : (i - 1) + 70] print("".join(sequence), file=OUT) printed_length += len(sequence) if printed_length != start_length: # pragma: no cover raise ValueError("Chromosome was truncated during printing") return None def _add_attribute(self, chrom_name, attr, cur=None): """ Add an attribute the the Fasta object. Attributes describe chromosomes and often follow the '>' token in the FASTA file. Parameters ---------- chrom_name : str The name of the chromosome you are adding an attribute to attr : str the attribute you are adding """ if cur is None: cur = self.m80.db.cursor() cur.execute( """ INSERT INTO attributes (chrom,attribute) VALUES (?,?) """, (chrom_name, attr), ) self.cache_clear() def _add_nickname(self, chrom, nickname, cur=None): """ Add a nickname for a chromosome Parameters ---------- chrom : str The chromosome you want to nickname nickname : str The alternative name for the chromosome """ if cur is None: cur = self.m80.db.cursor() cur.execute( """ INSERT OR REPLACE INTO nicknames (nickname,chrom) VALUES (?,?) """, (nickname, chrom), ) def _get_nickname(self, nickname): """ Get a chromosomem name by nickname """ return ( self.m80.db.cursor() .execute( """ SELECT chrom FROM nicknames WHERE nickname = ? """, (nickname,), ) .fetchone()[0] ) def __repr__(self): # pragma: nocover return pprint.saferepr(reprlib.repr(list(self)))
import pytest import numpy as np from itertools import chain from locuspocus import Locus from locuspocus.exceptions import StrandError, ChromosomeError @pytest.fixture def simple_Locus(): return Locus("1", 100, 200, attrs={"foo": "bar"}) def test_initialization(simple_Locus): # numeric chromosomes assert simple_Locus.chromosome == "1" assert simple_Locus.start == 100 assert simple_Locus.end == 200 assert len(simple_Locus) == 101 def test_getitem(simple_Locus): assert simple_Locus["foo"] == "bar" def test_default_getitem(simple_Locus): assert simple_Locus.default_getitem("name", "default") == "default" def test_start(simple_Locus): assert simple_Locus.start == 100 def test_plus_stranded_start(): l = Locus("1", 1, 100, strand="+") assert l.stranded_start == 1 def test_minus_stranded_start(): l = Locus("1", 1, 100, strand="-") assert l.stranded_start == 100 def test_end(simple_Locus): assert simple_Locus.end == 200 def test_plus_stranded_end(): l = Locus("1", 1, 100, strand="+") assert l.stranded_end == 100 def test_minus_stranded_end(): l = Locus("1", 1, 100, strand="-") assert l.stranded_end == 1 def test_hash(): l = Locus("1", 1, 100, strand="+") assert hash(l) == 530409172339088127 def test_coor(simple_Locus): assert simple_Locus.coor == (100, 200) def test_upstream(simple_Locus): assert simple_Locus.upstream(50) == 50 def test_upstream_minus_strand(simple_Locus): l = Locus("1", 1, 100, strand="-") assert l.upstream(50) == 150 def test_downstream(simple_Locus): assert simple_Locus.downstream(50) == 250 def test_downstream_minus_strand(simple_Locus): l = Locus("1", 100, 200, strand="-") assert l.downstream(50) == 50 def test_center(): l = Locus("1", 100, 200, strand="-") assert l.center == 150.5 def test_name(simple_Locus): assert simple_Locus.name is None def test_eq(simple_Locus): another_Locus = Locus(1, 110, 220) assert simple_Locus == simple_Locus assert simple_Locus != another_Locus def test_ne_diff_attrs(): x = Locus(1, 110, 220, attrs={"foo": "bar"}) y = Locus(1, 110, 220, attrs={"baz": "bat"}) assert x != y def test_empty_subloci_getitem(): a = Locus("1", 10, 20) with pytest.raises(IndexError): a.subloci[1] def test_empty_subloci_repr(): a = Locus("1", 10, 20) b = Locus("1", 20, 30) x = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[a, b]) assert repr(x) def test_ne_diff_subloci(): a = Locus("1", 10, 20) b = Locus("1", 20, 30) c = Locus("1", 30, 40) d = Locus("1", 40, 50) x = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[a, b]) y = Locus(1, 110, 220, attrs={"foo": "bar"}, subloci=[c, d]) assert x != y def test_loci_lt_by_chrom(): x = Locus("1", 1, 1) y = Locus("2", 1, 1) assert x < y def test_loci_gt_by_chrom(): x = Locus("1", 1, 1) y = Locus("2", 1, 1) assert y > x def test_loci_lt_by_pos(): x = Locus("1", 1, 100) y = Locus("1", 2, 100) assert x < y def test_loci_gt_by_pos(): x = Locus("1", 1, 100) y = Locus("1", 2, 200) assert y > x def test_len(simple_Locus): assert len(simple_Locus) == 101 assert len(Locus(1, 100, 100)) == 1 def test_lt(simple_Locus): same_chrom_Locus = Locus(1, 110, 220) diff_chrom_Locus = Locus(2, 90, 150) assert simple_Locus < same_chrom_Locus assert simple_Locus < diff_chrom_Locus def test_gt(simple_Locus): same_chrom_Locus = Locus(1, 90, 150) diff_chrom_Locus = Locus(2, 90, 150) assert simple_Locus > same_chrom_Locus assert diff_chrom_Locus > simple_Locus def test_repr(simple_Locus): assert repr(simple_Locus) def test_subloci_repr(simple_Locus): assert repr(simple_Locus.subloci) def test_subloci_getitem(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus") x.add_sublocus(y) assert x.subloci[0].name == "sublocus" def test_subloci_iter(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus1") z = Locus("1", 3, 4, name="sublocus2") x.add_sublocus(y) x.add_sublocus(z) for sub in x.subloci: assert sub.chromosome == "1" def test_subloci_len(): x = Locus("1", 1, 2) y = Locus("1", 3, 4, name="sublocus1") z = Locus("1", 3, 4, name="sublocus2") x.add_sublocus(y) x.add_sublocus(z) assert len(x.subloci) == 2 def test_empty_attr(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.keys() == [] def test_empty_attr_cmp(): x = Locus("chr1", 1, 100) y = Locus("chr1", 2, 200) # both are empty assert x.attrs == y.attrs def test_empty_attrs_contains(): x = Locus("chr1", 1, 100) assert "foo" not in x.attrs def test_empty_attr_values(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.values() == [] def test_empty_getitem(): # empty attr x = Locus("chr1", 1, 100) with pytest.raises(KeyError): x["test"] def test_empty_items(): # empty attr x = Locus("chr1", 1, 100) assert x.attrs.items() == {} def test_attrs_repr(): x = Locus("chr1", 1, 100, attrs={"foo": "bar"}) assert repr(x) def test_attrs_cmp_with_empty(): x = Locus("chr1", 1, 100, attrs={"foo": "bar"}) y = Locus("chr1", 2, 200) assert x.attrs != y.attrs def test_empty_setitem(): # empty attr x = Locus("chr1", 1, 100) x["test"] = "foo" def test_attrs_keys_method(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert sorted(x.keys()) == ["bar", "foo"] def test_attrs_keys_method_empty(): x = Locus("1", 3, 4, attrs={}) assert len(list(x.attrs.keys())) == 0 def test_attrs_vals_method(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert len(sorted(x.values())) == 2 def test_attrs_vals_method_empty(): x = Locus("1", 3, 4, attrs={}) assert len(list(x.attrs.values())) == 0 def test_attrs_getitem(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" def test_attrs_getitem_missing(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) with pytest.raises(KeyError): x["foobar"] def test_attrs_setitem(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" x["foo"] = "bar" assert x["foo"] == "bar" def test_setitem(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) assert x["foo"] == "locus1" x["foo"] = "bar" assert x["foo"] == "bar" def test_attrs_items(): from locuspocus.locus import LocusAttrs x = LocusAttrs(attrs={"foo": "locus1", "bar": "baz"}) assert len(sorted(x.items())) == 2 def test_attrs_contains(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) assert "foo" in x.attrs def test_le_equals(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x <= y def test_le_less(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 30, 40) assert x <= y def test_ge_equals(): x = Locus("1", 3, 4, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x >= y def test_ge_greater(): x = Locus("1", 30, 40, attrs={"foo": "locus1", "bar": "baz"}) y = Locus("1", 3, 4) assert x >= y def test_stranded_start_invalid(): # Strand cannot be '=' x = Locus("1", 3, 4, strand="=") with pytest.raises(StrandError): x.stranded_start def test_stranded_stop_invalid(): # Strand cannot be '=' x = Locus("1", 3, 4, strand="=") with pytest.raises(StrandError): x.stranded_end def test_as_record(): x = Locus("1", 3, 4, strand="+") # This doesn't compare the dictionaries of each ... assert x.as_record()[0] == ( "1", 3, 4, "locuspocus", "locus", "+", None, None, 2039807104618252476, ) def test_center_distance(): x = Locus("1", 1, 100, strand="+") # This needs to be 201 since x starts at 1 y = Locus("1", 201, 300, strand="=") assert x.center_distance(y) == 200 def test_center_distance_different_chroms(): x = Locus("1", 1, 100, strand="+") # This needs to be 201 since x starts at 1 y = Locus("2", 201, 300, strand="+") assert x.center_distance(y) == np.inf def test_str(): x = Locus("1", 1, 100, strand="+") assert str(x) == repr(x) def test_combine(): x = Locus("1", 1, 2) y = Locus("1", 3, 4) z = x.combine(y) assert z.start == 1 assert z.end == 4 assert x in z.subloci assert y in z.subloci def test_combine_chromosome_mismatch(): x = Locus("1", 1, 2) y = Locus("2", 3, 4) with pytest.raises(ChromosomeError): x.combine(y) def test_distance(): x = Locus("1", 1, 100) y = Locus("1", 150, 250) assert x.distance(y) == 49 def test_distance_diff_chroms(): x = Locus("1", 1, 100) y = Locus("2", 150, 250) assert x.distance(y) == np.inf
LinkageIO/LocusPocus
tests/test_Locus.py
locuspocus/fasta.py
"""Plugwise Climate component for Home Assistant.""" import logging import haanna import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice from homeassistant.components.climate.const import ( CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE _LOGGER = logging.getLogger(__name__) # Configuration directives CONF_MIN_TEMP = "min_temp" CONF_MAX_TEMP = "max_temp" CONF_LEGACY = "legacy_anna" # Default directives DEFAULT_NAME = "Plugwise Thermostat" DEFAULT_USERNAME = "smile" DEFAULT_TIMEOUT = 10 DEFAULT_PORT = 80 DEFAULT_ICON = "mdi:thermometer" DEFAULT_MIN_TEMP = 4 DEFAULT_MAX_TEMP = 30 # HVAC modes HVAC_MODES_1 = [HVAC_MODE_HEAT, HVAC_MODE_AUTO] HVAC_MODES_2 = [HVAC_MODE_HEAT_COOL, HVAC_MODE_AUTO] # Read platform configuration PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_LEGACY, default=False): cv.boolean, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, vol.Optional(CONF_MIN_TEMP, default=DEFAULT_MIN_TEMP): cv.positive_int, vol.Optional(CONF_MAX_TEMP, default=DEFAULT_MAX_TEMP): cv.positive_int, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Add the Plugwise (Anna) Thermostat.""" api = haanna.Haanna( config[CONF_USERNAME], config[CONF_PASSWORD], config[CONF_HOST], config[CONF_PORT], config[CONF_LEGACY], ) try: api.ping_anna_thermostat() except OSError: _LOGGER.debug("Ping failed, retrying later", exc_info=True) raise PlatformNotReady devices = [ ThermostatDevice( api, config[CONF_NAME], config[CONF_MIN_TEMP], config[CONF_MAX_TEMP] ) ] add_entities(devices, True) class ThermostatDevice(ClimateDevice): """Representation of the Plugwise thermostat.""" def __init__(self, api, name, min_temp, max_temp): """Set up the Plugwise API.""" self._api = api self._min_temp = min_temp self._max_temp = max_temp self._name = name self._direct_objects = None self._domain_objects = None self._outdoor_temperature = None self._selected_schema = None self._last_active_schema = None self._preset_mode = None self._presets = None self._presets_list = None self._boiler_status = None self._heating_status = None self._cooling_status = None self._dhw_status = None self._schema_names = None self._schema_status = None self._current_temperature = None self._thermostat_temperature = None self._boiler_temperature = None self._water_pressure = None self._schedule_temperature = None self._hvac_mode = None @property def hvac_action(self): """Return the current hvac action.""" if self._heating_status or self._boiler_status or self._dhw_status: return CURRENT_HVAC_HEAT if self._cooling_status: return CURRENT_HVAC_COOL return CURRENT_HVAC_IDLE @property def name(self): """Return the name of the thermostat, if any.""" return self._name @property def icon(self): """Return the icon to use in the frontend.""" return DEFAULT_ICON @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def device_state_attributes(self): """Return the device specific state attributes.""" attributes = {} if self._outdoor_temperature: attributes["outdoor_temperature"] = self._outdoor_temperature if self._schema_names: attributes["available_schemas"] = self._schema_names if self._selected_schema: attributes["selected_schema"] = self._selected_schema if self._boiler_temperature: attributes["boiler_temperature"] = self._boiler_temperature if self._water_pressure: attributes["water_pressure"] = self._water_pressure return attributes @property def preset_modes(self): """Return the available preset modes list. And make the presets with their temperatures available. """ return self._presets_list @property def hvac_modes(self): """Return the available hvac modes list.""" if self._heating_status is not None or self._boiler_status is not None: if self._cooling_status is not None: return HVAC_MODES_2 return HVAC_MODES_1 return None @property def hvac_mode(self): """Return current active hvac state.""" if self._schema_status: return HVAC_MODE_AUTO if self._heating_status or self._boiler_status or self._dhw_status: if self._cooling_status: return HVAC_MODE_HEAT_COOL return HVAC_MODE_HEAT return HVAC_MODE_OFF @property def target_temperature(self): """Return the target_temperature. From the XML the thermostat-value is used because it updates 'immediately' compared to the target_temperature-value. This way the information on the card is "immediately" updated after changing the preset, temperature, etc. """ return self._thermostat_temperature @property def preset_mode(self): """Return the active selected schedule-name. Or, return the active preset, or return Temporary in case of a manual change in the set-temperature with a weekschedule active. Or return Manual in case of a manual change and no weekschedule active. """ if self._presets: presets = self._presets preset_temperature = presets.get(self._preset_mode, "none") if self.hvac_mode == HVAC_MODE_AUTO: if self._thermostat_temperature == self._schedule_temperature: return "{}".format(self._selected_schema) if self._thermostat_temperature == preset_temperature: return self._preset_mode return "Temporary" if self._thermostat_temperature != preset_temperature: return "Manual" return self._preset_mode return None @property def current_temperature(self): """Return the current room temperature.""" return self._current_temperature @property def min_temp(self): """Return the minimal temperature possible to set.""" return self._min_temp @property def max_temp(self): """Return the maximum temperature possible to set.""" return self._max_temp @property def temperature_unit(self): """Return the unit of measured temperature.""" return TEMP_CELSIUS def set_temperature(self, **kwargs): """Set new target temperature.""" _LOGGER.debug("Adjusting temperature") temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is not None and self._min_temp < temperature < self._max_temp: _LOGGER.debug("Changing temporary temperature") self._api.set_temperature(self._domain_objects, temperature) else: _LOGGER.error("Invalid temperature requested") def set_hvac_mode(self, hvac_mode): """Set the hvac mode.""" _LOGGER.debug("Adjusting hvac_mode (i.e. schedule/schema)") schema_mode = "false" if hvac_mode == HVAC_MODE_AUTO: schema_mode = "true" self._api.set_schema_state( self._domain_objects, self._last_active_schema, schema_mode ) def set_preset_mode(self, preset_mode): """Set the preset mode.""" _LOGGER.debug("Changing preset mode") self._api.set_preset(self._domain_objects, preset_mode) def update(self): """Update the data from the thermostat.""" _LOGGER.debug("Update called") self._direct_objects = self._api.get_direct_objects() self._domain_objects = self._api.get_domain_objects() self._outdoor_temperature = self._api.get_outdoor_temperature( self._domain_objects ) self._selected_schema = self._api.get_active_schema_name(self._domain_objects) self._last_active_schema = self._api.get_last_active_schema_name( self._domain_objects ) self._preset_mode = self._api.get_current_preset(self._domain_objects) self._presets = self._api.get_presets(self._domain_objects) self._presets_list = list(self._api.get_presets(self._domain_objects)) self._boiler_status = self._api.get_boiler_status(self._direct_objects) self._heating_status = self._api.get_heating_status(self._direct_objects) self._cooling_status = self._api.get_cooling_status(self._direct_objects) self._dhw_status = self._api.get_domestic_hot_water_status(self._direct_objects) self._schema_names = self._api.get_schema_names(self._domain_objects) self._schema_status = self._api.get_schema_state(self._domain_objects) self._current_temperature = self._api.get_current_temperature( self._domain_objects ) self._thermostat_temperature = self._api.get_thermostat_temperature( self._domain_objects ) self._schedule_temperature = self._api.get_schedule_temperature( self._domain_objects ) self._boiler_temperature = self._api.get_boiler_temperature( self._domain_objects ) self._water_pressure = self._api.get_water_pressure(self._domain_objects)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/plugwise/climate.py
"""Support for Qwikswitch relays.""" from homeassistant.components.switch import SwitchDevice from . import DOMAIN as QWIKSWITCH, QSToggleEntity async def async_setup_platform(hass, _, add_entities, discovery_info=None): """Add switches from the main Qwikswitch component.""" if discovery_info is None: return qsusb = hass.data[QWIKSWITCH] devs = [QSSwitch(qsid, qsusb) for qsid in discovery_info[QWIKSWITCH]] add_entities(devs) class QSSwitch(QSToggleEntity, SwitchDevice): """Switch based on a Qwikswitch relay module."""
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/qwikswitch/switch.py
"""Config flow for Somfy.""" import logging from homeassistant import config_entries from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN _LOGGER = logging.getLogger(__name__) @config_entries.HANDLERS.register(DOMAIN) class SomfyFlowHandler(config_entry_oauth2_flow.AbstractOAuth2FlowHandler): """Config flow to handle Somfy OAuth2 authentication.""" DOMAIN = DOMAIN CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) async def async_step_user(self, user_input=None): """Handle a flow start.""" if self.hass.config_entries.async_entries(DOMAIN): return self.async_abort(reason="already_setup") return await super().async_step_user(user_input)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/somfy/config_flow.py
"""Trigger an automation when a LiteJet switch is released.""" import logging import voluptuous as vol from homeassistant.const import CONF_PLATFORM from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_point_in_utc_time import homeassistant.util.dt as dt_util # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) CONF_NUMBER = "number" CONF_HELD_MORE_THAN = "held_more_than" CONF_HELD_LESS_THAN = "held_less_than" TRIGGER_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): "litejet", vol.Required(CONF_NUMBER): cv.positive_int, vol.Optional(CONF_HELD_MORE_THAN): vol.All( cv.time_period, cv.positive_timedelta ), vol.Optional(CONF_HELD_LESS_THAN): vol.All( cv.time_period, cv.positive_timedelta ), } ) async def async_attach_trigger(hass, config, action, automation_info): """Listen for events based on configuration.""" number = config.get(CONF_NUMBER) held_more_than = config.get(CONF_HELD_MORE_THAN) held_less_than = config.get(CONF_HELD_LESS_THAN) pressed_time = None cancel_pressed_more_than = None @callback def call_action(): """Call action with right context.""" hass.async_run_job( action, { "trigger": { CONF_PLATFORM: "litejet", CONF_NUMBER: number, CONF_HELD_MORE_THAN: held_more_than, CONF_HELD_LESS_THAN: held_less_than, } }, ) # held_more_than and held_less_than: trigger on released (if in time range) # held_more_than: trigger after pressed with calculation # held_less_than: trigger on released with calculation # neither: trigger on pressed @callback def pressed_more_than_satisfied(now): """Handle the LiteJet's switch's button pressed >= held_more_than.""" call_action() def pressed(): """Handle the press of the LiteJet switch's button.""" nonlocal cancel_pressed_more_than, pressed_time nonlocal held_less_than, held_more_than pressed_time = dt_util.utcnow() if held_more_than is None and held_less_than is None: hass.add_job(call_action) if held_more_than is not None and held_less_than is None: cancel_pressed_more_than = track_point_in_utc_time( hass, pressed_more_than_satisfied, dt_util.utcnow() + held_more_than ) def released(): """Handle the release of the LiteJet switch's button.""" nonlocal cancel_pressed_more_than, pressed_time nonlocal held_less_than, held_more_than # pylint: disable=not-callable if cancel_pressed_more_than is not None: cancel_pressed_more_than() cancel_pressed_more_than = None held_time = dt_util.utcnow() - pressed_time if held_less_than is not None and held_time < held_less_than: if held_more_than is None or held_time > held_more_than: hass.add_job(call_action) hass.data["litejet_system"].on_switch_pressed(number, pressed) hass.data["litejet_system"].on_switch_released(number, released) @callback def async_remove(): """Remove all subscriptions used for this trigger.""" return return async_remove
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/automation/litejet.py
"""Errors for the UniFi component.""" from homeassistant.exceptions import HomeAssistantError class UnifiException(HomeAssistantError): """Base class for UniFi exceptions.""" class AlreadyConfigured(UnifiException): """Controller is already configured.""" class AuthenticationRequired(UnifiException): """Unknown error occurred.""" class CannotConnect(UnifiException): """Unable to connect to the controller.""" class LoginRequired(UnifiException): """Component got logged out.""" class UserLevel(UnifiException): """User level too low."""
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/unifi/errors.py
"""Consts for Kaiterra integration.""" from datetime import timedelta DOMAIN = "kaiterra" DISPATCHER_KAITERRA = "kaiterra_update" AQI_SCALE = { "cn": [0, 50, 100, 150, 200, 300, 400, 500], "in": [0, 50, 100, 200, 300, 400, 500], "us": [0, 50, 100, 150, 200, 300, 500], } AQI_LEVEL = { "cn": [ "Good", "Satisfactory", "Moderate", "Unhealthy for sensitive groups", "Unhealthy", "Very unhealthy", "Hazardous", ], "in": [ "Good", "Satisfactory", "Moderately polluted", "Poor", "Very poor", "Severe", ], "us": [ "Good", "Moderate", "Unhealthy for sensitive groups", "Unhealthy", "Very unhealthy", "Hazardous", ], } ATTR_VOC = "volatile_organic_compounds" ATTR_AQI_LEVEL = "air_quality_index_level" ATTR_AQI_POLLUTANT = "air_quality_index_pollutant" AVAILABLE_AQI_STANDARDS = ["us", "cn", "in"] AVAILABLE_UNITS = ["x", "%", "C", "F", "mg/m³", "µg/m³", "ppm", "ppb"] AVAILABLE_DEVICE_TYPES = ["laseregg", "sensedge"] CONF_AQI_STANDARD = "aqi_standard" CONF_PREFERRED_UNITS = "preferred_units" DEFAULT_AQI_STANDARD = "us" DEFAULT_PREFERRED_UNIT = [] DEFAULT_SCAN_INTERVAL = timedelta(seconds=30) KAITERRA_COMPONENTS = ["sensor", "air_quality"]
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/kaiterra/const.py
"""Support for IHC lights.""" import logging from homeassistant.components.light import ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO from .const import CONF_DIMMABLE, CONF_OFF_ID, CONF_ON_ID from .ihcdevice import IHCDevice from .util import async_pulse, async_set_bool, async_set_int _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the IHC lights platform.""" if discovery_info is None: return devices = [] for name, device in discovery_info.items(): ihc_id = device["ihc_id"] product_cfg = device["product_cfg"] product = device["product"] # Find controller that corresponds with device id ctrl_id = device["ctrl_id"] ihc_key = IHC_DATA.format(ctrl_id) info = hass.data[ihc_key][IHC_INFO] ihc_controller = hass.data[ihc_key][IHC_CONTROLLER] ihc_off_id = product_cfg.get(CONF_OFF_ID) ihc_on_id = product_cfg.get(CONF_ON_ID) dimmable = product_cfg[CONF_DIMMABLE] light = IhcLight( ihc_controller, name, ihc_id, ihc_off_id, ihc_on_id, info, dimmable, product ) devices.append(light) add_entities(devices) class IhcLight(IHCDevice, Light): """Representation of a IHC light. For dimmable lights, the associated IHC resource should be a light level (integer). For non dimmable light the IHC resource should be an on/off (boolean) resource """ def __init__( self, ihc_controller, name, ihc_id: int, ihc_off_id: int, ihc_on_id: int, info: bool, dimmable=False, product=None, ) -> None: """Initialize the light.""" super().__init__(ihc_controller, name, ihc_id, info, product) self._ihc_off_id = ihc_off_id self._ihc_on_id = ihc_on_id self._brightness = 0 self._dimmable = dimmable self._state = None @property def brightness(self) -> int: """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self) -> bool: """Return true if light is on.""" return self._state @property def supported_features(self): """Flag supported features.""" if self._dimmable: return SUPPORT_BRIGHTNESS return 0 async def async_turn_on(self, **kwargs): """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] else: brightness = self._brightness if brightness == 0: brightness = 255 if self._dimmable: await async_set_int( self.hass, self.ihc_controller, self.ihc_id, int(brightness * 100 / 255) ) else: if self._ihc_on_id: await async_pulse(self.hass, self.ihc_controller, self._ihc_on_id) else: await async_set_bool(self.hass, self.ihc_controller, self.ihc_id, True) async def async_turn_off(self, **kwargs): """Turn the light off.""" if self._dimmable: await async_set_int(self.hass, self.ihc_controller, self.ihc_id, 0) else: if self._ihc_off_id: await async_pulse(self.hass, self.ihc_controller, self._ihc_off_id) else: await async_set_bool(self.hass, self.ihc_controller, self.ihc_id, False) def on_ihc_change(self, ihc_id, value): """Handle IHC notifications.""" if isinstance(value, bool): self._dimmable = False self._state = value != 0 else: self._dimmable = True self._state = value > 0 if self._state: self._brightness = int(value * 255 / 100) self.schedule_update_ha_state()
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/ihc/light.py
"""Support for Homematic locks.""" import logging from homeassistant.components.lock import SUPPORT_OPEN, LockDevice from .const import ATTR_DISCOVER_DEVICES from .entity import HMDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Homematic lock platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: devices.append(HMLock(conf)) add_entities(devices, True) class HMLock(HMDevice, LockDevice): """Representation of a Homematic lock aka KeyMatic.""" @property def is_locked(self): """Return true if the lock is locked.""" return not bool(self._hm_get_state()) def lock(self, **kwargs): """Lock the lock.""" self._hmdevice.lock() def unlock(self, **kwargs): """Unlock the lock.""" self._hmdevice.unlock() def open(self, **kwargs): """Open the door latch.""" self._hmdevice.open() def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" self._state = "STATE" self._data.update({self._state: None}) @property def supported_features(self): """Flag supported features.""" return SUPPORT_OPEN
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/homematic/lock.py
"""OpenEnergyMonitor Thermostat Support.""" import logging from oemthermostat import Thermostat import requests import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default="Thermostat"): cv.string, vol.Optional(CONF_PORT, default=80): cv.port, vol.Inclusive(CONF_USERNAME, "authentication"): cv.string, vol.Inclusive(CONF_PASSWORD, "authentication"): cv.string, } ) SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE SUPPORT_HVAC = [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF] def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the oemthermostat platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) try: therm = Thermostat(host, port=port, username=username, password=password) except (ValueError, AssertionError, requests.RequestException): return False add_entities((ThermostatDevice(therm, name),), True) class ThermostatDevice(ClimateDevice): """Interface class for the oemthermostat module.""" def __init__(self, thermostat, name): """Initialize the device.""" self._name = name self.thermostat = thermostat # set up internal state varS self._state = None self._temperature = None self._setpoint = None self._mode = None @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._mode == 2: return HVAC_MODE_HEAT if self._mode == 1: return HVAC_MODE_AUTO return HVAC_MODE_OFF @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC @property def name(self): """Return the name of this Thermostat.""" return self._name @property def temperature_unit(self): """Return the unit of measurement used by the platform.""" return TEMP_CELSIUS @property def hvac_action(self): """Return current hvac i.e. heat, cool, idle.""" if not self._mode: return CURRENT_HVAC_OFF if self._state: return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE @property def current_temperature(self): """Return the current temperature.""" return self._temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._setpoint def set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_AUTO: self.thermostat.mode = 1 elif hvac_mode == HVAC_MODE_HEAT: self.thermostat.mode = 2 elif hvac_mode == HVAC_MODE_OFF: self.thermostat.mode = 0 def set_temperature(self, **kwargs): """Set the temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) self.thermostat.setpoint = temp def update(self): """Update local state.""" self._setpoint = self.thermostat.setpoint self._temperature = self.thermostat.temperature self._state = self.thermostat.state self._mode = self.thermostat.mode
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/oem/climate.py
"""Reproduce an Vacuum state.""" import asyncio import logging from typing import Iterable, Optional from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_IDLE, STATE_OFF, STATE_ON, STATE_PAUSED, ) from homeassistant.core import Context, State from homeassistant.helpers.typing import HomeAssistantType from . import ( ATTR_FAN_SPEED, DOMAIN, SERVICE_PAUSE, SERVICE_RETURN_TO_BASE, SERVICE_SET_FAN_SPEED, SERVICE_START, SERVICE_STOP, STATE_CLEANING, STATE_DOCKED, STATE_RETURNING, ) _LOGGER = logging.getLogger(__name__) VALID_STATES_TOGGLE = {STATE_ON, STATE_OFF} VALID_STATES_STATE = { STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_RETURNING, STATE_PAUSED, } async def _async_reproduce_state( hass: HomeAssistantType, state: State, context: Optional[Context] = 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_TOGGLE and state.state not in VALID_STATES_STATE: _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_FAN_SPEED ) == state.attributes.get(ATTR_FAN_SPEED): return service_data = {ATTR_ENTITY_ID: state.entity_id} if cur_state.state != state.state: # Wrong state if state.state == STATE_ON: service = SERVICE_TURN_ON elif state.state == STATE_OFF: service = SERVICE_TURN_OFF elif state.state == STATE_CLEANING: service = SERVICE_START elif state.state == STATE_DOCKED or state.state == STATE_RETURNING: service = SERVICE_RETURN_TO_BASE elif state.state == STATE_IDLE: service = SERVICE_STOP elif state.state == STATE_PAUSED: service = SERVICE_PAUSE await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) if cur_state.attributes.get(ATTR_FAN_SPEED) != state.attributes.get(ATTR_FAN_SPEED): # Wrong fan speed service_data["fan_speed"] = state.attributes[ATTR_FAN_SPEED] await hass.services.async_call( DOMAIN, SERVICE_SET_FAN_SPEED, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], context: Optional[Context] = None ) -> None: """Reproduce Vacuum states.""" # Reproduce states in parallel. await asyncio.gather( *(_async_reproduce_state(hass, state, context) for state in states) )
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/vacuum/reproduce_state.py
"""Support for HomeMatic covers.""" import logging from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, CoverDevice, ) from .const import ATTR_DISCOVER_DEVICES from .entity import HMDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: new_device = HMCover(conf) devices.append(new_device) add_entities(devices, True) class HMCover(HMDevice, CoverDevice): """Representation a HomeMatic Cover.""" @property def current_cover_position(self): """ Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ return int(self._hm_get_state() * 100) def set_cover_position(self, **kwargs): """Move the cover to a specific position.""" if ATTR_POSITION in kwargs: position = float(kwargs[ATTR_POSITION]) position = min(100, max(0, position)) level = position / 100.0 self._hmdevice.set_level(level, self._channel) @property def is_closed(self): """Return if the cover is closed.""" if self.current_cover_position is not None: return self.current_cover_position == 0 return None def open_cover(self, **kwargs): """Open the cover.""" self._hmdevice.move_up(self._channel) def close_cover(self, **kwargs): """Close the cover.""" self._hmdevice.move_down(self._channel) def stop_cover(self, **kwargs): """Stop the device if in motion.""" self._hmdevice.stop(self._channel) def _init_data_struct(self): """Generate a data dictionary (self._data) from metadata.""" self._state = "LEVEL" self._data.update({self._state: None}) if "LEVEL_2" in self._hmdevice.WRITENODE: self._data.update({"LEVEL_2": None}) @property def current_cover_tilt_position(self): """Return current position of cover tilt. None is unknown, 0 is closed, 100 is fully open. """ if "LEVEL_2" not in self._data: return None return int(self._data.get("LEVEL_2", 0) * 100) def set_cover_tilt_position(self, **kwargs): """Move the cover tilt to a specific position.""" if "LEVEL_2" in self._data and ATTR_TILT_POSITION in kwargs: position = float(kwargs[ATTR_TILT_POSITION]) position = min(100, max(0, position)) level = position / 100.0 self._hmdevice.set_cover_tilt_position(level, self._channel) def open_cover_tilt(self, **kwargs): """Open the cover tilt.""" if "LEVEL_2" in self._data: self._hmdevice.open_slats() def close_cover_tilt(self, **kwargs): """Close the cover tilt.""" if "LEVEL_2" in self._data: self._hmdevice.close_slats() def stop_cover_tilt(self, **kwargs): """Stop cover tilt.""" if "LEVEL_2" in self._data: self.stop_cover(**kwargs)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/homematic/cover.py
"""Support for Switchbot.""" import logging from typing import Any, Dict # pylint: disable=import-error, no-member import switchbot import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice from homeassistant.const import CONF_MAC, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Switchbot" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Switchbot devices.""" name = config.get(CONF_NAME) mac_addr = config[CONF_MAC] add_entities([SwitchBot(mac_addr, name)]) class SwitchBot(SwitchDevice, RestoreEntity): """Representation of a Switchbot.""" def __init__(self, mac, name) -> None: """Initialize the Switchbot.""" self._state = None self._last_run_success = None self._name = name self._mac = mac self._device = switchbot.Switchbot(mac=mac) async def async_added_to_hass(self): """Run when entity about to be added.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state == "on" def turn_on(self, **kwargs) -> None: """Turn device on.""" if self._device.turn_on(): self._state = True self._last_run_success = True else: self._last_run_success = False def turn_off(self, **kwargs) -> None: """Turn device off.""" if self._device.turn_off(): self._state = False self._last_run_success = True else: self._last_run_success = False @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" return True @property def is_on(self) -> bool: """Return true if device is on.""" return self._state @property def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return self._mac.replace(":", "") @property def name(self) -> str: """Return the name of the switch.""" return self._name @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes.""" return {"last_run_success": self._last_run_success}
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/switchbot/switch.py
"""Weather information for air and road temperature (by Trafikverket).""" import asyncio from datetime import timedelta import logging import aiohttp from pytrafikverket.trafikverket_weather import TrafikverketWeather import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_API_KEY, CONF_MONITORED_CONDITIONS, CONF_NAME, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, ) 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__) ATTRIBUTION = "Data provided by Trafikverket" ATTR_MEASURE_TIME = "measure_time" ATTR_ACTIVE = "active" CONF_STATION = "station" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) SCAN_INTERVAL = timedelta(seconds=300) SENSOR_TYPES = { "air_temp": [ "Air temperature", TEMP_CELSIUS, "air_temp", "mdi:thermometer", DEVICE_CLASS_TEMPERATURE, ], "road_temp": [ "Road temperature", TEMP_CELSIUS, "road_temp", "mdi:thermometer", DEVICE_CLASS_TEMPERATURE, ], "precipitation": [ "Precipitation type", None, "precipitationtype", "mdi:weather-snowy-rainy", None, ], "wind_direction": [ "Wind direction", "°", "winddirection", "mdi:flag-triangle", None, ], "wind_direction_text": [ "Wind direction text", None, "winddirectiontext", "mdi:flag-triangle", None, ], "wind_speed": ["Wind speed", "m/s", "windforce", "mdi:weather-windy", None], "humidity": [ "Humidity", "%", "humidity", "mdi:water-percent", DEVICE_CLASS_HUMIDITY, ], "precipitation_amount": [ "Precipitation amount", "mm", "precipitation_amount", "mdi:cup-water", None, ], "precipitation_amountname": [ "Precipitation name", None, "precipitation_amountname", "mdi:weather-pouring", None, ], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_NAME): cv.string, vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_STATION): cv.string, vol.Required(CONF_MONITORED_CONDITIONS, default=[]): [vol.In(SENSOR_TYPES)], } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Trafikverket sensor platform.""" sensor_name = config[CONF_NAME] sensor_api = config[CONF_API_KEY] sensor_station = config[CONF_STATION] web_session = async_get_clientsession(hass) weather_api = TrafikverketWeather(web_session, sensor_api) dev = [] for condition in config[CONF_MONITORED_CONDITIONS]: dev.append( TrafikverketWeatherStation( weather_api, sensor_name, condition, sensor_station ) ) if dev: async_add_entities(dev, True) class TrafikverketWeatherStation(Entity): """Representation of a Trafikverket sensor.""" def __init__(self, weather_api, name, sensor_type, sensor_station): """Initialize the sensor.""" self._client = name self._name = SENSOR_TYPES[sensor_type][0] self._type = sensor_type self._state = None self._unit = SENSOR_TYPES[sensor_type][1] self._station = sensor_station self._weather_api = weather_api self._icon = SENSOR_TYPES[sensor_type][3] self._device_class = SENSOR_TYPES[sensor_type][4] self._weather = None @property def name(self): """Return the name of the sensor.""" return f"{self._client} {self._name}" @property def icon(self): """Icon to use in the frontend.""" return self._icon @property def device_state_attributes(self): """Return the state attributes of Trafikverket Weatherstation.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_ACTIVE: self._weather.active, ATTR_MEASURE_TIME: self._weather.measure_time, } @property def device_class(self): """Return the device class of the sensor.""" return self._device_class @property def state(self): """Return the state of the device.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from Trafikverket and updates the states.""" try: self._weather = await self._weather_api.async_get_weather(self._station) self._state = getattr(self._weather, SENSOR_TYPES[self._type][2]) except (asyncio.TimeoutError, aiohttp.ClientError, ValueError) as error: _LOGGER.error("Could not fetch weather data: %s", error)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/trafikverket_weatherstation/sensor.py
"""Support for Lupusec Security System switches.""" from datetime import timedelta import logging import lupupy.constants as CONST from homeassistant.components.switch import SwitchDevice from . import DOMAIN as LUPUSEC_DOMAIN, LupusecDevice SCAN_INTERVAL = timedelta(seconds=2) _LOGGER = logging.getLogger(__name__) 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, SwitchDevice): """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
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/lupusec/switch.py
"""Support for OASA Telematics from telematics.oasa.gr.""" from datetime import timedelta import logging from operator import itemgetter import oasatelematics import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, DEVICE_CLASS_TIMESTAMP import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_STOP_ID = "stop_id" ATTR_STOP_NAME = "stop_name" ATTR_ROUTE_ID = "route_id" ATTR_ROUTE_NAME = "route_name" ATTR_NEXT_ARRIVAL = "next_arrival" ATTR_SECOND_NEXT_ARRIVAL = "second_next_arrival" ATTR_NEXT_DEPARTURE = "next_departure" ATTRIBUTION = "Data retrieved from telematics.oasa.gr" CONF_STOP_ID = "stop_id" CONF_ROUTE_ID = "route_id" DEFAULT_NAME = "OASA Telematics" ICON = "mdi:bus" SCAN_INTERVAL = timedelta(seconds=60) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_STOP_ID): cv.string, vol.Required(CONF_ROUTE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the OASA Telematics sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route_id = config.get(CONF_ROUTE_ID) data = OASATelematicsData(stop_id, route_id) add_entities([OASATelematicsSensor(data, stop_id, route_id, name)], True) class OASATelematicsSensor(Entity): """Implementation of the OASA Telematics sensor.""" def __init__(self, data, stop_id, route_id, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route_id = route_id self._name_data = self._times = self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" params = {} if self._times is not None: next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: next_arrival = next_arrival_data[ATTR_NEXT_ARRIVAL] params.update({ATTR_NEXT_ARRIVAL: next_arrival.isoformat()}) if len(self._times) > 1: second_next_arrival_time = self._times[1][ATTR_NEXT_ARRIVAL] if second_next_arrival_time is not None: second_arrival = second_next_arrival_time params.update( {ATTR_SECOND_NEXT_ARRIVAL: second_arrival.isoformat()} ) params.update( { ATTR_ROUTE_ID: self._times[0][ATTR_ROUTE_ID], ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION, } ) params.update( { ATTR_ROUTE_NAME: self._name_data[ATTR_ROUTE_NAME], ATTR_STOP_NAME: self._name_data[ATTR_STOP_NAME], } ) return {k: v for k, v in params.items() if v} @property def icon(self): """Icon to use in the frontend, if any.""" return ICON def update(self): """Get the latest data from OASA API and update the states.""" self.data.update() self._times = self.data.info self._name_data = self.data.name_data next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: self._state = next_arrival_data[ATTR_NEXT_ARRIVAL].isoformat() class OASATelematicsData: """The class for handling data retrieval.""" def __init__(self, stop_id, route_id): """Initialize the data object.""" self.stop_id = stop_id self.route_id = route_id self.info = self.empty_result() self.oasa_api = oasatelematics self.name_data = { ATTR_ROUTE_NAME: self.get_route_name(), ATTR_STOP_NAME: self.get_stop_name(), } def empty_result(self): """Object returned when no arrivals are found.""" return [{ATTR_ROUTE_ID: self.route_id}] def get_route_name(self): """Get the route name from the API.""" try: route = self.oasa_api.getRouteName(self.route_id) if route: return route[0].get("route_departure_eng") except TypeError: _LOGGER.error("Cannot get route name from OASA API") return None def get_stop_name(self): """Get the stop name from the API.""" try: name_data = self.oasa_api.getStopNameAndXY(self.stop_id) if name_data: return name_data[0].get("stop_descr_matrix_eng") except TypeError: _LOGGER.error("Cannot get stop name from OASA API") return None def update(self): """Get the latest arrival data from telematics.oasa.gr API.""" self.info = [] results = self.oasa_api.getStopArrivals(self.stop_id) if not results: self.info = self.empty_result() return # Parse results results = [r for r in results if r.get("route_code") in self.route_id] current_time = dt_util.utcnow() for result in results: btime2 = result.get("btime2") if btime2 is not None: arrival_min = int(btime2) timestamp = current_time + timedelta(minutes=arrival_min) arrival_data = { ATTR_NEXT_ARRIVAL: timestamp, ATTR_ROUTE_ID: self.route_id, } self.info.append(arrival_data) if not self.info: _LOGGER.debug("No arrivals with given parameters") self.info = self.empty_result() return # Sort the data by time sort = sorted(self.info, key=itemgetter(ATTR_NEXT_ARRIVAL)) self.info = sort
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/oasa_telematics/sensor.py
"""Support for FRITZ!Box routers.""" import logging from fritzconnection.lib.fritzhosts import FritzHosts import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DEFAULT_IP = "169.254.1.1" # This IP is valid for all FRITZ!Box routers. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_HOST, default=CONF_DEFAULT_IP): cv.string, vol.Optional(CONF_PASSWORD, default="admin"): cv.string, vol.Optional(CONF_USERNAME, default=""): cv.string, } ) def get_scanner(hass, config): """Validate the configuration and return FritzBoxScanner.""" scanner = FritzBoxScanner(config[DOMAIN]) return scanner if scanner.success_init else None class FritzBoxScanner(DeviceScanner): """This class queries a FRITZ!Box router.""" def __init__(self, config): """Initialize the scanner.""" self.last_results = [] self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.success_init = True # Establish a connection to the FRITZ!Box. try: self.fritz_box = FritzHosts( address=self.host, user=self.username, password=self.password ) except (ValueError, TypeError): self.fritz_box = None # At this point it is difficult to tell if a connection is established. # So just check for null objects. if self.fritz_box is None or not self.fritz_box.modelname: self.success_init = False if self.success_init: _LOGGER.info("Successfully connected to %s", self.fritz_box.modelname) self._update_info() else: _LOGGER.error( "Failed to establish connection to FRITZ!Box with IP: %s", self.host ) def scan_devices(self): """Scan for new devices and return a list of found device ids.""" self._update_info() active_hosts = [] for known_host in self.last_results: if known_host["status"] and known_host.get("mac"): active_hosts.append(known_host["mac"]) return active_hosts def get_device_name(self, device): """Return the name of the given device or None if is not known.""" ret = self.fritz_box.get_specific_host_entry(device).get("NewHostName") if ret == {}: return None return ret def get_extra_attributes(self, device): """Return the attributes (ip, mac) of the given device or None if is not known.""" ip_device = self.fritz_box.get_specific_host_entry(device).get("NewIPAddress") if not ip_device: return {} return {"ip": ip_device, "mac": device} def _update_info(self): """Retrieve latest information from the FRITZ!Box.""" if not self.success_init: return False _LOGGER.debug("Scanning") self.last_results = self.fritz_box.get_hosts_info() return True
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/fritz/device_tracker.py
"""Support for tracking consumption over given periods of time.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import CONF_NAME from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.restore_state import RestoreEntity from .const import ( ATTR_TARIFF, CONF_METER, CONF_METER_NET_CONSUMPTION, CONF_METER_OFFSET, CONF_METER_TYPE, CONF_SOURCE_SENSOR, CONF_TARIFF, CONF_TARIFF_ENTITY, CONF_TARIFFS, DATA_UTILITY, DOMAIN, METER_TYPES, SERVICE_RESET, SERVICE_SELECT_NEXT_TARIFF, SERVICE_SELECT_TARIFF, SIGNAL_RESET_METER, ) _LOGGER = logging.getLogger(__name__) TARIFF_ICON = "mdi:clock-outline" ATTR_TARIFFS = "tariffs" DEFAULT_OFFSET = timedelta(hours=0) METER_CONFIG_SCHEMA = vol.Schema( { vol.Required(CONF_SOURCE_SENSOR): cv.entity_id, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_METER_TYPE): vol.In(METER_TYPES), vol.Optional(CONF_METER_OFFSET, default=DEFAULT_OFFSET): vol.All( cv.time_period, cv.positive_timedelta ), vol.Optional(CONF_METER_NET_CONSUMPTION, default=False): cv.boolean, vol.Optional(CONF_TARIFFS, default=[]): vol.All(cv.ensure_list, [cv.string]), } ) CONFIG_SCHEMA = vol.Schema( {DOMAIN: vol.Schema({cv.slug: METER_CONFIG_SCHEMA})}, extra=vol.ALLOW_EXTRA ) async def async_setup(hass, config): """Set up an Utility Meter.""" component = EntityComponent(_LOGGER, DOMAIN, hass) hass.data[DATA_UTILITY] = {} register_services = False for meter, conf in config.get(DOMAIN).items(): _LOGGER.debug("Setup %s.%s", DOMAIN, meter) hass.data[DATA_UTILITY][meter] = conf if not conf[CONF_TARIFFS]: # only one entity is required hass.async_create_task( discovery.async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, [{CONF_METER: meter, CONF_NAME: meter}], config, ) ) else: # create tariff selection await component.async_add_entities( [TariffSelect(meter, list(conf[CONF_TARIFFS]))] ) hass.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] = "{}.{}".format( DOMAIN, meter ) # add one meter for each tariff tariff_confs = [] for tariff in conf[CONF_TARIFFS]: tariff_confs.append( { CONF_METER: meter, CONF_NAME: f"{meter} {tariff}", CONF_TARIFF: tariff, } ) hass.async_create_task( discovery.async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, tariff_confs, config ) ) register_services = True if register_services: component.async_register_entity_service(SERVICE_RESET, {}, "async_reset_meters") component.async_register_entity_service( SERVICE_SELECT_TARIFF, {vol.Required(ATTR_TARIFF): cv.string}, "async_select_tariff", ) component.async_register_entity_service( SERVICE_SELECT_NEXT_TARIFF, {}, "async_next_tariff" ) return True class TariffSelect(RestoreEntity): """Representation of a Tariff selector.""" def __init__(self, name, tariffs): """Initialize a tariff selector.""" self._name = name self._current_tariff = None self._tariffs = tariffs self._icon = TARIFF_ICON async def async_added_to_hass(self): """Run when entity about to be added.""" await super().async_added_to_hass() if self._current_tariff is not None: return state = await self.async_get_last_state() if not state or state.state not in self._tariffs: self._current_tariff = self._tariffs[0] else: self._current_tariff = state.state @property def should_poll(self): """If entity should be polled.""" return False @property def name(self): """Return the name of the select input.""" return self._name @property def icon(self): """Return the icon to be used for this entity.""" return self._icon @property def state(self): """Return the state of the component.""" return self._current_tariff @property def state_attributes(self): """Return the state attributes.""" return {ATTR_TARIFFS: self._tariffs} async def async_reset_meters(self): """Reset all sensors of this meter.""" _LOGGER.debug("reset meter %s", self.entity_id) async_dispatcher_send(self.hass, SIGNAL_RESET_METER, self.entity_id) async def async_select_tariff(self, tariff): """Select new option.""" if tariff not in self._tariffs: _LOGGER.warning( "Invalid tariff: %s (possible tariffs: %s)", tariff, ", ".join(self._tariffs), ) return self._current_tariff = tariff await self.async_update_ha_state() async def async_next_tariff(self): """Offset current index.""" current_index = self._tariffs.index(self._current_tariff) new_index = (current_index + 1) % len(self._tariffs) self._current_tariff = self._tariffs[new_index] await self.async_update_ha_state()
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/utility_meter/__init__.py
"""Support for Ombi.""" from datetime import timedelta import logging from pyombi import OmbiError from homeassistant.helpers.entity import Entity from .const import DOMAIN, SENSOR_TYPES _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=60) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Ombi sensor platform.""" if discovery_info is None: return sensors = [] ombi = hass.data[DOMAIN]["instance"] for sensor in SENSOR_TYPES: sensor_label = sensor sensor_type = SENSOR_TYPES[sensor]["type"] sensor_icon = SENSOR_TYPES[sensor]["icon"] sensors.append(OmbiSensor(sensor_label, sensor_type, ombi, sensor_icon)) add_entities(sensors, True) class OmbiSensor(Entity): """Representation of an Ombi sensor.""" def __init__(self, label, sensor_type, ombi, icon): """Initialize the sensor.""" self._state = None self._label = label self._type = sensor_type self._ombi = ombi self._icon = icon @property def name(self): """Return the name of the sensor.""" return f"Ombi {self._type}" @property def icon(self): """Return the icon to use in the frontend.""" return self._icon @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Update the sensor.""" try: if self._label == "movies": self._state = self._ombi.movie_requests elif self._label == "tv": self._state = self._ombi.tv_requests elif self._label == "music": self._state = self._ombi.music_requests elif self._label == "pending": self._state = self._ombi.total_requests["pending"] elif self._label == "approved": self._state = self._ombi.total_requests["approved"] elif self._label == "available": self._state = self._ombi.total_requests["available"] except OmbiError as err: _LOGGER.warning("Unable to update Ombi sensor: %s", err) self._state = None
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/ombi/sensor.py
"""Util for Conversation.""" import re def create_matcher(utterance): """Create a regex that matches the utterance.""" # Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL # Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name} parts = re.split(r"({\w+}|\[[\w\s]+\] *)", utterance) # Pattern to extract name from GROUP part. Matches {name} group_matcher = re.compile(r"{(\w+)}") # Pattern to extract text from OPTIONAL part. Matches [the color] optional_matcher = re.compile(r"\[([\w ]+)\] *") pattern = ["^"] for part in parts: group_match = group_matcher.match(part) optional_match = optional_matcher.match(part) # Normal part if group_match is None and optional_match is None: pattern.append(part) continue # Group part if group_match is not None: pattern.append(r"(?P<{}>[\w ]+?)\s*".format(group_match.groups()[0])) # Optional part elif optional_match is not None: pattern.append(r"(?:{} *)?".format(optional_match.groups()[0])) pattern.append("$") return re.compile("".join(pattern), re.I)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/conversation/util.py
"""Support for Repetier-Server sensors.""" from datetime import timedelta import logging import pyrepetier import voluptuous as vol from homeassistant.const import ( CONF_API_KEY, CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_PORT, CONF_SENSORS, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.event import track_time_interval from homeassistant.util import slugify as util_slugify _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "RepetierServer" DOMAIN = "repetier" REPETIER_API = "repetier_api" SCAN_INTERVAL = timedelta(seconds=10) UPDATE_SIGNAL = "repetier_update_signal" TEMP_DATA = {"tempset": "temp_set", "tempread": "state", "output": "output"} API_PRINTER_METHODS = { "bed_temperature": { "offline": {"heatedbeds": None, "state": "off"}, "state": {"heatedbeds": "temp_data"}, "temp_data": TEMP_DATA, "attribute": "heatedbeds", }, "extruder_temperature": { "offline": {"extruder": None, "state": "off"}, "state": {"extruder": "temp_data"}, "temp_data": TEMP_DATA, "attribute": "extruder", }, "chamber_temperature": { "offline": {"heatedchambers": None, "state": "off"}, "state": {"heatedchambers": "temp_data"}, "temp_data": TEMP_DATA, "attribute": "heatedchambers", }, "current_state": { "offline": {"state": None}, "state": { "state": "state", "activeextruder": "active_extruder", "hasxhome": "x_homed", "hasyhome": "y_homed", "haszhome": "z_homed", "firmware": "firmware", "firmwareurl": "firmware_url", }, }, "current_job": { "offline": {"job": None, "state": "off"}, "state": { "done": "state", "job": "job_name", "jobid": "job_id", "totallines": "total_lines", "linessent": "lines_sent", "oflayer": "total_layers", "layer": "current_layer", "speedmultiply": "feed_rate", "flowmultiply": "flow", "x": "x", "y": "y", "z": "z", }, }, "job_end": { "offline": {"job": None, "state": "off", "start": None, "printtime": None}, "state": { "job": "job_name", "start": "start", "printtime": "print_time", "printedtimecomp": "from_start", }, }, "job_start": { "offline": { "job": None, "state": "off", "start": None, "printedtimecomp": None, }, "state": {"job": "job_name", "start": "start", "printedtimecomp": "from_start"}, }, } def has_all_unique_names(value): """Validate that printers have an unique name.""" names = [util_slugify(printer[CONF_NAME]) for printer in value] vol.Schema(vol.Unique())(names) return value SENSOR_TYPES = { # Type, Unit, Icon, post "bed_temperature": ["temperature", TEMP_CELSIUS, "mdi:thermometer", "_bed_"], "extruder_temperature": [ "temperature", TEMP_CELSIUS, "mdi:thermometer", "_extruder_", ], "chamber_temperature": [ "temperature", TEMP_CELSIUS, "mdi:thermometer", "_chamber_", ], "current_state": ["state", None, "mdi:printer-3d", ""], "current_job": ["progress", "%", "mdi:file-percent", "_current_job"], "job_end": ["progress", None, "mdi:clock-end", "_job_end"], "job_start": ["progress", None, "mdi:clock-start", "_job_start"], } SENSOR_SCHEMA = vol.Schema( { vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( cv.ensure_list, [ vol.Schema( { vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=3344): cv.port, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA, } ) ], has_all_unique_names, ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up the Repetier Server component.""" hass.data[REPETIER_API] = {} for repetier in config[DOMAIN]: _LOGGER.debug("Repetier server config %s", repetier[CONF_HOST]) url = "http://{}".format(repetier[CONF_HOST]) port = repetier[CONF_PORT] api_key = repetier[CONF_API_KEY] client = pyrepetier.Repetier(url=url, port=port, apikey=api_key) printers = client.getprinters() if not printers: return False sensors = repetier[CONF_SENSORS][CONF_MONITORED_CONDITIONS] api = PrinterAPI(hass, client, printers, sensors, repetier[CONF_NAME], config) api.update() track_time_interval(hass, api.update, SCAN_INTERVAL) hass.data[REPETIER_API][repetier[CONF_NAME]] = api return True class PrinterAPI: """Handle the printer API.""" def __init__(self, hass, client, printers, sensors, conf_name, config): """Set up instance.""" self._hass = hass self._client = client self.printers = printers self.sensors = sensors self.conf_name = conf_name self.config = config self._known_entities = set() def get_data(self, printer_id, sensor_type, temp_id): """Get data from the state cache.""" printer = self.printers[printer_id] methods = API_PRINTER_METHODS[sensor_type] for prop, offline in methods["offline"].items(): state = getattr(printer, prop) if state == offline: # if state matches offline, sensor is offline return None data = {} for prop, attr in methods["state"].items(): prop_data = getattr(printer, prop) if attr == "temp_data": temp_methods = methods["temp_data"] for temp_prop, temp_attr in temp_methods.items(): data[temp_attr] = getattr(prop_data[temp_id], temp_prop) else: data[attr] = prop_data return data def update(self, now=None): """Update the state cache from the printer API.""" for printer in self.printers: printer.get_data() self._load_entities() dispatcher_send(self._hass, UPDATE_SIGNAL) def _load_entities(self): sensor_info = [] for pidx, printer in enumerate(self.printers): for sensor_type in self.sensors: info = {} info["sensor_type"] = sensor_type info["printer_id"] = pidx info["name"] = printer.slug info["printer_name"] = self.conf_name known = f"{printer.slug}-{sensor_type}" if known in self._known_entities: continue methods = API_PRINTER_METHODS[sensor_type] if "temp_data" in methods["state"].values(): prop_data = getattr(printer, methods["attribute"]) if prop_data is None: continue for idx, _ in enumerate(prop_data): prop_info = info.copy() prop_info["temp_id"] = idx sensor_info.append(prop_info) else: info["temp_id"] = None sensor_info.append(info) self._known_entities.add(known) if not sensor_info: return load_platform(self._hass, "sensor", DOMAIN, sensor_info, self.config)
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/repetier/__init__.py
"""Support for Ambient Weather Station binary sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.const import ATTR_NAME from . import ( SENSOR_TYPES, TYPE_BATT1, TYPE_BATT2, TYPE_BATT3, TYPE_BATT4, TYPE_BATT5, TYPE_BATT6, TYPE_BATT7, TYPE_BATT8, TYPE_BATT9, TYPE_BATT10, TYPE_BATTOUT, AmbientWeatherEntity, ) from .const import ( ATTR_LAST_DATA, ATTR_MONITORED_CONDITIONS, DATA_CLIENT, DOMAIN, TYPE_BINARY_SENSOR, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up Ambient PWS binary sensors based on a config entry.""" ambient = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] binary_sensor_list = [] for mac_address, station in ambient.stations.items(): for condition in station[ATTR_MONITORED_CONDITIONS]: name, _, kind, device_class = SENSOR_TYPES[condition] if kind == TYPE_BINARY_SENSOR: binary_sensor_list.append( AmbientWeatherBinarySensor( ambient, mac_address, station[ATTR_NAME], condition, name, device_class, ) ) async_add_entities(binary_sensor_list, True) class AmbientWeatherBinarySensor(AmbientWeatherEntity, BinarySensorDevice): """Define an Ambient binary sensor.""" @property def is_on(self): """Return the status of the sensor.""" if self._sensor_type in ( TYPE_BATT1, TYPE_BATT10, TYPE_BATT2, TYPE_BATT3, TYPE_BATT4, TYPE_BATT5, TYPE_BATT6, TYPE_BATT7, TYPE_BATT8, TYPE_BATT9, TYPE_BATTOUT, ): return self._state == 0 return self._state == 1 async def async_update(self): """Fetch new state data for the entity.""" self._state = self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get( self._sensor_type )
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/ambient_station/binary_sensor.py
"""Support for ESPHome covers.""" import logging from typing import Optional from aioesphomeapi import CoverInfo, CoverOperation, CoverState from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, CoverDevice, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome covers based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="cover", info_type=CoverInfo, entity_type=EsphomeCover, state_type=CoverState, ) class EsphomeCover(EsphomeEntity, CoverDevice): """A cover implementation for ESPHome.""" @property def _static_info(self) -> CoverInfo: return super()._static_info @property def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP if self._static_info.supports_position: flags |= SUPPORT_SET_POSITION if self._static_info.supports_tilt: flags |= SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION return flags @property def device_class(self) -> str: """Return the class of this device, from component DEVICE_CLASSES.""" return self._static_info.device_class @property def assumed_state(self) -> bool: """Return true if we do optimistic updates.""" return self._static_info.assumed_state @property def _state(self) -> Optional[CoverState]: return super()._state # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_closed(self) -> Optional[bool]: """Return if the cover is closed or not.""" # Check closed state with api version due to a protocol change return self._state.is_closed(self._client.api_version) @esphome_state_property def is_opening(self) -> bool: """Return if the cover is opening or not.""" return self._state.current_operation == CoverOperation.IS_OPENING @esphome_state_property def is_closing(self) -> bool: """Return if the cover is closing or not.""" return self._state.current_operation == CoverOperation.IS_CLOSING @esphome_state_property def current_cover_position(self) -> Optional[int]: """Return current position of cover. 0 is closed, 100 is open.""" if not self._static_info.supports_position: return None return round(self._state.position * 100.0) @esphome_state_property def current_cover_tilt_position(self) -> Optional[float]: """Return current position of cover tilt. 0 is closed, 100 is open.""" if not self._static_info.supports_tilt: return None return self._state.tilt * 100.0 async def async_open_cover(self, **kwargs) -> None: """Open the cover.""" await self._client.cover_command(key=self._static_info.key, position=1.0) async def async_close_cover(self, **kwargs) -> None: """Close cover.""" await self._client.cover_command(key=self._static_info.key, position=0.0) async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" await self._client.cover_command(key=self._static_info.key, stop=True) async def async_set_cover_position(self, **kwargs) -> None: """Move the cover to a specific position.""" await self._client.cover_command( key=self._static_info.key, position=kwargs[ATTR_POSITION] / 100 ) async def async_open_cover_tilt(self, **kwargs) -> None: """Open the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=1.0) async def async_close_cover_tilt(self, **kwargs) -> None: """Close the cover tilt.""" await self._client.cover_command(key=self._static_info.key, tilt=0.0) async def async_set_cover_tilt_position(self, **kwargs) -> None: """Move the cover tilt to a specific position.""" await self._client.cover_command( key=self._static_info.key, tilt=kwargs[ATTR_TILT_POSITION] / 100 )
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/esphome/cover.py
"""Support to graphs card in the UI.""" import logging import voluptuous as vol from homeassistant.const import ATTR_ENTITY_ID, CONF_ENTITIES, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent _LOGGER = logging.getLogger(__name__) DOMAIN = "history_graph" CONF_HOURS_TO_SHOW = "hours_to_show" CONF_REFRESH = "refresh" ATTR_HOURS_TO_SHOW = CONF_HOURS_TO_SHOW ATTR_REFRESH = CONF_REFRESH GRAPH_SCHEMA = vol.Schema( { vol.Required(CONF_ENTITIES): cv.entity_ids, vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_HOURS_TO_SHOW, default=24): vol.Range(min=1), vol.Optional(CONF_REFRESH, default=0): vol.Range(min=0), } ) CONFIG_SCHEMA = vol.Schema( {DOMAIN: cv.schema_with_slug_keys(GRAPH_SCHEMA)}, extra=vol.ALLOW_EXTRA ) async def async_setup(hass, config): """Load graph configurations.""" _LOGGER.warning( "The history_graph integration has been deprecated and is pending for removal " "in Home Assistant 0.107.0." ) component = EntityComponent(_LOGGER, DOMAIN, hass) graphs = [] for object_id, cfg in config[DOMAIN].items(): name = cfg.get(CONF_NAME, object_id) graph = HistoryGraphEntity(name, cfg) graphs.append(graph) await component.async_add_entities(graphs) return True class HistoryGraphEntity(Entity): """Representation of a graph entity.""" def __init__(self, name, cfg): """Initialize the graph.""" self._name = name self._hours = cfg[CONF_HOURS_TO_SHOW] self._refresh = cfg[CONF_REFRESH] self._entities = cfg[CONF_ENTITIES] @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the entity.""" return self._name @property def state_attributes(self): """Return the state attributes.""" attrs = { ATTR_HOURS_TO_SHOW: self._hours, ATTR_REFRESH: self._refresh, ATTR_ENTITY_ID: self._entities, } return attrs
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/history_graph/__init__.py
"""Provides device automations for Lock.""" from typing import List import voluptuous as vol from homeassistant.components.automation import AutomationActionType, state from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, STATE_LOCKED, STATE_UNLOCKED, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_TYPES = {"locked", "unlocked"} TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Lock devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue # Add triggers for each entity that belongs to this integration triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "locked", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "unlocked", } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "locked": from_state = STATE_UNLOCKED to_state = STATE_LOCKED else: from_state = STATE_LOCKED to_state = STATE_UNLOCKED state_config = { state.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state.CONF_FROM: from_state, state.CONF_TO: to_state, } state_config = state.TRIGGER_SCHEMA(state_config) return await state.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/lock/device_trigger.py
"""Sensor platform support for yeelight.""" import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import DATA_UPDATED, DATA_YEELIGHT _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Yeelight sensors.""" if not discovery_info: return device = hass.data[DATA_YEELIGHT][discovery_info["host"]] if device.is_nightlight_supported: _LOGGER.debug("Adding nightlight mode sensor for %s", device.name) add_entities([YeelightNightlightModeSensor(device)]) class YeelightNightlightModeSensor(BinarySensorDevice): """Representation of a Yeelight nightlight mode sensor.""" def __init__(self, device): """Initialize nightlight mode sensor.""" self._device = device @callback def _schedule_immediate_update(self): self.async_schedule_update_ha_state() async def async_added_to_hass(self): """Handle entity which will be added.""" async_dispatcher_connect( self.hass, DATA_UPDATED.format(self._device.ipaddr), self._schedule_immediate_update, ) @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the sensor.""" return f"{self._device.name} nightlight" @property def is_on(self): """Return true if nightlight mode is on.""" return self._device.is_nightlight_enabled
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/yeelight/binary_sensor.py
"""Provides device automations for Fan.""" from typing import List import voluptuous as vol from homeassistant.components.automation import AutomationActionType, state from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.const import ( CONF_DEVICE_ID, CONF_DOMAIN, CONF_ENTITY_ID, CONF_PLATFORM, CONF_TYPE, STATE_OFF, STATE_ON, ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant from homeassistant.helpers import config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType from . import DOMAIN TRIGGER_TYPES = {"turned_on", "turned_off"} TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(TRIGGER_TYPES), } ) async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Fan devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue # Add triggers for each entity that belongs to this integration triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_on", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turned_off", } ) return triggers async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "turned_on": from_state = STATE_OFF to_state = STATE_ON else: from_state = STATE_ON to_state = STATE_OFF state_config = { state.CONF_PLATFORM: "state", CONF_ENTITY_ID: config[CONF_ENTITY_ID], state.CONF_FROM: from_state, state.CONF_TO: to_state, } state_config = state.TRIGGER_SCHEMA(state_config) return await state.async_attach_trigger( hass, state_config, action, automation_info, platform_type="device" )
"""Tests for the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/fan/device_trigger.py
"""Support for interacting with Vultr subscriptions.""" import logging import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice 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(SwitchDevice): """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 the Linky config flow.""" from unittest.mock import Mock, patch from pylinky.exceptions import ( PyLinkyAccessException, PyLinkyEnedisException, PyLinkyException, PyLinkyWrongLoginException, ) import pytest from homeassistant import data_entry_flow from homeassistant.components.linky.const import DEFAULT_TIMEOUT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.helpers.typing import HomeAssistantType from tests.common import MockConfigEntry USERNAME = "username@hotmail.fr" USERNAME_2 = "username@free.fr" PASSWORD = "password" TIMEOUT = 20 @pytest.fixture(name="login") def mock_controller_login(): """Mock a successful login.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.login = Mock(return_value=True) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock @pytest.fixture(name="fetch_data") def mock_controller_fetch_data(): """Mock a successful get data.""" with patch( "homeassistant.components.linky.config_flow.LinkyClient" ) as service_mock: service_mock.return_value.fetch_data = Mock(return_value={}) service_mock.return_value.close_session = Mock(return_value=None) yield service_mock async def test_user(hass: HomeAssistantType, login, fetch_data): """Test user config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" # test with all provided result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT async def test_import(hass: HomeAssistantType, login, fetch_data): """Test import step.""" # import with username and password result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME assert result["title"] == USERNAME assert result["data"][CONF_USERNAME] == USERNAME assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == DEFAULT_TIMEOUT # import with all result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: USERNAME_2, CONF_PASSWORD: PASSWORD, CONF_TIMEOUT: TIMEOUT, }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["result"].unique_id == USERNAME_2 assert result["title"] == USERNAME_2 assert result["data"][CONF_USERNAME] == USERNAME_2 assert result["data"][CONF_PASSWORD] == PASSWORD assert result["data"][CONF_TIMEOUT] == TIMEOUT async def test_abort_if_already_setup(hass: HomeAssistantType, login, fetch_data): """Test we abort if Linky is already setup.""" MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, unique_id=USERNAME, ).add_to_hass(hass) # Should fail, same USERNAME (import) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" # Should fail, same USERNAME (flow) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_login_failed(hass: HomeAssistantType, login): """Test when we have errors during login.""" login.return_value.login.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.login.side_effect = PyLinkyWrongLoginException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "wrong_login"} hass.config_entries.flow.async_abort(result["flow_id"]) async def test_fetch_failed(hass: HomeAssistantType, login): """Test when we have errors during fetch.""" login.return_value.fetch_data.side_effect = PyLinkyAccessException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "access"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyEnedisException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "enedis"} hass.config_entries.flow.async_abort(result["flow_id"]) login.return_value.fetch_data.side_effect = PyLinkyException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "unknown"} hass.config_entries.flow.async_abort(result["flow_id"])
Teagan42/home-assistant
tests/components/linky/test_config_flow.py
homeassistant/components/vultr/switch.py
# -*- coding: utf-8 -*- """ Created on Wed Apr 3 13:16:47 2013 @author: Petr Hracek """ import os from gi.repository import Gtk from devassistant.config_manager import config_manager from devassistant import utils class PathWindow(object): """ Class shows option dialogs and checks settings for each assistant """ def __init__(self, parent, main_window, builder, gui_helper): self.parent = parent self.main_window = main_window self.path_window = builder.get_object("pathWindow") self.dir_name = builder.get_object("dirName") self.dir_name_browse_btn = builder.get_object("browsePathBtn") self.entry_project_name = builder.get_object("entryProjectName") self.builder = builder self.gui_helper = gui_helper self.box_path_main = builder.get_object("boxPathMain") self.box_project = builder.get_object("boxProject") self.box6 = builder.get_object("box6") self.run_btn = builder.get_object("nextPathBtn") self.args = dict() self.grid = self.gui_helper.create_gtk_grid(row_spacing=0, col_homogenous=False, row_homogenous=False) self.title = self.gui_helper.create_label("Available options:") self.title.set_alignment(0, 0) self.box_path_main.pack_start(self.title, False, False, 0) self.box_path_main.pack_start(self.grid, False, False, 0) self.kwargs = dict() self.label_caption = self.builder.get_object("labelCaption") self.label_prj_name = self.builder.get_object("labelPrjName") self.label_prj_dir = self.builder.get_object("labelPrjDir") self.label_full_prj_dir = self.builder.get_object("labelFullPrjDir") self.h_separator = self.builder.get_object("hseparator") self.top_assistant = None self.project_name_shown = True self.current_main_assistant = None self.data = dict() def arg_is_selected(self, arg_dict): if arg_dict['arg'].kwargs.get('required'): return True else: return arg_dict['checkbox'].get_active() def check_for_directory(self, dirname): """ Function checks the directory and report it to user """ return self.gui_helper.execute_dialog( "Directory {0} already exists".format( dirname)) def get_full_dir_name(self): """ Function returns a full dir name """ return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text()) def next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """ # check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve argument value if it is needed to be preserved for arg_dict in [x for x in self.args.values() if 'preserved' in x['arg'].kwargs]: preserve_key = arg_dict['arg'].kwargs['preserved'] # preserve entry text (string value) if 'entry' in arg_dict: if self.arg_is_selected(arg_dict): config_manager.set_config_value(preserve_key, arg_dict['entry'].get_text()) # preserve if checkbox is ticked (boolean value) else: config_manager.set_config_value(preserve_key, self.arg_is_selected(arg_dict)) # save configuration into file config_manager.save_configuration_file() # get project directory and name project_dir = self.dir_name.get_text() full_name = self.get_full_dir_name() # check whether project directory and name is properly set if not deps_only and self.current_main_assistant.name == 'crt': if project_dir == "": return self.gui_helper.execute_dialog("Specify directory for project") else: # check whether directory is existing if not os.path.isdir(project_dir): response = self.gui_helper.create_question_dialog( "Directory {0} does not exists".format(project_dir), "Do you want to create them?" ) if response == Gtk.ResponseType.NO: # User do not want to create a directory return else: # Create directory try: os.makedirs(project_dir) except OSError as os_err: return self.gui_helper.execute_dialog("{0}".format(os_err)) elif os.path.isdir(full_name): return self.check_for_directory(full_name) if not self._build_flags(): return if not deps_only and self.current_main_assistant.name == 'crt': self.kwargs['name'] = full_name self.kwargs['__ui__'] = 'gui_gtk+' self.data['kwargs'] = self.kwargs self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.current_main_assistant self.parent.run_window.open_window(widget, self.data) self.path_window.hide() def _build_flags(self): """ Function builds kwargs variable for run_window """ # Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_text(): self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label'])) return False # Check for active CheckButtons for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'entry' in arg_dict: self.kwargs[arg_name] = arg_dict['entry'].get_text() else: if arg_dict['arg'].get_gui_hint('type') == 'const': self.kwargs[arg_name] = arg_dict['arg'].kwargs['const'] else: self.kwargs[arg_name] = True # Check for non active CheckButtons but with defaults flag for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'default' in arg_dict['arg'].kwargs: self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default') elif arg_name in self.kwargs: del self.kwargs[arg_name] return True def _remove_widget_items(self): """ Function removes widgets from grid """ for btn in self.grid: self.grid.remove(btn) def get_default_project_dir(self): """Returns a project directory to prefill in GUI. It is either stored value or current directory (if exists) or home directory. """ ret = config_manager.get_config_value('da.project_dir') return ret or utils.get_cwd_or_homedir() def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.kwargs = data.get('kwargs', None) self.data['debugging'] = data.get('debugging', False) project_dir = self.get_default_project_dir() self.dir_name.set_text(project_dir) self.label_full_prj_dir.set_text(project_dir) self.dir_name.set_sensitive(True) self.dir_name_browse_btn.set_sensitive(True) self._remove_widget_items() if self.current_main_assistant.name != 'crt' and self.project_name_shown: self.box6.remove(self.box_project) self.project_name_shown = False elif self.current_main_assistant.name == 'crt' and not self.project_name_shown: self.box6.remove(self.box_path_main) self.box6.pack_start(self.box_project, False, False, 0) self.box6.pack_end(self.box_path_main, False, False, 0) self.project_name_shown = True caption_text = "Project: " row = 0 # get selectected assistants, but without TopAssistant itself path = self.top_assistant.get_selected_subassistant_path(**self.kwargs)[1:] caption_parts = [] # Finds any dependencies found_deps = [x for x in path if x.dependencies()] # This bool variable is used for showing text "Available options:" any_options = False for assistant in path: caption_parts.append("<b>" + assistant.fullname + "</b>") for arg in sorted([x for x in assistant.args if not '--name' in x.flags], key=lambda y: y.flags): if not (arg.name == "deps_only" and not found_deps): row = self._add_table_row(arg, len(arg.flags) - 1, row) + 1 any_options = True if not any_options: self.title.set_text("") else: self.title.set_text("Available options:") caption_text += ' -> '.join(caption_parts) self.label_caption.set_markup(caption_text) self.path_window.show_all() self.entry_project_name.set_text(os.path.basename(self.kwargs.get('name', ''))) self.entry_project_name.set_sensitive(True) self.run_btn.set_sensitive(not self.project_name_shown or self.entry_project_name.get_text() != "") if 'name' in self.kwargs: self.dir_name.set_text(os.path.dirname(self.kwargs.get('name', ''))) for arg_name, arg_dict in [(k, v) for (k, v) in self.args.items() if self.kwargs.get(k)]: if 'checkbox' in arg_dict: arg_dict['checkbox'].set_active(True) if 'entry' in arg_dict: arg_dict['entry'].set_sensitive(True) arg_dict['entry'].set_text(self.kwargs[arg_name]) if 'browse_btn' in arg_dict: arg_dict['browse_btn'].set_sensitive(True) def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all() def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """ active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.set_sensitive(not active) self.run_btn.set_sensitive(active or not self.project_name_shown or self.entry_project_name.get_text() != "") def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data) def get_data(self): """ Function returns project dirname and project name """ return self.dir_name.get_text(), self.entry_project_name.get_text() def browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """ text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(text) def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gui_helper.create_alignment() if arg.kwargs.get('required'): # If argument is required then red star instead of checkbox star_label = self.gui_helper.create_label('<span color="#FF0000">*</span>') star_label.set_padding(0, 3) label = self.gui_helper.create_label(check_box_title) box = self.gui_helper.create_box() box.pack_start(star_label, False, False, 6) box.pack_start(label, False, False, 6) align.add(box) else: chbox = self.gui_helper.create_checkbox(check_box_title) chbox.set_alignment(0, 0) if arg.name == "deps_only": chbox.connect("clicked", self._deps_only_toggled) else: chbox.connect("clicked", self._check_box_toggled, arg.name) align.add(chbox) self.args[arg.name]['checkbox'] = chbox if row == 0: self.grid.add(align) else: self.grid.attach(align, 0, row, 1, 1) label = self.gui_helper.create_label(arg.kwargs['help'], justify=Gtk.Justification.LEFT) label.set_alignment(0, 0) label.set_padding(0, 3) self.grid.attach(label, 1, row, 1, 1) label_check_box = self.gui_helper.create_label(name="") self.grid.attach(label_check_box, 0, row, 1, 1) if arg.get_gui_hint('type') not in ['bool', 'const']: new_box = self.gui_helper.create_box(spacing=6) entry = self.gui_helper.create_entry(text="") align = self.gui_helper.create_alignment() align.add(entry) new_box.pack_start(align, False, False, 6) align_btn = self.gui_helper.create_alignment() ''' If a button is needed please add there and in function _check_box_toggled Also do not forget to create a function for that button This can not be done by any automatic tool from those reasons Some fields needs a input user like user name for GitHub and some fields needs to have interaction from user like selecting directory ''' entry.set_text(arg.get_gui_hint('default')) entry.set_sensitive(arg.kwargs.get('required') == True) if arg.get_gui_hint('type') == 'path': browse_btn = self.gui_helper.button_with_label("Browse") browse_btn.connect("clicked", self.browse_clicked, entry) browse_btn.set_sensitive(arg.kwargs.get('required') == True) align_btn.add(browse_btn) self.args[arg.name]['browse_btn'] = browse_btn elif arg.get_gui_hint('type') == 'str': if arg.name == 'github' or arg.name == 'github-login': link_button = self.gui_helper.create_link_button(text="For registration visit GitHub Homepage", uri="https://www.github.com") align_btn.add(link_button) new_box.pack_start(align_btn, False, False, 6) row += 1 self.args[arg.name]['entry'] = entry self.grid.attach(new_box, 1, row, 1, 1) else: if 'preserved' in arg.kwargs and config_manager.get_config_value(arg.kwargs['preserved']): if 'checkbox' in self.args[arg.name]: self.args[arg.name]['checkbox'].set_active(True) return row def browse_clicked(self, widget, data=None): """ Function sets the directory to entry """ text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(text) def update_full_label(self): """ Function is used for updating whole path of project """ self.label_full_prj_dir.set_text(self.get_full_dir_name()) def project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """ if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label() def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in configuration manager """ config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
import pytest import os from devassistant import utils class TestFindFileInLoadDirs(object): fixtures = os.path.join(os.path.dirname(__file__), 'fixtures') def test_find_ok(self): assert utils.find_file_in_load_dirs('files/jinja_template.py') == \ os.path.join(self.fixtures, 'files', 'jinja_template.py') def test_find_not_there(self): assert utils.find_file_in_load_dirs('files/does_not_exist') is None class TestStripPrefix(object): @pytest.mark.parametrize(('inp', 'prefix', 'out'), [ ('foobar', 'foo', 'bar'), ('foobar', 'bar', 'foobar'), ('foobar', 'foobar', ''), ('foo', 'foobar', 'foo'), ('foo', str(1), 'foo'), # Should not strip regex ('foobar', 'foo|bar', 'foobar'), ('foobar', '[fo]*', 'foobar'), ('foobar', '.*', 'foobar'), ('foobar', 'fo.', 'foobar'), ]) def test_strip_noregex(self, inp, prefix, out): assert utils.strip_prefix(inp, prefix) == out @pytest.mark.parametrize(('inp', 'prefix', 'out'), [ ('foobar', 'foo|bar', 'bar'), ('foobar', '[fo]*', 'bar'), ('foobar', '.*', ''), ('foobar', 'fo.', 'bar'), ]) def test_strip_regex(self, inp, prefix, out): assert utils.strip_prefix(inp, prefix, regex=True) == out @pytest.mark.parametrize(('inp', 'prefix'), [ (1, 'foo'), (object(), object()), ('foo', None) ]) def test_fails(self, inp, prefix): with pytest.raises(TypeError) as e: utils.strip_prefix(inp, prefix) class TestStripSuffix(object): @pytest.mark.parametrize(('inp', 'suffix', 'out'), [ ('foobar', 'bar', 'foo'), ('foobar', 'r', 'fooba'), ('foobar', 'foobar', ''), ('foo', 'foobar', 'foo'), ('foo', str(1), 'foo'), # Should not strip regex ('foobar', 'foo|bar', 'foobar'), ('foobar', '[ar]*', 'foobar'), ('foobar', '.*', 'foobar'), ('foobar', '.bar', 'foobar'), ]) def test_strip_noregex(self, inp, suffix, out): assert utils.strip_suffix(inp, suffix) == out @pytest.mark.parametrize(('inp', 'prefix', 'out'), [ ('foobar', 'foo|bar', 'foo'), ('foobar', '[ar]*', 'foob'), ('foobar', '.*', ''), ('foobar', '.bar', 'fo'), ]) def test_strip_regex(self, inp, prefix, out): assert utils.strip_suffix(inp, prefix, regex=True) == out @pytest.mark.parametrize(('inp', 'suffix'), [ (1, 'foo'), (object(), object()), ('foo', None) ]) def test_fails(self, inp, suffix): with pytest.raises(TypeError) as e: utils.strip_suffix(inp, suffix)
bkabrda/devassistant
test/test_utils.py
devassistant/gui/path_window.py
from serializer import serialize from parser import parse from backends.static import compile as compile_static from backends.conditional import compile as compile_condition
import unittest import StringIO import pytest from .. import metadata, manifestupdate from mozlog import structuredlog, handlers, formatters class TestExpectedUpdater(unittest.TestCase): def create_manifest(self, data, test_path="path/to/test.ini"): f = StringIO.StringIO(data) return manifestupdate.compile(f, test_path) def create_updater(self, data, **kwargs): expected_tree = {} id_path_map = {} for test_path, test_ids, manifest_str in data: if isinstance(test_ids, (str, unicode)): test_ids = [test_ids] expected_tree[test_path] = self.create_manifest(manifest_str, test_path) for test_id in test_ids: id_path_map[test_id] = test_path return metadata.ExpectedUpdater(expected_tree, id_path_map, **kwargs) def create_log(self, *args, **kwargs): logger = structuredlog.StructuredLogger("expected_test") data = StringIO.StringIO() handler = handlers.StreamHandler(data, formatters.JSONFormatter()) logger.add_handler(handler) log_entries = ([("suite_start", {"tests": [], "run_info": kwargs.get("run_info", {})})] + list(args) + [("suite_end", {})]) for item in log_entries: action, kwargs = item getattr(logger, action)(**kwargs) logger.remove_handler(handler) data.seek(0) return data def coalesce_results(self, trees): for tree in trees: for test in tree.iterchildren(): for subtest in test.iterchildren(): subtest.coalesce_expected() test.coalesce_expected() @pytest.mark.xfail def test_update_0(self): prev_data = [("path/to/test.htm.ini", ["/path/to/test.htm"], """[test.htm] type: testharness [test1] expected: FAIL""")] new_data = self.create_log(("test_start", {"test": "/path/to/test.htm"}), ("test_status", {"test": "/path/to/test.htm", "subtest": "test1", "status": "PASS", "expected": "FAIL"}), ("test_end", {"test": "/path/to/test.htm", "status": "OK"})) updater = self.create_updater(prev_data) updater.update_from_log(new_data) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertTrue(new_manifest.is_empty) @pytest.mark.xfail def test_update_1(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: ERROR""")] new_data = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "ERROR"}), ("test_end", {"test": test_id, "status": "OK"})) updater = self.create_updater(prev_data) updater.update_from_log(new_data) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get("expected"), "FAIL") @pytest.mark.xfail def test_new_subtest(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: FAIL""")] new_data = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "FAIL"}), ("test_status", {"test": test_id, "subtest": "test2", "status": "FAIL", "expected": "PASS"}), ("test_end", {"test": test_id, "status": "OK"})) updater = self.create_updater(prev_data) updater.update_from_log(new_data) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get("expected"), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[1].get("expected"), "FAIL") @pytest.mark.xfail def test_update_multiple_0(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: FAIL""")] new_data_0 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "osx"}) new_data_1 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "TIMEOUT", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "linux"}) updater = self.create_updater(prev_data) updater.update_from_log(new_data_0) updater.update_from_log(new_data_1) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "osx"}), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "linux"}), "TIMEOUT") @pytest.mark.xfail def test_update_multiple_1(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: FAIL""")] new_data_0 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "osx"}) new_data_1 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "TIMEOUT", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "linux"}) updater = self.create_updater(prev_data) updater.update_from_log(new_data_0) updater.update_from_log(new_data_1) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "osx"}), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "linux"}), "TIMEOUT") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "windows"}), "FAIL") @pytest.mark.xfail def test_update_multiple_2(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: FAIL""")] new_data_0 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "osx"}) new_data_1 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "TIMEOUT", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": True, "os": "osx"}) updater = self.create_updater(prev_data) updater.update_from_log(new_data_0) updater.update_from_log(new_data_1) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "osx"}), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": True, "os": "osx"}), "TIMEOUT") @pytest.mark.xfail def test_update_multiple_3(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: if debug: FAIL if not debug and os == "osx": TIMEOUT""")] new_data_0 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "osx"}) new_data_1 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "TIMEOUT", "expected": "FAIL"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": True, "os": "osx"}) updater = self.create_updater(prev_data) updater.update_from_log(new_data_0) updater.update_from_log(new_data_1) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "osx"}), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": True, "os": "osx"}), "TIMEOUT") @pytest.mark.xfail def test_update_ignore_existing(self): test_id = "/path/to/test.htm" prev_data = [("path/to/test.htm.ini", [test_id], """[test.htm] type: testharness [test1] expected: if debug: TIMEOUT if not debug and os == "osx": NOTRUN""")] new_data_0 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "PASS"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": False, "os": "linux"}) new_data_1 = self.create_log(("test_start", {"test": test_id}), ("test_status", {"test": test_id, "subtest": "test1", "status": "FAIL", "expected": "PASS"}), ("test_end", {"test": test_id, "status": "OK"}), run_info={"debug": True, "os": "windows"}) updater = self.create_updater(prev_data, ignore_existing=True) updater.update_from_log(new_data_0) updater.update_from_log(new_data_1) new_manifest = updater.expected_tree["path/to/test.htm.ini"] self.coalesce_results([new_manifest]) self.assertFalse(new_manifest.is_empty) self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": True, "os": "osx"}), "FAIL") self.assertEquals(new_manifest.get_test(test_id).children[0].get( "expected", {"debug": False, "os": "osx"}), "FAIL")
Permutatrix/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/test_update.py
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptmanifest/__init__.py
from __future__ import absolute_import, division, print_function import pandas as pd import datashape from datashape import discover from ..append import append from ..convert import convert, ooc_types from ..chunks import chunks, Chunks from ..resource import resource HDFDataset = (pd.io.pytables.AppendableFrameTable, pd.io.pytables.FrameFixed) @discover.register(pd.HDFStore) def discover_hdfstore(f): d = dict() for key in f.keys(): d2 = d key2 = key.lstrip('/') while '/' in key2: group, key2 = key2.split('/', 1) if group not in d2: d2[group] = dict() d2 = d2[group] d2[key2] = f.get_storer(key) return discover(d) @discover.register(pd.io.pytables.Fixed) def discover_hdfstore_storer(storer): f = storer.parent n = storer.shape if isinstance(n, list): n = n[0] measure = discover(f.select(storer.pathname, start=0, stop=10)).measure return n * measure @convert.register(chunks(pd.DataFrame), pd.io.pytables.AppendableFrameTable) def hdfstore_to_chunks_dataframes(data, chunksize=1000000, **kwargs): return chunks(pd.DataFrame)(data.parent.select(data.pathname, chunksize=chunksize)) @convert.register(pd.DataFrame, (pd.io.pytables.AppendableFrameTable, pd.io.pytables.FrameFixed)) def hdfstore_to_chunks_dataframes(data, **kwargs): return data.read() from collections import namedtuple EmptyHDFStoreDataset = namedtuple('EmptyHDFStoreDataset', 'parent,pathname,dshape') @resource.register('hdfstore://.+', priority=11) def resource_hdfstore(uri, datapath=None, dshape=None, **kwargs): # TODO: # 1. Support nested datashapes (e.g. groups) # 2. Try translating unicode to ascii? (PyTables fails here) fn = uri.split('://')[1] f = pd.HDFStore(fn) if dshape is None: if datapath: return f.get_storer(datapath) else: return f dshape = datashape.dshape(dshape) # Already exists, return it if datapath in f: return f.get_storer(datapath) # Need to create new datast. # HDFStore doesn't support empty datasets, so we use a proxy object. return EmptyHDFStoreDataset(f, datapath, dshape) @append.register((pd.io.pytables.Fixed, EmptyHDFStoreDataset), pd.DataFrame) def append_dataframe_to_hdfstore(store, df, **kwargs): store.parent.append(store.pathname, df, append=True) return store.parent.get_storer(store.pathname) @append.register((pd.io.pytables.Fixed, EmptyHDFStoreDataset), chunks(pd.DataFrame)) def append_chunks_dataframe_to_hdfstore(store, c, **kwargs): parent = store.parent for chunk in c: parent.append(store.pathname, chunk) return parent.get_storer(store.pathname) @append.register((pd.io.pytables.Fixed, EmptyHDFStoreDataset), object) def append_object_to_hdfstore(store, o, **kwargs): return append(store, convert(chunks(pd.DataFrame), o, **kwargs), **kwargs) ooc_types |= set(HDFDataset)
from __future__ import absolute_import, division, print_function import pytest import os import numpy as np import sqlalchemy as sa from datashape import discover, dshape import datashape from into.backends.sql import (dshape_to_table, create_from_datashape, dshape_to_alchemy) from into.utils import tmpfile, raises from into import convert, append, resource, discover, into def test_resource(): sql = resource('sqlite:///:memory:::mytable', dshape='var * {x: int, y: int}') assert isinstance(sql, sa.Table) assert sql.name == 'mytable' assert isinstance(sql.bind, sa.engine.base.Engine) assert set([c.name for c in sql.c]) == set(['x', 'y']) def test_append_and_convert_round_trip(): engine = sa.create_engine('sqlite:///:memory:') metadata = sa.MetaData(engine) t = sa.Table('bank', metadata, sa.Column('name', sa.String, primary_key=True), sa.Column('balance', sa.Integer)) t.create() data = [('Alice', 1), ('Bob', 2)] append(t, data) assert convert(list, t) == data def test_plus_must_have_text(): with pytest.raises(NotImplementedError): resource('redshift+://user:pass@host:1234/db') def test_resource_on_file(): with tmpfile('.db') as fn: uri = 'sqlite:///' + fn sql = resource(uri, 'foo', dshape='var * {x: int, y: int}') assert isinstance(sql, sa.Table) with tmpfile('.db') as fn: uri = 'sqlite:///' + fn sql = resource(uri + '::' + 'foo', dshape='var * {x: int, y: int}') assert isinstance(sql, sa.Table) def test_resource_to_engine(): with tmpfile('.db') as fn: uri = 'sqlite:///' + fn r = resource(uri) assert isinstance(r, sa.engine.Engine) assert r.dialect.name == 'sqlite' def test_resource_to_engine_to_create_tables(): with tmpfile('.db') as fn: uri = 'sqlite:///' + fn ds = datashape.dshape('{mytable: var * {name: string, amt: int}}') r = resource(uri, dshape=ds) assert isinstance(r, sa.engine.Engine) assert r.dialect.name == 'sqlite' assert discover(r) == ds def test_discovery(): assert discover(sa.String()) == datashape.string metadata = sa.MetaData() s = sa.Table('accounts', metadata, sa.Column('name', sa.String), sa.Column('amount', sa.Integer), sa.Column('timestamp', sa.DateTime, primary_key=True)) assert discover(s) == \ dshape('var * {name: ?string, amount: ?int32, timestamp: datetime}') def test_discovery_numeric_column(): assert discover(sa.String()) == datashape.string metadata = sa.MetaData() s = sa.Table('name', metadata, sa.Column('name', sa.types.NUMERIC),) assert discover(s) def test_discover_null_columns(): assert dshape(discover(sa.Column('name', sa.String, nullable=True))) == \ dshape('{name: ?string}') assert dshape(discover(sa.Column('name', sa.String, nullable=False))) == \ dshape('{name: string}') def single_table_engine(): engine = sa.create_engine('sqlite:///:memory:') metadata = sa.MetaData(engine) t = sa.Table('accounts', metadata, sa.Column('name', sa.String), sa.Column('amount', sa.Integer)) t.create() return engine, t def test_select_to_iterator(): engine, t = single_table_engine() append(t, [('Alice', 100), ('Bob', 200)]) sel = sa.select([t.c.amount + 1]) assert convert(list, sel) == [(101,), (201,)] assert convert(list, sel, dshape=dshape('var * int')) == [101, 201] sel2 = sa.select([sa.sql.func.sum(t.c.amount)]) assert convert(int, sel2, dshape=dshape('int')) == 300 sel3 = sa.select([t]) result = convert(list, sel3, dshape=discover(t)) assert type(result[0]) is tuple def test_discovery_engine(): engine, t = single_table_engine() assert discover(engine, 'accounts') == discover(t) assert str(discover(engine)) == str(discover({'accounts': t})) def test_discovery_metadata(): engine, t = single_table_engine() metadata = t.metadata assert str(discover(metadata)) == str(discover({'accounts': t})) def test_discover_views(): engine, t = single_table_engine() metadata = t.metadata with engine.connect() as conn: conn.execute('''CREATE VIEW myview AS SELECT name, amount FROM accounts WHERE amount > 0''') assert str(discover(metadata)) == str(discover({'accounts': t, 'myview': t})) def test_extend_empty(): engine, t = single_table_engine() assert not convert(list, t) append(t, []) assert not convert(list, t) def test_dshape_to_alchemy(): assert dshape_to_alchemy('string') == sa.Text assert isinstance(dshape_to_alchemy('string[40]'), sa.String) assert not isinstance(dshape_to_alchemy('string["ascii"]'), sa.Unicode) assert isinstance(dshape_to_alchemy('string[40, "U8"]'), sa.Unicode) assert dshape_to_alchemy('string[40]').length == 40 assert dshape_to_alchemy('float32').precision == 24 assert dshape_to_alchemy('float64').precision == 53 def test_dshape_to_table(): t = dshape_to_table('bank', '{name: string, amount: int}') assert isinstance(t, sa.Table) assert t.name == 'bank' assert [c.name for c in t.c] == ['name', 'amount'] def test_create_from_datashape(): engine = sa.create_engine('sqlite:///:memory:') ds = dshape('''{bank: var * {name: string, amount: int}, points: var * {x: int, y: int}}''') engine = create_from_datashape(engine, ds) assert discover(engine) == ds def test_into_table_iterator(): engine = sa.create_engine('sqlite:///:memory:') metadata = sa.MetaData(engine) t = dshape_to_table('points', '{x: int, y: int}', metadata=metadata) t.create() data = [(1, 1), (2, 4), (3, 9)] append(t, data) assert convert(list, t) == data t2 = dshape_to_table('points2', '{x: int, y: int}', metadata=metadata) t2.create() data2 = [{'x': 1, 'y': 1}, {'x': 2, 'y': 4}, {'x': 3, 'y': 9}] append(t2, data2) assert convert(list, t2) == data def test_sql_field_names_disagree_on_order(): r = resource('sqlite:///:memory:::tb', dshape=dshape('{x: int, y: int}')) append(r, [(1, 2), (10, 20)], dshape=dshape('{y: int, x: int}')) assert convert(set, r) == set([(2, 1), (20, 10)]) def test_sql_field_names_disagree_on_names(): r = resource('sqlite:///:memory:::tb', dshape=dshape('{x: int, y: int}')) assert raises(Exception, lambda: append(r, [(1, 2), (10, 20)], dshape=dshape('{x: int, z: int}'))) def test_resource_on_dialects(): assert (resource.dispatch('mysql://foo') is resource.dispatch('mysql+pymysql://foo')) assert (resource.dispatch('never-before-seen-sql://foo') is resource.dispatch('mysql://foo')) @pytest.yield_fixture def sqlite_file(): try: yield 'sqlite:///db.db' finally: os.remove('db.db') def test_append_from_select(sqlite_file): # we can't test in memory here because that creates two independent # databases raw = np.array([(200.0, 'Glenn'), (314.14, 'Hope'), (235.43, 'Bob')], dtype=[('amount', 'float64'), ('name', 'S5')]) raw2 = np.array([(800.0, 'Joe'), (914.14, 'Alice'), (1235.43, 'Ratso')], dtype=[('amount', 'float64'), ('name', 'S5')]) t = into('%s::t' % sqlite_file, raw) s = into('%s::s' % sqlite_file, raw2) t = append(t, s.select()) result = into(list, t) expected = np.concatenate((raw, raw2)).tolist() assert result == expected def test_engine_metadata_caching(): with tmpfile('db') as fn: engine = resource('sqlite:///' + fn) a = resource('sqlite:///' + fn + '::a', dshape=dshape('var * {x: int}')) b = resource('sqlite:///' + fn + '::b', dshape=dshape('var * {y: int}')) assert a.metadata is b.metadata assert engine is a.bind is b.bind
mrocklin/into
into/backends/tests/test_sql.py
into/backends/hdfstore.py
""" Various kinds of button widgets. """ from __future__ import absolute_import import warnings from ...core.properties import abstract, HasProps from ...core.properties import Bool, Int, String, Enum, Instance, List, Tuple, Override from ...core.enums import ButtonType from ..callbacks import Callback from .widget import Widget from .icons import AbstractIcon @abstract class ButtonLike(HasProps): """ Shared properties for button-like widgets. """ button_type = Enum(ButtonType, help=""" A style for the button, signifying it's role. """) @property def type(self): warnings.warn( """ Property 'type' was deprecated in Bokeh 0.12.0 and will be removed. Use 'button_type' instead. """) return self.button_type @type.setter def type(self, type): warnings.warn( """ Property 'type' was deprecated in Bokeh 0.12.0 and will be removed. Use 'button_type' instead. """) self.button_type = type __deprecated_attributes__ = ('type',) @abstract class AbstractButton(Widget, ButtonLike): """ A base class that defines common properties for all button types. ``AbstractButton`` is not generally useful to instantiate on its own. """ label = String("Button", help=""" The text label for the button to display. """) icon = Instance(AbstractIcon, help=""" An optional image appearing to the left of button's text. """) callback = Instance(Callback, help=""" A callback to run in the browser whenever the button is activated. """) class Button(AbstractButton): """ A click button. """ clicks = Int(0, help=""" A private property used to trigger ``on_click`` event handler. """) def on_click(self, handler): """ Set up a handler for button clicks. Args: handler (func) : handler function to call when button is clicked. Returns: None """ self.on_change('clicks', lambda attr, old, new: handler()) class Toggle(AbstractButton): """ A two-state toggle button. """ label = Override(default="Toggle") active = Bool(False, help=""" The initial state of a button. Also used to trigger ``on_click`` event handler. """) def on_click(self, handler): """ Set up a handler for button state changes (clicks). Args: handler (func) : handler function to call when button is toggled. Returns: None """ self.on_change('active', lambda attr, old, new: handler(new)) class Dropdown(AbstractButton): """ A dropdown button. """ label = Override(default="Dropdown") value = String(help=""" A private property used to trigger ``on_click`` event handler. """) default_value = String(help=""" The default value, otherwise the first item in ``menu`` will be used. """) menu = List(Tuple(String, String), help=""" Button's dropdown menu consisting of entries containing item's text and value name. Use ``None`` as a menu separator. """) def on_click(self, handler): """ Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None """ self.on_change('value', lambda attr, old, new: handler(new))
from __future__ import absolute_import from bokeh.io import save from bokeh.models import HoverTool from bokeh.plotting import figure from selenium.webdriver.common.action_chains import ActionChains from tests.integration.utils import has_no_console_errors import pytest pytestmark = pytest.mark.integration HEIGHT = 600 WIDTH = 600 def hover_at_position(selenium, canvas, x, y): actions = ActionChains(selenium) actions.move_to_element_with_offset(canvas, x, y) actions.perform() @pytest.mark.screenshot def test_hover_changes_color(output_file_url, selenium, screenshot): # Make plot and add a taptool callback that generates an alert plot = figure(height=HEIGHT, width=WIDTH, tools='', toolbar_location="above") rect = plot.rect( x=[1, 2], y=[1, 1], width=1, height=1, fill_color='cyan', hover_fill_color='magenta', line_color=None, hover_line_color=None ) plot.add_tools(HoverTool(tooltips=None, renderers=[rect])) # Save the plot and start the test save(plot) selenium.get(output_file_url) assert has_no_console_errors(selenium) # Hover over plot and take screenshot canvas = selenium.find_element_by_tag_name('canvas') hover_at_position(selenium, canvas, WIDTH * 0.33, HEIGHT * 0.5) assert screenshot.is_valid()
azjps/bokeh
tests/integration/interaction/test_hover.py
bokeh/models/widgets/buttons.py