text
stringlengths 213
32.3k
|
---|
from .base import BaseOperation
class Deleter(BaseOperation):
"""
Removes remote branches from the remote.
"""
def remove_remote_refs(self, refs):
"""
Removes the remote refs from the remote.
``refs`` should be a lit of ``git.RemoteRefs`` objects.
"""
origin = self._origin
pushes = []
for ref in refs:
pushes.append(origin.push(':{0}'.format(ref.remote_head)))
return pushes
|
from cerberus import schema_registry, rules_set_registry, Validator
from cerberus.tests import (
assert_fail,
assert_normalized,
assert_schema_error,
assert_success,
)
def test_schema_registry_simple():
schema_registry.add('foo', {'bar': {'type': 'string'}})
schema = {'a': {'schema': 'foo'}, 'b': {'schema': 'foo'}}
document = {'a': {'bar': 'a'}, 'b': {'bar': 'b'}}
assert_success(document, schema)
def test_top_level_reference():
schema_registry.add('peng', {'foo': {'type': 'integer'}})
document = {'foo': 42}
assert_success(document, 'peng')
def test_rules_set_simple():
rules_set_registry.add('foo', {'type': 'integer'})
assert_success({'bar': 1}, {'bar': 'foo'})
assert_fail({'bar': 'one'}, {'bar': 'foo'})
def test_allow_unknown_as_reference():
rules_set_registry.add('foo', {'type': 'number'})
v = Validator(allow_unknown='foo')
assert_success({0: 1}, {}, v)
assert_fail({0: 'one'}, {}, v)
def test_recursion():
rules_set_registry.add('self', {'type': 'dict', 'allow_unknown': 'self'})
v = Validator(allow_unknown='self')
assert_success({0: {1: {2: {}}}}, {}, v)
def test_references_remain_unresolved(validator):
rules_set_registry.extend(
(('boolean', {'type': 'boolean'}), ('booleans', {'valuesrules': 'boolean'}))
)
validator.schema = {'foo': 'booleans'}
assert 'booleans' == validator.schema['foo']
assert 'boolean' == rules_set_registry._storage['booleans']['valuesrules']
def test_rules_registry_with_anyof_type():
rules_set_registry.add('string_or_integer', {'anyof_type': ['string', 'integer']})
schema = {'soi': 'string_or_integer'}
assert_success({'soi': 'hello'}, schema)
def test_schema_registry_with_anyof_type():
schema_registry.add('soi_id', {'id': {'anyof_type': ['string', 'integer']}})
schema = {'soi': {'schema': 'soi_id'}}
assert_success({'soi': {'id': 'hello'}}, schema)
def test_normalization_with_rules_set():
# https://github.com/pyeve/cerberus/issues/283
rules_set_registry.add('foo', {'default': 42})
assert_normalized({}, {'bar': 42}, {'bar': 'foo'})
rules_set_registry.add('foo', {'default_setter': lambda _: 42})
assert_normalized({}, {'bar': 42}, {'bar': 'foo'})
rules_set_registry.add('foo', {'type': 'integer', 'nullable': True})
assert_success({'bar': None}, {'bar': 'foo'})
def test_rules_set_with_dict_field():
document = {'a_dict': {'foo': 1}}
schema = {'a_dict': {'type': 'dict', 'schema': {'foo': 'rule'}}}
# the schema's not yet added to the valid ones, so test the faulty first
rules_set_registry.add('rule', {'tüpe': 'integer'})
assert_schema_error(document, schema)
rules_set_registry.add('rule', {'type': 'integer'})
assert_success(document, schema)
|
import random
import base
from docker_registry.core import compat
import docker_registry.images as images
import docker_registry.lib.signals as signals
json = compat.json
class TestImages(base.TestCase):
def test_unset_nginx_accel_redirect_layer(self):
image_id = self.gen_hex_string()
layer_data = self.gen_random_string(1024)
self.upload_image(image_id, parent_id=None, layer=layer_data)
resp = self.http_client.get('/v1/images/{0}/layer'.format(image_id))
self.assertEqual(layer_data, resp.data)
def test_nginx_accel_redirect_layer(self):
image_id = self.gen_hex_string()
layer_data = self.gen_random_string(1024)
self.upload_image(image_id, parent_id=None, layer=layer_data)
# ensure the storage mechanism is LocalStorage or this test is bad
self.assertTrue(images.store.scheme == 'file',
'Store must be LocalStorage')
# set the nginx accel config
accel_header = 'X-Accel-Redirect'
accel_prefix = '/registry'
images.cfg._config['nginx_x_accel_redirect'] = accel_prefix
layer_path = 'images/{0}/layer'.format(image_id)
try:
resp = self.http_client.get('/v1/%s' % layer_path)
self.assertTrue(accel_header in resp.headers)
expected = '%s/%s' % (accel_prefix, layer_path)
self.assertEqual(expected, resp.headers[accel_header])
self.assertEqual('', resp.data)
finally:
images.cfg._config.pop('nginx_x_accel_redirect')
def test_simple(self):
image_id = self.gen_hex_string()
parent_id = self.gen_hex_string()
layer_data = self.gen_random_string(1024)
self.upload_image(parent_id, parent_id=None, layer=layer_data)
self.upload_image(image_id, parent_id=parent_id, layer=layer_data)
# test fetching the ancestry
resp = self.http_client.get('/v1/images/{0}/ancestry'.format(image_id))
# Note(dmp): unicode patch XXX not applied assume requests does the job
ancestry = json.loads(resp.data)
self.assertEqual(len(ancestry), 2)
self.assertEqual(ancestry[0], image_id)
self.assertEqual(ancestry[1], parent_id)
def test_notfound(self):
resp = self.http_client.get('/v1/images/{0}/json'.format(
self.gen_random_string()))
self.assertEqual(resp.status_code, 404, resp.data)
def test_bytes_range(self):
image_id = self.gen_hex_string()
layer_data = self.gen_random_string(1024)
b = random.randint(0, len(layer_data) / 2)
bytes_range = (b, random.randint(b + 1, len(layer_data) - 1))
headers = {'Range': 'bytes={0}-{1}'.format(*bytes_range)}
self.upload_image(image_id, parent_id=None, layer=layer_data)
url = '/v1/images/{0}/layer'.format(image_id)
resp = self.http_client.get(url, headers=headers)
expected_data = layer_data[bytes_range[0]:bytes_range[1] + 1]
received_data = resp.data
msg = 'expected size: {0}; got: {1}'.format(len(expected_data),
len(received_data))
self.assertEqual(expected_data, received_data, msg)
def before_put_image_json_handler_ok(self, sender, image_json):
return None
def before_put_image_json_handler_not_ok(self, sender, image_json):
return "Not ok"
def test_before_put_image_json_ok(self):
image_id = self.gen_hex_string()
json_obj = {
'id': image_id
}
json_data = compat.json.dumps(json_obj)
with signals.before_put_image_json.connected_to(
self.before_put_image_json_handler_ok):
resp = self.http_client.put('/v1/images/{0}/json'.format(image_id),
data=json_data)
self.assertEqual(resp.status_code, 200, resp.data)
def test_before_put_image_json_not_ok(self):
image_id = self.gen_hex_string()
json_obj = {
'id': image_id
}
json_data = compat.json.dumps(json_obj)
with signals.before_put_image_json.connected_to(
self.before_put_image_json_handler_not_ok):
resp = self.http_client.put('/v1/images/{0}/json'.format(image_id),
data=json_data)
resp_data = json.loads(resp.data)
self.assertEqual(resp.status_code, 400, resp.data)
self.assertTrue('error' in resp_data,
'Expected error key in response')
self.assertEqual(resp_data['error'], 'Not ok', resp.data)
|
import math
from typing import Optional
from aioesphomeapi import SensorInfo, SensorState, TextSensorInfo, TextSensorState
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry
async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Set up esphome sensors based on a config entry."""
await platform_async_setup_entry(
hass,
entry,
async_add_entities,
component_key="sensor",
info_type=SensorInfo,
entity_type=EsphomeSensor,
state_type=SensorState,
)
await platform_async_setup_entry(
hass,
entry,
async_add_entities,
component_key="text_sensor",
info_type=TextSensorInfo,
entity_type=EsphomeTextSensor,
state_type=TextSensorState,
)
# https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property
# pylint: disable=invalid-overridden-method
class EsphomeSensor(EsphomeEntity):
"""A sensor implementation for esphome."""
@property
def _static_info(self) -> SensorInfo:
return super()._static_info
@property
def _state(self) -> Optional[SensorState]:
return super()._state
@property
def icon(self) -> str:
"""Return the icon."""
return self._static_info.icon
@property
def force_update(self) -> bool:
"""Return if this sensor should force a state update."""
return self._static_info.force_update
@esphome_state_property
def state(self) -> Optional[str]:
"""Return the state of the entity."""
if math.isnan(self._state.state):
return None
if self._state.missing_state:
return None
return f"{self._state.state:.{self._static_info.accuracy_decimals}f}"
@property
def unit_of_measurement(self) -> str:
"""Return the unit the value is expressed in."""
return self._static_info.unit_of_measurement
class EsphomeTextSensor(EsphomeEntity):
"""A text sensor implementation for ESPHome."""
@property
def _static_info(self) -> "TextSensorInfo":
return super()._static_info
@property
def _state(self) -> Optional["TextSensorState"]:
return super()._state
@property
def icon(self) -> str:
"""Return the icon."""
return self._static_info.icon
@esphome_state_property
def state(self) -> Optional[str]:
"""Return the state of the entity."""
if self._state.missing_state:
return None
return self._state.state
|
import logging
from homeassistant import config_entries
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle xbox OAuth2 authentication."""
DOMAIN = DOMAIN
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)
@property
def extra_authorize_data(self) -> dict:
"""Extra data that needs to be appended to the authorize url."""
scopes = ["Xboxlive.signin", "Xboxlive.offline_access"]
return {"scope": " ".join(scopes)}
async def async_step_user(self, user_input=None):
"""Handle a flow start."""
await self.async_set_unique_id(DOMAIN)
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
return await super().async_step_user(user_input)
|
import datetime
import pandas as pd
from pandas.tseries.offsets import BDay
import pytz
from qstrader.simulation.sim_engine import SimulationEngine
from qstrader.simulation.event import SimulationEvent
class DailyBusinessDaySimulationEngine(SimulationEngine):
"""
A SimulationEngine subclass that generates events on a daily
frequency defaulting to typical business days, that is
Monday-Friday.
In particular it does not take into account any specific
regional holidays, such as Federal Holidays in the USA or
Bank Holidays in the UK.
It produces a pre-market event, a market open event,
a market closing event and a post-market event for every day
between the starting and ending dates.
Parameters
----------
starting_day : `pd.Timestamp`
The starting day of the simulation.
ending_day : `pd.Timestamp`
The ending day of the simulation.
pre_market : `Boolean`, optional
Whether to include a pre-market event
post_market : `Boolean`, optional
Whether to include a post-market event
"""
def __init__(self, starting_day, ending_day, pre_market=True, post_market=True):
if ending_day < starting_day:
raise ValueError(
"Ending date time %s is earlier than starting date time %s. "
"Cannot create DailyBusinessDaySimulationEngine "
"instance." % (ending_day, starting_day)
)
self.starting_day = starting_day
self.ending_day = ending_day
self.pre_market = pre_market
self.post_market = post_market
self.business_days = self._generate_business_days()
def _generate_business_days(self):
"""
Generate the list of business days using midnight UTC as
the timestamp.
Returns
-------
`list[pd.Timestamp]`
The business day range list.
"""
days = pd.date_range(
self.starting_day, self.ending_day, freq=BDay()
)
return days
def __iter__(self):
"""
Generate the daily timestamps and event information
for pre-market, market open, market close and post-market.
Yields
------
`SimulationEvent`
Market time simulation event to yield
"""
for index, bday in enumerate(self.business_days):
year = bday.year
month = bday.month
day = bday.day
if self.pre_market:
yield SimulationEvent(
pd.Timestamp(
datetime.datetime(year, month, day), tz='UTC'
), event_type="pre_market"
)
yield SimulationEvent(
pd.Timestamp(
datetime.datetime(year, month, day, 14, 30),
tz=pytz.utc
), event_type="market_open"
)
yield SimulationEvent(
pd.Timestamp(
datetime.datetime(year, month, day, 21, 00),
tz=pytz.utc
), event_type="market_close"
)
if self.post_market:
yield SimulationEvent(
pd.Timestamp(
datetime.datetime(year, month, day, 23, 59), tz='UTC'
), event_type="post_market"
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import mock
from perfkitbenchmarker import resource
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.providers.openstack import utils
import six
_OPENSTACK_CLI_PATH = 'path/openstack'
class OpenStackResource(resource.BaseResource):
def __init__(self, **kwargs):
for k, v in six.iteritems(kwargs):
setattr(self, k, v)
def _Create(self):
raise NotImplementedError()
def _Delete(self):
raise NotImplementedError()
def _Exists(self):
return True
class OpenStackCLICommandTestCase(unittest.TestCase):
def setUp(self):
super(OpenStackCLICommandTestCase, self).setUp()
p = mock.patch(utils.__name__ + '.FLAGS')
self.mock_flags = p.start()
self.addCleanup(p.stop)
self.mock_flags.openstack_cli_path = _OPENSTACK_CLI_PATH
def testCommonFlagsWithoutOptionalFlags(self):
rack_resource = OpenStackResource()
cmd = utils.OpenStackCLICommand(rack_resource, 'image', 'list')
self.assertEqual(cmd._GetCommand(), [
'path/openstack', 'image', 'list', '--format', 'json'])
def testCommonFlagsWithOptionalFlags(self):
rack_resource = OpenStackResource()
cmd = utils.OpenStackCLICommand(rack_resource, 'image', 'list')
cmd.flags['public'] = True
self.assertEqual(cmd._GetCommand(), [
'path/openstack', 'image', 'list', '--format', 'json', '--public'])
@mock.patch.object(vm_util, 'IssueCommand')
def testIssueCommandRaiseOnFailureDefault(self, mock_cmd):
rack_resource = OpenStackResource()
cmd = utils.OpenStackCLICommand(rack_resource)
cmd.Issue()
mock_cmd.assert_called_with(['path/openstack', '--format', 'json'],
raise_on_failure=False)
@mock.patch.object(vm_util, 'IssueCommand')
def testIssueCommandRaiseOnFailureTrue(self, mock_cmd):
rack_resource = OpenStackResource()
cmd = utils.OpenStackCLICommand(rack_resource)
cmd.Issue(raise_on_failure=True)
mock_cmd.assert_called_with(['path/openstack', '--format', 'json'],
raise_on_failure=True)
@mock.patch.object(vm_util, 'IssueCommand')
def testIssueCommandRaiseOnFailureFalse(self, mock_cmd):
rack_resource = OpenStackResource()
cmd = utils.OpenStackCLICommand(rack_resource)
cmd.Issue(raise_on_failure=False)
mock_cmd.assert_called_with(['path/openstack', '--format', 'json'],
raise_on_failure=False)
if __name__ == '__main__':
unittest.main()
|
import os
import pytest
from nikola import __main__
from .helper import cd, patch_config
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
def test_day_archive(build, output_dir):
"""See that it builds"""
archive = os.path.join(output_dir, "2012", "03", "30", "index.html")
assert os.path.isfile(archive)
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
patch_config(
target_dir, ("# CREATE_DAILY_ARCHIVE = False", "CREATE_DAILY_ARCHIVE = True")
)
with cd(target_dir):
__main__.main(["build"])
|
import requests
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
ATTR_HVAC_MODE,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_COMFORT,
PRESET_ECO,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_TEMPERATURE,
CONF_DEVICES,
PRECISION_HALVES,
TEMP_CELSIUS,
)
from .const import (
ATTR_STATE_BATTERY_LOW,
ATTR_STATE_DEVICE_LOCKED,
ATTR_STATE_HOLIDAY_MODE,
ATTR_STATE_LOCKED,
ATTR_STATE_SUMMER_MODE,
ATTR_STATE_WINDOW_OPEN,
CONF_CONNECTIONS,
DOMAIN as FRITZBOX_DOMAIN,
LOGGER,
)
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
OPERATION_LIST = [HVAC_MODE_HEAT, HVAC_MODE_OFF]
MIN_TEMPERATURE = 8
MAX_TEMPERATURE = 28
PRESET_MANUAL = "manual"
# special temperatures for on/off in Fritz!Box API (modified by pyfritzhome)
ON_API_TEMPERATURE = 127.0
OFF_API_TEMPERATURE = 126.5
ON_REPORT_SET_TEMPERATURE = 30.0
OFF_REPORT_SET_TEMPERATURE = 0.0
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Fritzbox smarthome thermostat from config_entry."""
entities = []
devices = hass.data[FRITZBOX_DOMAIN][CONF_DEVICES]
fritz = hass.data[FRITZBOX_DOMAIN][CONF_CONNECTIONS][config_entry.entry_id]
for device in await hass.async_add_executor_job(fritz.get_devices):
if device.has_thermostat and device.ain not in devices:
entities.append(FritzboxThermostat(device, fritz))
devices.add(device.ain)
async_add_entities(entities)
class FritzboxThermostat(ClimateEntity):
"""The thermostat class for Fritzbox smarthome thermostates."""
def __init__(self, device, fritz):
"""Initialize the thermostat."""
self._device = device
self._fritz = fritz
self._current_temperature = self._device.actual_temperature
self._target_temperature = self._device.target_temperature
self._comfort_temperature = self._device.comfort_temperature
self._eco_temperature = self._device.eco_temperature
@property
def device_info(self):
"""Return device specific attributes."""
return {
"name": self.name,
"identifiers": {(FRITZBOX_DOMAIN, self._device.ain)},
"manufacturer": self._device.manufacturer,
"model": self._device.productname,
"sw_version": self._device.fw_version,
}
@property
def unique_id(self):
"""Return the unique ID of the device."""
return self._device.ain
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def available(self):
"""Return if thermostat is available."""
return self._device.present
@property
def name(self):
"""Return the name of the device."""
return self._device.name
@property
def temperature_unit(self):
"""Return the unit of measurement that is used."""
return TEMP_CELSIUS
@property
def precision(self):
"""Return precision 0.5."""
return PRECISION_HALVES
@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."""
if self._target_temperature == ON_API_TEMPERATURE:
return ON_REPORT_SET_TEMPERATURE
if self._target_temperature == OFF_API_TEMPERATURE:
return OFF_REPORT_SET_TEMPERATURE
return self._target_temperature
def set_temperature(self, **kwargs):
"""Set new target temperature."""
if ATTR_HVAC_MODE in kwargs:
hvac_mode = kwargs.get(ATTR_HVAC_MODE)
self.set_hvac_mode(hvac_mode)
elif ATTR_TEMPERATURE in kwargs:
temperature = kwargs.get(ATTR_TEMPERATURE)
self._device.set_target_temperature(temperature)
@property
def hvac_mode(self):
"""Return the current operation mode."""
if (
self._target_temperature == OFF_REPORT_SET_TEMPERATURE
or self._target_temperature == OFF_API_TEMPERATURE
):
return HVAC_MODE_OFF
return HVAC_MODE_HEAT
@property
def hvac_modes(self):
"""Return the list of available operation modes."""
return OPERATION_LIST
def set_hvac_mode(self, hvac_mode):
"""Set new operation mode."""
if hvac_mode == HVAC_MODE_OFF:
self.set_temperature(temperature=OFF_REPORT_SET_TEMPERATURE)
else:
self.set_temperature(temperature=self._comfort_temperature)
@property
def preset_mode(self):
"""Return current preset mode."""
if self._target_temperature == self._comfort_temperature:
return PRESET_COMFORT
if self._target_temperature == self._eco_temperature:
return PRESET_ECO
@property
def preset_modes(self):
"""Return supported preset modes."""
return [PRESET_ECO, PRESET_COMFORT]
def set_preset_mode(self, preset_mode):
"""Set preset mode."""
if preset_mode == PRESET_COMFORT:
self.set_temperature(temperature=self._comfort_temperature)
elif preset_mode == PRESET_ECO:
self.set_temperature(temperature=self._eco_temperature)
@property
def min_temp(self):
"""Return the minimum temperature."""
return MIN_TEMPERATURE
@property
def max_temp(self):
"""Return the maximum temperature."""
return MAX_TEMPERATURE
@property
def device_state_attributes(self):
"""Return the device specific state attributes."""
attrs = {
ATTR_STATE_BATTERY_LOW: self._device.battery_low,
ATTR_STATE_DEVICE_LOCKED: self._device.device_lock,
ATTR_STATE_LOCKED: self._device.lock,
}
# the following attributes are available since fritzos 7
if self._device.battery_level is not None:
attrs[ATTR_BATTERY_LEVEL] = self._device.battery_level
if self._device.holiday_active is not None:
attrs[ATTR_STATE_HOLIDAY_MODE] = self._device.holiday_active
if self._device.summer_active is not None:
attrs[ATTR_STATE_SUMMER_MODE] = self._device.summer_active
if ATTR_STATE_WINDOW_OPEN is not None:
attrs[ATTR_STATE_WINDOW_OPEN] = self._device.window_open
return attrs
def update(self):
"""Update the data from the thermostat."""
try:
self._device.update()
self._current_temperature = self._device.actual_temperature
self._target_temperature = self._device.target_temperature
self._comfort_temperature = self._device.comfort_temperature
self._eco_temperature = self._device.eco_temperature
except requests.exceptions.HTTPError as ex:
LOGGER.warning("Fritzbox connection error: %s", ex)
self._fritz.login()
|
import os
import sys
import logging
import argparse
import threading
import tempfile
import queue as Queue
import Pyro4
from gensim.models import lsimodel
from gensim import utils
logger = logging.getLogger(__name__)
SAVE_DEBUG = 0 # save intermediate models after every SAVE_DEBUG updates (0 for never)
class Worker:
def __init__(self):
"""Partly initialize the model.
A full initialization requires a call to :meth:`~gensim.models.lsi_worker.Worker.initialize`.
"""
self.model = None
@Pyro4.expose
def initialize(self, myid, dispatcher, **model_params):
"""Fully initialize the worker.
Parameters
----------
myid : int
An ID number used to identify this worker in the dispatcher object.
dispatcher : :class:`~gensim.models.lsi_dispatcher.Dispatcher`
The dispatcher responsible for scheduling this worker.
**model_params
Keyword parameters to initialize the inner LSI model, see :class:`~gensim.models.lsimodel.LsiModel`.
"""
self.lock_update = threading.Lock()
self.jobsdone = 0 # how many jobs has this worker completed?
# id of this worker in the dispatcher; just a convenience var for easy access/logging TODO remove?
self.myid = myid
self.dispatcher = dispatcher
self.finished = False
logger.info("initializing worker #%s", myid)
self.model = lsimodel.LsiModel(**model_params)
@Pyro4.expose
@Pyro4.oneway
def requestjob(self):
"""Request jobs from the dispatcher, in a perpetual loop until :meth:`~gensim.models.lsi_worker.Worker.getstate`
is called.
Raises
------
RuntimeError
If `self.model` is None (i.e. worker not initialized).
"""
if self.model is None:
raise RuntimeError("worker must be initialized before receiving jobs")
job = None
while job is None and not self.finished:
try:
job = self.dispatcher.getjob(self.myid)
except Queue.Empty:
# no new job: try again, unless we're finished with all work
continue
if job is not None:
logger.info("worker #%s received job #%i", self.myid, self.jobsdone)
self.processjob(job)
self.dispatcher.jobdone(self.myid)
else:
logger.info("worker #%i stopping asking for jobs", self.myid)
@utils.synchronous('lock_update')
def processjob(self, job):
"""Incrementally process the job and potentially logs progress.
Parameters
----------
job : iterable of list of (int, float)
Corpus in BoW format.
"""
self.model.add_documents(job)
self.jobsdone += 1
if SAVE_DEBUG and self.jobsdone % SAVE_DEBUG == 0:
fname = os.path.join(tempfile.gettempdir(), 'lsi_worker.pkl')
self.model.save(fname)
@Pyro4.expose
@utils.synchronous('lock_update')
def getstate(self):
"""Log and get the LSI model's current projection.
Returns
-------
:class:`~gensim.models.lsimodel.Projection`
The current projection.
"""
logger.info("worker #%i returning its state after %s jobs", self.myid, self.jobsdone)
assert isinstance(self.model.projection, lsimodel.Projection)
self.finished = True
return self.model.projection
@Pyro4.expose
@utils.synchronous('lock_update')
def reset(self):
"""Reset the worker by deleting its current projection."""
logger.info("resetting worker #%i", self.myid)
self.model.projection = self.model.projection.empty_like()
self.finished = False
@Pyro4.oneway
def exit(self):
"""Terminate the worker."""
logger.info("terminating worker #%i", self.myid)
os._exit(0)
if __name__ == '__main__':
"""The main script. """
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
parser = argparse.ArgumentParser(description=__doc__[:-135], formatter_class=argparse.RawTextHelpFormatter)
_ = parser.parse_args()
logger.info("running %s", " ".join(sys.argv))
utils.pyro_daemon('gensim.lsi_worker', Worker(), random_suffix=True)
logger.info("finished running %s", parser.prog)
|
import unittest
import numpy as np
import numpy.testing as np_test
from pgmpy.factors.distributions import GaussianDistribution as JGD
from pgmpy.factors.continuous import CanonicalDistribution
class TestCanonicalFactor(unittest.TestCase):
def test_class_init(self):
phi = CanonicalDistribution(
["x1", ("y", "z"), "x3"],
np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),
np.array([[1], [4.7], [-1]]),
-2,
)
self.assertEqual(phi.variables, ["x1", ("y", "z"), "x3"])
np_test.assert_array_equal(
phi.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)
)
np_test.assert_array_equal(phi.h, np.array([[1], [4.7], [-1]], dtype=float))
self.assertEqual(phi.g, -2)
phi = CanonicalDistribution(
["x1", ("y", "z"), "x3"],
np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),
np.array([1, 4.7, -1]),
-2,
)
self.assertEqual(phi.variables, ["x1", ("y", "z"), "x3"])
np_test.assert_array_equal(
phi.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)
)
np_test.assert_array_equal(phi.h, np.array([[1], [4.7], [-1]], dtype=float))
self.assertEqual(phi.g, -2)
phi = CanonicalDistribution(["x"], [[1]], [0], 1)
self.assertEqual(phi.variables, ["x"])
np_test.assert_array_equal(phi.K, np.array([[1]], dtype=float))
np_test.assert_array_equal(phi.h, np.array([[0]], dtype=float))
self.assertEqual(phi.g, 1)
def test_class_init_valueerror(self):
self.assertRaises(
ValueError,
CanonicalDistribution,
["x1", "x2", "x3"],
np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float),
np.array([1, 2], dtype=float),
7,
)
self.assertRaises(
ValueError,
CanonicalDistribution,
["x1", "x2", "x3"],
np.array([[1.1, -1, 0], [-1, 4], [0, -2, 4]], dtype=object),
np.array([1, 2, 3], dtype=float),
7,
)
self.assertRaises(
ValueError,
CanonicalDistribution,
["x1", "x2", "x3"],
np.array([[1.1, -1, 0], [0, -2, 4]], dtype=float),
np.array([1, 2, 3], dtype=float),
7,
)
self.assertRaises(
ValueError,
CanonicalDistribution,
["x1", "x3"],
np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float),
np.array([1, 2, 3], dtype=float),
7,
)
class TestJGDMethods(unittest.TestCase):
def setUp(self):
self.phi1 = CanonicalDistribution(
["x1", "x2", "x3"],
np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]]),
np.array([[1], [4.7], [-1]]),
-2,
)
self.phi2 = CanonicalDistribution(["x"], [[1]], [0], 1)
self.phi3 = self.phi1.copy()
self.gauss_phi1 = JGD(
["x1", "x2", "x3"],
np.array([[3.13043478], [2.44347826], [0.97173913]]),
np.array(
[
[1.30434783, 0.43478261, 0.2173913],
[0.43478261, 0.47826087, 0.23913043],
[0.2173913, 0.23913043, 0.36956522],
],
dtype=float,
),
)
self.gauss_phi2 = JGD(["x"], np.array([0]), np.array([[1]]))
def test_assignment(self):
np_test.assert_almost_equal(self.phi1.assignment(1, 2, 3), 0.0007848640)
np_test.assert_almost_equal(self.phi2.assignment(1.2), 1.323129812337)
def test_to_joint_gaussian(self):
jgd1 = self.phi1.to_joint_gaussian()
jgd2 = self.phi2.to_joint_gaussian()
self.assertEqual(jgd1.variables, self.gauss_phi1.variables)
np_test.assert_almost_equal(jgd1.covariance, self.gauss_phi1.covariance)
np_test.assert_almost_equal(jgd1.mean, self.gauss_phi1.mean)
self.assertEqual(jgd2.variables, self.gauss_phi2.variables)
np_test.assert_almost_equal(jgd2.covariance, self.gauss_phi2.covariance)
np_test.assert_almost_equal(jgd2.mean, self.gauss_phi2.mean)
def test_reduce(self):
phi = self.phi1.reduce([("x1", 7)], inplace=False)
self.assertEqual(phi.variables, ["x2", "x3"])
np_test.assert_almost_equal(phi.K, np.array([[4.0, -2.0], [-2.0, 4.0]]))
np_test.assert_almost_equal(phi.h, np.array([[11.7], [-1.0]]))
np_test.assert_almost_equal(phi.g, -21.95)
phi = self.phi1.reduce([("x1", 4), ("x2", 1.23)], inplace=False)
self.assertEqual(phi.variables, ["x3"])
np_test.assert_almost_equal(phi.K, np.array([[4.0]]))
np_test.assert_almost_equal(phi.h, np.array([[1.46]]))
np_test.assert_almost_equal(phi.g, 0.8752)
self.phi1.reduce([("x1", 7)])
self.assertEqual(self.phi1.variables, ["x2", "x3"])
np_test.assert_almost_equal(self.phi1.K, np.array([[4.0, -2.0], [-2.0, 4.0]]))
np_test.assert_almost_equal(self.phi1.h, np.array([[11.7], [-1.0]]))
np_test.assert_almost_equal(self.phi1.g, -21.95)
self.phi1 = self.phi3.copy()
self.phi1.reduce([("x1", 4), ("x2", 1.23)])
self.assertEqual(self.phi1.variables, ["x3"])
np_test.assert_almost_equal(self.phi1.K, np.array([[4.0]]))
np_test.assert_almost_equal(self.phi1.h, np.array([[1.46]]))
np_test.assert_almost_equal(self.phi1.g, 0.8752)
self.phi1 = self.phi3.copy()
self.phi1.reduce([("x2", 1.23), ("x1", 4)])
self.assertEqual(self.phi1.variables, ["x3"])
np_test.assert_almost_equal(self.phi1.K, np.array([[4.0]]))
np_test.assert_almost_equal(self.phi1.h, np.array([[1.46]]))
np_test.assert_almost_equal(self.phi1.g, 0.8752)
def test_marginalize(self):
phi = self.phi1.marginalize(["x1"], inplace=False)
self.assertEqual(phi.variables, ["x2", "x3"])
np_test.assert_almost_equal(phi.K, np.array([[3.090909, -2.0], [-2.0, 4.0]]))
np_test.assert_almost_equal(phi.h, np.array([[5.6090909], [-1.0]]))
np_test.assert_almost_equal(phi.g, -0.5787165566)
phi = self.phi1.marginalize(["x1", "x2"], inplace=False)
self.assertEqual(phi.variables, ["x3"])
np_test.assert_almost_equal(phi.K, np.array([[2.70588235]]))
np_test.assert_almost_equal(phi.h, np.array([[2.62941176]]))
np_test.assert_almost_equal(phi.g, 39.25598935059)
self.phi1.marginalize(["x1"])
self.assertEqual(self.phi1.variables, ["x2", "x3"])
np_test.assert_almost_equal(
self.phi1.K, np.array([[3.090909, -2.0], [-2.0, 4.0]])
)
np_test.assert_almost_equal(self.phi1.h, np.array([[5.6090909], [-1.0]]))
np_test.assert_almost_equal(self.phi1.g, -0.5787165566)
self.phi1 = self.phi3
self.phi1.marginalize(["x1", "x2"])
self.assertEqual(self.phi1.variables, ["x3"])
np_test.assert_almost_equal(self.phi1.K, np.array([[2.70588235]]))
np_test.assert_almost_equal(self.phi1.h, np.array([[2.62941176]]))
np_test.assert_almost_equal(self.phi1.g, 39.25598935059)
self.phi1 = self.phi3
def test_operate(self):
phi1 = self.phi1 * CanonicalDistribution(
["x2", "x4"], [[1, 2], [3, 4]], [0, 4.56], -6.78
)
phi2 = self.phi1 / CanonicalDistribution(
["x2", "x3"], [[1, 2], [3, 4]], [0, 4.56], -6.78
)
self.assertEqual(phi1.variables, ["x1", "x2", "x3", "x4"])
np_test.assert_almost_equal(
phi1.K,
np.array(
[
[1.1, -1.0, 0.0, 0.0],
[-1.0, 5.0, -2.0, 2.0],
[0.0, -2.0, 4.0, 0.0],
[0.0, 3.0, 0.0, 4.0],
]
),
)
np_test.assert_almost_equal(phi1.h, np.array([[1.0], [4.7], [-1.0], [4.56]]))
np_test.assert_almost_equal(phi1.g, -8.78)
self.assertEqual(phi2.variables, ["x1", "x2", "x3"])
np_test.assert_almost_equal(
phi2.K, np.array([[1.1, -1.0, 0.0], [-1.0, 3.0, -4.0], [0.0, -5.0, 0.0]])
)
np_test.assert_almost_equal(phi2.h, np.array([[1.0], [4.7], [-5.56]]))
np_test.assert_almost_equal(phi2.g, 4.78)
def test_copy(self):
copy_phi1 = self.phi1.copy()
self.assertEqual(copy_phi1.variables, self.phi1.variables)
np_test.assert_array_equal(copy_phi1.K, self.phi1.K)
np_test.assert_array_equal(copy_phi1.h, self.phi1.h)
np_test.assert_array_equal(copy_phi1.g, self.phi1.g)
copy_phi1.marginalize(["x1"])
self.assertEqual(self.phi1.variables, ["x1", "x2", "x3"])
np_test.assert_array_equal(
self.phi1.K, np.array([[1.1, -1, 0], [-1, 4, -2], [0, -2, 4]], dtype=float)
)
np_test.assert_array_equal(
self.phi1.h, np.array([[1], [4.7], [-1]], dtype=float)
)
self.assertEqual(self.phi1.g, -2)
self.phi1.marginalize(["x2"])
self.assertEqual(copy_phi1.variables, ["x2", "x3"])
np_test.assert_almost_equal(
copy_phi1.K, np.array([[3.090909, -2.0], [-2.0, 4.0]])
)
np_test.assert_almost_equal(copy_phi1.h, np.array([[5.6090909], [-1.0]]))
np_test.assert_almost_equal(copy_phi1.g, -0.5787165566)
self.phi1 = self.phi3
def tearDown(self):
del self.phi1
del self.phi2
del self.phi3
del self.gauss_phi1
del self.gauss_phi2
|
from diff_match_patch import diff_match_patch
from django.utils.html import escape
def html_diff(old, new):
"""Generate HTML formatted diff of two strings."""
dmp = diff_match_patch()
diff = dmp.diff_main(old, new)
dmp.diff_cleanupSemantic(diff)
result = []
for op, data in diff:
if op == dmp.DIFF_DELETE:
result.append("<del>{}</del>".format(escape(data)))
elif op == dmp.DIFF_INSERT:
result.append("<ins>{}</ins>".format(escape(data)))
elif op == dmp.DIFF_EQUAL:
result.append(escape(data))
return "".join(result)
|
from a_sync import block
from pyramid.response import Response
from pyramid.view import view_config
from paasta_tools.mesos_tools import get_mesos_master
from paasta_tools.metrics import metastatus_lib
def parse_filters(filters):
# The swagger config verifies that the data is in this format
# "pattern": "(.*):(.*,)*(.*)"
if filters is None:
return {}
f = {s[0]: s[1] for s in [e.split(":") for e in filters]}
f = {k: v.split(",") for k, v in f.items()}
return f
@view_config(route_name="resources.utilization", request_method="GET", renderer="json")
def resources_utilization(request):
master = get_mesos_master()
mesos_state = block(master.state)
groupings = request.swagger_data.get("groupings", ["superregion"])
# swagger actually makes the key None if it's not set
if groupings is None:
groupings = ["superregion"]
grouping_function = metastatus_lib.key_func_for_attribute_multi(groupings)
sorting_function = metastatus_lib.sort_func_for_attributes(groupings)
filters = request.swagger_data.get("filter", [])
filters = parse_filters(filters)
filter_funcs = [
metastatus_lib.make_filter_slave_func(attr, vals)
for attr, vals in filters.items()
]
resource_info_dict = metastatus_lib.get_resource_utilization_by_grouping(
grouping_func=grouping_function,
mesos_state=mesos_state,
filters=filter_funcs,
sort_func=sorting_function,
)
response_body = []
for k, v in resource_info_dict.items():
group = {"groupings": {}}
for grouping, value in k:
group["groupings"][grouping] = value
for resource, value in v["total"]._asdict().items():
group[resource] = {"total": value}
for resource, value in v["free"]._asdict().items():
group[resource]["free"] = value
for resource in v["free"]._fields:
group[resource]["used"] = group[resource]["total"] - group[resource]["free"]
response_body.append(group)
return Response(json_body=response_body, status_code=200)
|
import os.path as op
import pytest
from numpy.testing import assert_array_almost_equal
import numpy as np
from mne.io import read_raw_fif, read_raw_ctf
from mne.io.proj import make_projector, activate_proj
from mne.preprocessing.ssp import compute_proj_ecg, compute_proj_eog
from mne.datasets import testing
from mne import pick_types
data_path = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(data_path, 'test_raw.fif')
dur_use = 5.0
eog_times = np.array([0.5, 2.3, 3.6, 14.5])
ctf_fname = op.join(testing.data_path(download=False), 'CTF',
'testdata_ctf.ds')
@pytest.fixture()
def short_raw():
"""Create a short, picked raw instance."""
raw = read_raw_fif(raw_fname).crop(0, 7).pick_types(
meg=True, eeg=True, eog=True)
raw.pick(raw.ch_names[:306:10] + raw.ch_names[306:]).load_data()
raw.info.normalize_proj()
return raw
@pytest.mark.parametrize('average', (True, False))
def test_compute_proj_ecg(short_raw, average):
"""Test computation of ECG SSP projectors."""
raw = short_raw
# For speed, let's not filter here (must also not reject then)
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs, events = compute_proj_ecg(
raw, n_mag=2, n_grad=2, n_eeg=2, ch_name='MEG 1531',
bads=['MEG 2443'], average=average, avg_ref=True, no_proj=True,
l_freq=None, h_freq=None, reject=None, tmax=dur_use,
qrs_threshold=0.5, filter_length=1000)
assert len(projs) == 7
# heart rate at least 0.5 Hz, but less than 3 Hz
assert (events.shape[0] > 0.5 * dur_use and
events.shape[0] < 3 * dur_use)
ssp_ecg = [proj for proj in projs if proj['desc'].startswith('ECG')]
# check that the first principal component have a certain minimum
ssp_ecg = [proj for proj in ssp_ecg if 'PCA-01' in proj['desc']]
thresh_eeg, thresh_axial, thresh_planar = .9, .3, .1
for proj in ssp_ecg:
if 'planar' in proj['desc']:
assert proj['explained_var'] > thresh_planar
elif 'axial' in proj['desc']:
assert proj['explained_var'] > thresh_axial
elif 'eeg' in proj['desc']:
assert proj['explained_var'] > thresh_eeg
# XXX: better tests
# without setting a bad channel, this should throw a warning
with pytest.warns(RuntimeWarning, match='No good epochs found'):
projs, events, drop_log = compute_proj_ecg(
raw, n_mag=2, n_grad=2, n_eeg=2, ch_name='MEG 1531', bads=[],
average=average, avg_ref=True, no_proj=True, l_freq=None,
h_freq=None, tmax=dur_use, return_drop_log=True)
assert projs is None
assert len(events) == len(drop_log)
@pytest.mark.parametrize('average', [True, False])
def test_compute_proj_eog(average, short_raw):
"""Test computation of EOG SSP projectors."""
raw = short_raw
n_projs_init = len(raw.info['projs'])
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs, events = compute_proj_eog(
raw, n_mag=2, n_grad=2, n_eeg=2, bads=['MEG 2443'],
average=average, avg_ref=True, no_proj=False, l_freq=None,
h_freq=None, reject=None, tmax=dur_use, filter_length=1000)
assert (len(projs) == (7 + n_projs_init))
assert (np.abs(events.shape[0] -
np.sum(np.less(eog_times, dur_use))) <= 1)
ssp_eog = [proj for proj in projs if proj['desc'].startswith('EOG')]
# check that the first principal component have a certain minimum
ssp_eog = [proj for proj in ssp_eog if 'PCA-01' in proj['desc']]
thresh_eeg, thresh_axial, thresh_planar = .9, .3, .1
for proj in ssp_eog:
if 'planar' in proj['desc']:
assert (proj['explained_var'] > thresh_planar)
elif 'axial' in proj['desc']:
assert (proj['explained_var'] > thresh_axial)
elif 'eeg' in proj['desc']:
assert (proj['explained_var'] > thresh_eeg)
# XXX: better tests
with pytest.warns(RuntimeWarning, match='longer'):
projs, events = compute_proj_eog(
raw, n_mag=2, n_grad=2, n_eeg=2, average=average, bads=[],
avg_ref=True, no_proj=False, l_freq=None, h_freq=None,
tmax=dur_use)
assert projs is None
@pytest.mark.slowtest # can be slow on OSX
def test_compute_proj_parallel(short_raw):
"""Test computation of ExG projectors using parallelization."""
short_raw = short_raw.copy().pick(('eeg', 'eog')).resample(100)
raw = short_raw.copy()
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs, _ = compute_proj_eog(
raw, n_eeg=2, bads=raw.ch_names[1:2], average=False,
avg_ref=True, no_proj=False, n_jobs=1, l_freq=None, h_freq=None,
reject=None, tmax=dur_use, filter_length=100)
raw_2 = short_raw.copy()
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs_2, _ = compute_proj_eog(
raw_2, n_eeg=2, bads=raw.ch_names[1:2],
average=False, avg_ref=True, no_proj=False, n_jobs=2,
l_freq=None, h_freq=None, reject=None, tmax=dur_use,
filter_length=100)
projs = activate_proj(projs)
projs_2 = activate_proj(projs_2)
projs, _, _ = make_projector(projs, raw_2.info['ch_names'],
bads=['MEG 2443'])
projs_2, _, _ = make_projector(projs_2, raw_2.info['ch_names'],
bads=['MEG 2443'])
assert_array_almost_equal(projs, projs_2, 10)
def _check_projs_for_expected_channels(projs, n_mags, n_grads, n_eegs):
assert projs is not None
for p in projs:
if 'planar' in p['desc']:
assert len(p['data']['col_names']) == n_grads
elif 'axial' in p['desc']:
assert len(p['data']['col_names']) == n_mags
elif 'eeg' in p['desc']:
assert len(p['data']['col_names']) == n_eegs
@pytest.mark.slowtest # can be slow on OSX
@testing.requires_testing_data
def test_compute_proj_ctf():
"""Test to show that projector code completes on CTF data."""
raw = read_raw_ctf(ctf_fname, preload=True)
# expected channels per projector type
mag_picks = pick_types(
raw.info, meg='mag', ref_meg=False, exclude='bads')[::10]
n_mags = len(mag_picks)
grad_picks = pick_types(raw.info, meg='grad', ref_meg=False,
exclude='bads')[::10]
n_grads = len(grad_picks)
eeg_picks = pick_types(raw.info, meg=False, eeg=True, ref_meg=False,
exclude='bads')[2::3]
n_eegs = len(eeg_picks)
ref_picks = pick_types(raw.info, meg=False, ref_meg=True)
raw.pick(np.sort(np.concatenate(
[mag_picks, grad_picks, eeg_picks, ref_picks])))
del mag_picks, grad_picks, eeg_picks, ref_picks
# Test with and without gradient compensation
raw.apply_gradient_compensation(0)
n_projs_init = len(raw.info['projs'])
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs, _ = compute_proj_eog(
raw, n_mag=2, n_grad=2, n_eeg=2, average=True, ch_name='EEG059',
avg_ref=True, no_proj=False, l_freq=None, h_freq=None,
reject=None, tmax=dur_use, filter_length=1000)
_check_projs_for_expected_channels(projs, n_mags, n_grads, n_eegs)
assert len(projs) == (5 + n_projs_init)
raw.apply_gradient_compensation(1)
with pytest.warns(RuntimeWarning, match='Attenuation'):
projs, _ = compute_proj_ecg(
raw, n_mag=1, n_grad=1, n_eeg=2, average=True, ch_name='EEG059',
avg_ref=True, no_proj=False, l_freq=None, h_freq=None,
reject=None, tmax=dur_use, filter_length=1000)
_check_projs_for_expected_channels(projs, n_mags, n_grads, n_eegs)
assert len(projs) == (4 + n_projs_init)
|
import collections
import itertools
import os
import time
from absl import flags
from perfkitbenchmarker import context
from perfkitbenchmarker import custom_virtual_machine_spec
from perfkitbenchmarker import data
from perfkitbenchmarker import events
from perfkitbenchmarker import kubernetes_helper
from perfkitbenchmarker import os_types
from perfkitbenchmarker import resource
from perfkitbenchmarker import sample
from perfkitbenchmarker import virtual_machine
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import option_decoders
from perfkitbenchmarker.configs import spec
import requests
import yaml
KUBERNETES = 'Kubernetes'
FLAGS = flags.FLAGS
flags.DEFINE_string('kubeconfig', None,
'Path to kubeconfig to be used by kubectl. '
'If unspecified, it will be set to a file in this run\'s '
'temporary directory.')
flags.DEFINE_string('kubectl', 'kubectl',
'Path to kubectl tool')
flags.DEFINE_boolean('local_container_build', False,
'Force container images to be built locally rather than '
'just as a fallback if there is no remote image builder '
'associated with the registry.')
flags.DEFINE_boolean('static_container_image', True,
'Whether container images are static (i.e. are not '
'managed by PKB). If this is set, PKB will accept the '
'image as fully qualified (including repository) and will '
'not attempt to build it.')
flags.DEFINE_boolean('force_container_build', False,
'Whether to force PKB to build container images even '
'if they already exist in the registry.')
flags.DEFINE_string('container_cluster_cloud', None,
'Sets the cloud to use for the container cluster. '
'This will override both the value set in the config and '
'the value set using the generic "cloud" flag.')
flags.DEFINE_integer('container_cluster_num_vms', None,
'Number of nodes in the cluster. Defaults to '
'container_cluster.vm_count')
flags.DEFINE_string('container_cluster_type', KUBERNETES,
'The type of container cluster.')
flags.DEFINE_string('container_cluster_version', None,
'Optional version flag to pass to the cluster create '
'command. If not specified, the cloud-specific container '
'implementation will chose an appropriate default.')
_K8S_FINISHED_PHASES = frozenset(['Succeeded', 'Failed'])
_K8S_INGRESS = """
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: {service_name}-ingress
spec:
backend:
serviceName: {service_name}
servicePort: 8080
"""
class ContainerSpec(spec.BaseSpec):
"""Class containing options for creating containers."""
@classmethod
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['image'].present:
config_values['image'] = flag_values.image
if flag_values['static_container_image'].present:
config_values['static_image'] = flag_values.static_container_image
@classmethod
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor args for each configurable option.
Can be overridden by derived classes to add options or impose additional
requirements on existing options.
Returns:
dict. Maps option name string to a (ConfigOptionDecoder class, dict) pair.
The pair specifies a decoder class and its __init__() keyword
arguments to construct in order to decode the named option.
"""
result = super(ContainerSpec, cls)._GetOptionDecoderConstructions()
result.update({
'image': (option_decoders.StringDecoder, {}),
'static_image': (option_decoders.BooleanDecoder, {'default': False}),
'cpus': (option_decoders.FloatDecoder, {'default': 1.0}),
'memory': (custom_virtual_machine_spec.MemoryDecoder, {}),
'command': (_CommandDecoder, {}),
'container_port': (option_decoders.IntDecoder, {'default': 8080}),
})
return result
class _CommandDecoder(option_decoders.ListDecoder):
"""Decodes the command/arg list for containers."""
def __init__(self, **kwargs):
super(_CommandDecoder, self).__init__(
default=None, none_ok=True,
item_decoder=option_decoders.StringDecoder(),
**kwargs)
class BaseContainer(resource.BaseResource):
"""Class representing a single container."""
def __init__(self, container_spec):
super(BaseContainer, self).__init__()
self.cpus = container_spec.cpus
self.memory = container_spec.memory
self.command = container_spec.command
self.image = container_spec.image
self.ip_address = None
def WaitForExit(self, timeout=1200):
"""Waits until the container has finished running."""
raise NotImplementedError()
def GetLogs(self):
"""Returns the logs from the container."""
raise NotImplementedError()
class BaseContainerService(resource.BaseResource):
"""Class representing a service backed by containers."""
def __init__(self, container_spec):
super(BaseContainerService, self).__init__()
self.cpus = container_spec.cpus
self.memory = container_spec.memory
self.command = container_spec.command
self.image = container_spec.image
self.container_port = container_spec.container_port
self.ip_address = None
self.port = None
self.host_header = None
class _ContainerImage(object):
"""Simple class for tracking container image names and source locations."""
def __init__(self, name):
self.name = name
self.directory = os.path.dirname(
data.ResourcePath(os.path.join('docker', self.name, 'Dockerfile')))
class ContainerRegistrySpec(spec.BaseSpec):
"""Spec containing options for creating a Container Registry."""
def __init__(self, component_full_name, flag_values=None, **kwargs):
super(ContainerRegistrySpec, self).__init__(
component_full_name, flag_values=flag_values, **kwargs)
registry_spec = getattr(self.spec, self.cloud, {})
self.project = registry_spec.get('project')
self.zone = registry_spec.get('zone')
self.name = registry_spec.get('name')
@classmethod
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag values to the spec."""
super(ContainerRegistrySpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['cloud'].present or 'cloud' not in config_values:
config_values['cloud'] = flag_values.cloud
updated_spec = {}
if flag_values['project'].present:
updated_spec['project'] = flag_values.project
if flag_values['zones'].present:
updated_spec['zone'] = flag_values.zones[0]
cloud = config_values['cloud']
cloud_spec = config_values.get('spec', {}).get(cloud, {})
cloud_spec.update(updated_spec)
config_values['spec'] = {cloud: cloud_spec}
@classmethod
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor args for each configurable option.
Can be overridden by derived classes to add options or impose additional
requirements on existing options.
Returns:
dict. Maps option name string to a (ConfigOptionDecoder class, dict) pair.
The pair specifies a decoder class and its __init__() keyword
arguments to construct in order to decode the named option.
"""
result = super(ContainerRegistrySpec, cls)._GetOptionDecoderConstructions()
result.update({
'cloud': (option_decoders.StringDecoder, {}),
'spec': (option_decoders.PerCloudConfigDecoder, {'default': {}})
})
return result
def GetContainerRegistryClass(cloud):
return resource.GetResourceClass(BaseContainerRegistry, CLOUD=cloud)
class BaseContainerRegistry(resource.BaseResource):
"""Base class for container image registries."""
RESOURCE_TYPE = 'BaseContainerRegistry'
def __init__(self, registry_spec):
super(BaseContainerRegistry, self).__init__()
benchmark_spec = context.GetThreadBenchmarkSpec()
container_cluster = getattr(benchmark_spec, 'container_cluster', None)
zone = getattr(container_cluster, 'zone', None)
project = getattr(container_cluster, 'project', None)
self.zone = registry_spec.zone or zone
self.project = registry_spec.project or project
self.name = registry_spec.name or 'pkb%s' % FLAGS.run_uri
self.local_build_times = {}
self.remote_build_times = {}
self.metadata.update({
'cloud': self.CLOUD
})
def _Create(self):
"""Creates the image registry."""
pass
def _Delete(self):
"""Deletes the image registry."""
pass
def GetSamples(self):
"""Returns image build related samples."""
samples = []
metadata = self.GetResourceMetadata()
for image_name, build_time in self.local_build_times.items():
metadata.update({
'build_type': 'local',
'image': image_name,
})
samples.append(sample.Sample(
'Image Build Time', build_time, 'seconds', metadata))
for image_name, build_time in self.remote_build_times.items():
metadata.update({
'build_type': 'remote',
'image': image_name,
})
samples.append(sample.Sample(
'Image Build Time', build_time, 'seconds', metadata))
return samples
def GetFullRegistryTag(self, image):
"""Returns the full name of the image for the registry.
Args:
image: The PKB name of the image (string).
"""
raise NotImplementedError()
def Push(self, image):
"""Push a locally built image to the repo.
Args:
image: Instance of _ContainerImage representing the image to push.
"""
full_tag = self.GetFullRegistryTag(image.name)
tag_cmd = ['docker', 'tag', image.name, full_tag]
vm_util.IssueCommand(tag_cmd)
push_cmd = ['docker', 'push', full_tag]
vm_util.IssueCommand(push_cmd)
def RemoteBuild(self, image):
"""Build the image remotely.
Args:
image: Instance of _ContainerImage representing the image to build.
"""
raise NotImplementedError()
def Login(self):
"""Log in to the registry (in order to push to it)."""
raise NotImplementedError()
def LocalBuild(self, image):
"""Build the image locally.
Args:
image: Instance of _ContainerImage representing the image to build.
"""
build_cmd = [
'docker', 'build', '--no-cache',
'-t', image.name, image.directory
]
vm_util.IssueCommand(build_cmd)
def GetOrBuild(self, image):
"""Finds the image in the registry or builds it.
Args:
image: The PKB name for the image (string).
Returns:
The full image name (including the registry).
"""
full_image = self.GetFullRegistryTag(image)
if not FLAGS.force_container_build:
inspect_cmd = ['docker', 'image', 'inspect', full_image]
_, _, retcode = vm_util.IssueCommand(inspect_cmd, suppress_warning=True,
raise_on_failure=False)
if retcode == 0:
return full_image
self._Build(image)
return full_image
def _Build(self, image):
"""Builds the image and pushes it to the registry if necessary.
Args:
image: The PKB name for the image (string).
"""
image = _ContainerImage(image)
build_start = time.time()
if not FLAGS.local_container_build:
try:
# Build the image remotely using an image building service.
self.RemoteBuild(image)
self.remote_build_times[image.name] = time.time() - build_start
return
except NotImplementedError:
pass
# Build the image locally using docker.
self.LocalBuild(image)
self.local_build_times[image.name] = time.time() - build_start
# Log in to the registry so we can push the image.
self.Login()
# Push the built image to the registry.
self.Push(image)
@events.benchmark_start.connect
def _SetKubeConfig(unused_sender, benchmark_spec):
"""Sets the value for the kubeconfig flag if it's unspecified."""
if not FLAGS.kubeconfig:
FLAGS.kubeconfig = vm_util.PrependTempDir(
'kubeconfig' + str(benchmark_spec.sequence_number))
# Store the value for subsequent run stages.
benchmark_spec.config.flags['kubeconfig'] = FLAGS.kubeconfig
def GetContainerClusterClass(cloud, cluster_type):
return resource.GetResourceClass(BaseContainerCluster,
CLOUD=cloud, CLUSTER_TYPE=cluster_type)
class BaseContainerCluster(resource.BaseResource):
"""A cluster that can be used to schedule containers."""
RESOURCE_TYPE = 'BaseContainerCluster'
REQUIRED_ATTRS = ['CLOUD', 'CLUSTER_TYPE']
def __init__(self, cluster_spec):
super(BaseContainerCluster, self).__init__()
self.name = 'pkb-%s' % FLAGS.run_uri
# Use Virtual Machine class to resolve VM Spec. This lets subclasses parse
# Provider specific information like disks out of the spec.
self.vm_config = virtual_machine.GetVmClass(self.CLOUD, os_types.DEFAULT)(
cluster_spec.vm_spec)
self.num_nodes = cluster_spec.vm_count
self.min_nodes = cluster_spec.min_vm_count or self.num_nodes
self.max_nodes = cluster_spec.max_vm_count or self.num_nodes
self.containers = collections.defaultdict(list)
self.services = {}
self.zone = self.vm_config.zone
def DeleteContainers(self):
"""Delete containers belonging to the cluster."""
for container in itertools.chain(*list(self.containers.values())):
container.Delete()
def DeleteServices(self):
"""Delete services belonging to the cluster."""
for service in self.services.values():
service.Delete()
def GetResourceMetadata(self):
"""Returns a dictionary of cluster metadata."""
metadata = {
'cloud': self.CLOUD,
'cluster_type': self.CLUSTER_TYPE,
'zone': self.zone,
'size': self.num_nodes,
'machine_type': self.vm_config.machine_type,
}
if self.min_nodes != self.num_nodes or self.max_nodes != self.num_nodes:
metadata.update({
'max_size': self.max_nodes,
'min_size': self.min_nodes,
})
return metadata
def DeployContainer(self, name, container_spec):
"""Deploys Containers according to the ContainerSpec."""
raise NotImplementedError()
def DeployContainerService(self, name, container_spec, num_containers):
"""Deploys a ContainerSerivice according to the ContainerSpec."""
raise NotImplementedError()
def GetSamples(self):
"""Return samples with information about deployment times."""
samples = []
samples.append(sample.Sample(
'Cluster Creation Time',
self.resource_ready_time - self.create_start_time,
'seconds'))
for container in itertools.chain(*list(self.containers.values())):
metadata = {'image': container.image.split('/')[-1]}
if container.resource_ready_time and container.create_start_time:
samples.append(sample.Sample(
'Container Deployment Time',
container.resource_ready_time - container.create_start_time,
'seconds', metadata))
if container.delete_end_time and container.delete_start_time:
samples.append(sample.Sample(
'Container Delete Time',
container.delete_end_time - container.delete_start_time,
'seconds', metadata))
for service in self.services.values():
metadata = {'image': service.image.split('/')[-1]}
if service.resource_ready_time and service.create_start_time:
samples.append(sample.Sample(
'Service Deployment Time',
service.resource_ready_time - service.create_start_time,
'seconds', metadata))
if service.delete_end_time and service.delete_start_time:
samples.append(sample.Sample(
'Service Delete Time',
service.delete_end_time - service.delete_start_time,
'seconds', metadata))
return samples
class KubernetesContainer(BaseContainer):
"""A Kubernetes flavor of Container."""
def __init__(self, container_spec, name):
super(KubernetesContainer, self).__init__(container_spec)
self.name = name
def _Create(self):
"""Creates the container."""
run_cmd = [
FLAGS.kubectl, '--kubeconfig', FLAGS.kubeconfig,
'run',
self.name,
'--image=%s' % self.image,
'--restart=Never',
'--limits=cpu=%sm,memory=%sMi' % (int(1000 * self.cpus), self.memory),
]
if self.command:
run_cmd.extend(['--command', '--'])
run_cmd.extend(self.command)
vm_util.IssueCommand(run_cmd)
def _Delete(self):
"""Deletes the container."""
pass
def _IsReady(self):
"""Returns true if the container has stopped pending."""
return self._GetPod()['status']['phase'] != 'Pending'
def _GetPod(self):
"""Gets a representation of the POD and returns it."""
stdout, _, _ = vm_util.IssueCommand([
FLAGS.kubectl, '--kubeconfig', FLAGS.kubeconfig,
'get', 'pod', self.name, '-o', 'yaml'])
pod = yaml.safe_load(stdout)
if pod:
self.ip_address = pod.get('status', {}).get('podIP', None)
return pod
def WaitForExit(self, timeout=None):
"""Waits until the container has finished running."""
@vm_util.Retry(timeout=timeout)
def _WaitForExit():
phase = self._GetPod()['status']['phase']
if phase not in _K8S_FINISHED_PHASES:
raise Exception('POD phase (%s) not in finished phases.' % phase)
_WaitForExit()
def GetLogs(self):
"""Returns the logs from the container."""
stdout, _, _ = vm_util.IssueCommand([
FLAGS.kubectl, '--kubeconfig', FLAGS.kubeconfig, 'logs', self.name])
return stdout
class KubernetesContainerService(BaseContainerService):
"""A Kubernetes flavor of Container Service."""
def __init__(self, container_spec, name):
super(KubernetesContainerService, self).__init__(container_spec)
self.name = name
self.port = 8080
def _Create(self):
run_cmd = [
FLAGS.kubectl,
'run',
self.name,
'--image=%s' % self.image,
'--limits=cpu=%sm,memory=%sMi' % (int(1000 * self.cpus), self.memory),
'--port', str(self.port)
]
if self.command:
run_cmd.extend(['--command', '--'])
run_cmd.extend(self.command)
vm_util.IssueCommand(run_cmd)
expose_cmd = [
FLAGS.kubectl,
'--kubeconfig', FLAGS.kubeconfig,
'expose', 'deployment', self.name,
'--type', 'NodePort',
'--target-port', str(self.port)
]
vm_util.IssueCommand(expose_cmd)
with vm_util.NamedTemporaryFile() as tf:
tf.write(_K8S_INGRESS.format(service_name=self.name))
tf.close()
kubernetes_helper.CreateFromFile(tf.name)
def _GetIpAddress(self):
"""Attempts to set the Service's ip address."""
ingress_name = '%s-ingress' % self.name
get_cmd = [
FLAGS.kubectl, '--kubeconfig', FLAGS.kubeconfig,
'get', 'ing', ingress_name,
'-o', 'jsonpath="{.status.loadBalancer.ingress[*][\'ip\']}"'
]
stdout, _, _ = vm_util.IssueCommand(get_cmd)
ip_address = yaml.safe_load(stdout)
if ip_address:
self.ip_address = ip_address
def _IsReady(self):
"""Returns True if the Service is ready."""
if self.ip_address is None:
self._GetIpAddress()
if self.ip_address is not None:
url = 'http://%s' % (self.ip_address)
r = requests.get(url)
if r.status_code == 200:
return True
return False
def _Delete(self):
"""Deletes the service."""
with vm_util.NamedTemporaryFile() as tf:
tf.write(_K8S_INGRESS.format(service_name=self.name))
tf.close()
kubernetes_helper.DeleteFromFile(tf.name)
delete_cmd = [
FLAGS.kubectl,
'--kubeconfig', FLAGS.kubeconfig,
'delete', 'deployment',
self.name
]
vm_util.IssueCommand(delete_cmd, raise_on_failure=False)
class KubernetesCluster(BaseContainerCluster):
"""A Kubernetes flavor of Container Cluster."""
CLUSTER_TYPE = KUBERNETES
def DeployContainer(self, base_name, container_spec):
"""Deploys Containers according to the ContainerSpec."""
name = base_name + str(len(self.containers[base_name]))
container = KubernetesContainer(container_spec, name)
self.containers[base_name].append(container)
container.Create()
def DeployContainerService(self, name, container_spec):
"""Deploys a ContainerSerivice according to the ContainerSpec."""
service = KubernetesContainerService(container_spec, name)
self.services[name] = service
service.Create()
|
import re
import unittest
from absl import flags
import mock
from perfkitbenchmarker import sample
from perfkitbenchmarker import test_util
from perfkitbenchmarker import timing_util
flags.FLAGS.mark_as_parsed()
class ValidateMeasurementsFlagTestCase(unittest.TestCase):
"""Tests exercising ValidateMeasurementsFlag."""
def testInvalidValue(self):
"""Passing an unrecognized value is not allowed."""
exp_str = 'test: Invalid value for --timing_measurements'
exp_regex = r'^%s$' % re.escape(exp_str)
with self.assertRaisesRegexp(flags.ValidationError, exp_regex):
timing_util.ValidateMeasurementsFlag(['test'])
def testNoneWithAnother(self):
"""Passing none with another value is not allowed."""
exp_str = 'none: Cannot combine with other --timing_measurements options'
exp_regex = r'^%s$' % re.escape(exp_str)
with self.assertRaisesRegexp(flags.ValidationError, exp_regex):
timing_util.ValidateMeasurementsFlag(['none', 'runtimes'])
def testValid(self):
"""Test various valid combinations."""
validate = timing_util.ValidateMeasurementsFlag
self.assertIs(validate([]), True)
self.assertIs(validate(['none']), True)
self.assertIs(validate(['end_to_end_runtime']), True)
self.assertIs(validate(['runtimes']), True)
self.assertIs(validate(['timestamps']), True)
self.assertIs(validate(['end_to_end_runtime', 'runtimes']), True)
self.assertIs(validate(['end_to_end_runtime', 'timestamps']), True)
self.assertIs(validate(['runtimes', 'timestamps']), True)
self.assertIs(
validate(['end_to_end_runtime', 'runtimes', 'timestamps']), True)
class IntervalTimerTestCase(unittest.TestCase, test_util.SamplesTestMixin):
"""Tests exercising IntervalTimer."""
def testMeasureSequential(self):
"""Verify correct interval tuple generation in sequential measurements."""
timer = timing_util.IntervalTimer()
self.assertEqual(timer.intervals, [])
with timer.Measure('First Interval'):
pass
with timer.Measure('Second Interval'):
pass
self.assertEqual(len(timer.intervals), 2)
first_interval = timer.intervals[0]
self.assertEqual(len(first_interval), 3)
first_name = first_interval[0]
first_start = first_interval[1]
first_stop = first_interval[2]
self.assertEqual(first_name, 'First Interval')
second_interval = timer.intervals[1]
self.assertEqual(len(second_interval), 3)
second_name = second_interval[0]
second_start = second_interval[1]
second_stop = second_interval[2]
self.assertEqual(second_name, 'Second Interval')
self.assertLessEqual(first_start, first_stop)
self.assertLessEqual(first_stop, second_start)
self.assertLessEqual(second_start, second_stop)
def testMeasureNested(self):
"""Verify correct interval tuple generation in nested measurements."""
timer = timing_util.IntervalTimer()
self.assertEqual(timer.intervals, [])
with timer.Measure('Outer Interval'):
with timer.Measure('Inner Interval'):
pass
self.assertEqual(len(timer.intervals), 2)
inner_interval = timer.intervals[0]
self.assertEqual(len(inner_interval), 3)
inner_name = inner_interval[0]
inner_start = inner_interval[1]
inner_stop = inner_interval[2]
self.assertEqual(inner_name, 'Inner Interval')
outer_interval = timer.intervals[1]
self.assertEqual(len(outer_interval), 3)
outer_name = outer_interval[0]
outer_start = outer_interval[1]
outer_stop = outer_interval[2]
self.assertEqual(outer_name, 'Outer Interval')
self.assertLessEqual(outer_start, inner_start)
self.assertLessEqual(inner_start, inner_stop)
self.assertLessEqual(inner_stop, outer_stop)
def testGenerateSamplesMeasureNotCalled(self):
"""GenerateSamples should return an empty list if Measure was not called."""
timer = timing_util.IntervalTimer()
self.assertEqual(timer.intervals, [])
samples = timer.GenerateSamples()
self.assertEqual(timer.intervals, [])
self.assertEqual(samples, [])
def testGenerateSamplesRuntimeNoTimestamps(self):
"""Test generating runtime sample but no timestamp samples."""
timer = timing_util.IntervalTimer()
with timer.Measure('First'):
pass
with timer.Measure('Second'):
pass
start0 = timer.intervals[0][1]
stop0 = timer.intervals[0][2]
start1 = timer.intervals[1][1]
stop1 = timer.intervals[1][2]
samples = timer.GenerateSamples()
exp_samples = [
sample.Sample('First Runtime', stop0 - start0, 'seconds'),
sample.Sample('Second Runtime', stop1 - start1, 'seconds')]
self.assertSampleListsEqualUpToTimestamp(samples, exp_samples)
def testGenerateSamplesRuntimeAndTimestamps(self):
"""Test generating both runtime and timestamp samples."""
timer = timing_util.IntervalTimer()
with timer.Measure('First'):
pass
with timer.Measure('Second'):
pass
start0 = timer.intervals[0][1]
stop0 = timer.intervals[0][2]
start1 = timer.intervals[1][1]
stop1 = timer.intervals[1][2]
with mock.patch(
'perfkitbenchmarker.timing_util.TimestampMeasurementsEnabled',
return_value=True):
samples = timer.GenerateSamples()
exp_samples = [
sample.Sample('First Runtime', stop0 - start0, 'seconds'),
sample.Sample('First Start Timestamp', start0, 'seconds'),
sample.Sample('First Stop Timestamp', stop0, 'seconds'),
sample.Sample('Second Runtime', stop1 - start1, 'seconds'),
sample.Sample('Second Start Timestamp', start1, 'seconds'),
sample.Sample('Second Stop Timestamp', stop1, 'seconds')]
self.assertSampleListsEqualUpToTimestamp(samples, exp_samples)
if __name__ == '__main__':
unittest.main()
|
import os
from contextlib import suppress
import pytest
from xarray import DataArray, tutorial
from . import assert_identical, network
@network
class TestLoadDataset:
@pytest.fixture(autouse=True)
def setUp(self):
self.testfile = "tiny"
self.testfilepath = os.path.expanduser(
os.sep.join(("~", ".xarray_tutorial_data", self.testfile))
)
with suppress(OSError):
os.remove(f"{self.testfilepath}.nc")
with suppress(OSError):
os.remove(f"{self.testfilepath}.md5")
def test_download_from_github(self):
ds = tutorial.open_dataset(self.testfile).load()
tiny = DataArray(range(5), name="tiny").to_dataset()
assert_identical(ds, tiny)
def test_download_from_github_load_without_cache(self):
ds_nocache = tutorial.open_dataset(self.testfile, cache=False).load()
ds_cache = tutorial.open_dataset(self.testfile).load()
assert_identical(ds_cache, ds_nocache)
|
import pytest
from homeassistant.auth import models as auth_models
from homeassistant.components.config import auth as auth_config
from tests.common import CLIENT_ID, MockGroup, MockUser
@pytest.fixture(autouse=True)
def setup_config(hass, aiohttp_client):
"""Fixture that sets up the auth provider homeassistant module."""
hass.loop.run_until_complete(auth_config.async_setup(hass))
async def test_list_requires_admin(hass, hass_ws_client, hass_read_only_access_token):
"""Test get users requires auth."""
client = await hass_ws_client(hass, hass_read_only_access_token)
await client.send_json({"id": 5, "type": auth_config.WS_TYPE_LIST})
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "unauthorized"
async def test_list(hass, hass_ws_client, hass_admin_user):
"""Test get users."""
group = MockGroup().add_to_hass(hass)
owner = MockUser(
id="abc", name="Test Owner", is_owner=True, groups=[group]
).add_to_hass(hass)
owner.credentials.append(
auth_models.Credentials(
auth_provider_type="homeassistant", auth_provider_id=None, data={}
)
)
system = MockUser(id="efg", name="Test Hass.io", system_generated=True).add_to_hass(
hass
)
inactive = MockUser(
id="hij", name="Inactive User", is_active=False, groups=[group]
).add_to_hass(hass)
refresh_token = await hass.auth.async_create_refresh_token(owner, CLIENT_ID)
access_token = hass.auth.async_create_access_token(refresh_token)
client = await hass_ws_client(hass, access_token)
await client.send_json({"id": 5, "type": auth_config.WS_TYPE_LIST})
result = await client.receive_json()
assert result["success"], result
data = result["result"]
assert len(data) == 4
assert data[0] == {
"id": hass_admin_user.id,
"name": "Mock User",
"is_owner": False,
"is_active": True,
"system_generated": False,
"group_ids": [group.id for group in hass_admin_user.groups],
"credentials": [],
}
assert data[1] == {
"id": owner.id,
"name": "Test Owner",
"is_owner": True,
"is_active": True,
"system_generated": False,
"group_ids": [group.id for group in owner.groups],
"credentials": [{"type": "homeassistant"}],
}
assert data[2] == {
"id": system.id,
"name": "Test Hass.io",
"is_owner": False,
"is_active": True,
"system_generated": True,
"group_ids": [],
"credentials": [],
}
assert data[3] == {
"id": inactive.id,
"name": "Inactive User",
"is_owner": False,
"is_active": False,
"system_generated": False,
"group_ids": [group.id for group in inactive.groups],
"credentials": [],
}
async def test_delete_requires_admin(hass, hass_ws_client, hass_read_only_access_token):
"""Test delete command requires an admin."""
client = await hass_ws_client(hass, hass_read_only_access_token)
await client.send_json(
{"id": 5, "type": auth_config.WS_TYPE_DELETE, "user_id": "abcd"}
)
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "unauthorized"
async def test_delete_unable_self_account(hass, hass_ws_client, hass_access_token):
"""Test we cannot delete our own account."""
client = await hass_ws_client(hass, hass_access_token)
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
await client.send_json(
{"id": 5, "type": auth_config.WS_TYPE_DELETE, "user_id": refresh_token.user.id}
)
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "no_delete_self"
async def test_delete_unknown_user(hass, hass_ws_client, hass_access_token):
"""Test we cannot delete an unknown user."""
client = await hass_ws_client(hass, hass_access_token)
await client.send_json(
{"id": 5, "type": auth_config.WS_TYPE_DELETE, "user_id": "abcd"}
)
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "not_found"
async def test_delete(hass, hass_ws_client, hass_access_token):
"""Test delete command works."""
client = await hass_ws_client(hass, hass_access_token)
test_user = MockUser(id="efg").add_to_hass(hass)
assert len(await hass.auth.async_get_users()) == 2
await client.send_json(
{"id": 5, "type": auth_config.WS_TYPE_DELETE, "user_id": test_user.id}
)
result = await client.receive_json()
assert result["success"], result
assert len(await hass.auth.async_get_users()) == 1
async def test_create(hass, hass_ws_client, hass_access_token):
"""Test create command works."""
client = await hass_ws_client(hass, hass_access_token)
assert len(await hass.auth.async_get_users()) == 1
await client.send_json({"id": 5, "type": "config/auth/create", "name": "Paulus"})
result = await client.receive_json()
assert result["success"], result
assert len(await hass.auth.async_get_users()) == 2
data_user = result["result"]["user"]
user = await hass.auth.async_get_user(data_user["id"])
assert user is not None
assert user.name == data_user["name"]
assert user.is_active
assert user.groups == []
assert not user.is_admin
assert not user.is_owner
assert not user.system_generated
async def test_create_user_group(hass, hass_ws_client, hass_access_token):
"""Test create user with a group."""
client = await hass_ws_client(hass, hass_access_token)
assert len(await hass.auth.async_get_users()) == 1
await client.send_json(
{
"id": 5,
"type": "config/auth/create",
"name": "Paulus",
"group_ids": ["system-admin"],
}
)
result = await client.receive_json()
assert result["success"], result
assert len(await hass.auth.async_get_users()) == 2
data_user = result["result"]["user"]
user = await hass.auth.async_get_user(data_user["id"])
assert user is not None
assert user.name == data_user["name"]
assert user.is_active
assert user.groups[0].id == "system-admin"
assert user.is_admin
assert not user.is_owner
assert not user.system_generated
async def test_create_requires_admin(hass, hass_ws_client, hass_read_only_access_token):
"""Test create command requires an admin."""
client = await hass_ws_client(hass, hass_read_only_access_token)
await client.send_json({"id": 5, "type": "config/auth/create", "name": "YO"})
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "unauthorized"
async def test_update(hass, hass_ws_client):
"""Test update command works."""
client = await hass_ws_client(hass)
user = await hass.auth.async_create_user("Test user")
await client.send_json(
{
"id": 5,
"type": "config/auth/update",
"user_id": user.id,
"name": "Updated name",
"group_ids": ["system-read-only"],
}
)
result = await client.receive_json()
assert result["success"], result
data_user = result["result"]["user"]
assert user.name == "Updated name"
assert data_user["name"] == "Updated name"
assert len(user.groups) == 1
assert user.groups[0].id == "system-read-only"
assert data_user["group_ids"] == ["system-read-only"]
async def test_update_requires_admin(hass, hass_ws_client, hass_read_only_access_token):
"""Test update command requires an admin."""
client = await hass_ws_client(hass, hass_read_only_access_token)
user = await hass.auth.async_create_user("Test user")
await client.send_json(
{
"id": 5,
"type": "config/auth/update",
"user_id": user.id,
"name": "Updated name",
}
)
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "unauthorized"
assert user.name == "Test user"
async def test_update_system_generated(hass, hass_ws_client):
"""Test update command cannot update a system generated."""
client = await hass_ws_client(hass)
user = await hass.auth.async_create_system_user("Test user")
await client.send_json(
{
"id": 5,
"type": "config/auth/update",
"user_id": user.id,
"name": "Updated name",
}
)
result = await client.receive_json()
assert not result["success"], result
assert result["error"]["code"] == "cannot_modify_system_generated"
assert user.name == "Test user"
|
try:
from appdirs import AppDirs
my_appdirs = AppDirs('gmusicapi', 'Simon Weber')
except ImportError:
print('warning: could not import appdirs; will use current directory')
class FakeAppDirs:
to_spoof = {base + '_dir' for base in
('user_data', 'site_data', 'user_config', 'site_config', 'user_cache',
'user_log')}
def __getattr__(self, name):
if name in self.to_spoof:
return '.' # current dir
else:
raise AttributeError
my_appdirs = FakeAppDirs()
|
import numpy as np
from scattertext.domain.CombineDocsIntoDomains import CombineDocsIntoDomains
class NeedsMaxOrMinDomainCountException(Exception):
pass
class DomainCompactor(object):
def __init__(self, doc_domains, min_domain_count=None, max_domain_count=None):
'''
Parameters
----------
doc_domains : np.array like
Length of documents in corpus. Specifies a single domain for each document.
min_domain_count : int, None
Term should appear in at least this number of domains
Default 0
max_domain_count : int, None
Term should appear in at most this number of domains
Default is the number of domains in doc_domains
'''
self.doc_domains = doc_domains
if max_domain_count is None and min_domain_count is None:
raise NeedsMaxOrMinDomainCountException(
"Either max_domain_count or min_domain_count must be entered"
)
self.min_domain_count = (0 if min_domain_count is None
else min_domain_count)
self.max_domain_count = (len(doc_domains) if max_domain_count is None
else max_domain_count)
def compact(self, term_doc_matrix, non_text=False):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
'''
domain_mat = CombineDocsIntoDomains(term_doc_matrix).get_new_term_doc_mat(self.doc_domains, non_text)
domain_count = (domain_mat > 0).sum(axis=0)
valid_term_mask = (self.max_domain_count >= domain_count) \
& (domain_count >= self.min_domain_count)
indices_to_compact = np.arange(self._get_num_terms(term_doc_matrix, non_text))[~valid_term_mask.A1]
return term_doc_matrix.remove_terms_by_indices(indices_to_compact, non_text=non_text)
def _get_num_terms(self, term_doc_matrix, non_text):
return term_doc_matrix.get_num_metadata() if non_text else term_doc_matrix.get_num_terms()
|
from sqlalchemy import and_
from lemur import database
from lemur.certificates.models import Certificate
from lemur.domains.models import Domain
def get(domain_id):
"""
Fetches one domain
:param domain_id:
:return:
"""
return database.get(Domain, domain_id)
def get_all():
"""
Fetches all domains
:return:
"""
query = database.session_query(Domain)
return database.find_all(query, Domain, {}).all()
def get_by_name(name):
"""
Fetches domain by its name
:param name:
:return:
"""
return database.get_all(Domain, name, field="name").all()
def is_domain_sensitive(name):
"""
Return True if domain is marked sensitive
:param name:
:return:
"""
query = database.session_query(Domain)
query = query.filter(and_(Domain.sensitive, Domain.name == name))
return database.find_all(query, Domain, {}).all()
def create(name, sensitive):
"""
Create a new domain
:param name:
:param sensitive:
:return:
"""
domain = Domain(name=name, sensitive=sensitive)
return database.create(domain)
def update(domain_id, name, sensitive):
"""
Update an existing domain
:param domain_id:
:param name:
:param sensitive:
:return:
"""
domain = get(domain_id)
domain.name = name
domain.sensitive = sensitive
database.update(domain)
def render(args):
"""
Helper to parse REST Api requests
:param args:
:return:
"""
query = database.session_query(Domain)
filt = args.pop("filter")
certificate_id = args.pop("certificate_id", None)
if filt:
terms = filt.split(";")
query = database.filter(query, Domain, terms)
if certificate_id:
query = query.join(Certificate, Domain.certificates)
query = query.filter(Certificate.id == certificate_id)
return database.sort_and_page(query, Domain, args)
|
import os
import pytest
from molecule import config
from molecule.verifier import inspec
from molecule.verifier.lint import rubocop
@pytest.fixture
def _patched_ansible_verify(mocker):
m = mocker.patch('molecule.provisioner.ansible.Ansible.verify')
m.return_value = 'patched-ansible-verify-stdout'
return m
@pytest.fixture
def _patched_inspec_get_tests(mocker):
m = mocker.patch('molecule.verifier.inspec.Inspec._get_tests')
m.return_value = [
'foo.rb',
'bar.rb',
]
return m
@pytest.fixture
def _verifier_section_data():
return {
'verifier': {
'name': 'inspec',
'env': {
'FOO': 'bar',
},
'lint': {
'name': 'rubocop',
},
}
}
# NOTE(retr0h): The use of the `patched_config_validate` fixture, disables
# config.Config._validate from executing. Thus preventing odd side-effects
# throughout patched.assert_called unit tests.
@pytest.fixture
def _instance(_verifier_section_data, patched_config_validate,
config_instance):
return inspec.Inspec(config_instance)
def test_config_private_member(_instance):
assert isinstance(_instance._config, config.Config)
def test_default_options_property(_instance):
assert {} == _instance.default_options
def test_default_env_property(_instance):
assert 'MOLECULE_FILE' in _instance.default_env
assert 'MOLECULE_INVENTORY_FILE' in _instance.default_env
assert 'MOLECULE_SCENARIO_DIRECTORY' in _instance.default_env
assert 'MOLECULE_INSTANCE_CONFIG' in _instance.default_env
@pytest.mark.parametrize(
'config_instance', ['_verifier_section_data'], indirect=True)
def test_env_property(_instance):
assert 'bar' == _instance.env['FOO']
@pytest.mark.parametrize(
'config_instance', ['_verifier_section_data'], indirect=True)
def test_lint_property(_instance):
assert isinstance(_instance.lint, rubocop.RuboCop)
def test_name_property(_instance):
assert 'inspec' == _instance.name
def test_enabled_property(_instance):
assert _instance.enabled
def test_directory_property(_instance):
parts = _instance.directory.split(os.path.sep)
assert 'tests' == parts[-1]
@pytest.mark.parametrize(
'config_instance', ['_verifier_section_data'], indirect=True)
def test_options_property(_instance):
x = {}
assert x == _instance.options
@pytest.mark.parametrize(
'config_instance', ['_verifier_section_data'], indirect=True)
def test_options_property_handles_cli_args(_instance):
_instance._config.args = {'debug': True}
x = {}
# Does nothing. The `inspec` command does not support
# a `debug` flag.
assert x == _instance.options
def test_bake(_instance):
assert _instance.bake() is None
def test_execute(patched_logger_info, _patched_ansible_verify,
_patched_inspec_get_tests, patched_logger_success, _instance):
_instance.execute()
_patched_ansible_verify.assert_called_once_with()
msg = 'Executing Inspec tests found in {}/...'.format(_instance.directory)
patched_logger_info.assert_called_once_with(msg)
msg = 'Verifier completed successfully.'
patched_logger_success.assert_called_once_with(msg)
def test_execute_does_not_execute(patched_ansible_converge,
patched_logger_warn, _instance):
_instance._config.config['verifier']['enabled'] = False
_instance.execute()
assert not patched_ansible_converge.called
msg = 'Skipping, verifier is disabled.'
patched_logger_warn.assert_called_once_with(msg)
def test_does_not_execute_without_tests(patched_ansible_converge,
patched_logger_warn, _instance):
_instance.execute()
assert not patched_ansible_converge.called
msg = 'Skipping, no tests found.'
patched_logger_warn.assert_called_once_with(msg)
def test_execute_bakes():
pass
|
import shutil
import unittest
import subprocess
from subprocess import PIPE
from integration_tests.fake_trash_dir import FakeTrashDir, a_trashinfo
from integration_tests.files import read_file
from trashcli import base_dir
import tempfile
import os
from os.path import join as pj
from os.path import exists as file_exists
class TestEndToEndRestore(unittest.TestCase):
def setUp(self):
self.tmpdir = os.path.realpath(tempfile.mkdtemp())
self.curdir = os.path.join(self.tmpdir, "cwd")
self.trash_dir = os.path.join(self.tmpdir, "trash-dir")
os.makedirs(self.curdir)
self.fake_trash_dir = FakeTrashDir(self.trash_dir)
def test_no_file_trashed(self):
result = self.run_command("trash-restore")
self.assertEqual("""\
No files trashed from current dir ('%s')
""" % self.curdir, result.stdout)
def test_original_file_not_existing(self):
self.fake_trash_dir.add_trashinfo(a_trashinfo("/path"))
result = self.run_command("trash-restore", ["/"], input='0')
self.assertEqual("""\
0 2000-01-01 00:00:01 /path
What file to restore [0..0]: """,
result.stdout)
self.assertEqual("[Errno 2] No such file or directory: '%s/files/1'\n" %
self.trash_dir,
result.stderr)
def test_restore_happy_path(self):
self.fake_trash_dir.add_trashed_file("file1",
pj(self.curdir, "path/to/file1"),
"contents")
self.fake_trash_dir.add_trashed_file("file2",
pj(self.curdir, "path/to/file2"),
"contents")
self.assertEqual(True, file_exists(pj(self.trash_dir, "info", "file2.trashinfo")))
self.assertEqual(True, file_exists(pj(self.trash_dir, "files", "file2")))
result = self.run_command("trash-restore", ["/", '--sort=path'], input='1')
self.assertEqual("""\
0 2000-01-01 00:00:01 %(curdir)s/path/to/file1
1 2000-01-01 00:00:01 %(curdir)s/path/to/file2
What file to restore [0..1]: """ % { 'curdir': self.curdir},
result.stdout)
self.assertEqual("", result.stderr)
self.assertEqual("contents", read_file(pj(self.curdir, "path/to/file2")))
self.assertEqual(False, file_exists(pj(self.trash_dir, "info", "file2.trashinfo")))
self.assertEqual(False, file_exists(pj(self.trash_dir, "files", "file2")))
def run_command(self, command, args=None, input=''):
class Result:
def __init__(self, stdout, stderr):
self.stdout = stdout
self.stderr = stderr
if args == None:
args = []
command_full_path = os.path.join(base_dir, command)
process = subprocess.Popen(["python", command_full_path,
"--trash-dir", self.trash_dir] + args,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE, cwd=self.curdir)
stdout, stderr = process.communicate(input=input.encode('utf-8'))
return Result(stdout.decode('utf-8'), stderr.decode('utf-8'))
def tearDown(self):
shutil.rmtree(self.tmpdir)
|
import unittest
import unittest.mock
import openrazer_daemon.misc.effect_sync
# msg type = effect, arg = orig_device, arg = effect_name, arg.. = arg..
MSG1 = ('effect', None, 'setBrightness', 255)
# Static effect message from blackwidow chroma
MSG2 = ('effect', None, 'setStatic', 255, 255, 0)
# Static effect message from blackwidow standard
MSG3 = ('effect', None, 'setStatic')
# Breathing effect message from blackwidow chroma
MSG4 = ('effect', None, 'setBreathSingle', 255, 255, 0)
# Pulsate effect message from blackwidow standard
MSG5 = ('effect', None, 'setPulsate')
def logger_mock(*args):
return unittest.mock.MagicMock()
class DummyHardwareDevice(object):
def __init__(self):
self.observer_list = []
self.disable_notify = None
self.effect_call = None
def register_observer(self, obs):
if obs not in self.observer_list:
self.observer_list.append(obs)
def remove_observer(self, obs):
if obs in self.observer_list:
self.observer_list.remove(obs)
# Effect functions
def setBrightness(self, brightness):
self.effect_call = ('setBrightness', brightness)
def setStatic(self):
raise Exception("test")
class DummyHardwareBlackWidowStandard(DummyHardwareDevice):
def setStatic(self):
self.effect_call = ('setStatic',)
def setPulsate(self):
self.effect_call = ('setPulsate',)
class DummyHardwareBlackWidowChroma(DummyHardwareDevice):
def setStatic(self, red, green, blue):
self.effect_call = ('setStatic', red, green, blue)
def setBreathSingle(self, red, green, blue):
self.effect_call = ('setBreathSingle', red, green, blue)
class EffectSyncTest(unittest.TestCase):
@unittest.mock.patch('openrazer_daemon.misc.effect_sync.logging.getLogger', logger_mock)
def setUp(self):
self.hardware_device = DummyHardwareDevice()
self.effect_sync = openrazer_daemon.misc.effect_sync.EffectSync(self.hardware_device, 1)
def test_observers(self):
self.assertIn(self.effect_sync, self.hardware_device.observer_list)
# Remove observers
self.effect_sync.close()
self.assertEqual(len(self.hardware_device.observer_list), 0)
def test_get_num_arguments(self):
def func_2_args(x, y): return x + y
num_args = self.effect_sync.get_num_arguments(func_2_args)
self.assertEqual(num_args, 2)
def test_notify_invalid_message(self):
self.effect_sync.notify("test")
self.assertTrue(self.effect_sync._logger.warning.called)
def test_notify_message_from_other(self):
# Patch run_effect
self.effect_sync.run_effect = unittest.mock.MagicMock()
self.effect_sync.notify(MSG1)
self.assertTrue(self.effect_sync.run_effect.called)
new_msg = self.effect_sync.run_effect.call_args_list[0][0]
# Check function is called run_effect('setBrightness', 255)
self.assertEqual(new_msg[0], MSG1[2])
self.assertEqual(new_msg[1], MSG1[3])
def test_notify_run_effect(self):
self.effect_sync.notify(MSG1)
self.assertEqual(self.hardware_device.effect_call[0], MSG1[2])
self.assertEqual(self.hardware_device.effect_call[1], MSG1[3])
self.assertIsNotNone(self.hardware_device.disable_notify)
self.assertFalse(self.hardware_device.disable_notify)
def test_notify_run_effect_edge_case_1(self):
# Set the parent to a blackwidow (non chroma)
self.hardware_device = DummyHardwareBlackWidowStandard()
self.effect_sync._parent = self.hardware_device
self.hardware_device.register_observer(self.effect_sync)
self.effect_sync.notify(MSG2)
self.assertEqual(self.hardware_device.effect_call[0], MSG2[2])
def test_notify_run_effect_edge_case_2(self):
# Set the parent to a blackwidow chroma
self.hardware_device = DummyHardwareBlackWidowChroma()
self.effect_sync._parent = self.hardware_device
self.hardware_device.register_observer(self.effect_sync)
self.effect_sync.notify(MSG3)
self.assertTupleEqual(self.hardware_device.effect_call, ('setStatic', 0, 255, 0))
def test_notify_run_effect_edge_case_3(self):
# Set the parent to a blackwidow (non chroma)
self.hardware_device = DummyHardwareBlackWidowStandard()
self.effect_sync._parent = self.hardware_device
self.hardware_device.register_observer(self.effect_sync)
self.effect_sync.notify(MSG4)
# Send setBreath but converted it to setPulsate
self.assertEqual(self.hardware_device.effect_call[0], 'setPulsate')
def test_notify_run_effect_edge_case_4(self):
# Set the parent to a blackwidow chroma
self.hardware_device = DummyHardwareBlackWidowChroma()
self.effect_sync._parent = self.hardware_device
self.hardware_device.register_observer(self.effect_sync)
self.effect_sync.notify(MSG5)
self.assertTupleEqual(self.hardware_device.effect_call, ('setBreathSingle', 0, 255, 0))
def test_notify_run_effect_edge_case_5(self):
# Exception of standard setStatic() should be caught
self.effect_sync.notify(MSG3)
# Logger should have called .exception
self.assertTrue(self.effect_sync._logger.exception.called)
|
from homeassistant.components.atag.sensor import SENSORS
from homeassistant.core import HomeAssistant
from tests.components.atag import UID, init_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_sensors(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the creation of ATAG sensors."""
entry = await init_integration(hass, aioclient_mock)
registry = await hass.helpers.entity_registry.async_get_registry()
for item in SENSORS:
sensor_id = "_".join(f"sensor.{item}".lower().split())
assert registry.async_is_registered(sensor_id)
entry = registry.async_get(sensor_id)
assert entry.unique_id in [f"{UID}-{v}" for v in SENSORS.values()]
|
from easydict import EasyDict as edict
import numpy as np
config = edict()
config.IMG_HEIGHT = 375
config.IMG_WIDTH = 1242
# TODO(shizehao): infer fea shape in run time
config.FEA_HEIGHT = 12
config.FEA_WIDTH = 39
config.EPSILON = 1e-16
config.LOSS_COEF_BBOX = 5.0
config.LOSS_COEF_CONF_POS = 75.0
config.LOSS_COEF_CONF_NEG = 100.0
config.LOSS_COEF_CLASS = 1.0
config.EXP_THRESH = 1.0
config.RBG_MEANS = np.array([[[ 123.68, 116.779, 103.939]]])
def set_anchors(H, W):
B = 9
shape = np.array(
[[ 36., 37.], [ 366., 174.], [ 115., 59.],
[ 162., 87.], [ 38., 90.], [ 258., 173.],
[ 224., 108.], [ 78., 170.], [ 72., 43.]])
# # scale
# shape[:, 0] = shape[:, 0] / config.IMG_HEIGHT
# shape[:, 1] = shape[:, 1] / config.IMG_WIDTH
anchor_shapes = np.reshape(
[shape] * H * W,
(H, W, B, 2)
)
center_x = np.reshape(
np.transpose(
np.reshape(
np.array([np.arange(1, W+1)*float(config.IMG_WIDTH)/(W+1)]*H*B),
(B, H, W)
),
(1, 2, 0)
),
(H, W, B, 1)
)
center_y = np.reshape(
np.transpose(
np.reshape(
np.array([np.arange(1, H+1)*float(config.IMG_HEIGHT)/(H+1)]*W*B),
(B, W, H)
),
(2, 1, 0)
),
(H, W, B, 1)
)
anchors = np.reshape(
np.concatenate((center_x, center_y, anchor_shapes), axis=3),
(-1, 4)
)
return anchors
config.ANCHOR_SHAPE = set_anchors(config.FEA_HEIGHT, config.FEA_WIDTH)
config.NUM_ANCHORS = 9
config.NUM_CLASSES = 3
config.ANCHORS = config.NUM_ANCHORS * config.FEA_HEIGHT * config.FEA_WIDTH
config.PLOT_PROB_THRESH = 0.4
config.NMS_THRESH = 0.4
config.PROB_THRESH = 0.005
config.TOP_N_DETECTION = 64
|
from homeassistant.components.geonetnz_quakes import DOMAIN, FEED
from tests.async_mock import patch
async def test_component_unload_config_entry(hass, config_entry):
"""Test that loading and unloading of a config entry works."""
config_entry.add_to_hass(hass)
with patch(
"aio_geojson_geonetnz_quakes.GeonetnzQuakesFeedManager.update"
) as mock_feed_manager_update:
# Load config entry.
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert mock_feed_manager_update.call_count == 1
assert hass.data[DOMAIN][FEED][config_entry.entry_id] is not None
# Unload config entry.
assert await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done()
assert hass.data[DOMAIN][FEED].get(config_entry.entry_id) is None
|
import logging
from absl import flags
from perfkitbenchmarker import configs
from perfkitbenchmarker import errors
from perfkitbenchmarker.linux_packages import blazemark
flags.DEFINE_list('blazemark_set', ['all'],
'A set of blazemark benchmarks to run.'
'See following link for a complete list of benchmarks to run:'
' https://bitbucket.org/blaze-lib/blaze/wiki/Blazemark.')
# TODO: Support other library.
flags.DEFINE_list('blazemark_kernels', ['-only-blaze'], 'A list of additional '
'flags send to blazemark, in order to '
'enable/disable kernels/libraries. '
'Currently only support blaze. '
'See following link for more details: '
'https://bitbucket.org/blaze-lib/blaze/wiki/'
'Blazemark#!command-line-parameters')
FLAGS = flags.FLAGS
BENCHMARK_NAME = 'blazemark'
BENCHMARK_CONFIG = """
blazemark:
description: >
Run blazemark. See:
https://bitbucket.org/blaze-lib/blaze/wiki/Blazemark
vm_groups:
default:
vm_spec: *default_single_core
"""
def GetConfig(user_config):
return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
def CheckPrerequisites(benchmark_config):
"""Perform flag checks."""
if 'all' not in FLAGS.blazemark_set:
requested = frozenset(FLAGS.blazemark_set)
binaries = blazemark.GetBinaries()
if requested - binaries:
raise errors.Benchmarks.PrepareException(
'Binaries %s not available. Options are %s' % (
requested - binaries, binaries))
def Prepare(benchmark_spec):
"""Prepare vm for blazemark.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
vm = benchmark_spec.vms[0]
vm.Install('blazemark')
def Run(benchmark_spec):
"""Measure the boot time for all VMs.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample objects with individual machine boot times.
"""
vm = benchmark_spec.vms[0]
if 'all' not in FLAGS.blazemark_set:
run = FLAGS.blazemark_set
else:
run = blazemark.GetBinaries()
results = []
for test in run:
logging.info('Running %s', test)
results.extend(blazemark.RunTest(vm, test))
return results
def Cleanup(benchmark_spec):
pass
|
from datetime import timedelta
import time
import pytest
import zigpy.profiles.zha
import zigpy.zcl.clusters.general as general
import homeassistant.components.automation as automation
import homeassistant.components.zha.core.device as zha_core_device
from homeassistant.helpers.device_registry import async_get_registry
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from .common import async_enable_traffic
from tests.common import (
async_fire_time_changed,
async_get_device_automations,
async_mock_service,
)
ON = 1
OFF = 0
SHAKEN = "device_shaken"
COMMAND = "command"
COMMAND_SHAKE = "shake"
COMMAND_HOLD = "hold"
COMMAND_SINGLE = "single"
COMMAND_DOUBLE = "double"
DOUBLE_PRESS = "remote_button_double_press"
SHORT_PRESS = "remote_button_short_press"
LONG_PRESS = "remote_button_long_press"
LONG_RELEASE = "remote_button_long_release"
def _same_lists(list_a, list_b):
if len(list_a) != len(list_b):
return False
for item in list_a:
if item not in list_b:
return False
return True
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture
async def mock_devices(hass, zigpy_device_mock, zha_device_joined_restored):
"""IAS device fixture."""
zigpy_device = zigpy_device_mock(
{
1: {
"in_clusters": [general.Basic.cluster_id],
"out_clusters": [general.OnOff.cluster_id],
"device_type": zigpy.profiles.zha.DeviceType.ON_OFF_SWITCH,
}
}
)
zha_device = await zha_device_joined_restored(zigpy_device)
zha_device.update_available(True)
await hass.async_block_till_done()
return zigpy_device, zha_device
async def test_triggers(hass, mock_devices):
"""Test zha device triggers."""
zigpy_device, zha_device = mock_devices
zigpy_device.device_automation_triggers = {
(SHAKEN, SHAKEN): {COMMAND: COMMAND_SHAKE},
(DOUBLE_PRESS, DOUBLE_PRESS): {COMMAND: COMMAND_DOUBLE},
(SHORT_PRESS, SHORT_PRESS): {COMMAND: COMMAND_SINGLE},
(LONG_PRESS, LONG_PRESS): {COMMAND: COMMAND_HOLD},
(LONG_RELEASE, LONG_RELEASE): {COMMAND: COMMAND_HOLD},
}
ieee_address = str(zha_device.ieee)
ha_device_registry = await async_get_registry(hass)
reg_device = ha_device_registry.async_get_device({("zha", ieee_address)}, set())
triggers = await async_get_device_automations(hass, "trigger", reg_device.id)
expected_triggers = [
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": "device_offline",
"subtype": "device_offline",
},
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": SHAKEN,
"subtype": SHAKEN,
},
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": DOUBLE_PRESS,
"subtype": DOUBLE_PRESS,
},
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": SHORT_PRESS,
"subtype": SHORT_PRESS,
},
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": LONG_PRESS,
"subtype": LONG_PRESS,
},
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": LONG_RELEASE,
"subtype": LONG_RELEASE,
},
]
assert _same_lists(triggers, expected_triggers)
async def test_no_triggers(hass, mock_devices):
"""Test zha device with no triggers."""
_, zha_device = mock_devices
ieee_address = str(zha_device.ieee)
ha_device_registry = await async_get_registry(hass)
reg_device = ha_device_registry.async_get_device({("zha", ieee_address)}, set())
triggers = await async_get_device_automations(hass, "trigger", reg_device.id)
assert triggers == [
{
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": "device_offline",
"subtype": "device_offline",
}
]
async def test_if_fires_on_event(hass, mock_devices, calls):
"""Test for remote triggers firing."""
zigpy_device, zha_device = mock_devices
zigpy_device.device_automation_triggers = {
(SHAKEN, SHAKEN): {COMMAND: COMMAND_SHAKE},
(DOUBLE_PRESS, DOUBLE_PRESS): {COMMAND: COMMAND_DOUBLE},
(SHORT_PRESS, SHORT_PRESS): {COMMAND: COMMAND_SINGLE},
(LONG_PRESS, LONG_PRESS): {COMMAND: COMMAND_HOLD},
(LONG_RELEASE, LONG_RELEASE): {COMMAND: COMMAND_HOLD},
}
ieee_address = str(zha_device.ieee)
ha_device_registry = await async_get_registry(hass)
reg_device = ha_device_registry.async_get_device({("zha", ieee_address)}, set())
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": SHORT_PRESS,
"subtype": SHORT_PRESS,
},
"action": {
"service": "test.automation",
"data": {"message": "service called"},
},
}
]
},
)
await hass.async_block_till_done()
channel = zha_device.channels.pools[0].client_channels["1:0x0006"]
channel.zha_send_event(COMMAND_SINGLE, [])
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["message"] == "service called"
async def test_device_offline_fires(
hass, zigpy_device_mock, zha_device_restored, calls
):
"""Test for device offline triggers firing."""
zigpy_device = zigpy_device_mock(
{
1: {
"in_clusters": [general.Basic.cluster_id],
"out_clusters": [general.OnOff.cluster_id],
"device_type": 0,
}
}
)
zha_device = await zha_device_restored(zigpy_device, last_seen=time.time())
await async_enable_traffic(hass, [zha_device])
await hass.async_block_till_done()
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"device_id": zha_device.device_id,
"domain": "zha",
"platform": "device",
"type": "device_offline",
"subtype": "device_offline",
},
"action": {
"service": "test.automation",
"data": {"message": "service called"},
},
}
]
},
)
await hass.async_block_till_done()
assert zha_device.available is True
zigpy_device.last_seen = (
time.time() - zha_core_device.CONSIDER_UNAVAILABLE_BATTERY - 2
)
# there are 3 checkins to perform before marking the device unavailable
future = dt_util.utcnow() + timedelta(seconds=90)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
future = dt_util.utcnow() + timedelta(seconds=90)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
future = dt_util.utcnow() + timedelta(
seconds=zha_core_device.CONSIDER_UNAVAILABLE_BATTERY + 100
)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert zha_device.available is False
assert len(calls) == 1
assert calls[0].data["message"] == "service called"
async def test_exception_no_triggers(hass, mock_devices, calls, caplog):
"""Test for exception on event triggers firing."""
_, zha_device = mock_devices
ieee_address = str(zha_device.ieee)
ha_device_registry = await async_get_registry(hass)
reg_device = ha_device_registry.async_get_device({("zha", ieee_address)}, set())
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": "junk",
"subtype": "junk",
},
"action": {
"service": "test.automation",
"data": {"message": "service called"},
},
}
]
},
)
await hass.async_block_till_done()
assert "Invalid config for [automation]" in caplog.text
async def test_exception_bad_trigger(hass, mock_devices, calls, caplog):
"""Test for exception on event triggers firing."""
zigpy_device, zha_device = mock_devices
zigpy_device.device_automation_triggers = {
(SHAKEN, SHAKEN): {COMMAND: COMMAND_SHAKE},
(DOUBLE_PRESS, DOUBLE_PRESS): {COMMAND: COMMAND_DOUBLE},
(SHORT_PRESS, SHORT_PRESS): {COMMAND: COMMAND_SINGLE},
(LONG_PRESS, LONG_PRESS): {COMMAND: COMMAND_HOLD},
(LONG_RELEASE, LONG_RELEASE): {COMMAND: COMMAND_HOLD},
}
ieee_address = str(zha_device.ieee)
ha_device_registry = await async_get_registry(hass)
reg_device = ha_device_registry.async_get_device({("zha", ieee_address)}, set())
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"device_id": reg_device.id,
"domain": "zha",
"platform": "device",
"type": "junk",
"subtype": "junk",
},
"action": {
"service": "test.automation",
"data": {"message": "service called"},
},
}
]
},
)
await hass.async_block_till_done()
assert "Invalid config for [automation]" in caplog.text
|
import pytest
import homeassistant.components.time_date.sensor as time_date
import homeassistant.util.dt as dt_util
from tests.async_mock import patch
ORIG_TZ = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture(autouse=True)
def restore_ts():
"""Restore default TZ."""
yield
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
# pylint: disable=protected-access
async def test_intervals(hass):
"""Test timing intervals of sensors."""
device = time_date.TimeDateSensor(hass, "time")
now = dt_util.utc_from_timestamp(45)
next_time = device.get_next_interval(now)
assert next_time == dt_util.utc_from_timestamp(60)
device = time_date.TimeDateSensor(hass, "beat")
now = dt_util.utc_from_timestamp(29)
next_time = device.get_next_interval(now)
assert next_time == dt_util.utc_from_timestamp(86.4)
device = time_date.TimeDateSensor(hass, "date_time")
now = dt_util.utc_from_timestamp(1495068899)
next_time = device.get_next_interval(now)
assert next_time == dt_util.utc_from_timestamp(1495068900)
now = dt_util.utcnow()
device = time_date.TimeDateSensor(hass, "time_date")
next_time = device.get_next_interval()
assert next_time > now
async def test_states(hass):
"""Test states of sensors."""
now = dt_util.utc_from_timestamp(1495068856)
device = time_date.TimeDateSensor(hass, "time")
device._update_internal_state(now)
assert device.state == "00:54"
device = time_date.TimeDateSensor(hass, "date")
device._update_internal_state(now)
assert device.state == "2017-05-18"
device = time_date.TimeDateSensor(hass, "time_utc")
device._update_internal_state(now)
assert device.state == "00:54"
device = time_date.TimeDateSensor(hass, "date_time")
device._update_internal_state(now)
assert device.state == "2017-05-18, 00:54"
device = time_date.TimeDateSensor(hass, "date_time_utc")
device._update_internal_state(now)
assert device.state == "2017-05-18, 00:54"
device = time_date.TimeDateSensor(hass, "beat")
device._update_internal_state(now)
assert device.state == "@079"
device = time_date.TimeDateSensor(hass, "date_time_iso")
device._update_internal_state(now)
assert device.state == "2017-05-18T00:54:00"
async def test_states_non_default_timezone(hass):
"""Test states of sensors in a timezone other than UTC."""
new_tz = dt_util.get_time_zone("America/New_York")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
now = dt_util.utc_from_timestamp(1495068856)
device = time_date.TimeDateSensor(hass, "time")
device._update_internal_state(now)
assert device.state == "20:54"
device = time_date.TimeDateSensor(hass, "date")
device._update_internal_state(now)
assert device.state == "2017-05-17"
device = time_date.TimeDateSensor(hass, "time_utc")
device._update_internal_state(now)
assert device.state == "00:54"
device = time_date.TimeDateSensor(hass, "date_time")
device._update_internal_state(now)
assert device.state == "2017-05-17, 20:54"
device = time_date.TimeDateSensor(hass, "date_time_utc")
device._update_internal_state(now)
assert device.state == "2017-05-18, 00:54"
device = time_date.TimeDateSensor(hass, "beat")
device._update_internal_state(now)
assert device.state == "@079"
device = time_date.TimeDateSensor(hass, "date_time_iso")
device._update_internal_state(now)
assert device.state == "2017-05-17T20:54:00"
# pylint: disable=no-member
async def test_timezone_intervals(hass):
"""Test date sensor behavior in a timezone besides UTC."""
new_tz = dt_util.get_time_zone("America/New_York")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
device = time_date.TimeDateSensor(hass, "date")
now = dt_util.utc_from_timestamp(50000)
next_time = device.get_next_interval(now)
# start of local day in EST was 18000.0
# so the second day was 18000 + 86400
assert next_time.timestamp() == 104400
new_tz = dt_util.get_time_zone("America/Edmonton")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
now = dt_util.parse_datetime("2017-11-13 19:47:19-07:00")
device = time_date.TimeDateSensor(hass, "date")
next_time = device.get_next_interval(now)
assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00")
@patch(
"homeassistant.util.dt.utcnow",
return_value=dt_util.parse_datetime("2017-11-14 02:47:19-00:00"),
)
async def test_timezone_intervals_empty_parameter(hass):
"""Test get_interval() without parameters."""
new_tz = dt_util.get_time_zone("America/Edmonton")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
device = time_date.TimeDateSensor(hass, "date")
next_time = device.get_next_interval()
assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00")
async def test_icons(hass):
"""Test attributes of sensors."""
device = time_date.TimeDateSensor(hass, "time")
assert device.icon == "mdi:clock"
device = time_date.TimeDateSensor(hass, "date")
assert device.icon == "mdi:calendar"
device = time_date.TimeDateSensor(hass, "date_time")
assert device.icon == "mdi:calendar-clock"
device = time_date.TimeDateSensor(hass, "date_time_utc")
assert device.icon == "mdi:calendar-clock"
device = time_date.TimeDateSensor(hass, "date_time_iso")
assert device.icon == "mdi:calendar-clock"
|
from kalliope.core.Models.settings.SettingsEntry import SettingsEntry
class Trigger(SettingsEntry):
"""
This Class is representing a Trigger with its name and parameters
.. note:: must be defined in the settings.yml
"""
def __init__(self, name=None, parameters=None):
super(Trigger, self).__init__(name=name)
self.parameters = parameters
def __str__(self):
return str(self.serialize())
def serialize(self):
# TODO fix Trigger to remove "callback" from parameters
return {
'name': self.name,
'parameters': dict((key, value) for key, value in self.parameters.items() if key != "callback"),
}
def __eq__(self, other):
"""
This is used to compare 2 objects
:param other: the Trigger to compare
:return: True if both triggers are similar, False otherwise
"""
return self.__dict__ == other.__dict__
|
import cProfile
import pstats
from weblate.trans.models import Component, Project
from weblate.utils.management.base import BaseCommand
class Command(BaseCommand):
"""Run simple project import to perform benchmarks."""
help = "performs import benchmark"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--profile-sort", default="cumulative", help="sort order for profile stats"
)
parser.add_argument(
"--profile-filter", default="/weblate", help="filter for profile stats"
)
parser.add_argument(
"--profile-count",
type=int,
default=20,
help="number of profile stats to show",
)
parser.add_argument("--template", default="", help="template monolingual files")
parser.add_argument(
"--delete", action="store_true", help="delete after testing"
)
parser.add_argument("--format", default="po", help="file format")
parser.add_argument("project", help="Existing project slug for tests")
parser.add_argument("repo", help="Test VCS repository URL")
parser.add_argument("mask", help="File mask")
def handle(self, *args, **options):
project = Project.objects.get(slug=options["project"])
# Delete any possible previous tests
Component.objects.filter(project=project, slug="benchmark").delete()
profiler = cProfile.Profile()
component = profiler.runcall(
Component.objects.create,
name="Benchmark",
slug="benchmark",
repo=options["repo"],
filemask=options["mask"],
template=options["template"],
file_format=options["format"],
project=project,
)
profiler.runcall(component.after_save, True, False, False, False, True)
stats = pstats.Stats(profiler, stream=self.stdout)
stats.sort_stats(options["profile_sort"])
stats.print_stats(options["profile_filter"], options["profile_count"])
# Delete after testing
if options["delete"]:
component.delete()
|
from openzwavemqtt.const import CommandClass
from homeassistant.components.cover import (
ATTR_POSITION,
DEVICE_CLASS_GARAGE,
DOMAIN as COVER_DOMAIN,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
CoverEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DATA_UNSUBSCRIBE, DOMAIN
from .entity import ZWaveDeviceEntity
SUPPORTED_FEATURES_POSITION = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION
SUPPORT_GARAGE = SUPPORT_OPEN | SUPPORT_CLOSE
VALUE_SELECTED_ID = "Selected_id"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Cover from Config Entry."""
@callback
def async_add_cover(values):
"""Add Z-Wave Cover."""
if values.primary.command_class == CommandClass.BARRIER_OPERATOR:
cover = ZwaveGarageDoorBarrier(values)
else:
cover = ZWaveCoverEntity(values)
async_add_entities([cover])
hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(
async_dispatcher_connect(hass, f"{DOMAIN}_new_{COVER_DOMAIN}", async_add_cover)
)
def percent_to_zwave_position(value):
"""Convert position in 0-100 scale to 0-99 scale.
`value` -- (int) Position byte value from 0-100.
"""
if value > 0:
return max(1, round((value / 100) * 99))
return 0
class ZWaveCoverEntity(ZWaveDeviceEntity, CoverEntity):
"""Representation of a Z-Wave Cover device."""
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORTED_FEATURES_POSITION
@property
def is_closed(self):
"""Return true if cover is closed."""
return self.values.primary.value == 0
@property
def current_cover_position(self):
"""Return the current position of cover where 0 means closed and 100 is fully open."""
return round((self.values.primary.value / 99) * 100)
async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
self.values.primary.send_value(percent_to_zwave_position(kwargs[ATTR_POSITION]))
async def async_open_cover(self, **kwargs):
"""Open the cover."""
self.values.primary.send_value(99)
async def async_close_cover(self, **kwargs):
"""Close cover."""
self.values.primary.send_value(0)
class ZwaveGarageDoorBarrier(ZWaveDeviceEntity, CoverEntity):
"""Representation of a barrier operator Zwave garage door device."""
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_GARAGE
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_GARAGE
@property
def is_opening(self):
"""Return true if cover is in an opening state."""
return self.values.primary.value[VALUE_SELECTED_ID] == 3
@property
def is_closing(self):
"""Return true if cover is in a closing state."""
return self.values.primary.value[VALUE_SELECTED_ID] == 1
@property
def is_closed(self):
"""Return the current position of Zwave garage door."""
return self.values.primary.value[VALUE_SELECTED_ID] == 0
async def async_close_cover(self, **kwargs):
"""Close the garage door."""
self.values.primary.send_value(0)
async def async_open_cover(self, **kwargs):
"""Open the garage door."""
self.values.primary.send_value(4)
|
from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import ZWaveDeviceEntity, const
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Z-Wave Sensor from Config Entry."""
@callback
def async_add_sensor(sensor):
"""Add Z-Wave Sensor."""
async_add_entities([sensor])
async_dispatcher_connect(hass, "zwave_new_sensor", async_add_sensor)
def get_device(node, values, **kwargs):
"""Create Z-Wave entity device."""
# Generic Device mappings
if values.primary.command_class == const.COMMAND_CLASS_BATTERY:
return ZWaveBatterySensor(values)
if node.has_command_class(const.COMMAND_CLASS_SENSOR_MULTILEVEL):
return ZWaveMultilevelSensor(values)
if (
node.has_command_class(const.COMMAND_CLASS_METER)
and values.primary.type == const.TYPE_DECIMAL
):
return ZWaveMultilevelSensor(values)
if node.has_command_class(const.COMMAND_CLASS_ALARM) or node.has_command_class(
const.COMMAND_CLASS_SENSOR_ALARM
):
return ZWaveAlarmSensor(values)
return None
class ZWaveSensor(ZWaveDeviceEntity):
"""Representation of a Z-Wave sensor."""
def __init__(self, values):
"""Initialize the sensor."""
ZWaveDeviceEntity.__init__(self, values, DOMAIN)
self.update_properties()
def update_properties(self):
"""Handle the data changes for node values."""
self._state = self.values.primary.data
self._units = self.values.primary.units
@property
def force_update(self):
"""Return force_update."""
return True
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement the value is expressed in."""
return self._units
class ZWaveMultilevelSensor(ZWaveSensor):
"""Representation of a multi level sensor Z-Wave sensor."""
@property
def state(self):
"""Return the state of the sensor."""
if self._units in ("C", "F"):
return round(self._state, 1)
if isinstance(self._state, float):
return round(self._state, 2)
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
if self._units == "C":
return TEMP_CELSIUS
if self._units == "F":
return TEMP_FAHRENHEIT
return self._units
class ZWaveAlarmSensor(ZWaveSensor):
"""Representation of a Z-Wave sensor that sends Alarm alerts.
Examples include certain Multisensors that have motion and vibration
capabilities. Z-Wave defines various alarm types such as Smoke, Flood,
Burglar, CarbonMonoxide, etc.
This wraps these alarms and allows you to use them to trigger things, etc.
COMMAND_CLASS_ALARM is what we get here.
"""
class ZWaveBatterySensor(ZWaveSensor):
"""Representation of Z-Wave device battery level."""
@property
def device_class(self):
"""Return the class of this device."""
return DEVICE_CLASS_BATTERY
|
import io
import logging
import optparse
import os
import signal
from gi.repository import Gdk, Gio, GLib, Gtk
import meld.accelerators
import meld.conf
from meld.conf import _
from meld.filediff import FileDiff
from meld.meldwindow import MeldWindow
from meld.preferences import PreferencesDialog
log = logging.getLogger(__name__)
# Monkeypatching optparse like this is obviously awful, but this is to
# handle Unicode translated strings within optparse itself that will
# otherwise crash badly. This just makes optparse use our ugettext
# import of _, rather than the non-unicode gettext.
optparse._ = _
try:
import gi
gi.require_version('GtkosxApplication', '1.0')
from gi.repository import GtkosxApplication
class BASE_CLASS(Gtk.Application, GtkosxApplication.Application):
pass
except:
class BASE_CLASS(Gtk.Application):
pass
class MeldApp(BASE_CLASS):
def __init__(self):
super().__init__(
application_id=meld.conf.APPLICATION_ID,
flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
)
GtkosxApplication.Application.__init__(self)
GLib.set_application_name(meld.conf.APPLICATION_NAME)
GLib.set_prgname(meld.conf.APPLICATION_ID)
Gtk.Window.set_default_icon_name(meld.conf.APPLICATION_ID)
self.set_resource_base_path(meld.conf.RESOURCE_BASE)
provider = Gtk.CssProvider()
provider.load_from_resource(self.make_resource_path('meld.css'))
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(), provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
def make_resource_path(self, resource_path: str) -> str:
return f'{self.props.resource_base_path}/{resource_path}'
def do_startup(self):
Gtk.Application.do_startup(self)
meld.accelerators.register_accels(self)
actions = (
("preferences", self.preferences_callback),
("help", self.help_callback),
("about", self.about_callback),
("quit", self.quit_callback),
("mac_shell_integration", self.mac_shell_integration_callback),
)
for (name, callback) in actions:
action = Gio.SimpleAction.new(name, None)
action.connect('activate', callback)
self.add_action(action)
self.new_window()
self.ready()
def do_activate(self):
self.get_active_window().present()
def do_command_line(self, command_line):
tab = self.parse_args(command_line)
if isinstance(tab, int):
return tab
elif tab:
def done(tab, status):
self.release()
tab.command_line.set_exit_status(status)
tab.command_line = None
self.hold()
tab.command_line = command_line
tab.close_signal.connect(done)
window = self.get_active_window()
if not window.has_pages():
window.append_new_comparison()
self.activate()
return 0
# We can't override do_local_command_line because it has no introspection
# annotations: https://bugzilla.gnome.org/show_bug.cgi?id=687912
# def do_local_command_line(self, command_line):
# return False
def preferences_callback(self, action, parameter):
parent = self.get_active_window()
dialog = PreferencesDialog(transient_for=parent)
dialog.present()
def help_callback(self, action, parameter):
if meld.conf.DATADIR_IS_UNINSTALLED:
uri = "http://meldmerge.org/help/"
else:
uri = "help:meld"
Gtk.show_uri(
Gdk.Screen.get_default(), uri, Gtk.get_current_event_time())
def about_callback(self, action, parameter):
builder = Gtk.Builder.new_from_resource(
'/org/gnome/meld/ui/about-dialog.ui')
dialog = builder.get_object('about-dialog')
dialog.set_version(meld.conf.__version__)
dialog.set_logo_icon_name(meld.conf.APPLICATION_ID)
dialog.set_transient_for(self.get_active_window())
dialog.run()
dialog.destroy()
def quit_callback(self, action, parameter):
for window in self.get_windows():
cancelled = window.emit(
"delete-event", Gdk.Event.new(Gdk.EventType.DELETE))
if cancelled:
return
window.destroy()
self.quit()
def mac_shell_integration_callback(self, action, parameter):
from meld.misc import MacShellIntegration
MacShellIntegration().setup_integration()
def new_window(self):
window = MeldWindow()
self.add_window(window)
return window
def open_files(
self, gfiles, *, window=None, close_on_error=False, **kwargs):
"""Open a comparison between files in a Meld window
:param gfiles: list of Gio.File to be compared
:param window: window in which to open comparison tabs; if
None, the current window is used
:param close_on_error: if true, close window if an error occurs
"""
window = window or self.get_active_window()
try:
return window.open_paths(gfiles, **kwargs)
except ValueError:
if close_on_error:
self.remove_window(window)
raise
def diff_files_callback(self, option, opt_str, value, parser):
"""Gather --diff arguments and append to a list"""
assert value is None
diff_files_args = []
while parser.rargs:
# Stop if we find a short- or long-form arg, or a '--'
# Note that this doesn't handle negative numbers.
arg = parser.rargs[0]
if arg[:2] == "--" or (arg[:1] == "-" and len(arg) > 1):
break
else:
diff_files_args.append(arg)
del parser.rargs[0]
if len(diff_files_args) not in (1, 2, 3):
raise optparse.OptionValueError(
_("wrong number of arguments supplied to --diff"))
parser.values.diff.append(diff_files_args)
def setup_mac_integration(self, menubar):
import warnings
def ignore_warning(message, category, filename, lineno, file, line):
return
old_showwarning = warnings.showwarning
warnings.showwarning = ignore_warning
self.set_use_quartz_accelerators(True)
self.set_menu_bar(menubar) # We're skipping the cast warning in here
warnings.showwarning = old_showwarning
item = Gtk.MenuItem.new_with_label(_("About"))
item.connect("activate", self.about_callback, None)
menubar.add(item)
self.insert_app_menu_item(item, 0)
self.set_about_item(item)
separator = Gtk.SeparatorMenuItem()
menubar.add(separator)
self.insert_app_menu_item(separator, 1)
item = Gtk.MenuItem.new_with_label(_("Preferences"))
item.connect("activate", self.preferences_callback, None)
menubar.add(item)
self.insert_app_menu_item(item, 2)
# TODO: Re-enable shell integration for Catalina now that zsh is default
# item = Gtk.MenuItem.new_with_label(_("Shell Integration"))
# item.connect("activate", self.mac_shell_integration_callback, None)
# menubar.add(item)
# self.insert_app_menu_item(item, 3)
separator = Gtk.SeparatorMenuItem()
menubar.add(separator)
self.insert_app_menu_item(separator, 4)
self.sync_menubar()
self.ready()
def parse_args(self, command_line):
usages = [
("", _("Start with an empty window")),
("<%s|%s>" % (_("file"), _("folder")),
_("Start a version control comparison")),
("<%s> <%s> [<%s>]" % ((_("file"),) * 3),
_("Start a 2- or 3-way file comparison")),
("<%s> <%s> [<%s>]" % ((_("folder"),) * 3),
_("Start a 2- or 3-way folder comparison")),
]
pad_args_fmt = "%-" + str(max([len(s[0]) for s in usages])) + "s %s"
usage_lines = [" %prog " + pad_args_fmt % u for u in usages]
usage = "\n" + "\n".join(usage_lines)
class GLibFriendlyOptionParser(optparse.OptionParser):
def __init__(self, command_line, *args, **kwargs):
self.command_line = command_line
self.should_exit = False
self.output = io.StringIO()
self.exit_status = 0
super().__init__(*args, **kwargs)
def exit(self, status=0, msg=None):
self.should_exit = True
# FIXME: This is... let's say... an unsupported method. Let's
# be circumspect about the likelihood of this working.
try:
self.command_line.do_print_literal(
self.command_line, self.output.getvalue())
except Exception:
print(self.output.getvalue())
self.exit_status = status
def print_usage(self, file=None):
if self.usage:
print(self.get_usage(), file=self.output)
def print_version(self, file=None):
if self.version:
print(self.get_version(), file=self.output)
def print_help(self, file=None):
print(self.format_help(), file=self.output)
def error(self, msg):
self.local_error(msg)
raise ValueError()
def local_error(self, msg):
self.print_usage()
error_string = _("Error: %s\n") % msg
print(error_string, file=self.output)
self.exit(2)
parser = GLibFriendlyOptionParser(
command_line=command_line,
usage=usage,
description=_("Meld is a file and directory comparison tool."),
version="%prog " + meld.conf.__version__)
parser.add_option(
"-L", "--label", action="append", default=[],
help=_("Set label to use instead of file name"))
parser.add_option(
"-n", "--newtab", action="store_true", default=False,
help=_("Open a new tab in an already running instance"))
parser.add_option(
"-a", "--auto-compare", action="store_true", default=False,
help=_("Automatically compare all differing files on startup"))
parser.add_option(
"-u", "--unified", action="store_true",
help=_("Ignored for compatibility"))
parser.add_option(
"-o", "--output", action="store", type="string",
dest="outfile", default=None,
help=_("Set the target file for saving a merge result"))
parser.add_option(
"--auto-merge", None, action="store_true", default=False,
help=_("Automatically merge files"))
parser.add_option(
"", "--comparison-file", action="store", type="string",
dest="comparison_file", default=None,
help=_("Load a saved comparison from a Meld comparison file"))
parser.add_option(
"", "--diff", action="callback", callback=self.diff_files_callback,
dest="diff", default=[],
help=_("Create a diff tab for the supplied files or folders"))
def cleanup():
if not command_line.get_is_remote():
self.quit()
parser.command_line = None
rawargs = command_line.get_arguments()[1:]
try:
options, args = parser.parse_args(rawargs)
except ValueError:
# Thrown to avert further parsing when we've hit an error, because
# of our weird when-to-exit issues.
pass
if parser.should_exit:
cleanup()
return parser.exit_status
if len(args) > 3:
parser.local_error(_("too many arguments (wanted 0-3, got %d)") %
len(args))
elif options.auto_merge and len(args) < 3:
parser.local_error(_("can’t auto-merge less than 3 files"))
elif options.auto_merge and any([os.path.isdir(f) for f in args]):
parser.local_error(_("can’t auto-merge directories"))
if parser.should_exit:
cleanup()
return parser.exit_status
if options.comparison_file or (len(args) == 1 and
args[0].endswith(".meldcmp")):
path = options.comparison_file or args[0]
comparison_file_path = os.path.expanduser(path)
gio_file = Gio.File.new_for_path(comparison_file_path)
try:
tab = self.get_active_window().append_recent(
gio_file.get_uri())
except (IOError, ValueError):
parser.local_error(_("Error reading saved comparison file"))
if parser.should_exit:
cleanup()
return parser.exit_status
return tab
def make_file_from_command_line(arg):
f = command_line.create_file_for_arg(arg)
if not f.query_exists(cancellable=None):
# May be a relative path with ':', misinterpreted as a URI
cwd = Gio.File.new_for_path(command_line.get_cwd())
relative = Gio.File.resolve_relative_path(cwd, arg)
if relative.query_exists(cancellable=None):
return relative
# Return the original arg for a better error message
if f.get_uri() is None:
raise ValueError(_("invalid path or URI “%s”") % arg)
# TODO: support for directories specified by URIs
file_type = f.query_file_type(Gio.FileQueryInfoFlags.NONE, None)
if not f.is_native() and file_type == Gio.FileType.DIRECTORY:
raise ValueError(
_("remote folder “{}” not supported").format(arg))
return f
tab = None
error = None
comparisons = [c for c in [args] + options.diff if c]
# Every Meld invocation creates at most one window. If there is
# no existing application, a window is created in do_startup().
# If there is an existing application, then this is a remote
# invocation, in which case we'll create a window if and only
# if the new-tab flag is not provided.
#
# In all cases, all tabs newly created here are attached to the
# same window, either implicitly by using the most-recently-
# focused window, or explicitly as below.
window = None
close_on_error = False
if command_line.get_is_remote() and not options.newtab:
window = self.new_window()
close_on_error = True
for i, paths in enumerate(comparisons):
auto_merge = options.auto_merge and i == 0
try:
files = [make_file_from_command_line(p) for p in paths]
tab = self.open_files(
files,
window=window,
close_on_error=close_on_error,
auto_compare=options.auto_compare,
auto_merge=auto_merge,
focus=i == 0,
)
except ValueError as err:
error = err
log.debug("Couldn't open comparison: %s", error, exc_info=True)
else:
if i > 0:
continue
if options.label:
tab.set_labels(options.label)
if options.outfile and isinstance(tab, FileDiff):
outfile = make_file_from_command_line(options.outfile)
tab.set_merge_output_file(outfile)
if error:
if not tab:
parser.local_error(error)
else:
print(error)
# Delete the error here; otherwise we keep the local app
# alive in a reference cycle, and the command line hangs.
del error
if parser.should_exit:
cleanup()
return parser.exit_status
parser.command_line = None
return tab if len(comparisons) == 1 else None
|
import unittest
import numpy as np
import numpy.testing as np_test
from pgmpy.factors.discrete import DiscreteFactor, TabularCPD
from pgmpy.models import BayesianModel
from pgmpy.inference import Inference
from pgmpy.inference import VariableElimination
class TestStateNameInit(unittest.TestCase):
def setUp(self):
self.sn2 = {
"grade": ["A", "B", "F"],
"diff": ["high", "low"],
"intel": ["poor", "good", "very good"],
}
self.sn1 = {
"speed": ["low", "medium", "high"],
"switch": ["on", "off"],
"time": ["day", "night"],
}
self.sn2_no_names = {"grade": [0, 1, 2], "diff": [0, 1], "intel": [0, 1, 2]}
self.sn1_no_names = {"speed": [0, 1, 2], "switch": [0, 1], "time": [0, 1]}
self.phi1 = DiscreteFactor(["speed", "switch", "time"], [3, 2, 2], np.ones(12))
self.phi2 = DiscreteFactor(
["speed", "switch", "time"], [3, 2, 2], np.ones(12), state_names=self.sn1
)
self.cpd1 = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
)
self.cpd2 = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
state_names=self.sn2,
)
student = BayesianModel([("diff", "grade"), ("intel", "grade")])
diff_cpd = TabularCPD("diff", 2, [[0.2], [0.8]])
intel_cpd = TabularCPD("intel", 2, [[0.3], [0.7]])
grade_cpd = TabularCPD(
"grade",
3,
[[0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8]],
evidence=["diff", "intel"],
evidence_card=[2, 2],
)
student.add_cpds(diff_cpd, intel_cpd, grade_cpd)
self.model1 = Inference(student)
self.model2 = Inference(student)
def test_factor_init_statename(self):
self.assertEqual(self.phi1.state_names, self.sn1_no_names)
self.assertEqual(self.phi2.state_names, self.sn1)
def test_cpd_init_statename(self):
self.assertEqual(self.cpd1.state_names, self.sn2_no_names)
self.assertEqual(self.cpd2.state_names, self.sn2)
class StateNameDecorator(unittest.TestCase):
def setUp(self):
self.sn2 = {
"grade": ["A", "B", "F"],
"diff": ["high", "low"],
"intel": ["poor", "good", "very good"],
}
self.sn1 = {
"speed": ["low", "medium", "high"],
"switch": ["on", "off"],
"time": ["day", "night"],
}
self.phi1 = DiscreteFactor(["speed", "switch", "time"], [3, 2, 2], np.ones(12))
self.phi2 = DiscreteFactor(
["speed", "switch", "time"], [3, 2, 2], np.ones(12), state_names=self.sn1
)
self.cpd1 = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
)
self.cpd2 = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
state_names=self.sn2,
)
student = BayesianModel([("diff", "grade"), ("intel", "grade")])
student_state_names = BayesianModel([("diff", "grade"), ("intel", "grade")])
diff_cpd = TabularCPD("diff", 2, [[0.2], [0.8]])
intel_cpd = TabularCPD("intel", 2, [[0.3], [0.7]])
grade_cpd = TabularCPD(
"grade",
3,
[[0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8]],
evidence=["diff", "intel"],
evidence_card=[2, 2],
)
diff_cpd_state_names = TabularCPD(
variable="diff",
variable_card=2,
values=[[0.2], [0.8]],
state_names={"diff": ["high", "low"]},
)
intel_cpd_state_names = TabularCPD(
variable="intel",
variable_card=2,
values=[[0.3], [0.7]],
state_names={"intel": ["poor", "good", "very good"]},
)
grade_cpd_state_names = TabularCPD(
"grade",
3,
[[0.1, 0.1, 0.1, 0.1], [0.1, 0.1, 0.1, 0.1], [0.8, 0.8, 0.8, 0.8]],
evidence=["diff", "intel"],
evidence_card=[2, 2],
state_names=self.sn2,
)
student.add_cpds(diff_cpd, intel_cpd, grade_cpd)
student_state_names.add_cpds(
diff_cpd_state_names, intel_cpd_state_names, grade_cpd_state_names
)
self.model_no_state_names = VariableElimination(student)
self.model_with_state_names = VariableElimination(student_state_names)
def test_assignment_statename(self):
req_op1 = [
[("speed", "low"), ("switch", "on"), ("time", "night")],
[("speed", "low"), ("switch", "off"), ("time", "day")],
]
req_op2 = [
[("speed", 0), ("switch", 0), ("time", 1)],
[("speed", 0), ("switch", 1), ("time", 0)],
]
self.assertEqual(self.phi1.assignment([1, 2]), req_op2)
self.assertEqual(self.phi2.assignment([1, 2]), req_op1)
def test_factor_reduce_statename(self):
phi = DiscreteFactor(
["speed", "switch", "time"], [3, 2, 2], np.ones(12), state_names=self.sn1
)
phi.reduce([("speed", "medium"), ("time", "day")])
self.assertEqual(phi.variables, ["switch"])
self.assertEqual(phi.cardinality, [2])
np_test.assert_array_equal(phi.values, np.array([1, 1]))
phi = DiscreteFactor(
["speed", "switch", "time"], [3, 2, 2], np.ones(12), state_names=self.sn1
)
phi = phi.reduce([("speed", "medium"), ("time", "day")], inplace=False)
self.assertEqual(phi.variables, ["switch"])
self.assertEqual(phi.cardinality, [2])
np_test.assert_array_equal(phi.values, np.array([1, 1]))
phi = DiscreteFactor(["speed", "switch", "time"], [3, 2, 2], np.ones(12))
phi.reduce([("speed", 1), ("time", 0)])
self.assertEqual(phi.variables, ["switch"])
self.assertEqual(phi.cardinality, [2])
np_test.assert_array_equal(phi.values, np.array([1, 1]))
phi = DiscreteFactor(["speed", "switch", "time"], [3, 2, 2], np.ones(12))
phi = phi.reduce([("speed", 1), ("time", 0)], inplace=False)
self.assertEqual(phi.variables, ["switch"])
self.assertEqual(phi.cardinality, [2])
np_test.assert_array_equal(phi.values, np.array([1, 1]))
def test_reduce_cpd_statename(self):
cpd = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
state_names=self.sn2,
)
cpd.reduce([("diff", "high")])
self.assertEqual(cpd.variable, "grade")
self.assertEqual(cpd.variables, ["grade", "intel"])
np_test.assert_array_equal(
cpd.get_values(),
np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.8, 0.8, 0.8]]),
)
cpd = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
)
cpd.reduce([("diff", 0)])
self.assertEqual(cpd.variable, "grade")
self.assertEqual(cpd.variables, ["grade", "intel"])
np_test.assert_array_equal(
cpd.get_values(),
np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.8, 0.8, 0.8]]),
)
cpd = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
state_names=self.sn2,
)
cpd = cpd.reduce([("diff", "high")], inplace=False)
self.assertEqual(cpd.variable, "grade")
self.assertEqual(cpd.variables, ["grade", "intel"])
np_test.assert_array_equal(
cpd.get_values(),
np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.8, 0.8, 0.8]]),
)
cpd = TabularCPD(
"grade",
3,
[
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8],
],
evidence=["diff", "intel"],
evidence_card=[2, 3],
)
cpd = cpd.reduce([("diff", 0)], inplace=False)
self.assertEqual(cpd.variable, "grade")
self.assertEqual(cpd.variables, ["grade", "intel"])
np_test.assert_array_equal(
cpd.get_values(),
np.array([[0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.8, 0.8, 0.8]]),
)
def test_inference_query_statename(self):
inf_op1 = self.model_with_state_names.query(
["grade"], evidence={"intel": "poor"}
)
inf_op2 = self.model_no_state_names.query(["grade"], evidence={"intel": 0})
req_op = DiscreteFactor(
["grade"],
[3],
np.array([0.1, 0.1, 0.8]),
state_names={"grade": ["A", "B", "F"]},
)
self.assertEqual(inf_op1, req_op)
self.assertEqual(inf_op1, req_op)
inf_op1 = self.model_with_state_names.map_query(
["grade"], evidence={"intel": "poor"}
)
inf_op2 = self.model_no_state_names.map_query(["grade"], evidence={"intel": 0})
req_op1 = {"grade": "F"}
req_op2 = {"grade": 2}
self.assertEqual(inf_op1, req_op1)
self.assertEqual(inf_op2, req_op2)
|
import logging
import voluptuous as vol
from homeassistant.components.alarm_control_panel import (
FORMAT_NUMBER,
AlarmControlPanelEntity,
)
from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
SUPPORT_ALARM_ARM_NIGHT,
SUPPORT_ALARM_TRIGGER,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_DISARMED,
STATE_ALARM_PENDING,
STATE_ALARM_TRIGGERED,
STATE_UNKNOWN,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import (
CONF_CODE,
CONF_PANIC,
CONF_PARTITIONNAME,
DATA_EVL,
DOMAIN,
PARTITION_SCHEMA,
SIGNAL_KEYPAD_UPDATE,
SIGNAL_PARTITION_UPDATE,
EnvisalinkDevice,
)
_LOGGER = logging.getLogger(__name__)
SERVICE_ALARM_KEYPRESS = "alarm_keypress"
ATTR_KEYPRESS = "keypress"
ALARM_KEYPRESS_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_KEYPRESS): cv.string,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Perform the setup for Envisalink alarm panels."""
configured_partitions = discovery_info["partitions"]
code = discovery_info[CONF_CODE]
panic_type = discovery_info[CONF_PANIC]
devices = []
for part_num in configured_partitions:
device_config_data = PARTITION_SCHEMA(configured_partitions[part_num])
device = EnvisalinkAlarm(
hass,
part_num,
device_config_data[CONF_PARTITIONNAME],
code,
panic_type,
hass.data[DATA_EVL].alarm_state["partition"][part_num],
hass.data[DATA_EVL],
)
devices.append(device)
async_add_entities(devices)
@callback
def alarm_keypress_handler(service):
"""Map services to methods on Alarm."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
keypress = service.data.get(ATTR_KEYPRESS)
target_devices = [
device for device in devices if device.entity_id in entity_ids
]
for device in target_devices:
device.async_alarm_keypress(keypress)
hass.services.async_register(
DOMAIN,
SERVICE_ALARM_KEYPRESS,
alarm_keypress_handler,
schema=ALARM_KEYPRESS_SCHEMA,
)
return True
class EnvisalinkAlarm(EnvisalinkDevice, AlarmControlPanelEntity):
"""Representation of an Envisalink-based alarm panel."""
def __init__(
self, hass, partition_number, alarm_name, code, panic_type, info, controller
):
"""Initialize the alarm panel."""
self._partition_number = partition_number
self._code = code
self._panic_type = panic_type
_LOGGER.debug("Setting up alarm: %s", alarm_name)
super().__init__(alarm_name, info, controller)
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_KEYPAD_UPDATE, self._update_callback
)
)
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_PARTITION_UPDATE, self._update_callback
)
)
@callback
def _update_callback(self, partition):
"""Update Home Assistant state, if needed."""
if partition is None or int(partition) == self._partition_number:
self.async_write_ha_state()
@property
def code_format(self):
"""Regex for code format or None if no code is required."""
if self._code:
return None
return FORMAT_NUMBER
@property
def state(self):
"""Return the state of the device."""
state = STATE_UNKNOWN
if self._info["status"]["alarm"]:
state = STATE_ALARM_TRIGGERED
elif self._info["status"]["armed_zero_entry_delay"]:
state = STATE_ALARM_ARMED_NIGHT
elif self._info["status"]["armed_away"]:
state = STATE_ALARM_ARMED_AWAY
elif self._info["status"]["armed_stay"]:
state = STATE_ALARM_ARMED_HOME
elif self._info["status"]["exit_delay"]:
state = STATE_ALARM_PENDING
elif self._info["status"]["entry_delay"]:
state = STATE_ALARM_PENDING
elif self._info["status"]["alpha"]:
state = STATE_ALARM_DISARMED
return state
@property
def supported_features(self) -> int:
"""Return the list of supported features."""
return (
SUPPORT_ALARM_ARM_HOME
| SUPPORT_ALARM_ARM_AWAY
| SUPPORT_ALARM_ARM_NIGHT
| SUPPORT_ALARM_TRIGGER
)
async def async_alarm_disarm(self, code=None):
"""Send disarm command."""
if code:
self.hass.data[DATA_EVL].disarm_partition(str(code), self._partition_number)
else:
self.hass.data[DATA_EVL].disarm_partition(
str(self._code), self._partition_number
)
async def async_alarm_arm_home(self, code=None):
"""Send arm home command."""
if code:
self.hass.data[DATA_EVL].arm_stay_partition(
str(code), self._partition_number
)
else:
self.hass.data[DATA_EVL].arm_stay_partition(
str(self._code), self._partition_number
)
async def async_alarm_arm_away(self, code=None):
"""Send arm away command."""
if code:
self.hass.data[DATA_EVL].arm_away_partition(
str(code), self._partition_number
)
else:
self.hass.data[DATA_EVL].arm_away_partition(
str(self._code), self._partition_number
)
async def async_alarm_trigger(self, code=None):
"""Alarm trigger command. Will be used to trigger a panic alarm."""
self.hass.data[DATA_EVL].panic_alarm(self._panic_type)
async def async_alarm_arm_night(self, code=None):
"""Send arm night command."""
self.hass.data[DATA_EVL].arm_night_partition(
str(code) if code else str(self._code), self._partition_number
)
@callback
def async_alarm_keypress(self, keypress=None):
"""Send custom keypress."""
if keypress:
self.hass.data[DATA_EVL].keypresses_to_partition(
self._partition_number, keypress
)
|
from homeassistant.components.ipma import DOMAIN, config_flow
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE
from homeassistant.helpers import entity_registry
from homeassistant.setup import async_setup_component
from .test_weather import MockLocation
from tests.async_mock import Mock, patch
from tests.common import MockConfigEntry, mock_registry
async def test_show_config_form():
"""Test show configuration form."""
hass = Mock()
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
result = await flow._show_config_form()
assert result["type"] == "form"
assert result["step_id"] == "user"
async def test_show_config_form_default_values():
"""Test show configuration form."""
hass = Mock()
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
result = await flow._show_config_form(name="test", latitude="0", longitude="0")
assert result["type"] == "form"
assert result["step_id"] == "user"
async def test_flow_with_home_location(hass):
"""Test config flow .
Tests the flow when a default location is configured
then it should return a form with default values
"""
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
hass.config.location_name = "Home"
hass.config.latitude = 1
hass.config.longitude = 1
result = await flow.async_step_user()
assert result["type"] == "form"
assert result["step_id"] == "user"
async def test_flow_show_form():
"""Test show form scenarios first time.
Test when the form should show when no configurations exists
"""
hass = Mock()
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
with patch(
"homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form"
) as config_form:
await flow.async_step_user()
assert len(config_form.mock_calls) == 1
async def test_flow_entry_created_from_user_input():
"""Test that create data from user input.
Test when the form should show when no configurations exists
"""
hass = Mock()
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
test_data = {"name": "home", CONF_LONGITUDE: "0", CONF_LATITUDE: "0"}
# Test that entry created when user_input name not exists
with patch(
"homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form"
) as config_form, patch.object(
flow.hass.config_entries,
"async_entries",
return_value=[],
) as config_entries:
result = await flow.async_step_user(user_input=test_data)
assert result["type"] == "create_entry"
assert result["data"] == test_data
assert len(config_entries.mock_calls) == 1
assert not config_form.mock_calls
async def test_flow_entry_config_entry_already_exists():
"""Test that create data from user input and config_entry already exists.
Test when the form should show when user puts existing name
in the config gui. Then the form should show with error
"""
hass = Mock()
flow = config_flow.IpmaFlowHandler()
flow.hass = hass
test_data = {"name": "home", CONF_LONGITUDE: "0", CONF_LATITUDE: "0"}
# Test that entry created when user_input name not exists
with patch(
"homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form"
) as config_form, patch.object(
flow.hass.config_entries, "async_entries", return_value={"home": test_data}
) as config_entries:
await flow.async_step_user(user_input=test_data)
assert len(config_form.mock_calls) == 1
assert len(config_entries.mock_calls) == 1
assert len(flow._errors) == 1
async def test_config_entry_migration(hass):
"""Tests config entry without mode in unique_id can be migrated."""
ipma_entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
data={CONF_LATITUDE: 0, CONF_LONGITUDE: 0, CONF_MODE: "daily"},
)
ipma_entry.add_to_hass(hass)
ipma_entry2 = MockConfigEntry(
domain=DOMAIN,
title="Home",
data={CONF_LATITUDE: 0, CONF_LONGITUDE: 0, CONF_MODE: "hourly"},
)
ipma_entry2.add_to_hass(hass)
mock_registry(
hass,
{
"weather.hometown": entity_registry.RegistryEntry(
entity_id="weather.hometown",
unique_id="0, 0",
platform="ipma",
config_entry_id=ipma_entry.entry_id,
),
"weather.hometown_2": entity_registry.RegistryEntry(
entity_id="weather.hometown_2",
unique_id="0, 0, hourly",
platform="ipma",
config_entry_id=ipma_entry.entry_id,
),
},
)
with patch(
"homeassistant.components.ipma.weather.async_get_location",
return_value=MockLocation(),
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
ent_reg = await entity_registry.async_get_registry(hass)
weather_home = ent_reg.async_get("weather.hometown")
assert weather_home.unique_id == "0, 0, daily"
weather_home2 = ent_reg.async_get("weather.hometown_2")
assert weather_home2.unique_id == "0, 0, hourly"
|
from time import time
import psutil
import asyncio
from flexx import flx
nsamples = 16
class Relay(flx.Component):
number_of_connections = flx.IntProp(settable=True)
def init(self):
self.update_number_of_connections()
self.refresh()
@flx.manager.reaction('connections_changed')
def update_number_of_connections(self, *events):
n = 0
for name in flx.manager.get_app_names():
sessions = flx.manager.get_connections(name)
n += len(sessions)
self.set_number_of_connections(n)
@flx.emitter
def system_info(self):
return dict(cpu=psutil.cpu_percent(),
mem=psutil.virtual_memory().percent,
sessions=self.number_of_connections,
total_sessions=flx.manager.total_sessions,
)
def refresh(self):
self.system_info()
asyncio.get_event_loop().call_later(1, self.refresh)
# Create global relay
relay = Relay()
class Monitor(flx.PyComponent):
cpu_count = psutil.cpu_count()
nsamples = nsamples
def init(self):
with flx.VBox():
flx.Label(html='<h3>Server monitor</h3>')
if flx.current_server().serving[0] == 'localhost':
# Don't do this for a public server
self.button = flx.Button(text='Do some work')
self.button.reaction(self._do_work, 'pointer_down')
self.view = MonitorView(flex=1)
@relay.reaction('system_info') # note that we connect to relay
def _push_info(self, *events):
if not self.session.status:
return relay.disconnect('system_info:' + self.id)
for ev in events:
self.view.update_info(dict(cpu=ev.cpu,
mem=ev.mem,
sessions=ev.sessions,
total_sessions=ev.total_sessions))
def _do_work(self, *events):
etime = time() + len(events)
# print('doing work for %i s' % len(events))
while time() < etime:
pass
class MonitorView(flx.VBox):
def init(self):
self.start_time = time()
self.status = flx.Label(text='...')
self.cpu_plot = flx.PlotWidget(flex=1, style='width: 640px; height: 320px;',
xdata=[], yrange=(0, 100),
ylabel='CPU usage (%)')
self.mem_plot = flx.PlotWidget(flex=1, style='width: 640px; height: 320px;',
xdata=[], yrange=(0, 100),
ylabel='Mem usage (%)')
@flx.action
def update_info(self, info):
# Set connections
n = info.sessions, info.total_sessions
self.status.set_html('There are %i connected clients.<br />' % n[0] +
'And in total we served %i connections.<br />' % n[1])
# Prepare plots
times = list(self.cpu_plot.xdata)
times.append(time() - self.start_time)
times = times[-self.nsamples:]
# cpu data
usage = list(self.cpu_plot.ydata)
usage.append(info.cpu)
usage = usage[-self.nsamples:]
self.cpu_plot.set_data(times, usage)
# mem data
usage = list(self.mem_plot.ydata)
usage.append(info.mem)
usage = usage[-self.nsamples:]
self.mem_plot.set_data(times, usage)
if __name__ == '__main__':
a = flx.App(Monitor)
a.serve()
# m = a.launch('browser') # for use during development
flx.start()
|
import logging
import pizone
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.typing import HomeAssistantType
from .const import (
DATA_DISCOVERY_SERVICE,
DISPATCH_CONTROLLER_DISCONNECTED,
DISPATCH_CONTROLLER_DISCOVERED,
DISPATCH_CONTROLLER_RECONNECTED,
DISPATCH_CONTROLLER_UPDATE,
DISPATCH_ZONE_UPDATE,
)
_LOGGER = logging.getLogger(__name__)
class DiscoveryService(pizone.Listener):
"""Discovery data and interfacing with pizone library."""
def __init__(self, hass):
"""Initialise discovery service."""
super().__init__()
self.hass = hass
self.pi_disco = None
# Listener interface
def controller_discovered(self, ctrl: pizone.Controller) -> None:
"""Handle new controller discoverery."""
async_dispatcher_send(self.hass, DISPATCH_CONTROLLER_DISCOVERED, ctrl)
def controller_disconnected(self, ctrl: pizone.Controller, ex: Exception) -> None:
"""On disconnect from controller."""
async_dispatcher_send(self.hass, DISPATCH_CONTROLLER_DISCONNECTED, ctrl, ex)
def controller_reconnected(self, ctrl: pizone.Controller) -> None:
"""On reconnect to controller."""
async_dispatcher_send(self.hass, DISPATCH_CONTROLLER_RECONNECTED, ctrl)
def controller_update(self, ctrl: pizone.Controller) -> None:
"""System update message is received from the controller."""
async_dispatcher_send(self.hass, DISPATCH_CONTROLLER_UPDATE, ctrl)
def zone_update(self, ctrl: pizone.Controller, zone: pizone.Zone) -> None:
"""Zone update message is received from the controller."""
async_dispatcher_send(self.hass, DISPATCH_ZONE_UPDATE, ctrl, zone)
async def async_start_discovery_service(hass: HomeAssistantType):
"""Set up the pizone internal discovery."""
disco = hass.data.get(DATA_DISCOVERY_SERVICE)
if disco:
# Already started
return disco
# discovery local services
disco = DiscoveryService(hass)
hass.data[DATA_DISCOVERY_SERVICE] = disco
# Start the pizone discovery service, disco is the listener
session = aiohttp_client.async_get_clientsession(hass)
loop = hass.loop
disco.pi_disco = pizone.discovery(disco, loop=loop, session=session)
await disco.pi_disco.start_discovery()
async def shutdown_event(event):
await async_stop_discovery_service(hass)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown_event)
return disco
async def async_stop_discovery_service(hass: HomeAssistantType):
"""Stop the discovery service."""
disco = hass.data.get(DATA_DISCOVERY_SERVICE)
if not disco:
return
await disco.pi_disco.close()
del hass.data[DATA_DISCOVERY_SERVICE]
|
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import PLATFORM_SCHEMA, BinarySensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import BINARY_SENSORS, DATA_HYDRAWISE, HydrawiseEntity
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_MONITORED_CONDITIONS, default=BINARY_SENSORS): vol.All(
cv.ensure_list, [vol.In(BINARY_SENSORS)]
)
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a sensor for a Hydrawise device."""
hydrawise = hass.data[DATA_HYDRAWISE].data
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == "status":
sensors.append(
HydrawiseBinarySensor(hydrawise.current_controller, sensor_type)
)
else:
# create a sensor for each zone
for zone in hydrawise.relays:
sensors.append(HydrawiseBinarySensor(zone, sensor_type))
add_entities(sensors, True)
class HydrawiseBinarySensor(HydrawiseEntity, BinarySensorEntity):
"""A sensor implementation for Hydrawise device."""
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._state
def update(self):
"""Get the latest data and updates the state."""
_LOGGER.debug("Updating Hydrawise binary sensor: %s", self._name)
mydata = self.hass.data[DATA_HYDRAWISE].data
if self._sensor_type == "status":
self._state = mydata.status == "All good!"
elif self._sensor_type == "is_watering":
relay_data = mydata.relays[self.data["relay"] - 1]
self._state = relay_data["timestr"] == "Now"
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
from absl.testing import parameterized
from compare_gan.tpu import tpu_ops
import numpy as np
import tensorflow as tf
class TpuOpsTpuTest(parameterized.TestCase, tf.test.TestCase):
def testRunsOnTpu(self):
"""Verify that the test cases runs on a TPU chip and has 2 cores."""
expected_device_names = [
"/job:localhost/replica:0/task:0/device:CPU:0",
"/job:localhost/replica:0/task:0/device:TPU:0",
"/job:localhost/replica:0/task:0/device:TPU:1",
"/job:localhost/replica:0/task:0/device:TPU_SYSTEM:0",
]
with self.session() as sess:
devices = sess.list_devices()
logging.info("devices:\n%s", "\n".join([str(d) for d in devices]))
self.assertAllEqual([d.name for d in devices], expected_device_names)
def testCrossReplicaConcat(self):
def computation(x, replica_id):
logging.info("x: %s\nreplica_id: %s", x, replica_id[0])
return tpu_ops.cross_replica_concat(x, replica_id[0], num_replicas=2)
inputs = np.asarray([[3, 4], [1, 5]])
expected_output = np.asarray([[3, 4], [1, 5], [3, 4], [1, 5]])
with tf.Graph().as_default():
x = tf.constant(inputs)
replica_ids = tf.constant([0, 1], dtype=tf.int32)
x_concat, = tf.contrib.tpu.batch_parallel(
computation, [x, replica_ids], num_shards=2)
self.assertAllEqual(x.shape.as_list(), [2, 2])
self.assertAllEqual(x_concat.shape.as_list(), [4, 2])
with self.session() as sess:
sess.run(tf.contrib.tpu.initialize_system())
sess.run(tf.global_variables_initializer())
x_concat = sess.run(x_concat)
logging.info("x_concat: %s", x_concat)
self.assertAllClose(x_concat, expected_output)
# Test with group size 2 (test case has 2 cores, so this global batch norm).
@parameterized.parameters(
{"group_size": None}, # Defaults to number of TPU cores.
{"group_size": 0}, # Defaults to number of TPU cores.
{"group_size": 2},
)
def testCrossReplicaMean(self, group_size):
# Verify that we average across replicas by feeding 2 vectors to the system.
# Each replica should get one vector which is then averaged across
# all replicas and simply returned.
# After that each replica has the same vector and since the outputs gets
# concatenated we see the same vector twice.
inputs = np.asarray(
[[0.55, 0.70, -1.29, 0.502], [0.57, 0.90, 1.290, 0.202]],
dtype=np.float32)
expected_output = np.asarray(
[[0.56, 0.8, 0.0, 0.352], [0.56, 0.8, 0.0, 0.352]], dtype=np.float32)
def computation(x):
self.assertAllEqual(x.shape.as_list(), [1, 4])
return tpu_ops.cross_replica_mean(x, group_size=group_size)
with tf.Graph().as_default():
# Note: Using placeholders for feeding TPUs is discouraged but fine for
# a simple test case.
x = tf.placeholder(name="x", dtype=tf.float32, shape=inputs.shape)
y = tf.contrib.tpu.batch_parallel(computation, inputs=[x], num_shards=2)
with self.session() as sess:
sess.run(tf.contrib.tpu.initialize_system())
# y is actually a list with one tensor. computation would be allowed
# to return multiple tensors (and ops).
actual_output = sess.run(y, {x: inputs})[0]
self.assertAllEqual(actual_output.shape, (2, 4))
self.assertAllClose(actual_output, expected_output)
def testCrossReplicaMeanGroupSizeOne(self, group_size=1):
# Since the group size is 1 we only average over 1 replica.
inputs = np.asarray(
[[0.55, 0.70, -1.29, 0.502], [0.57, 0.90, 1.290, 0.202]],
dtype=np.float32)
expected_output = np.asarray(
[[0.55, 0.7, -1.29, 0.502], [0.57, 0.9, 1.290, 0.202]],
dtype=np.float32)
def computation(x):
self.assertAllEqual(x.shape.as_list(), [1, 4])
return tpu_ops.cross_replica_mean(x, group_size=group_size)
with tf.Graph().as_default():
# Note: Using placeholders for feeding TPUs is discouraged but fine for
# a simple test case.
x = tf.placeholder(name="x", dtype=tf.float32, shape=inputs.shape)
y = tf.contrib.tpu.batch_parallel(computation, inputs=[x], num_shards=2)
with self.session() as sess:
sess.run(tf.contrib.tpu.initialize_system())
# y is actually a list with one tensor. computation would be allowed
# to return multiple tensors (and ops).
actual_output = sess.run(y, {x: inputs})[0]
self.assertAllEqual(actual_output.shape, (2, 4))
self.assertAllClose(actual_output, expected_output)
if __name__ == "__main__":
tf.test.main()
|
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)
from homeassistant.core import callback
from . import get_api
from .const import (
CONF_LIMIT,
CONF_ORDER,
DEFAULT_LIMIT,
DEFAULT_NAME,
DEFAULT_ORDER,
DEFAULT_PORT,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
SUPPORTED_ORDER_MODES,
)
from .errors import AuthenticationError, CannotConnect, UnknownError
DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME, default=DEFAULT_NAME): str,
vol.Required(CONF_HOST): str,
vol.Optional(CONF_USERNAME): str,
vol.Optional(CONF_PASSWORD): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
)
class TransmissionFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle Tansmission config flow."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return TransmissionOptionsFlowHandler(config_entry)
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}
if user_input is not None:
for entry in self.hass.config_entries.async_entries(DOMAIN):
if (
entry.data[CONF_HOST] == user_input[CONF_HOST]
and entry.data[CONF_PORT] == user_input[CONF_PORT]
):
return self.async_abort(reason="already_configured")
if entry.data[CONF_NAME] == user_input[CONF_NAME]:
errors[CONF_NAME] = "name_exists"
break
try:
await get_api(self.hass, user_input)
except AuthenticationError:
errors[CONF_USERNAME] = "invalid_auth"
errors[CONF_PASSWORD] = "invalid_auth"
except (CannotConnect, UnknownError):
errors["base"] = "cannot_connect"
if not errors:
return self.async_create_entry(
title=user_input[CONF_NAME], data=user_input
)
return self.async_show_form(
step_id="user",
data_schema=DATA_SCHEMA,
errors=errors,
)
async def async_step_import(self, import_config):
"""Import from Transmission client config."""
import_config[CONF_SCAN_INTERVAL] = import_config[CONF_SCAN_INTERVAL].seconds
return await self.async_step_user(user_input=import_config)
class TransmissionOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle Transmission client options."""
def __init__(self, config_entry):
"""Initialize Transmission options flow."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None):
"""Manage the Transmission options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
options = {
vol.Optional(
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(
CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
),
): int,
vol.Optional(
CONF_LIMIT,
default=self.config_entry.options.get(CONF_LIMIT, DEFAULT_LIMIT),
): vol.All(vol.Coerce(int), vol.Range(min=1, max=500)),
vol.Optional(
CONF_ORDER,
default=self.config_entry.options.get(CONF_ORDER, DEFAULT_ORDER),
): vol.All(vol.Coerce(str), vol.In(SUPPORTED_ORDER_MODES.keys())),
}
return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
|
import re
from pytest import mark, raises
from cerberus import (
errors,
schema_registry,
SchemaError,
UnconcernedValidator,
Validator,
)
from cerberus.tests import assert_schema_error, assert_success
def test_empty_schema():
validator = Validator()
with raises(SchemaError, match=errors.MISSING_SCHEMA):
validator({}, schema=None)
def test_bad_schema_type(validator):
schema = "this string should really be dict"
msg = errors.SCHEMA_TYPE.format(schema)
with raises(SchemaError, match=msg):
validator.schema = schema
def test_bad_schema_type_field(validator):
field = 'foo'
schema = {field: {'schema': {'bar': {'type': 'strong'}}}}
with raises(SchemaError):
validator.schema = schema
def test_unknown_rule(validator):
msg = "{'foo': [{'unknown': ['unknown rule']}]}"
with raises(SchemaError, match=re.escape(msg)):
validator.schema = {'foo': {'unknown': 'rule'}}
def test_unknown_type(validator):
msg = str(
{
'foo': [
{
'type': [
{
0: [
'none or more than one rule validate',
{
'oneof definition 0': [
'Unsupported type name: unknown'
],
'oneof definition 1': [
"must be one of these types: "
"('type', 'generic_type_alias')"
],
},
]
}
]
}
]
}
)
with raises(SchemaError, match=re.escape(msg)):
validator.schema = {'foo': {'type': 'unknown'}}
def test_bad_schema_definition(validator):
field = 'name'
msg = str({field: ["must be one of these types: ('Mapping',)"]})
with raises(SchemaError, match=re.escape(msg)):
validator.schema = {field: 'this should really be a dict'}
def test_bad_of_rules():
schema = {'foo': {'anyof': {'type': 'string'}}}
assert_schema_error({}, schema)
def test_normalization_rules_are_invalid_in_of_rules():
schema = {0: {'anyof': [{'coerce': lambda x: x}]}}
assert_schema_error({}, schema)
def test_anyof_allof_schema_validate():
# make sure schema with 'anyof' and 'allof' constraints are checked
# correctly
schema = {
'doc': {'type': 'dict', 'anyof': [{'schema': [{'param': {'type': 'number'}}]}]}
}
assert_schema_error({'doc': 'this is my document'}, schema)
schema = {
'doc': {'type': 'dict', 'allof': [{'schema': [{'param': {'type': 'number'}}]}]}
}
assert_schema_error({'doc': 'this is my document'}, schema)
def test_repr():
v = Validator({'foo': {'type': 'string'}})
assert repr(v.schema) == "{'foo': {'type': ('string',)}}"
def test_expansion_in_nested_schema():
schema = {'detroit': {'itemsrules': {'anyof_regex': ['^Aladdin', 'Sane$']}}}
v = Validator(schema)
assert v.schema['detroit']['itemsrules'] == {
'anyof': ({'regex': '^Aladdin'}, {'regex': 'Sane$'})
}
def test_shortcut_expansion():
def foo(field, value, error):
pass
def bar(field, value, error):
pass
validator = Validator({'field': {'anyof_check_with': [foo, bar]}})
assert validator.schema == {
'field': {'anyof': ({'check_with': foo}, {'check_with': bar})}
}
def test_expansion_with_unvalidated_schema():
validator = UnconcernedValidator(
{"field": {'allof_regex': ['^Aladdin .*', '.* Sane$']}}
)
assert_success(document={"field": "Aladdin Sane"}, validator=validator)
def test_rulename_space_is_normalized():
validator = Validator(
schema={"field": {"default setter": lambda x: x, "type": "string"}}
)
assert "default_setter" in validator.schema["field"]
@mark.parametrize("rule", ("itemsrules", "keysrules", "valuesrules"))
def test_schema_normalization_does_not_abort(rule):
schema_registry.clear()
schema_registry.add(
"schema_ref",
{},
)
validator = Validator(
schema={
"field": {
rule: {"type": "string"},
"schema": "schema_ref",
},
}
)
assert validator.schema["field"][rule]["type"] == ("string",)
|
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_LOCK,
SERVICE_UNLOCK,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from tests.components.august.mocks import (
_create_august_with_devices,
_mock_activities_from_fixture,
_mock_doorbell_from_fixture,
_mock_lock_from_fixture,
)
async def test_doorsense(hass):
"""Test creation of a lock with doorsense and bridge."""
lock_one = await _mock_lock_from_fixture(
hass, "get_lock.online_with_doorsense.json"
)
await _create_august_with_devices(hass, [lock_one])
binary_sensor_online_with_doorsense_name = hass.states.get(
"binary_sensor.online_with_doorsense_name_open"
)
assert binary_sensor_online_with_doorsense_name.state == STATE_ON
data = {ATTR_ENTITY_ID: "lock.online_with_doorsense_name"}
assert await hass.services.async_call(
LOCK_DOMAIN, SERVICE_UNLOCK, data, blocking=True
)
await hass.async_block_till_done()
binary_sensor_online_with_doorsense_name = hass.states.get(
"binary_sensor.online_with_doorsense_name_open"
)
assert binary_sensor_online_with_doorsense_name.state == STATE_ON
assert await hass.services.async_call(
LOCK_DOMAIN, SERVICE_LOCK, data, blocking=True
)
await hass.async_block_till_done()
binary_sensor_online_with_doorsense_name = hass.states.get(
"binary_sensor.online_with_doorsense_name_open"
)
assert binary_sensor_online_with_doorsense_name.state == STATE_OFF
async def test_create_doorbell(hass):
"""Test creation of a doorbell."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.json")
await _create_august_with_devices(hass, [doorbell_one])
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF
binary_sensor_k98gidt45gul_name_online = hass.states.get(
"binary_sensor.k98gidt45gul_name_online"
)
assert binary_sensor_k98gidt45gul_name_online.state == STATE_ON
binary_sensor_k98gidt45gul_name_ding = hass.states.get(
"binary_sensor.k98gidt45gul_name_ding"
)
assert binary_sensor_k98gidt45gul_name_ding.state == STATE_OFF
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF
async def test_create_doorbell_offline(hass):
"""Test creation of a doorbell that is offline."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.offline.json")
await _create_august_with_devices(hass, [doorbell_one])
binary_sensor_tmt100_name_motion = hass.states.get(
"binary_sensor.tmt100_name_motion"
)
assert binary_sensor_tmt100_name_motion.state == STATE_UNAVAILABLE
binary_sensor_tmt100_name_online = hass.states.get(
"binary_sensor.tmt100_name_online"
)
assert binary_sensor_tmt100_name_online.state == STATE_OFF
binary_sensor_tmt100_name_ding = hass.states.get("binary_sensor.tmt100_name_ding")
assert binary_sensor_tmt100_name_ding.state == STATE_UNAVAILABLE
async def test_create_doorbell_with_motion(hass):
"""Test creation of a doorbell."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.json")
activities = await _mock_activities_from_fixture(
hass, "get_activity.doorbell_motion.json"
)
await _create_august_with_devices(hass, [doorbell_one], activities=activities)
binary_sensor_k98gidt45gul_name_motion = hass.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_ON
binary_sensor_k98gidt45gul_name_online = hass.states.get(
"binary_sensor.k98gidt45gul_name_online"
)
assert binary_sensor_k98gidt45gul_name_online.state == STATE_ON
binary_sensor_k98gidt45gul_name_ding = hass.states.get(
"binary_sensor.k98gidt45gul_name_ding"
)
assert binary_sensor_k98gidt45gul_name_ding.state == STATE_OFF
async def test_doorbell_device_registry(hass):
"""Test creation of a lock with doorsense and bridge ands up in the registry."""
doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.offline.json")
await _create_august_with_devices(hass, [doorbell_one])
device_registry = await hass.helpers.device_registry.async_get_registry()
reg_device = device_registry.async_get_device(
identifiers={("august", "tmt100")}, connections=set()
)
assert reg_device.model == "hydra1"
assert reg_device.name == "tmt100 Name"
assert reg_device.manufacturer == "August Home Inc."
assert reg_device.sw_version == "3.1.0-HYDRC75+201909251139"
|
from urllib.parse import urlparse
from pyfritzhome import Fritzhome, LoginError
from requests.exceptions import HTTPError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.ssdp import (
ATTR_SSDP_LOCATION,
ATTR_UPNP_FRIENDLY_NAME,
ATTR_UPNP_UDN,
)
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
# pylint:disable=unused-import
from .const import DEFAULT_HOST, DEFAULT_USERNAME, DOMAIN
DATA_SCHEMA_USER = vol.Schema(
{
vol.Required(CONF_HOST, default=DEFAULT_HOST): str,
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
DATA_SCHEMA_CONFIRM = vol.Schema(
{
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
RESULT_INVALID_AUTH = "invalid_auth"
RESULT_NO_DEVICES_FOUND = "no_devices_found"
RESULT_NOT_SUPPORTED = "not_supported"
RESULT_SUCCESS = "success"
class FritzboxConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a AVM Fritz!Box config flow."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
def __init__(self):
"""Initialize flow."""
self._host = None
self._name = None
self._password = None
self._username = None
def _get_entry(self):
return self.async_create_entry(
title=self._name,
data={
CONF_HOST: self._host,
CONF_PASSWORD: self._password,
CONF_USERNAME: self._username,
},
)
def _try_connect(self):
"""Try to connect and check auth."""
fritzbox = Fritzhome(
host=self._host, user=self._username, password=self._password
)
try:
fritzbox.login()
fritzbox.get_device_elements()
fritzbox.logout()
return RESULT_SUCCESS
except LoginError:
return RESULT_INVALID_AUTH
except HTTPError:
return RESULT_NOT_SUPPORTED
except OSError:
return RESULT_NO_DEVICES_FOUND
async def async_step_import(self, user_input=None):
"""Handle configuration by yaml file."""
return await self.async_step_user(user_input)
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}
if user_input is not None:
for entry in self.hass.config_entries.async_entries(DOMAIN):
if entry.data[CONF_HOST] == user_input[CONF_HOST]:
return self.async_abort(reason="already_configured")
self._host = user_input[CONF_HOST]
self._name = user_input[CONF_HOST]
self._password = user_input[CONF_PASSWORD]
self._username = user_input[CONF_USERNAME]
result = await self.hass.async_add_executor_job(self._try_connect)
if result == RESULT_SUCCESS:
return self._get_entry()
if result != RESULT_INVALID_AUTH:
return self.async_abort(reason=result)
errors["base"] = result
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA_USER, errors=errors
)
async def async_step_ssdp(self, discovery_info):
"""Handle a flow initialized by discovery."""
host = urlparse(discovery_info[ATTR_SSDP_LOCATION]).hostname
self.context[CONF_HOST] = host
uuid = discovery_info.get(ATTR_UPNP_UDN)
if uuid:
if uuid.startswith("uuid:"):
uuid = uuid[5:]
await self.async_set_unique_id(uuid)
self._abort_if_unique_id_configured({CONF_HOST: host})
for progress in self._async_in_progress():
if progress.get("context", {}).get(CONF_HOST) == host:
return self.async_abort(reason="already_in_progress")
# update old and user-configured config entries
for entry in self.hass.config_entries.async_entries(DOMAIN):
if entry.data[CONF_HOST] == host:
if uuid and not entry.unique_id:
self.hass.config_entries.async_update_entry(entry, unique_id=uuid)
return self.async_abort(reason="already_configured")
self._host = host
self._name = discovery_info.get(ATTR_UPNP_FRIENDLY_NAME) or host
self.context["title_placeholders"] = {"name": self._name}
return await self.async_step_confirm()
async def async_step_confirm(self, user_input=None):
"""Handle user-confirmation of discovered node."""
errors = {}
if user_input is not None:
self._password = user_input[CONF_PASSWORD]
self._username = user_input[CONF_USERNAME]
result = await self.hass.async_add_executor_job(self._try_connect)
if result == RESULT_SUCCESS:
return self._get_entry()
if result != RESULT_INVALID_AUTH:
return self.async_abort(reason=result)
errors["base"] = result
return self.async_show_form(
step_id="confirm",
data_schema=DATA_SCHEMA_CONFIRM,
description_placeholders={"name": self._name},
errors=errors,
)
|
import os
import pytest
from nikola.plugins.command.import_wordpress import (
modernize_qtranslate_tags,
separate_qtranslate_tagged_langs,
)
def legacy_qtranslate_separate(text):
"""This method helps keeping the legacy tests covering various
corner cases, but plugged on the newer methods."""
text_bytes = text.encode("utf-8")
modern_bytes = modernize_qtranslate_tags(text_bytes)
modern_text = modern_bytes.decode("utf-8")
return separate_qtranslate_tagged_langs(modern_text)
@pytest.mark.parametrize(
"content, french_translation, english_translation",
[
pytest.param("[:fr]Voila voila[:en]BLA[:]", "Voila voila", "BLA", id="simple"),
pytest.param(
"[:fr]Voila voila[:]COMMON[:en]BLA[:]",
"Voila voila COMMON",
"COMMON BLA",
id="pre modern with intermission",
),
pytest.param(
"<!--:fr-->Voila voila<!--:-->COMMON<!--:en-->BLA<!--:-->",
"Voila voila COMMON",
"COMMON BLA",
id="withintermission",
),
pytest.param(
"<!--:fr-->Voila voila<!--:-->COMMON<!--:fr-->MOUF<!--:--><!--:en-->BLA<!--:-->",
"Voila voila COMMON MOUF",
"COMMON BLA",
id="with uneven repartition",
),
pytest.param(
"<!--:fr-->Voila voila<!--:--><!--:en-->BLA<!--:-->COMMON<!--:fr-->MOUF<!--:-->",
"Voila voila COMMON MOUF",
"BLA COMMON",
id="with uneven repartition bis",
),
],
)
def test_legacy_split_a_two_language_post(
content, french_translation, english_translation
):
content_translations = legacy_qtranslate_separate(content)
assert french_translation == content_translations["fr"]
assert english_translation == content_translations["en"]
def test_conserves_qtranslate_less_post():
content = """Si vous préférez savoir à qui vous parlez commencez par visiter l'<a title="À propos" href="http://some.blog/about/">À propos</a>.
Quoiqu'il en soit, commentaires, questions et suggestions sont les bienvenues !"""
content_translations = legacy_qtranslate_separate(content)
assert 1 == len(content_translations)
assert content == content_translations[""]
def test_modernize_a_wordpress_export_xml_chunk(test_dir):
raw_export_path = os.path.join(
test_dir, "data", "wordpress_import", "wordpress_qtranslate_item_raw_export.xml"
)
with open(raw_export_path, "rb") as raw_xml_chunk_file:
content = raw_xml_chunk_file.read()
output = modernize_qtranslate_tags(content)
modernized_xml_path = os.path.join(
test_dir, "data", "wordpress_import", "wordpress_qtranslate_item_modernized.xml"
)
with open(modernized_xml_path, "rb") as modernized_chunk_file:
expected = modernized_chunk_file.read()
assert expected == output
def test_modernize_qtranslate_tags():
content = b"<!--:fr-->Voila voila<!--:-->COMMON<!--:fr-->MOUF<!--:--><!--:en-->BLA<!--:-->"
output = modernize_qtranslate_tags(content)
assert b"[:fr]Voila voila[:]COMMON[:fr]MOUF[:][:en]BLA[:]" == output
def test_split_a_two_language_post():
content = """<!--:fr-->Si vous préférez savoir à qui vous parlez commencez par visiter l'<a title="À propos" href="http://some.blog/about/">À propos</a>.
Quoiqu'il en soit, commentaires, questions et suggestions sont les bienvenues !
<!--:--><!--:en-->If you'd like to know who you're talking to, please visit the <a title="À propos" href="http://some.blog/about/">about page</a>.
Comments, questions and suggestions are welcome !
<!--:-->"""
content_translations = legacy_qtranslate_separate(content)
assert (
content_translations["fr"] == """Si vous préférez savoir à qui vous parlez commencez par visiter l'<a title="À propos" href="http://some.blog/about/">À propos</a>.
Quoiqu'il en soit, commentaires, questions et suggestions sont les bienvenues !
"""
)
assert (
content_translations["en"] == """If you'd like to know who you're talking to, please visit the <a title="À propos" href="http://some.blog/about/">about page</a>.
Comments, questions and suggestions are welcome !
"""
)
def test_split_a_two_language_post_with_teaser():
content = """<!--:fr-->Si vous préférez savoir à qui vous parlez commencez par visiter l'<a title="À propos" href="http://some.blog/about/">À propos</a>.
Quoiqu'il en soit, commentaires, questions et suggestions sont les bienvenues !
<!--:--><!--:en-->If you'd like to know who you're talking to, please visit the <a title="À propos" href="http://some.blog/about/">about page</a>.
Comments, questions and suggestions are welcome !
<!--:--><!--more--><!--:fr-->
Plus de détails ici !
<!--:--><!--:en-->
More details here !
<!--:-->"""
content_translations = legacy_qtranslate_separate(content)
assert (
content_translations["fr"] == """Si vous préférez savoir à qui vous parlez commencez par visiter l'<a title="À propos" href="http://some.blog/about/">À propos</a>.
Quoiqu'il en soit, commentaires, questions et suggestions sont les bienvenues !
<!--more--> \n\
Plus de détails ici !
"""
)
assert (
content_translations["en"] == """If you'd like to know who you're talking to, please visit the <a title="À propos" href="http://some.blog/about/">about page</a>.
Comments, questions and suggestions are welcome !
<!--more--> \n\
More details here !
"""
)
|
import importlib
from docker_registry.core import exceptions
from .. import config
from .. import signals
__all__ = ['load']
class Index (object):
"""A backend for the search endpoint
The backend can use .walk_storage to generate an initial index,
._handle_repository_* to stay up to date with registry changes,
and .results to respond to queries.
"""
def __init__(self):
signals.repository_created.connect(self._handle_repository_created)
signals.repository_updated.connect(self._handle_repository_updated)
signals.repository_deleted.connect(self._handle_repository_deleted)
def _walk_storage(self, store):
"""Iterate through repositories in storage
This helper is useful for building an initial database for
your search index. Yields dictionaries:
{'name': name, 'description': description}
"""
try:
namespace_paths = list(
store.list_directory(path=store.repositories))
except exceptions.FileNotFoundError:
namespace_paths = []
for namespace_path in namespace_paths:
namespace = namespace_path.rsplit('/', 1)[-1]
try:
repository_paths = list(
store.list_directory(path=namespace_path))
except exceptions.FileNotFoundError:
repository_paths = []
for path in repository_paths:
repository = path.rsplit('/', 1)[-1]
name = '{0}/{1}'.format(namespace, repository)
description = None # TODO(wking): store descriptions
yield({'name': name, 'description': description})
def _handle_repository_created(
self, sender, namespace, repository, value):
pass
def _handle_repository_updated(
self, sender, namespace, repository, value):
pass
def _handle_repository_deleted(self, sender, namespace, repository):
pass
def results(self, search_term=None):
"""Return a list of results matching search_term
The list elements should be dictionaries:
{'name': name, 'description': description}
"""
raise NotImplementedError('results method for {0!r}'.format(self))
def load(kind=None):
"""Returns an Index instance according to the configuration."""
cfg = config.load()
if not kind:
kind = cfg.search_backend.lower()
if kind == 'sqlalchemy':
from . import db
return db.SQLAlchemyIndex()
try:
module = importlib.import_module(kind)
except ImportError:
pass
else:
return module.Index()
raise NotImplementedError('Unknown index type {0!r}'.format(kind))
|
import unittest
import os
import mock as mock
import inspect
import shutil
from kalliope.core.Models import Singleton
from kalliope.core.ConfigurationManager import SettingLoader
from kalliope.core import HookManager
class TestInit(unittest.TestCase):
def setUp(self):
# Init the folders, otherwise it raises an exceptions
os.makedirs("/tmp/kalliope/tests/kalliope_resources_dir/neurons")
os.makedirs("/tmp/kalliope/tests/kalliope_resources_dir/stt")
os.makedirs("/tmp/kalliope/tests/kalliope_resources_dir/tts")
os.makedirs("/tmp/kalliope/tests/kalliope_resources_dir/trigger")
# get current script directory path. We are in /an/unknown/path/kalliope/core/tests
cur_script_directory = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# get parent dir. Now we are in /an/unknown/path/kalliope
root_dir = os.path.normpath(cur_script_directory + os.sep + os.pardir)
self.settings_file_to_test = root_dir + os.sep + "Tests/settings/settings_test.yml"
self.settings = SettingLoader(file_path=self.settings_file_to_test)
def tearDown(self):
# Cleanup
shutil.rmtree('/tmp/kalliope/tests/kalliope_resources_dir')
Singleton._instances = {}
def test_on_start(self):
"""
test list of synapse
"""
with mock.patch("kalliope.core.SynapseLauncher.start_synapse_by_list_name") as mock_synapse_launcher:
HookManager.on_start()
mock_synapse_launcher.assert_called_with(["on-start-synapse", "bring-led-on"], new_lifo=True)
mock_synapse_launcher.reset_mock()
def test_on_waiting_for_trigger(self):
"""
test with single synapse
"""
with mock.patch("kalliope.core.SynapseLauncher.start_synapse_by_list_name") as mock_synapse_launcher:
HookManager.on_waiting_for_trigger()
mock_synapse_launcher.assert_called_with(["test"], new_lifo=True)
mock_synapse_launcher.reset_mock()
def test_on_triggered(self):
with mock.patch("kalliope.core.SynapseLauncher.start_synapse_by_list_name") as mock_synapse_launcher:
HookManager.on_triggered()
mock_synapse_launcher.assert_called_with(["on-triggered-synapse"], new_lifo=True)
mock_synapse_launcher.reset_mock()
def test_on_start_listening(self):
self.assertIsNone(HookManager.on_start_listening())
def test_on_stop_listening(self):
self.assertIsNone(HookManager.on_stop_listening())
def test_on_order_found(self):
self.assertIsNone(HookManager.on_order_found())
def test_on_order_not_found(self):
with mock.patch("kalliope.core.SynapseLauncher.start_synapse_by_list_name") as mock_synapse_launcher:
HookManager.on_order_not_found()
mock_synapse_launcher.assert_called_with(["order-not-found-synapse"], new_lifo=True)
mock_synapse_launcher.reset_mock()
def test_on_processed_synapses(self):
self.assertIsNone(HookManager.on_processed_synapses())
def test_on_deaf(self):
"""
test that empty list of synapse return none
"""
self.assertIsNone(HookManager.on_deaf())
if __name__ == '__main__':
unittest.main()
# suite = unittest.TestSuite()
# suite.addTest(TestInit("test_main"))
# runner = unittest.TextTestRunner()
# runner.run(suite)
|
import logging
from homeassistant.core import split_entity_id
# mypy: allow-untyped-defs
_LOGGER = logging.getLogger(__name__)
def is_on(hass, entity_id=None):
"""Load up the module to call the is_on method.
If there is no entity id given we will check all.
"""
if entity_id:
entity_ids = hass.components.group.expand_entity_ids([entity_id])
else:
entity_ids = hass.states.entity_ids()
for ent_id in entity_ids:
domain = split_entity_id(ent_id)[0]
try:
component = getattr(hass.components, domain)
except ImportError:
_LOGGER.error("Failed to call %s.is_on: component not found", domain)
continue
if not hasattr(component, "is_on"):
_LOGGER.warning("Integration %s has no is_on method", domain)
continue
if component.is_on(ent_id):
return True
return False
|
import logging
from homeassistant.const import (
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
TEMP_FAHRENHEIT,
)
from homeassistant.helpers.entity import Entity
from .const import DOMAIN, TYPE_TEMPERATURE, TYPE_WIFI_STRENGTH
_LOGGER = logging.getLogger(__name__)
SENSORS = {
TYPE_TEMPERATURE: ["Temperature", TEMP_FAHRENHEIT, DEVICE_CLASS_TEMPERATURE],
TYPE_WIFI_STRENGTH: [
"Wifi Signal",
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
DEVICE_CLASS_SIGNAL_STRENGTH,
],
}
async def async_setup_entry(hass, config, async_add_entities):
"""Initialize a Blink sensor."""
data = hass.data[DOMAIN][config.entry_id]
entities = []
for camera in data.cameras:
for sensor_type in SENSORS:
entities.append(BlinkSensor(data, camera, sensor_type))
async_add_entities(entities)
class BlinkSensor(Entity):
"""A Blink camera sensor."""
def __init__(self, data, camera, sensor_type):
"""Initialize sensors from Blink camera."""
name, units, device_class = SENSORS[sensor_type]
self._name = f"{DOMAIN} {camera} {name}"
self._camera_name = name
self._type = sensor_type
self._device_class = device_class
self.data = data
self._camera = data.cameras[camera]
self._state = None
self._unit_of_measurement = units
self._unique_id = f"{self._camera.serial}-{self._type}"
self._sensor_key = self._type
if self._type == "temperature":
self._sensor_key = "temperature_calibrated"
@property
def name(self):
"""Return the name of the camera."""
return self._name
@property
def unique_id(self):
"""Return the unique id for the camera sensor."""
return self._unique_id
@property
def state(self):
"""Return the camera's current state."""
return self._state
@property
def device_class(self):
"""Return the device's class."""
return self._device_class
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
def update(self):
"""Retrieve sensor data from the camera."""
self.data.refresh()
try:
self._state = self._camera.attributes[self._sensor_key]
except KeyError:
self._state = None
_LOGGER.error(
"%s not a valid camera attribute. Did the API change?", self._sensor_key
)
|
from sqlalchemy.orm import relationship
from sqlalchemy import Integer, String, Column, Boolean, Text
from sqlalchemy_utils import JSONType
from lemur.database import db
from lemur.plugins.base import plugins
from lemur.models import (
certificate_notification_associations,
pending_cert_notification_associations,
)
class Notification(db.Model):
__tablename__ = "notifications"
id = Column(Integer, primary_key=True)
label = Column(String(128), unique=True)
description = Column(Text())
options = Column(JSONType)
active = Column(Boolean, default=True)
plugin_name = Column(String(32))
certificates = relationship(
"Certificate",
secondary=certificate_notification_associations,
passive_deletes=True,
backref="notification",
cascade="all,delete",
)
pending_certificates = relationship(
"PendingCertificate",
secondary=pending_cert_notification_associations,
passive_deletes=True,
backref="notification",
cascade="all,delete",
)
@property
def plugin(self):
return plugins.get(self.plugin_name)
def __repr__(self):
return "Notification(label={label})".format(label=self.label)
|
import pytest
import shutil
import matchzoo as mz
from matchzoo.engine.base_preprocessor import BasePreprocessor
@pytest.fixture
def base_preprocessor():
BasePreprocessor.__abstractmethods__ = set()
base_processor = BasePreprocessor()
return base_processor
def test_save_load(base_preprocessor):
dirpath = '.tmpdir'
base_preprocessor.save(dirpath)
assert mz.load_preprocessor(dirpath)
with pytest.raises(FileExistsError):
base_preprocessor.save(dirpath)
shutil.rmtree(dirpath)
|
import numpy as np
import chainer
from chainer.backends import cuda
import chainer.functions as F
import chainer.links as L
from chainercv.links.model.faster_rcnn.utils.generate_anchor_base import \
generate_anchor_base
from chainercv.links.model.faster_rcnn.utils.proposal_creator import \
ProposalCreator
class RegionProposalNetwork(chainer.Chain):
"""Region Proposal Network introduced in Faster R-CNN.
This is Region Proposal Network introduced in Faster R-CNN [#]_.
This takes features extracted from images and propose
class agnostic bounding boxes around "objects".
.. [#] Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun. \
Faster R-CNN: Towards Real-Time Object Detection with \
Region Proposal Networks. NIPS 2015.
Args:
in_channels (int): The channel size of input.
mid_channels (int): The channel size of the intermediate tensor.
ratios (list of floats): This is ratios of width to height of
the anchors.
anchor_scales (list of numbers): This is areas of anchors.
Those areas will be the product of the square of an element in
:obj:`anchor_scales` and the original area of the reference
window.
feat_stride (int): Stride size after extracting features from an
image.
initialW (callable): Initial weight value. If :obj:`None` then this
function uses Gaussian distribution scaled by 0.1 to
initialize weight.
May also be a callable that takes an array and edits its values.
proposal_creator_params (dict): Key valued paramters for
:class:`~chainercv.links.model.faster_rcnn.ProposalCreator`.
.. seealso::
:class:`~chainercv.links.model.faster_rcnn.ProposalCreator`
"""
def __init__(
self, in_channels=512, mid_channels=512, ratios=[0.5, 1, 2],
anchor_scales=[8, 16, 32], feat_stride=16,
initialW=None,
proposal_creator_params={},
):
self.anchor_base = generate_anchor_base(
anchor_scales=anchor_scales, ratios=ratios)
self.feat_stride = feat_stride
self.proposal_layer = ProposalCreator(**proposal_creator_params)
n_anchor = self.anchor_base.shape[0]
super(RegionProposalNetwork, self).__init__()
with self.init_scope():
self.conv1 = L.Convolution2D(
in_channels, mid_channels, 3, 1, 1, initialW=initialW)
self.score = L.Convolution2D(
mid_channels, n_anchor * 2, 1, 1, 0, initialW=initialW)
self.loc = L.Convolution2D(
mid_channels, n_anchor * 4, 1, 1, 0, initialW=initialW)
def forward(self, x, img_size, scales=None):
"""Forward Region Proposal Network.
Here are notations.
* :math:`N` is batch size.
* :math:`C` channel size of the input.
* :math:`H` and :math:`W` are height and witdh of the input feature.
* :math:`A` is number of anchors assigned to each pixel.
Args:
x (~chainer.Variable): The Features extracted from images.
Its shape is :math:`(N, C, H, W)`.
img_size (tuple of ints): A tuple :obj:`height, width`,
which contains image size after scaling.
scales (tuple of floats): The amount of scaling done to each input
image during preprocessing.
Returns:
(~chainer.Variable, ~chainer.Variable, array, array, array):
This is a tuple of five following values.
* **rpn_locs**: Predicted bounding box offsets and scales for \
anchors. Its shape is :math:`(N, H W A, 4)`.
* **rpn_scores**: Predicted foreground scores for \
anchors. Its shape is :math:`(N, H W A, 2)`.
* **rois**: A bounding box array containing coordinates of \
proposal boxes. This is a concatenation of bounding box \
arrays from multiple images in the batch. \
Its shape is :math:`(R', 4)`. Given :math:`R_i` predicted \
bounding boxes from the :math:`i` th image, \
:math:`R' = \\sum _{i=1} ^ N R_i`.
* **roi_indices**: An array containing indices of images to \
which RoIs correspond to. Its shape is :math:`(R',)`.
* **anchor**: Coordinates of enumerated shifted anchors. \
Its shape is :math:`(H W A, 4)`.
"""
n, _, hh, ww = x.shape
if scales is None:
scales = [1.0] * n
if not isinstance(scales, chainer.utils.collections_abc.Iterable):
scales = [scales] * n
anchor = _enumerate_shifted_anchor(
self.xp.array(self.anchor_base), self.feat_stride, hh, ww)
n_anchor = anchor.shape[0] // (hh * ww)
h = F.relu(self.conv1(x))
rpn_locs = self.loc(h)
rpn_locs = rpn_locs.transpose((0, 2, 3, 1)).reshape((n, -1, 4))
rpn_scores = self.score(h)
rpn_scores = rpn_scores.transpose((0, 2, 3, 1))
rpn_fg_scores =\
rpn_scores.reshape((n, hh, ww, n_anchor, 2))[:, :, :, :, 1]
rpn_fg_scores = rpn_fg_scores.reshape((n, -1))
rpn_scores = rpn_scores.reshape((n, -1, 2))
rois = []
roi_indices = []
for i in range(n):
roi = self.proposal_layer(
rpn_locs[i].array, rpn_fg_scores[i].array, anchor, img_size,
scale=scales[i])
batch_index = i * self.xp.ones((len(roi),), dtype=np.int32)
rois.append(roi)
roi_indices.append(batch_index)
rois = self.xp.concatenate(rois, axis=0)
roi_indices = self.xp.concatenate(roi_indices, axis=0)
return rpn_locs, rpn_scores, rois, roi_indices, anchor
def _enumerate_shifted_anchor(anchor_base, feat_stride, height, width):
# Enumerate all shifted anchors:
#
# add A anchors (1, A, 4) to
# cell K shifts (K, 1, 4) to get
# shift anchors (K, A, 4)
# reshape to (K*A, 4) shifted anchors
xp = cuda.get_array_module(anchor_base)
shift_y = xp.arange(0, height * feat_stride, feat_stride)
shift_x = xp.arange(0, width * feat_stride, feat_stride)
shift_x, shift_y = xp.meshgrid(shift_x, shift_y)
shift = xp.stack((shift_y.ravel(), shift_x.ravel(),
shift_y.ravel(), shift_x.ravel()), axis=1)
A = anchor_base.shape[0]
K = shift.shape[0]
anchor = anchor_base.reshape((1, A, 4)) + \
shift.reshape((1, K, 4)).transpose((1, 0, 2))
anchor = anchor.reshape((K * A, 4)).astype(np.float32)
return anchor
|
import logging
from aiohttp.hdrs import CONTENT_TYPE
import requests
import voluptuous as vol
from homeassistant.components.device_tracker import (
DOMAIN,
PLATFORM_SCHEMA,
DeviceScanner,
)
from homeassistant.const import CONF_HOST
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_IP = "192.168.1.1"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_HOST, default=DEFAULT_IP): cv.string}
)
def get_scanner(hass, config):
"""Return the Swisscom device scanner."""
scanner = SwisscomDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None
class SwisscomDeviceScanner(DeviceScanner):
"""This class queries a router running Swisscom Internet-Box firmware."""
def __init__(self, config):
"""Initialize the scanner."""
self.host = config[CONF_HOST]
self.last_results = {}
# Test the router is accessible.
data = self.get_swisscom_data()
self.success_init = data is not None
def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [client["mac"] for client in self.last_results]
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
if not self.last_results:
return None
for client in self.last_results:
if client["mac"] == device:
return client["host"]
return None
def _update_info(self):
"""Ensure the information from the Swisscom router is up to date.
Return boolean if scanning successful.
"""
if not self.success_init:
return False
_LOGGER.info("Loading data from Swisscom Internet Box")
data = self.get_swisscom_data()
if not data:
return False
active_clients = [client for client in data.values() if client["status"]]
self.last_results = active_clients
return True
def get_swisscom_data(self):
"""Retrieve data from Swisscom and return parsed result."""
url = f"http://{self.host}/ws"
headers = {CONTENT_TYPE: "application/x-sah-ws-4-call+json"}
data = """
{"service":"Devices", "method":"get",
"parameters":{"expression":"lan and not self"}}"""
devices = {}
try:
request = requests.post(url, headers=headers, data=data, timeout=10)
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
requests.exceptions.ConnectTimeout,
):
_LOGGER.info("No response from Swisscom Internet Box")
return devices
if "status" not in request.json():
_LOGGER.info("No status in response from Swisscom Internet Box")
return devices
for device in request.json()["status"]:
try:
devices[device["Key"]] = {
"ip": device["IPAddress"],
"mac": device["PhysAddress"],
"host": device["Name"],
"status": device["Active"],
}
except (KeyError, requests.exceptions.RequestException):
pass
return devices
|
import compileall
import fnmatch
import json
import os
import os.path
import re
import sys
from coverage import env
from coverage.backward import binary_bytes
from coverage.execfile import run_python_file, run_python_module
from coverage.files import python_reported_file
from coverage.misc import NoCode, NoSource
from tests.coveragetest import CoverageTest, TESTS_DIR, UsingModulesMixin
TRY_EXECFILE = os.path.join(TESTS_DIR, "modules/process_test/try_execfile.py")
class RunFileTest(CoverageTest):
"""Test cases for `run_python_file`."""
def test_run_python_file(self):
run_python_file([TRY_EXECFILE, "arg1", "arg2"])
mod_globs = json.loads(self.stdout())
# The file should think it is __main__
self.assertEqual(mod_globs['__name__'], "__main__")
# It should seem to come from a file named try_execfile.py
dunder_file = os.path.basename(mod_globs['__file__'])
self.assertEqual(dunder_file, "try_execfile.py")
# It should have its correct module data.
self.assertEqual(mod_globs['__doc__'].splitlines()[0],
"Test file for run_python_file.")
self.assertEqual(mod_globs['DATA'], "xyzzy")
self.assertEqual(mod_globs['FN_VAL'], "my_fn('fooey')")
# It must be self-importable as __main__.
self.assertEqual(mod_globs['__main__.DATA'], "xyzzy")
# Argv should have the proper values.
self.assertEqual(mod_globs['argv0'], TRY_EXECFILE)
self.assertEqual(mod_globs['argv1-n'], ["arg1", "arg2"])
# __builtins__ should have the right values, like open().
self.assertEqual(mod_globs['__builtins__.has_open'], True)
def test_no_extra_file(self):
# Make sure that running a file doesn't create an extra compiled file.
self.make_file("xxx", """\
desc = "a non-.py file!"
""")
self.assertEqual(os.listdir("."), ["xxx"])
run_python_file(["xxx"])
self.assertEqual(os.listdir("."), ["xxx"])
def test_universal_newlines(self):
# Make sure we can read any sort of line ending.
pylines = """# try newlines|print('Hello, world!')|""".split('|')
for nl in ('\n', '\r\n', '\r'):
with open('nl.py', 'wb') as fpy:
fpy.write(nl.join(pylines).encode('utf-8'))
run_python_file(['nl.py'])
self.assertEqual(self.stdout(), "Hello, world!\n"*3)
def test_missing_final_newline(self):
# Make sure we can deal with a Python file with no final newline.
self.make_file("abrupt.py", """\
if 1:
a = 1
print("a is %r" % a)
#""")
with open("abrupt.py") as f:
abrupt = f.read()
self.assertEqual(abrupt[-1], '#')
run_python_file(["abrupt.py"])
self.assertEqual(self.stdout(), "a is 1\n")
def test_no_such_file(self):
path = python_reported_file('xyzzy.py')
msg = re.escape("No file to run: '{}'".format(path))
with self.assertRaisesRegex(NoSource, msg):
run_python_file(["xyzzy.py"])
def test_directory_with_main(self):
self.make_file("with_main/__main__.py", """\
print("I am __main__")
""")
run_python_file(["with_main"])
self.assertEqual(self.stdout(), "I am __main__\n")
def test_directory_without_main(self):
self.make_file("without_main/__init__.py", "")
with self.assertRaisesRegex(NoSource, "Can't find '__main__' module in 'without_main'"):
run_python_file(["without_main"])
class RunPycFileTest(CoverageTest):
"""Test cases for `run_python_file`."""
def make_pyc(self): # pylint: disable=inconsistent-return-statements
"""Create a .pyc file, and return the path to it."""
if env.JYTHON:
self.skipTest("Can't make .pyc files on Jython")
self.make_file("compiled.py", """\
def doit():
print("I am here!")
doit()
""")
compileall.compile_dir(".", quiet=True)
os.remove("compiled.py")
# Find the .pyc file!
roots = ["."]
prefix = getattr(sys, "pycache_prefix", None)
if prefix:
roots.append(prefix)
for root in roots: # pragma: part covered
for there, _, files in os.walk(root): # pragma: part covered
for fname in files:
if fnmatch.fnmatch(fname, "compiled*.pyc"):
return os.path.join(there, fname)
def test_running_pyc(self):
pycfile = self.make_pyc()
run_python_file([pycfile])
self.assertEqual(self.stdout(), "I am here!\n")
def test_running_pyo(self):
pycfile = self.make_pyc()
pyofile = re.sub(r"[.]pyc$", ".pyo", pycfile)
self.assertNotEqual(pycfile, pyofile)
os.rename(pycfile, pyofile)
run_python_file([pyofile])
self.assertEqual(self.stdout(), "I am here!\n")
def test_running_pyc_from_wrong_python(self):
pycfile = self.make_pyc()
# Jam Python 2.1 magic number into the .pyc file.
with open(pycfile, "r+b") as fpyc:
fpyc.seek(0)
fpyc.write(binary_bytes([0x2a, 0xeb, 0x0d, 0x0a]))
with self.assertRaisesRegex(NoCode, "Bad magic number in .pyc file"):
run_python_file([pycfile])
# In some environments, the pycfile persists and pollutes another test.
os.remove(pycfile)
def test_no_such_pyc_file(self):
path = python_reported_file('xyzzy.pyc')
msg = re.escape("No file to run: '{}'".format(path))
with self.assertRaisesRegex(NoCode, msg):
run_python_file(["xyzzy.pyc"])
def test_running_py_from_binary(self):
# Use make_file to get the bookkeeping. Ideally, it would
# be able to write binary files.
bf = self.make_file("binary")
with open(bf, "wb") as f:
f.write(b'\x7fELF\x02\x01\x01\x00\x00\x00')
path = python_reported_file('binary')
msg = (
re.escape("Couldn't run '{}' as Python code: ".format(path)) +
r"(TypeError|ValueError): "
r"("
r"compile\(\) expected string without null bytes" # for py2
r"|"
r"source code string cannot contain null bytes" # for py3
r")"
)
with self.assertRaisesRegex(Exception, msg):
run_python_file([bf])
class RunModuleTest(UsingModulesMixin, CoverageTest):
"""Test run_python_module."""
run_in_temp_dir = False
def test_runmod1(self):
run_python_module(["runmod1", "hello"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "runmod1: passed hello\n")
def test_runmod2(self):
run_python_module(["pkg1.runmod2", "hello"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\nrunmod2: passed hello\n")
def test_runmod3(self):
run_python_module(["pkg1.sub.runmod3", "hello"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\nrunmod3: passed hello\n")
def test_pkg1_main(self):
run_python_module(["pkg1", "hello"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.__main__: passed hello\n")
def test_pkg1_sub_main(self):
run_python_module(["pkg1.sub", "hello"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.sub.__main__: passed hello\n")
def test_pkg1_init(self):
run_python_module(["pkg1.__init__", "wut?"])
self.assertEqual(self.stderr(), "")
self.assertEqual(self.stdout(), "pkg1.__init__: pkg1\npkg1.__init__: __main__\n")
def test_no_such_module(self):
with self.assertRaisesRegex(NoSource, "No module named '?i_dont_exist'?"):
run_python_module(["i_dont_exist"])
with self.assertRaisesRegex(NoSource, "No module named '?i'?"):
run_python_module(["i.dont_exist"])
with self.assertRaisesRegex(NoSource, "No module named '?i'?"):
run_python_module(["i.dont.exist"])
def test_no_main(self):
with self.assertRaises(NoSource):
run_python_module(["pkg2", "hi"])
|
import random
import requests
import string
from unittest import TestCase
from httpobs.scanner.retriever import retrieve_all
class TestRetriever(TestCase):
def test_retrieve_non_existent_domain(self):
domain = ''.join(random.choice(string.ascii_lowercase) for _ in range(223)) + '.net'
reqs = retrieve_all(domain)
self.assertIsNone(reqs['responses']['auto'])
self.assertIsNone(reqs['responses']['cors'])
self.assertIsNone(reqs['responses']['http'])
self.assertIsNone(reqs['responses']['https'])
self.assertIsNone(reqs['session'])
self.assertEquals(domain, reqs['hostname'])
self.assertEquals({}, reqs['resources'])
def test_retrieve_mozilla(self):
reqs = retrieve_all('mozilla.org')
# Various things we know about mozilla.org
self.assertIsNotNone(reqs['resources']['__path__'])
self.assertIsNotNone(reqs['resources']['/contribute.json'])
self.assertIsNotNone(reqs['resources']['/robots.txt'])
self.assertIsNone(reqs['resources']['/clientaccesspolicy.xml'])
self.assertIsNone(reqs['resources']['/crossdomain.xml'])
self.assertIsInstance(reqs['responses']['auto'], requests.Response)
self.assertIsInstance(reqs['responses']['cors'], requests.Response)
self.assertIsInstance(reqs['responses']['http'], requests.Response)
self.assertIsInstance(reqs['responses']['https'], requests.Response)
self.assertIsInstance(reqs['session'], requests.Session)
self.assertEquals(reqs['hostname'], 'mozilla.org')
self.assertEquals('text/html', reqs['responses']['auto'].headers['Content-Type'][0:9])
self.assertEquals(2, len(reqs['responses']['auto'].history))
self.assertEquals(200, reqs['responses']['auto'].status_code)
self.assertEquals('https://www.mozilla.org/en-US/', reqs['responses']['auto'].url)
def test_retrieve_invalid_cert(self):
reqs = retrieve_all('expired.badssl.com')
self.assertFalse(reqs['responses']['auto'].verified)
|
from collections import deque
from time import monotonic
__all__ = ('TokenBucket',)
class TokenBucket:
"""Token Bucket Algorithm.
See Also:
https://en.wikipedia.org/wiki/Token_Bucket
Most of this code was stolen from an entry in the ASPN Python Cookbook:
https://code.activestate.com/recipes/511490/
Warning:
Thread Safety: This implementation is not thread safe.
Access to a `TokenBucket` instance should occur within the critical
section of any multithreaded code.
"""
#: The rate in tokens/second that the bucket will be refilled.
fill_rate = None
#: Maximum number of tokens in the bucket.
capacity = 1
#: Timestamp of the last time a token was taken out of the bucket.
timestamp = None
def __init__(self, fill_rate, capacity=1):
self.capacity = float(capacity)
self._tokens = capacity
self.fill_rate = float(fill_rate)
self.timestamp = monotonic()
self.contents = deque()
def add(self, item):
self.contents.append(item)
def pop(self):
return self.contents.popleft()
def clear_pending(self):
self.contents.clear()
def can_consume(self, tokens=1):
"""Check if one or more tokens can be consumed.
Returns:
bool: true if the number of tokens can be consumed
from the bucket. If they can be consumed, a call will also
consume the requested number of tokens from the bucket.
Calls will only consume `tokens` (the number requested)
or zero tokens -- it will never consume a partial number
of tokens.
"""
if tokens <= self._get_tokens():
self._tokens -= tokens
return True
return False
def expected_time(self, tokens=1):
"""Return estimated time of token availability.
Returns:
float: the time in seconds.
"""
_tokens = self._get_tokens()
tokens = max(tokens, _tokens)
return (tokens - _tokens) / self.fill_rate
def _get_tokens(self):
if self._tokens < self.capacity:
now = monotonic()
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
return self._tokens
|
import pytest
from qutebrowser.utils import usertypes
class TestInit:
"""Just try to init some neighborlists."""
def test_empty(self):
"""Test constructing an empty NeighborList."""
nl = usertypes.NeighborList()
assert nl.items == []
def test_items(self):
"""Test constructing a NeighborList with items."""
nl = usertypes.NeighborList([1, 2, 3])
assert nl.items == [1, 2, 3]
def test_len(self):
"""Test len() on NeighborList."""
nl = usertypes.NeighborList([1, 2, 3])
assert len(nl) == 3
def test_contains(self):
"""Test 'in' on NeighborList."""
nl = usertypes.NeighborList([1, 2, 3])
assert 2 in nl
assert 4 not in nl
def test_invalid_mode(self):
"""Test with an invalid mode."""
with pytest.raises(TypeError):
usertypes.NeighborList(mode='blah')
class TestDefaultArg:
"""Test the default argument."""
def test_simple(self):
"""Test default with a numeric argument."""
nl = usertypes.NeighborList([1, 2, 3], default=2)
assert nl._idx == 1
def test_none(self):
"""Test default 'None'."""
nl = usertypes.NeighborList([1, 2, None], default=None)
assert nl._idx == 2
def test_unset(self):
"""Test unset default value."""
nl = usertypes.NeighborList([1, 2, 3])
assert nl._idx is None
def test_invalid_reset(self):
"""Test reset without default."""
nl = usertypes.NeighborList([1, 2, 3, 4, 5])
with pytest.raises(ValueError):
nl.reset()
class TestEmpty:
"""Tests with no items."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList()
def test_curitem(self, neighborlist):
"""Test curitem with no item."""
with pytest.raises(IndexError):
neighborlist.curitem()
def test_firstitem(self, neighborlist):
"""Test firstitem with no item."""
with pytest.raises(IndexError):
neighborlist.firstitem()
def test_lastitem(self, neighborlist):
"""Test lastitem with no item."""
with pytest.raises(IndexError):
neighborlist.lastitem()
def test_getitem(self, neighborlist):
"""Test getitem with no item."""
with pytest.raises(IndexError):
neighborlist.getitem(1)
class TestItems:
"""Tests with items."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList([1, 2, 3, 4, 5], default=3)
def test_curitem(self, neighborlist):
"""Test curitem()."""
assert neighborlist._idx == 2
assert neighborlist.curitem() == 3
assert neighborlist._idx == 2
def test_nextitem(self, neighborlist):
"""Test nextitem()."""
assert neighborlist.nextitem() == 4
assert neighborlist._idx == 3
assert neighborlist.nextitem() == 5
assert neighborlist._idx == 4
def test_previtem(self, neighborlist):
"""Test previtem()."""
assert neighborlist.previtem() == 2
assert neighborlist._idx == 1
assert neighborlist.previtem() == 1
assert neighborlist._idx == 0
def test_firstitem(self, neighborlist):
"""Test firstitem()."""
assert neighborlist.firstitem() == 1
assert neighborlist._idx == 0
def test_lastitem(self, neighborlist):
"""Test lastitem()."""
assert neighborlist.lastitem() == 5
assert neighborlist._idx == 4
def test_reset(self, neighborlist):
"""Test reset()."""
neighborlist.nextitem()
assert neighborlist._idx == 3
neighborlist.reset()
assert neighborlist._idx == 2
def test_getitem(self, neighborlist):
"""Test getitem()."""
assert neighborlist.getitem(2) == 5
assert neighborlist._idx == 4
neighborlist.reset()
assert neighborlist.getitem(-2) == 1
assert neighborlist._idx == 0
class TestSingleItem:
"""Tests with a list with only one item."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList([1], default=1)
def test_first_edge(self, neighborlist):
"""Test out of bounds previtem() with mode=edge."""
neighborlist._mode = usertypes.NeighborList.Modes.edge
neighborlist.firstitem()
assert neighborlist._idx == 0
assert neighborlist.previtem() == 1
assert neighborlist._idx == 0
def test_first_raise(self, neighborlist):
"""Test out of bounds previtem() with mode=raise."""
neighborlist._mode = usertypes.NeighborList.Modes.exception
neighborlist.firstitem()
assert neighborlist._idx == 0
with pytest.raises(IndexError):
neighborlist.previtem()
assert neighborlist._idx == 0
def test_last_edge(self, neighborlist):
"""Test out of bounds nextitem() with mode=edge."""
neighborlist._mode = usertypes.NeighborList.Modes.edge
neighborlist.lastitem()
assert neighborlist._idx == 0
assert neighborlist.nextitem() == 1
assert neighborlist._idx == 0
def test_last_raise(self, neighborlist):
"""Test out of bounds nextitem() with mode=raise."""
neighborlist._mode = usertypes.NeighborList.Modes.exception
neighborlist.lastitem()
assert neighborlist._idx == 0
with pytest.raises(IndexError):
neighborlist.nextitem()
assert neighborlist._idx == 0
class TestEdgeMode:
"""Tests with mode=edge."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList(
[1, 2, 3, 4, 5], default=3,
mode=usertypes.NeighborList.Modes.edge)
def test_first(self, neighborlist):
"""Test out of bounds previtem()."""
neighborlist.firstitem()
assert neighborlist._idx == 0
assert neighborlist.previtem() == 1
assert neighborlist._idx == 0
def test_last(self, neighborlist):
"""Test out of bounds nextitem()."""
neighborlist.lastitem()
assert neighborlist._idx == 4
assert neighborlist.nextitem() == 5
assert neighborlist._idx == 4
class TestExceptionMode:
"""Tests with mode=exception."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList(
[1, 2, 3, 4, 5], default=3,
mode=usertypes.NeighborList.Modes.exception)
def test_first(self, neighborlist):
"""Test out of bounds previtem()."""
neighborlist.firstitem()
assert neighborlist._idx == 0
with pytest.raises(IndexError):
neighborlist.previtem()
assert neighborlist._idx == 0
def test_last(self, neighborlist):
"""Test out of bounds nextitem()."""
neighborlist.lastitem()
assert neighborlist._idx == 4
with pytest.raises(IndexError):
neighborlist.nextitem()
assert neighborlist._idx == 4
class TestSnapIn:
"""Tests for the fuzzyval/_snap_in features."""
@pytest.fixture
def neighborlist(self):
return usertypes.NeighborList([20, 9, 1, 5])
def test_bigger(self, neighborlist):
"""Test fuzzyval with snapping to a bigger value."""
neighborlist.fuzzyval = 7
assert neighborlist.nextitem() == 9
assert neighborlist._idx == 1
assert neighborlist.nextitem() == 1
assert neighborlist._idx == 2
def test_smaller(self, neighborlist):
"""Test fuzzyval with snapping to a smaller value."""
neighborlist.fuzzyval = 7
assert neighborlist.previtem() == 5
assert neighborlist._idx == 3
assert neighborlist.previtem() == 1
assert neighborlist._idx == 2
def test_equal_bigger(self, neighborlist):
"""Test fuzzyval with matching value, snapping to a bigger value."""
neighborlist.fuzzyval = 20
assert neighborlist.nextitem() == 9
assert neighborlist._idx == 1
def test_equal_smaller(self, neighborlist):
"""Test fuzzyval with matching value, snapping to a smaller value."""
neighborlist.fuzzyval = 5
assert neighborlist.previtem() == 1
assert neighborlist._idx == 2
def test_too_big_next(self, neighborlist):
"""Test fuzzyval/next with a value bigger than any in the list."""
neighborlist.fuzzyval = 30
assert neighborlist.nextitem() == 20
assert neighborlist._idx == 0
def test_too_big_prev(self, neighborlist):
"""Test fuzzyval/prev with a value bigger than any in the list."""
neighborlist.fuzzyval = 30
assert neighborlist.previtem() == 20
assert neighborlist._idx == 0
def test_too_small_next(self, neighborlist):
"""Test fuzzyval/next with a value smaller than any in the list."""
neighborlist.fuzzyval = 0
assert neighborlist.nextitem() == 1
assert neighborlist._idx == 2
def test_too_small_prev(self, neighborlist):
"""Test fuzzyval/prev with a value smaller than any in the list."""
neighborlist.fuzzyval = 0
assert neighborlist.previtem() == 1
assert neighborlist._idx == 2
|
import asyncio
import logging
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from ssl import CertificateError
import aiohttp
import click
import humanize
from twtxt.helper import generate_user_agent
from twtxt.parser import parse_tweets
logger = logging.getLogger(__name__)
class SourceResponse:
"""A :class:`SourceResponse` contains information about a :class:`Source`’s HTTP request.
:param int status_code: response status code
:param str content_length: Content-Length header field
:param str last_modified: Last-Modified header field
"""
def __init__(self, status_code, content_length, last_modified):
self.status_code = status_code
self.content_length = content_length
self.last_modified = last_modified
@property
def natural_content_length(self):
return humanize.naturalsize(self.content_length)
@property
def natural_last_modified(self):
last_modified = parsedate_to_datetime(self.last_modified)
now = datetime.now(timezone.utc)
tense = "from now" if last_modified > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - last_modified), tense)
@asyncio.coroutine
def retrieve_status(client, source):
status = None
try:
response = yield from client.head(source.url)
if response.headers.get("Content-Length"):
content_length = response.headers.get("Content-Length")
else:
content_length = 0
status = SourceResponse(status_code=response.status,
content_length=content_length,
last_modified=response.headers.get("Last-Modified"))
yield from response.release()
except CertificateError as e:
click.echo("✗ SSL Certificate Error: The feed's ({0}) SSL certificate is untrusted. Try using HTTP, "
"or contact the feed's owner to report this issue.".format(source.url))
logger.debug("{0}: {1}".format(source.url, e))
except Exception as e:
logger.debug("{0}: {1}".format(source.url, e))
finally:
return source, status
@asyncio.coroutine
def retrieve_file(client, source, limit, cache):
is_cached = cache.is_cached(source.url) if cache else None
headers = {"If-Modified-Since": cache.last_modified(source.url)} if is_cached else {}
try:
response = yield from client.get(source.url, headers=headers)
content = yield from response.text()
except Exception as e:
if is_cached:
logger.debug("{0}: {1} - using cached content".format(source.url, e))
return cache.get_tweets(source.url, limit)
else:
logger.debug("{0}: {1}".format(source.url, e))
return []
if response.status == 200:
tweets = parse_tweets(content.splitlines(), source)
if cache:
last_modified_header = response.headers.get("Last-Modified")
if last_modified_header:
logger.debug("{0} returned 200 and Last-Modified header - adding content to cache".format(source.url))
cache.add_tweets(source.url, last_modified_header, tweets)
else:
logger.debug("{0} returned 200 but no Last-Modified header - can’t cache content".format(source.url))
else:
logger.debug("{0} returned 200".format(source.url))
return sorted(tweets, reverse=True)[:limit]
elif response.status == 410 and is_cached:
# 410 Gone:
# The resource requested is no longer available,
# and will not be available again.
logger.debug("{0} returned 410 - deleting cached content".format(source.url))
cache.remove_tweets(source.url)
return []
elif is_cached:
logger.debug("{0} returned {1} - using cached content".format(source.url, response.status))
return cache.get_tweets(source.url, limit)
else:
logger.debug("{0} returned {1}".format(source.url, response.status))
return []
@asyncio.coroutine
def process_sources_for_status(client, sources):
g_status = []
coroutines = [retrieve_status(client, source) for source in sources]
for coroutine in asyncio.as_completed(coroutines):
status = yield from coroutine
g_status.append(status)
return sorted(g_status, key=lambda x: x[0].nick)
@asyncio.coroutine
def process_sources_for_file(client, sources, limit, cache=None):
g_tweets = []
coroutines = [retrieve_file(client, source, limit, cache) for source in sources]
for coroutine in asyncio.as_completed(coroutines):
tweets = yield from coroutine
g_tweets.extend(tweets)
return sorted(g_tweets, reverse=True)[:limit]
def get_remote_tweets(sources, limit=None, timeout=5.0, cache=None):
conn = aiohttp.TCPConnector(use_dns_cache=True)
headers = generate_user_agent()
with aiohttp.ClientSession(connector=conn, headers=headers, conn_timeout=timeout) as client:
loop = asyncio.get_event_loop()
def start_loop(client, sources, limit, cache=None):
return loop.run_until_complete(process_sources_for_file(client, sources, limit, cache))
tweets = start_loop(client, sources, limit, cache)
return tweets
def get_remote_status(sources, timeout=5.0):
conn = aiohttp.TCPConnector(use_dns_cache=True)
headers = generate_user_agent()
with aiohttp.ClientSession(connector=conn, headers=headers, conn_timeout=timeout) as client:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(process_sources_for_status(client, sources))
return result
|
import logging
from pyuptimerobot import UptimeRobot
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import ATTR_ATTRIBUTION, CONF_API_KEY
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
ATTR_TARGET = "target"
ATTRIBUTION = "Data provided by Uptime Robot"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_API_KEY): cv.string})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Uptime Robot binary_sensors."""
up_robot = UptimeRobot()
api_key = config.get(CONF_API_KEY)
monitors = up_robot.getMonitors(api_key)
devices = []
if not monitors or monitors.get("stat") != "ok":
_LOGGER.error("Error connecting to Uptime Robot")
return
for monitor in monitors["monitors"]:
devices.append(
UptimeRobotBinarySensor(
api_key,
up_robot,
monitor["id"],
monitor["friendly_name"],
monitor["url"],
)
)
add_entities(devices, True)
class UptimeRobotBinarySensor(BinarySensorEntity):
"""Representation of a Uptime Robot binary sensor."""
def __init__(self, api_key, up_robot, monitor_id, name, target):
"""Initialize Uptime Robot the binary sensor."""
self._api_key = api_key
self._monitor_id = str(monitor_id)
self._name = name
self._target = target
self._up_robot = up_robot
self._state = None
@property
def name(self):
"""Return the name of the binary sensor."""
return self._name
@property
def is_on(self):
"""Return the state of the binary sensor."""
return self._state
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return DEVICE_CLASS_CONNECTIVITY
@property
def device_state_attributes(self):
"""Return the state attributes of the binary sensor."""
return {ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_TARGET: self._target}
def update(self):
"""Get the latest state of the binary sensor."""
monitor = self._up_robot.getMonitors(self._api_key, self._monitor_id)
if not monitor or monitor.get("stat") != "ok":
_LOGGER.warning("Failed to get new state")
return
status = monitor["monitors"][0]["status"]
self._state = 1 if status == 2 else 0
|
import asyncio
import socket
from pyfritzhome import Fritzhome
import voluptuous as vol
from homeassistant.const import (
CONF_DEVICES,
CONF_HOST,
CONF_PASSWORD,
CONF_USERNAME,
EVENT_HOMEASSISTANT_STOP,
)
import homeassistant.helpers.config_validation as cv
from .const import CONF_CONNECTIONS, DEFAULT_HOST, DEFAULT_USERNAME, DOMAIN, PLATFORMS
def ensure_unique_hosts(value):
"""Validate that all configs have a unique host."""
vol.Schema(vol.Unique("duplicate host entries found"))(
[socket.gethostbyname(entry[CONF_HOST]) for entry in value]
)
return value
CONFIG_SCHEMA = vol.Schema(
vol.All(
cv.deprecated(DOMAIN),
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_DEVICES): vol.All(
cv.ensure_list,
[
vol.Schema(
{
vol.Required(
CONF_HOST, default=DEFAULT_HOST
): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(
CONF_USERNAME, default=DEFAULT_USERNAME
): cv.string,
}
)
],
ensure_unique_hosts,
)
}
)
},
),
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass, config):
"""Set up the AVM Fritz!Box integration."""
if DOMAIN in config:
for entry_config in config[DOMAIN][CONF_DEVICES]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": "import"}, data=entry_config
)
)
return True
async def async_setup_entry(hass, entry):
"""Set up the AVM Fritz!Box platforms."""
fritz = Fritzhome(
host=entry.data[CONF_HOST],
user=entry.data[CONF_USERNAME],
password=entry.data[CONF_PASSWORD],
)
await hass.async_add_executor_job(fritz.login)
hass.data.setdefault(DOMAIN, {CONF_CONNECTIONS: {}, CONF_DEVICES: set()})
hass.data[DOMAIN][CONF_CONNECTIONS][entry.entry_id] = fritz
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
def logout_fritzbox(event):
"""Close connections to this fritzbox."""
fritz.logout()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox)
return True
async def async_unload_entry(hass, entry):
"""Unloading the AVM Fritz!Box platforms."""
fritz = hass.data[DOMAIN][CONF_CONNECTIONS][entry.entry_id]
await hass.async_add_executor_job(fritz.logout)
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN][CONF_CONNECTIONS].pop(entry.entry_id)
return unload_ok
|
import json
import unittest
from absl import flags
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import errors
from perfkitbenchmarker import placement_group
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_placement_group
from tests import pkb_common_test_case
_PROJECT = 'myproject'
_ZONE = 'us-east1-b'
_REGION = 'us-east1'
_RUN_URI = 'be67a2dd-e312-496d-864a-1d5bc1857dec'
_PLACEMENT_GROUP_NAME = 'perfkit-{}'.format(_RUN_URI)
_STRATEGY = placement_group.PLACEMENT_GROUP_CLUSTER
# The GcePlacementGroup._Create()
_CREATE_RESPONSE = (json.dumps({
'creationTimestamp': '2020-03-16T15:31:23.802-07:00',
'description': 'PKB: test',
'groupPlacementPolicy': {
'collocation': 'COLLOCATED',
'vmCount': 2
},
'id': '123',
'kind': 'compute#resourcePolicy',
'name': 'perfkit-test',
'region': 'https://www.googleapis.com/test',
'selfLink': 'https://www.googleapis.com/test',
'status': 'READY'
}), '', 0)
_QUOTA_FAILURE_RESPONSE = (
'',
'ERROR: (gcloud.alpha.compute.resource-policies.create.group-placement) '
'Could not fetch resource: - Quota \'RESOURCE_POLICIES\' exceeded. Limit: '
'10.0 in region europe-west4.', 1)
# The GcePlacementGroup._Exists() response done after a Create() call.
_EXISTS_RESPONSE = json.dumps({'status': 'ACTIVE'}), '', 0
# The GcePlacementGroup._Exists() response done after a Delete() call.
_DELETE_RESPONSE = json.dumps({}), '', 1
FLAGS = flags.FLAGS
def _BenchmarkSpec(num_vms=2, benchmark='cluster_boot'):
# Creates a fake BenchmarkSpec() that will be the response for calls to
# perfkitbenchmarker.context.GetThreadBenchmarkSpec().
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
benchmark, flag_values=FLAGS)
config_spec.vm_groups = {'x': mock.Mock(vm_count=num_vms, static_vms=[])}
bm_module = mock.MagicMock(BENCHMARK_NAME=benchmark)
bm_spec = benchmark_spec.BenchmarkSpec(bm_module, config_spec, 'uid')
bm_spec.uuid = _RUN_URI
def _CreateGcePlacementGroupSpec(group_style=_STRATEGY):
FLAGS.placement_group_style = group_style
return gce_placement_group.GcePlacementGroupSpec(
'GcePlacementGroupSpec',
zone=_ZONE,
project=_PROJECT,
num_vms=2,
flag_values=FLAGS)
def _CreateGcePlacementGroup(group_style=_STRATEGY):
return gce_placement_group.GcePlacementGroup(
_CreateGcePlacementGroupSpec(group_style))
class GcePlacementGroupTest(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GcePlacementGroupTest, self).setUp()
self.mock_cmd = self.enter_context(
mock.patch.object(vm_util, 'IssueCommand'))
# Register a fake benchmark
_BenchmarkSpec(2)
def testPlacementGroupCreate(self):
self.mock_cmd.return_value = _CREATE_RESPONSE
_CreateGcePlacementGroup()._Create()
self.mock_cmd.assert_called_with([
'gcloud', 'compute', 'resource-policies', 'create',
'group-placement', _PLACEMENT_GROUP_NAME, '--collocation', 'COLLOCATED',
'--format', 'json',
'--project', 'myproject', '--quiet', '--region', 'us-east1',
'--vm-count', '2'
], raise_on_failure=False)
def testPlacementGroupDelete(self):
self.mock_cmd.side_effect = [_EXISTS_RESPONSE, _DELETE_RESPONSE]
_CreateGcePlacementGroup().Delete()
self.mock_cmd.assert_called_with([
'gcloud', 'compute', 'resource-policies', 'describe',
_PLACEMENT_GROUP_NAME, '--format', 'json', '--project', 'myproject',
'--quiet', '--region', 'us-east1'
], raise_on_failure=False)
def testPlacementGroupQuotaFailure(self):
self.mock_cmd.return_value = _QUOTA_FAILURE_RESPONSE
with self.assertRaises(errors.Benchmarks.QuotaFailure):
_CreateGcePlacementGroup()._Create()
if __name__ == '__main__':
unittest.main()
|
import unittest
from absl import flags
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import configs
from perfkitbenchmarker import context
from perfkitbenchmarker import linux_benchmarks
from perfkitbenchmarker import pkb # pylint: disable=unused-import # noqa
from perfkitbenchmarker import providers
from perfkitbenchmarker import static_virtual_machine as static_vm
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.linux_benchmarks import iperf_benchmark
from perfkitbenchmarker.providers.aws import aws_virtual_machine as aws_vm
from perfkitbenchmarker.providers.gcp import gce_virtual_machine as gce_vm
from tests import pkb_common_test_case
flags.DEFINE_integer('benchmark_spec_test_flag', 0, 'benchmark_spec_test flag.')
FLAGS = flags.FLAGS
NAME = 'cluster_boot'
UID = 'name0'
SIMPLE_CONFIG = """
cluster_boot:
vm_groups:
default:
vm_spec:
GCP:
machine_type: n1-standard-4
zone: us-central1-c
project: my-project
"""
MULTI_CLOUD_CONFIG = """
cluster_boot:
vm_groups:
group1:
cloud: AWS
vm_spec:
AWS:
machine_type: c3.2xlarge
zone: us-east-1a
group2:
cloud: GCP
vm_spec:
GCP:
machine_type: n1-standard-4
project: my-project
"""
STATIC_VM_CONFIG = """
static_vms:
- &vm1
ip_address: 1.1.1.1
ssh_private_key: /path/to/key1
user_name: user1
cluster_boot:
vm_groups:
group1:
vm_spec: *default_single_core
group2:
vm_count: 3
vm_spec: *default_single_core
static_vms:
- *vm1
- ip_address: 2.2.2.2
os_type: rhel7
ssh_private_key: /path/to/key2
user_name: user2
disk_specs:
- mount_point: /scratch
"""
VALID_CONFIG_WITH_DISK_SPEC = """
cluster_boot:
vm_groups:
default:
disk_count: 3
disk_spec:
GCP:
disk_size: 75
vm_count: 2
vm_spec:
GCP:
machine_type: n1-standard-4
"""
ALWAYS_SUPPORTED = 'iperf'
NEVER_SUPPORTED = 'sysbench'
_SIMPLE_EDW_CONFIG = """
edw_benchmark:
description: Sample edw benchmark
edw_service:
type: snowflake_aws
cluster_identifier: _fake_cluster_id_
vm_groups:
client:
vm_spec: *default_single_core
"""
class _BenchmarkSpecTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(_BenchmarkSpecTestCase, self).setUp()
FLAGS.cloud = providers.GCP
FLAGS.temp_dir = 'tmp'
self.addCleanup(context.SetThreadBenchmarkSpec, None)
def _CreateBenchmarkSpecFromYaml(self, yaml_string, benchmark_name=NAME):
config = configs.LoadConfig(yaml_string, {}, benchmark_name)
return self._CreateBenchmarkSpecFromConfigDict(config, benchmark_name)
def _CreateBenchmarkSpecFromConfigDict(self, config_dict, benchmark_name):
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
benchmark_name, flag_values=FLAGS, **config_dict)
benchmark_module = next((b for b in linux_benchmarks.BENCHMARKS
if b.BENCHMARK_NAME == benchmark_name))
return benchmark_spec.BenchmarkSpec(benchmark_module, config_spec, UID)
class ConstructEdwServiceTestCase(_BenchmarkSpecTestCase):
def testSimpleConfig(self):
spec = self._CreateBenchmarkSpecFromYaml(
yaml_string=_SIMPLE_EDW_CONFIG, benchmark_name='edw_benchmark')
spec.ConstructEdwService()
self.assertEqual('snowflake_aws', spec.edw_service.SERVICE_TYPE)
self.assertIsInstance(spec.edw_service, providers.aws.snowflake.Snowflake)
class ConstructVmsTestCase(_BenchmarkSpecTestCase):
def testSimpleConfig(self):
spec = self._CreateBenchmarkSpecFromYaml(SIMPLE_CONFIG)
spec.ConstructVirtualMachines()
self.assertEqual(len(spec.vms), 1)
vm = spec.vms[0]
self.assertEqual(vm.machine_type, 'n1-standard-4')
self.assertEqual(vm.zone, 'us-central1-c')
self.assertEqual(vm.project, 'my-project')
self.assertEqual(vm.disk_specs, [])
def testMultiCloud(self):
spec = self._CreateBenchmarkSpecFromYaml(MULTI_CLOUD_CONFIG)
spec.ConstructVirtualMachines()
self.assertEqual(len(spec.vms), 2)
self.assertIsInstance(spec.vm_groups['group1'][0], aws_vm.AwsVirtualMachine)
self.assertIsInstance(spec.vm_groups['group2'][0], gce_vm.GceVirtualMachine)
def testStaticVms(self):
spec = self._CreateBenchmarkSpecFromYaml(STATIC_VM_CONFIG)
spec.ConstructVirtualMachines()
self.assertEqual(len(spec.vms), 4)
vm0 = spec.vm_groups['group1'][0]
vm1, vm2, vm3 = spec.vm_groups['group2']
self.assertIsInstance(vm0, gce_vm.GceVirtualMachine)
self.assertIsInstance(vm1, static_vm.StaticVirtualMachine)
self.assertIsInstance(vm2, static_vm.Rhel7BasedStaticVirtualMachine)
self.assertIsInstance(vm3, gce_vm.GceVirtualMachine)
self.assertEqual(vm2.disk_specs[0].mount_point, '/scratch')
def testValidConfigWithDiskSpec(self):
spec = self._CreateBenchmarkSpecFromYaml(VALID_CONFIG_WITH_DISK_SPEC)
spec.ConstructVirtualMachines()
vms = spec.vm_groups['default']
self.assertEqual(len(vms), 2)
for vm in vms:
self.assertEqual(len(vm.disk_specs), 3)
self.assertTrue(all(disk_spec.disk_size == 75
for disk_spec in vm.disk_specs))
def testZonesFlag(self):
FLAGS.zones = ['us-east-1b', 'zone2']
FLAGS.extra_zones = []
spec = self._CreateBenchmarkSpecFromYaml(MULTI_CLOUD_CONFIG)
spec.ConstructVirtualMachines()
self.assertEqual(len(spec.vms), 2)
self.assertEqual(spec.vm_groups['group1'][0].zone, 'us-east-1b')
self.assertEqual(spec.vm_groups['group2'][0].zone, 'zone2')
def testZonesFlagWithZoneFlag(self):
FLAGS.zones = ['us-east-1b']
FLAGS.extra_zones = []
FLAGS.zone = ['us-west-2b']
spec = self._CreateBenchmarkSpecFromYaml(MULTI_CLOUD_CONFIG)
spec.ConstructVirtualMachines()
self.assertEqual(len(spec.vms), 2)
self.assertEqual(spec.vm_groups['group1'][0].zone, 'us-east-1b')
self.assertEqual(spec.vm_groups['group2'][0].zone, 'us-west-2b')
class BenchmarkSupportTestCase(_BenchmarkSpecTestCase):
def createBenchmarkSpec(self, config, benchmark):
spec = self._CreateBenchmarkSpecFromConfigDict(config, benchmark)
spec.ConstructVirtualMachines()
return True
def testBenchmarkSupportFlag(self):
"""Test the benchmark_compatibility_checking flag.
We use Kubernetes as our test cloud platform because it has
supported benchmarks (IsBenchmarkSupported returns true)
unsupported benchmarks (IsBenchmarkSupported returns false)
and returns None if the benchmark isn't in either list.
"""
FLAGS.cloud = 'Kubernetes'
config = configs.LoadConfig(iperf_benchmark.BENCHMARK_CONFIG, {},
ALWAYS_SUPPORTED)
self.assertTrue(self.createBenchmarkSpec(config, ALWAYS_SUPPORTED))
with self.assertRaises(ValueError):
self.createBenchmarkSpec(config, NEVER_SUPPORTED)
FLAGS.benchmark_compatibility_checking = 'permissive'
self.assertTrue(
self.createBenchmarkSpec(config, ALWAYS_SUPPORTED),
'benchmark is supported, mode is permissive')
with self.assertRaises(ValueError):
self.createBenchmarkSpec(config, NEVER_SUPPORTED)
FLAGS.benchmark_compatibility_checking = 'none'
self.assertTrue(self.createBenchmarkSpec(config, ALWAYS_SUPPORTED))
self.assertTrue(self.createBenchmarkSpec(config, NEVER_SUPPORTED))
class RedirectGlobalFlagsTestCase(pkb_common_test_case.PkbCommonTestCase):
def testNoFlagOverride(self):
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
NAME, flag_values=FLAGS, vm_groups={})
spec = benchmark_spec.BenchmarkSpec(mock.MagicMock(), config_spec, UID)
self.assertEqual(FLAGS.benchmark_spec_test_flag, 0)
with spec.RedirectGlobalFlags():
self.assertEqual(FLAGS.benchmark_spec_test_flag, 0)
self.assertEqual(FLAGS.benchmark_spec_test_flag, 0)
def testFlagOverride(self):
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
NAME, flag_values=FLAGS, flags={'benchmark_spec_test_flag': 1},
vm_groups={})
spec = benchmark_spec.BenchmarkSpec(mock.MagicMock(), config_spec, UID)
self.assertEqual(FLAGS.benchmark_spec_test_flag, 0)
with spec.RedirectGlobalFlags():
self.assertEqual(FLAGS.benchmark_spec_test_flag, 1)
FLAGS.benchmark_spec_test_flag = 2
self.assertEqual(FLAGS.benchmark_spec_test_flag, 2)
self.assertEqual(FLAGS.benchmark_spec_test_flag, 0)
if __name__ == '__main__':
unittest.main()
|
import os
import unittest
from perfkitbenchmarker import sample
from perfkitbenchmarker import test_util
from perfkitbenchmarker.linux_benchmarks import specsfs2014_benchmark
class SpecSfs2014BenchmarkTestCase(unittest.TestCase,
test_util.SamplesTestMixin):
def setUp(self):
self.maxDiff = None
# Load data
path = os.path.join(os.path.dirname(__file__),
'..', 'data',
'specsfs2014_results.xml')
with open(path) as fp:
self.specsfs2014_xml_results = fp.read()
def testSpecSfs2014Parsing(self):
samples = specsfs2014_benchmark._ParseSpecSfsOutput(
self.specsfs2014_xml_results)
expected_metadata = {
'client data set size (MiB)': '4296',
'starting data set size (MiB)': '4296',
'maximum file space (MiB)': '4687', 'file size (KB)': '16',
'run time (seconds)': '300', 'benchmark': 'SWBUILD',
'business_metric': '1', 'op rate (ops/s)': '500.00',
'processes per client': '5', 'initial file space (MiB)': '4296',
'valid_run': True
}
expected_samples = [
sample.Sample(
'achieved rate', 500.05, 'ops/s', expected_metadata),
sample.Sample(
'average latency', 1.48, 'milliseconds', expected_metadata),
sample.Sample(
'overall throughput', 6463.95, 'KB/s', expected_metadata),
sample.Sample(
'read throughput', 3204.78, 'KB/s', expected_metadata),
sample.Sample(
'write throughput', 3259.17, 'KB/s', expected_metadata)
]
self.assertSampleListsEqualUpToTimestamp(expected_samples, samples)
if __name__ == '__main__':
unittest.main()
|
import asyncio
from datetime import datetime, timedelta
import logging
import async_timeout
from pywemo.ouimeaux_device.api.service import ActionException
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import STATE_OFF, STATE_ON, STATE_STANDBY, STATE_UNKNOWN
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util import convert
from .const import DOMAIN as WEMO_DOMAIN
SCAN_INTERVAL = timedelta(seconds=10)
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
# The WEMO_ constants below come from pywemo itself
ATTR_SENSOR_STATE = "sensor_state"
ATTR_SWITCH_MODE = "switch_mode"
ATTR_CURRENT_STATE_DETAIL = "state_detail"
ATTR_COFFEMAKER_MODE = "coffeemaker_mode"
MAKER_SWITCH_MOMENTARY = "momentary"
MAKER_SWITCH_TOGGLE = "toggle"
WEMO_ON = 1
WEMO_OFF = 0
WEMO_STANDBY = 8
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up WeMo switches."""
async def _discovered_wemo(device):
"""Handle a discovered Wemo device."""
async_add_entities([WemoSwitch(device)])
async_dispatcher_connect(hass, f"{WEMO_DOMAIN}.switch", _discovered_wemo)
await asyncio.gather(
*[
_discovered_wemo(device)
for device in hass.data[WEMO_DOMAIN]["pending"].pop("switch")
]
)
class WemoSwitch(SwitchEntity):
"""Representation of a WeMo switch."""
def __init__(self, device):
"""Initialize the WeMo switch."""
self.wemo = device
self.insight_params = None
self.maker_params = None
self.coffeemaker_mode = None
self._state = None
self._mode_string = None
self._available = True
self._update_lock = None
self._model_name = self.wemo.model_name
self._name = self.wemo.name
self._serialnumber = self.wemo.serialnumber
def _subscription_callback(self, _device, _type, _params):
"""Update the state by the Wemo device."""
_LOGGER.info("Subscription update for %s", self.name)
updated = self.wemo.subscription_update(_type, _params)
self.hass.add_job(self._async_locked_subscription_callback(not updated))
async def _async_locked_subscription_callback(self, force_update):
"""Handle an update from a subscription."""
# If an update is in progress, we don't do anything
if self._update_lock.locked():
return
await self._async_locked_update(force_update)
self.async_write_ha_state()
@property
def unique_id(self):
"""Return the ID of this WeMo switch."""
return self._serialnumber
@property
def name(self):
"""Return the name of the switch if any."""
return self._name
@property
def device_info(self):
"""Return the device info."""
return {
"name": self._name,
"identifiers": {(WEMO_DOMAIN, self._serialnumber)},
"model": self._model_name,
"manufacturer": "Belkin",
}
@property
def device_state_attributes(self):
"""Return the state attributes of the device."""
attr = {}
if self.maker_params:
# Is the maker sensor on or off.
if self.maker_params["hassensor"]:
# Note a state of 1 matches the WeMo app 'not triggered'!
if self.maker_params["sensorstate"]:
attr[ATTR_SENSOR_STATE] = STATE_OFF
else:
attr[ATTR_SENSOR_STATE] = STATE_ON
# Is the maker switch configured as toggle(0) or momentary (1).
if self.maker_params["switchmode"]:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_MOMENTARY
else:
attr[ATTR_SWITCH_MODE] = MAKER_SWITCH_TOGGLE
if self.insight_params or (self.coffeemaker_mode is not None):
attr[ATTR_CURRENT_STATE_DETAIL] = self.detail_state
if self.insight_params:
attr["on_latest_time"] = WemoSwitch.as_uptime(self.insight_params["onfor"])
attr["on_today_time"] = WemoSwitch.as_uptime(self.insight_params["ontoday"])
attr["on_total_time"] = WemoSwitch.as_uptime(self.insight_params["ontotal"])
attr["power_threshold_w"] = (
convert(self.insight_params["powerthreshold"], float, 0.0) / 1000.0
)
if self.coffeemaker_mode is not None:
attr[ATTR_COFFEMAKER_MODE] = self.coffeemaker_mode
return attr
@staticmethod
def as_uptime(_seconds):
"""Format seconds into uptime string in the format: 00d 00h 00m 00s."""
uptime = datetime(1, 1, 1) + timedelta(seconds=_seconds)
return "{:0>2d}d {:0>2d}h {:0>2d}m {:0>2d}s".format(
uptime.day - 1, uptime.hour, uptime.minute, uptime.second
)
@property
def current_power_w(self):
"""Return the current power usage in W."""
if self.insight_params:
return convert(self.insight_params["currentpower"], float, 0.0) / 1000.0
@property
def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
if self.insight_params:
miliwatts = convert(self.insight_params["todaymw"], float, 0.0)
return round(miliwatts / (1000.0 * 1000.0 * 60), 2)
@property
def detail_state(self):
"""Return the state of the device."""
if self.coffeemaker_mode is not None:
return self._mode_string
if self.insight_params:
standby_state = int(self.insight_params["state"])
if standby_state == WEMO_ON:
return STATE_ON
if standby_state == WEMO_OFF:
return STATE_OFF
if standby_state == WEMO_STANDBY:
return STATE_STANDBY
return STATE_UNKNOWN
@property
def is_on(self):
"""Return true if switch is on. Standby is on."""
return self._state
@property
def available(self):
"""Return true if switch is available."""
return self._available
@property
def icon(self):
"""Return the icon of device based on its type."""
if self._model_name == "CoffeeMaker":
return "mdi:coffee"
return None
def turn_on(self, **kwargs):
"""Turn the switch on."""
try:
if self.wemo.on():
self._state = WEMO_ON
except ActionException as err:
_LOGGER.warning("Error while turning on device %s (%s)", self.name, err)
self._available = False
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn the switch off."""
try:
if self.wemo.off():
self._state = WEMO_OFF
except ActionException as err:
_LOGGER.warning("Error while turning off device %s (%s)", self.name, err)
self._available = False
self.schedule_update_ha_state()
async def async_added_to_hass(self):
"""Wemo switch added to Home Assistant."""
# Define inside async context so we know our event loop
self._update_lock = asyncio.Lock()
registry = self.hass.data[WEMO_DOMAIN]["registry"]
await self.hass.async_add_executor_job(registry.register, self.wemo)
registry.on(self.wemo, None, self._subscription_callback)
async def async_update(self):
"""Update WeMo state.
Wemo has an aggressive retry logic that sometimes can take over a
minute to return. If we don't get a state after 5 seconds, assume the
Wemo switch is unreachable. If update goes through, it will be made
available again.
"""
# If an update is in progress, we don't do anything
if self._update_lock.locked():
return
try:
with async_timeout.timeout(5):
await asyncio.shield(self._async_locked_update(True))
except asyncio.TimeoutError:
_LOGGER.warning("Lost connection to %s", self.name)
self._available = False
async def _async_locked_update(self, force_update):
"""Try updating within an async lock."""
async with self._update_lock:
await self.hass.async_add_executor_job(self._update, force_update)
def _update(self, force_update):
"""Update the device state."""
try:
self._state = self.wemo.get_state(force_update)
if self._model_name == "Insight":
self.insight_params = self.wemo.insight_params
self.insight_params["standby_state"] = self.wemo.get_standby_state
elif self._model_name == "Maker":
self.maker_params = self.wemo.maker_params
elif self._model_name == "CoffeeMaker":
self.coffeemaker_mode = self.wemo.mode
self._mode_string = self.wemo.mode_string
if not self._available:
_LOGGER.info("Reconnected to %s", self.name)
self._available = True
except (AttributeError, ActionException) as err:
_LOGGER.warning("Could not update status for %s (%s)", self.name, err)
self._available = False
self.wemo.reconnect_with_device()
|
from datetime import timedelta
import logging
from unittest import mock
import pytest
from homeassistant import setup
from homeassistant.components import litejet
import homeassistant.components.automation as automation
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed, async_mock_service
_LOGGER = logging.getLogger(__name__)
ENTITY_SWITCH = "switch.mock_switch_1"
ENTITY_SWITCH_NUMBER = 1
ENTITY_OTHER_SWITCH = "switch.mock_switch_2"
ENTITY_OTHER_SWITCH_NUMBER = 2
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
def get_switch_name(number):
"""Get a mock switch name."""
return f"Mock Switch #{number}"
@pytest.fixture
def mock_lj(hass):
"""Initialize components."""
with mock.patch("homeassistant.components.litejet.LiteJet") as mock_pylitejet:
mock_lj = mock_pylitejet.return_value
mock_lj.switch_pressed_callbacks = {}
mock_lj.switch_released_callbacks = {}
def on_switch_pressed(number, callback):
mock_lj.switch_pressed_callbacks[number] = callback
def on_switch_released(number, callback):
mock_lj.switch_released_callbacks[number] = callback
mock_lj.loads.return_value = range(0)
mock_lj.button_switches.return_value = range(1, 3)
mock_lj.all_switches.return_value = range(1, 6)
mock_lj.scenes.return_value = range(0)
mock_lj.get_switch_name.side_effect = get_switch_name
mock_lj.on_switch_pressed.side_effect = on_switch_pressed
mock_lj.on_switch_released.side_effect = on_switch_released
config = {"litejet": {"port": "/dev/serial/by-id/mock-litejet"}}
assert hass.loop.run_until_complete(
setup.async_setup_component(hass, litejet.DOMAIN, config)
)
mock_lj.start_time = dt_util.utcnow()
mock_lj.last_delta = timedelta(0)
return mock_lj
async def simulate_press(hass, mock_lj, number):
"""Test to simulate a press."""
_LOGGER.info("*** simulate press of %d", number)
callback = mock_lj.switch_pressed_callbacks.get(number)
with mock.patch(
"homeassistant.helpers.condition.dt_util.utcnow",
return_value=mock_lj.start_time + mock_lj.last_delta,
):
if callback is not None:
await hass.async_add_executor_job(callback)
await hass.async_block_till_done()
async def simulate_release(hass, mock_lj, number):
"""Test to simulate releasing."""
_LOGGER.info("*** simulate release of %d", number)
callback = mock_lj.switch_released_callbacks.get(number)
with mock.patch(
"homeassistant.helpers.condition.dt_util.utcnow",
return_value=mock_lj.start_time + mock_lj.last_delta,
):
if callback is not None:
await hass.async_add_executor_job(callback)
await hass.async_block_till_done()
async def simulate_time(hass, mock_lj, delta):
"""Test to simulate time."""
_LOGGER.info(
"*** simulate time change by %s: %s", delta, mock_lj.start_time + delta
)
mock_lj.last_delta = delta
with mock.patch(
"homeassistant.helpers.condition.dt_util.utcnow",
return_value=mock_lj.start_time + delta,
):
_LOGGER.info("now=%s", dt_util.utcnow())
async_fire_time_changed(hass, mock_lj.start_time + delta)
await hass.async_block_till_done()
_LOGGER.info("done with now=%s", dt_util.utcnow())
async def setup_automation(hass, trigger):
"""Test setting up the automation."""
assert await setup.async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"alias": "My Test",
"trigger": trigger,
"action": {"service": "test.automation"},
}
]
},
)
await hass.async_block_till_done()
async def test_simple(hass, calls, mock_lj):
"""Test the simplest form of a LiteJet trigger."""
await setup_automation(
hass, {"platform": "litejet", "number": ENTITY_OTHER_SWITCH_NUMBER}
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 1
async def test_held_more_than_short(hass, calls, mock_lj):
"""Test a too short hold."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_more_than": {"milliseconds": "200"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
await simulate_time(hass, mock_lj, timedelta(seconds=0.1))
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
async def test_held_more_than_long(hass, calls, mock_lj):
"""Test a hold that is long enough."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_more_than": {"milliseconds": "200"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
await simulate_time(hass, mock_lj, timedelta(seconds=0.3))
assert len(calls) == 1
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 1
async def test_held_less_than_short(hass, calls, mock_lj):
"""Test a hold that is short enough."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_less_than": {"milliseconds": "200"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
await simulate_time(hass, mock_lj, timedelta(seconds=0.1))
assert len(calls) == 0
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 1
async def test_held_less_than_long(hass, calls, mock_lj):
"""Test a hold that is too long."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_less_than": {"milliseconds": "200"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
await simulate_time(hass, mock_lj, timedelta(seconds=0.3))
assert len(calls) == 0
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
async def test_held_in_range_short(hass, calls, mock_lj):
"""Test an in-range trigger with a too short hold."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_more_than": {"milliseconds": "100"},
"held_less_than": {"milliseconds": "300"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
await simulate_time(hass, mock_lj, timedelta(seconds=0.05))
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
async def test_held_in_range_just_right(hass, calls, mock_lj):
"""Test an in-range trigger with a just right hold."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_more_than": {"milliseconds": "100"},
"held_less_than": {"milliseconds": "300"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
await simulate_time(hass, mock_lj, timedelta(seconds=0.2))
assert len(calls) == 0
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 1
async def test_held_in_range_long(hass, calls, mock_lj):
"""Test an in-range trigger with a too long hold."""
await setup_automation(
hass,
{
"platform": "litejet",
"number": ENTITY_OTHER_SWITCH_NUMBER,
"held_more_than": {"milliseconds": "100"},
"held_less_than": {"milliseconds": "300"},
},
)
await simulate_press(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
await simulate_time(hass, mock_lj, timedelta(seconds=0.4))
assert len(calls) == 0
await simulate_release(hass, mock_lj, ENTITY_OTHER_SWITCH_NUMBER)
assert len(calls) == 0
|
import unittest
from urwid import canvas
from urwid.compat import B
import urwid
class CanvasCacheTest(unittest.TestCase):
def setUp(self):
# purge the cache
urwid.CanvasCache._widgets.clear()
def cct(self, widget, size, focus, expected):
got = urwid.CanvasCache.fetch(widget, urwid.Widget, size, focus)
assert expected==got, "got: %s expected: %s"%(got, expected)
def test1(self):
a = urwid.Text("")
b = urwid.Text("")
blah = urwid.TextCanvas()
blah.finalize(a, (10,1), False)
blah2 = urwid.TextCanvas()
blah2.finalize(a, (15,1), False)
bloo = urwid.TextCanvas()
bloo.finalize(b, (20,2), True)
urwid.CanvasCache.store(urwid.Widget, blah)
urwid.CanvasCache.store(urwid.Widget, blah2)
urwid.CanvasCache.store(urwid.Widget, bloo)
self.cct(a, (10,1), False, blah)
self.cct(a, (15,1), False, blah2)
self.cct(a, (15,1), True, None)
self.cct(a, (10,2), False, None)
self.cct(b, (20,2), True, bloo)
self.cct(b, (21,2), True, None)
urwid.CanvasCache.invalidate(a)
self.cct(a, (10,1), False, None)
self.cct(a, (15,1), False, None)
self.cct(b, (20,2), True, bloo)
class CanvasTest(unittest.TestCase):
def ct(self, text, attr, exp_content):
c = urwid.TextCanvas([B(t) for t in text], attr)
content = list(c.content())
assert content == exp_content, "got: %r expected: %r" % (content,
exp_content)
def ct2(self, text, attr, left, top, cols, rows, def_attr, exp_content):
c = urwid.TextCanvas([B(t) for t in text], attr)
content = list(c.content(left, top, cols, rows, def_attr))
assert content == exp_content, "got: %r expected: %r" % (content,
exp_content)
def test1(self):
self.ct(["Hello world"], None, [[(None, None, B("Hello world"))]])
self.ct(["Hello world"], [[("a",5)]],
[[("a", None, B("Hello")), (None, None, B(" world"))]])
self.ct(["Hi","There"], None,
[[(None, None, B("Hi "))], [(None, None, B("There"))]])
def test2(self):
self.ct2(["Hello"], None, 0, 0, 5, 1, None,
[[(None, None, B("Hello"))]])
self.ct2(["Hello"], None, 1, 0, 4, 1, None,
[[(None, None, B("ello"))]])
self.ct2(["Hello"], None, 0, 0, 4, 1, None,
[[(None, None, B("Hell"))]])
self.ct2(["Hi","There"], None, 1, 0, 3, 2, None,
[[(None, None, B("i "))], [(None, None, B("her"))]])
self.ct2(["Hi","There"], None, 0, 0, 5, 1, None,
[[(None, None, B("Hi "))]])
self.ct2(["Hi","There"], None, 0, 1, 5, 1, None,
[[(None, None, B("There"))]])
class ShardBodyTest(unittest.TestCase):
def sbt(self, shards, shard_tail, expected):
result = canvas.shard_body(shards, shard_tail, False)
assert result == expected, "got: %r expected: %r" % (result, expected)
def sbttail(self, num_rows, sbody, expected):
result = canvas.shard_body_tail(num_rows, sbody)
assert result == expected, "got: %r expected: %r" % (result, expected)
def sbtrow(self, sbody, expected):
result = list(canvas.shard_body_row(sbody))
assert result == expected, "got: %r expected: %r" % (result, expected)
def test1(self):
cviews = [(0,0,10,5,None,"foo"),(0,0,5,5,None,"bar")]
self.sbt(cviews, [],
[(0, None, (0,0,10,5,None,"foo")),
(0, None, (0,0,5,5,None,"bar"))])
self.sbt(cviews, [(0, 3, None, (0,0,5,8,None,"baz"))],
[(3, None, (0,0,5,8,None,"baz")),
(0, None, (0,0,10,5,None,"foo")),
(0, None, (0,0,5,5,None,"bar"))])
self.sbt(cviews, [(10, 3, None, (0,0,5,8,None,"baz"))],
[(0, None, (0,0,10,5,None,"foo")),
(3, None, (0,0,5,8,None,"baz")),
(0, None, (0,0,5,5,None,"bar"))])
self.sbt(cviews, [(15, 3, None, (0,0,5,8,None,"baz"))],
[(0, None, (0,0,10,5,None,"foo")),
(0, None, (0,0,5,5,None,"bar")),
(3, None, (0,0,5,8,None,"baz"))])
def test2(self):
sbody = [(0, None, (0,0,10,5,None,"foo")),
(0, None, (0,0,5,5,None,"bar")),
(3, None, (0,0,5,8,None,"baz"))]
self.sbttail(5, sbody, [])
self.sbttail(3, sbody,
[(0, 3, None, (0,0,10,5,None,"foo")),
(0, 3, None, (0,0,5,5,None,"bar")),
(0, 6, None, (0,0,5,8,None,"baz"))])
sbody = [(0, None, (0,0,10,3,None,"foo")),
(0, None, (0,0,5,5,None,"bar")),
(3, None, (0,0,5,9,None,"baz"))]
self.sbttail(3, sbody,
[(10, 3, None, (0,0,5,5,None,"bar")),
(0, 6, None, (0,0,5,9,None,"baz"))])
def test3(self):
self.sbtrow([(0, None, (0,0,10,5,None,"foo")),
(0, None, (0,0,5,5,None,"bar")),
(3, None, (0,0,5,8,None,"baz"))],
[20])
self.sbtrow([(0, iter("foo"), (0,0,10,5,None,"foo")),
(0, iter("bar"), (0,0,5,5,None,"bar")),
(3, iter("zzz"), (0,0,5,8,None,"baz"))],
["f","b","z"])
class ShardsTrimTest(unittest.TestCase):
def sttop(self, shards, top, expected):
result = canvas.shards_trim_top(shards, top)
assert result == expected, "got: %r expected: %r" % (result, expected)
def strows(self, shards, rows, expected):
result = canvas.shards_trim_rows(shards, rows)
assert result == expected, "got: %r expected: %r" % (result, expected)
def stsides(self, shards, left, cols, expected):
result = canvas.shards_trim_sides(shards, left, cols)
assert result == expected, "got: %r expected: %r" % (result, expected)
def test1(self):
shards = [(5, [(0,0,10,5,None,"foo"),(0,0,5,5,None,"bar")])]
self.sttop(shards, 2,
[(3, [(0,2,10,3,None,"foo"),(0,2,5,3,None,"bar")])])
self.strows(shards, 2,
[(2, [(0,0,10,2,None,"foo"),(0,0,5,2,None,"bar")])])
shards = [(5, [(0,0,10,5,None,"foo")]),(3,[(0,0,10,3,None,"bar")])]
self.sttop(shards, 2,
[(3, [(0,2,10,3,None,"foo")]),(3,[(0,0,10,3,None,"bar")])])
self.sttop(shards, 5,
[(3, [(0,0,10,3,None,"bar")])])
self.sttop(shards, 7,
[(1, [(0,2,10,1,None,"bar")])])
self.strows(shards, 7,
[(5, [(0,0,10,5,None,"foo")]),(2, [(0,0,10,2,None,"bar")])])
self.strows(shards, 5,
[(5, [(0,0,10,5,None,"foo")])])
self.strows(shards, 4,
[(4, [(0,0,10,4,None,"foo")])])
shards = [(5, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz")]),
(3,[(0,0,10,3,None,"bar")])]
self.sttop(shards, 2,
[(3, [(0,2,10,3,None,"foo"), (0,2,5,6,None,"baz")]),
(3,[(0,0,10,3,None,"bar")])])
self.sttop(shards, 5,
[(3, [(0,0,10,3,None,"bar"), (0,5,5,3,None,"baz")])])
self.sttop(shards, 7,
[(1, [(0,2,10,1,None,"bar"), (0,7,5,1,None,"baz")])])
self.strows(shards, 7,
[(5, [(0,0,10,5,None,"foo"), (0,0,5,7,None,"baz")]),
(2, [(0,0,10,2,None,"bar")])])
self.strows(shards, 5,
[(5, [(0,0,10,5,None,"foo"), (0,0,5,5,None,"baz")])])
self.strows(shards, 4,
[(4, [(0,0,10,4,None,"foo"), (0,0,5,4,None,"baz")])])
def test2(self):
shards = [(5, [(0,0,10,5,None,"foo"),(0,0,5,5,None,"bar")])]
self.stsides(shards, 0, 15,
[(5, [(0,0,10,5,None,"foo"),(0,0,5,5,None,"bar")])])
self.stsides(shards, 6, 9,
[(5, [(6,0,4,5,None,"foo"),(0,0,5,5,None,"bar")])])
self.stsides(shards, 6, 6,
[(5, [(6,0,4,5,None,"foo"),(0,0,2,5,None,"bar")])])
self.stsides(shards, 0, 10,
[(5, [(0,0,10,5,None,"foo")])])
self.stsides(shards, 10, 5,
[(5, [(0,0,5,5,None,"bar")])])
self.stsides(shards, 1, 7,
[(5, [(1,0,7,5,None,"foo")])])
shards = [(5, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz")]),
(3,[(0,0,10,3,None,"bar")])]
self.stsides(shards, 0, 15,
[(5, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz")]),
(3,[(0,0,10,3,None,"bar")])])
self.stsides(shards, 2, 13,
[(5, [(2,0,8,5,None,"foo"), (0,0,5,8,None,"baz")]),
(3,[(2,0,8,3,None,"bar")])])
self.stsides(shards, 2, 10,
[(5, [(2,0,8,5,None,"foo"), (0,0,2,8,None,"baz")]),
(3,[(2,0,8,3,None,"bar")])])
self.stsides(shards, 2, 8,
[(5, [(2,0,8,5,None,"foo")]),
(3,[(2,0,8,3,None,"bar")])])
self.stsides(shards, 2, 6,
[(5, [(2,0,6,5,None,"foo")]),
(3,[(2,0,6,3,None,"bar")])])
self.stsides(shards, 10, 5,
[(8, [(0,0,5,8,None,"baz")])])
self.stsides(shards, 11, 3,
[(8, [(1,0,3,8,None,"baz")])])
class ShardsJoinTest(unittest.TestCase):
def sjt(self, shard_lists, expected):
result = canvas.shards_join(shard_lists)
assert result == expected, "got: %r expected: %r" % (result, expected)
def test(self):
shards1 = [(5, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz")]),
(3,[(0,0,10,3,None,"bar")])]
shards2 = [(3, [(0,0,10,3,None,"aaa")]),
(5,[(0,0,10,5,None,"bbb")])]
shards3 = [(3, [(0,0,10,3,None,"111")]),
(2,[(0,0,10,3,None,"222")]),
(3,[(0,0,10,3,None,"333")])]
self.sjt([shards1], shards1)
self.sjt([shards1, shards2],
[(3, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz"),
(0,0,10,3,None,"aaa")]),
(2, [(0,0,10,5,None,"bbb")]),
(3, [(0,0,10,3,None,"bar")])])
self.sjt([shards1, shards3],
[(3, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz"),
(0,0,10,3,None,"111")]),
(2, [(0,0,10,3,None,"222")]),
(3, [(0,0,10,3,None,"bar"), (0,0,10,3,None,"333")])])
self.sjt([shards1, shards2, shards3],
[(3, [(0,0,10,5,None,"foo"), (0,0,5,8,None,"baz"),
(0,0,10,3,None,"aaa"), (0,0,10,3,None,"111")]),
(2, [(0,0,10,5,None,"bbb"), (0,0,10,3,None,"222")]),
(3, [(0,0,10,3,None,"bar"), (0,0,10,3,None,"333")])])
class CanvasJoinTest(unittest.TestCase):
def cjtest(self, desc, l, expected):
l = [(c, None, False, n) for c, n in l]
result = list(urwid.CanvasJoin(l).content())
assert result == expected, "%s expected %r, got %r"%(
desc, expected, result)
def test(self):
C = urwid.TextCanvas
hello = C([B("hello")])
there = C([B("there")], [[("a",5)]])
a = C([B("a")])
hi = C([B("hi")])
how = C([B("how")], [[("a",1)]])
dy = C([B("dy")])
how_you = C([B("how"), B("you")])
self.cjtest("one", [(hello, 5)],
[[(None, None, B("hello"))]])
self.cjtest("two", [(hello, 5), (there, 5)],
[[(None, None, B("hello")), ("a", None, B("there"))]])
self.cjtest("two space", [(hello, 7), (there, 5)],
[[(None, None, B("hello")),(None,None,B(" ")),
("a", None, B("there"))]])
self.cjtest("three space", [(hi, 4), (how, 3), (dy, 2)],
[[(None, None, B("hi")),(None,None,B(" ")),("a",None, B("h")),
(None,None,B("ow")),(None,None,B("dy"))]])
self.cjtest("four space", [(a, 2), (hi, 3), (dy, 3), (a, 1)],
[[(None, None, B("a")),(None,None,B(" ")),
(None, None, B("hi")),(None,None,B(" ")),
(None, None, B("dy")),(None,None,B(" ")),
(None, None, B("a"))]])
self.cjtest("pile 2", [(how_you, 4), (hi, 2)],
[[(None, None, B('how')), (None, None, B(' ')),
(None, None, B('hi'))],
[(None, None, B('you')), (None, None, B(' ')),
(None, None, B(' '))]])
self.cjtest("pile 2r", [(hi, 4), (how_you, 3)],
[[(None, None, B('hi')), (None, None, B(' ')),
(None, None, B('how'))],
[(None, None, B(' ')),
(None, None, B('you'))]])
class CanvasOverlayTest(unittest.TestCase):
def cotest(self, desc, bgt, bga, fgt, fga, l, r, et):
bgt = B(bgt)
fgt = B(fgt)
bg = urwid.CompositeCanvas(
urwid.TextCanvas([bgt],[bga]))
fg = urwid.CompositeCanvas(
urwid.TextCanvas([fgt],[fga]))
bg.overlay(fg, l, 0)
result = list(bg.content())
assert result == et, "%s expected %r, got %r"%(
desc, et, result)
def test1(self):
self.cotest("left", "qxqxqxqx", [], "HI", [], 0, 6,
[[(None, None, B("HI")),(None,None,B("qxqxqx"))]])
self.cotest("right", "qxqxqxqx", [], "HI", [], 6, 0,
[[(None, None, B("qxqxqx")),(None,None,B("HI"))]])
self.cotest("center", "qxqxqxqx", [], "HI", [], 3, 3,
[[(None, None, B("qxq")),(None,None,B("HI")),
(None,None,B("xqx"))]])
self.cotest("center2", "qxqxqxqx", [], "HI ", [], 2, 2,
[[(None, None, B("qx")),(None,None,B("HI ")),
(None,None,B("qx"))]])
self.cotest("full", "rz", [], "HI", [], 0, 0,
[[(None, None, B("HI"))]])
def test2(self):
self.cotest("same","asdfghjkl",[('a',9)],"HI",[('a',2)],4,3,
[[('a',None,B("asdf")),('a',None,B("HI")),('a',None,B("jkl"))]])
self.cotest("diff","asdfghjkl",[('a',9)],"HI",[('b',2)],4,3,
[[('a',None,B("asdf")),('b',None,B("HI")),('a',None,B("jkl"))]])
self.cotest("None end","asdfghjkl",[('a',9)],"HI ",[('a',2)],
2,3,
[[('a',None,B("as")),('a',None,B("HI")),
(None,None,B(" ")),('a',None,B("jkl"))]])
self.cotest("float end","asdfghjkl",[('a',3)],"HI",[('a',2)],
4,3,
[[('a',None,B("asd")),(None,None,B("f")),
('a',None,B("HI")),(None,None,B("jkl"))]])
self.cotest("cover 2","asdfghjkl",[('a',5),('c',4)],"HI",
[('b',2)],4,3,
[[('a',None,B("asdf")),('b',None,B("HI")),('c',None,B("jkl"))]])
self.cotest("cover 2-2","asdfghjkl",
[('a',4),('d',1),('e',1),('c',3)],
"HI",[('b',2)], 4, 3,
[[('a',None,B("asdf")),('b',None,B("HI")),('c',None,B("jkl"))]])
def test3(self):
urwid.set_encoding("euc-jp")
self.cotest("db0","\xA1\xA1\xA1\xA1\xA1\xA1",[],"HI",[],2,2,
[[(None,None,B("\xA1\xA1")),(None,None,B("HI")),
(None,None,B("\xA1\xA1"))]])
self.cotest("db1","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHI",[],1,2,
[[(None,None,B(" ")),(None,None,B("OHI")),
(None,None,B("\xA1\xA1"))]])
self.cotest("db2","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHI",[],2,1,
[[(None,None,B("\xA1\xA1")),(None,None,B("OHI")),
(None,None,B(" "))]])
self.cotest("db3","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHIO",[],1,1,
[[(None,None,B(" ")),(None,None,B("OHIO")),(None,None,B(" "))]])
class CanvasPadTrimTest(unittest.TestCase):
def cptest(self, desc, ct, ca, l, r, et):
ct = B(ct)
c = urwid.CompositeCanvas(
urwid.TextCanvas([ct], [ca]))
c.pad_trim_left_right(l, r)
result = list(c.content())
assert result == et, "%s expected %r, got %r"%(
desc, et, result)
def test1(self):
self.cptest("none", "asdf", [], 0, 0,
[[(None,None,B("asdf"))]])
self.cptest("left pad", "asdf", [], 2, 0,
[[(None,None,B(" ")),(None,None,B("asdf"))]])
self.cptest("right pad", "asdf", [], 0, 2,
[[(None,None,B("asdf")),(None,None,B(" "))]])
def test2(self):
self.cptest("left trim", "asdf", [], -2, 0,
[[(None,None,B("df"))]])
self.cptest("right trim", "asdf", [], 0, -2,
[[(None,None,B("as"))]])
|
import pytest
import socket
from kombu import Connection, Exchange, Queue, Consumer, Producer
class test_PyroTransport:
def setup(self):
self.c = Connection(transport='pyro', virtual_host="kombu.broker")
self.e = Exchange('test_transport_pyro')
self.q = Queue('test_transport_pyro',
exchange=self.e,
routing_key='test_transport_pyro')
self.q2 = Queue('test_transport_pyro2',
exchange=self.e,
routing_key='test_transport_pyro2')
self.fanout = Exchange('test_transport_pyro_fanout', type='fanout')
self.q3 = Queue('test_transport_pyro_fanout1',
exchange=self.fanout)
self.q4 = Queue('test_transport_pyro_fanout2',
exchange=self.fanout)
def test_driver_version(self):
assert self.c.transport.driver_version()
@pytest.mark.skip("requires running Pyro nameserver and Kombu Broker")
def test_produce_consume_noack(self):
channel = self.c.channel()
producer = Producer(channel, self.e)
consumer = Consumer(channel, self.q, no_ack=True)
for i in range(10):
producer.publish({'foo': i}, routing_key='test_transport_pyro')
_received = []
def callback(message_data, message):
_received.append(message)
consumer.register_callback(callback)
consumer.consume()
while 1:
if len(_received) == 10:
break
self.c.drain_events()
assert len(_received) == 10
def test_drain_events(self):
with pytest.raises(socket.timeout):
self.c.drain_events(timeout=0.1)
c1 = self.c.channel()
c2 = self.c.channel()
with pytest.raises(socket.timeout):
self.c.drain_events(timeout=0.1)
del(c1) # so pyflakes doesn't complain.
del(c2)
@pytest.mark.skip("requires running Pyro nameserver and Kombu Broker")
def test_drain_events_unregistered_queue(self):
c1 = self.c.channel()
producer = self.c.Producer()
consumer = self.c.Consumer([self.q2])
producer.publish(
{'hello': 'world'},
declare=consumer.queues,
routing_key=self.q2.routing_key,
exchange=self.q2.exchange,
)
message = consumer.queues[0].get()._raw
class Cycle:
def get(self, callback, timeout=None):
return (message, 'foo'), c1
self.c.transport.cycle = Cycle()
self.c.drain_events()
@pytest.mark.skip("requires running Pyro nameserver and Kombu Broker")
def test_queue_for(self):
chan = self.c.channel()
x = chan._queue_for('foo')
assert x
assert chan._queue_for('foo') is x
|
import asyncio
import logging
from urllib.parse import urlparse
import async_timeout
import upb_lib
import voluptuous as vol
from homeassistant import config_entries, exceptions
from homeassistant.const import CONF_ADDRESS, CONF_FILE_PATH, CONF_HOST, CONF_PROTOCOL
from .const import DOMAIN # pylint:disable=unused-import
_LOGGER = logging.getLogger(__name__)
PROTOCOL_MAP = {"TCP": "tcp://", "Serial port": "serial://"}
DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_PROTOCOL, default="Serial port"): vol.In(
["TCP", "Serial port"]
),
vol.Required(CONF_ADDRESS): str,
vol.Required(CONF_FILE_PATH, default=""): str,
}
)
VALIDATE_TIMEOUT = 15
async def _validate_input(data):
"""Validate the user input allows us to connect."""
def _connected_callback():
connected_event.set()
connected_event = asyncio.Event()
file_path = data.get(CONF_FILE_PATH)
url = _make_url_from_data(data)
upb = upb_lib.UpbPim({"url": url, "UPStartExportFile": file_path})
if not upb.config_ok:
_LOGGER.error("Missing or invalid UPB file: %s", file_path)
raise InvalidUpbFile
upb.connect(_connected_callback)
try:
with async_timeout.timeout(VALIDATE_TIMEOUT):
await connected_event.wait()
except asyncio.TimeoutError:
pass
upb.disconnect()
if not connected_event.is_set():
_LOGGER.error(
"Timed out after %d seconds trying to connect with UPB PIM at %s",
VALIDATE_TIMEOUT,
url,
)
raise CannotConnect
# Return info that you want to store in the config entry.
return (upb.network_id, {"title": "UPB", CONF_HOST: url, CONF_FILE_PATH: file_path})
def _make_url_from_data(data):
host = data.get(CONF_HOST)
if host:
return host
protocol = PROTOCOL_MAP[data[CONF_PROTOCOL]]
address = data[CONF_ADDRESS]
return f"{protocol}{address}"
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for UPB PIM."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
def __init__(self):
"""Initialize the UPB config flow."""
self.importing = False
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
if self._url_already_configured(_make_url_from_data(user_input)):
return self.async_abort(reason="already_configured")
network_id, info = await _validate_input(user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidUpbFile:
errors["base"] = "invalid_upb_file"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if "base" not in errors:
await self.async_set_unique_id(network_id)
self._abort_if_unique_id_configured()
if self.importing:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_create_entry(
title=info["title"],
data={
CONF_HOST: info[CONF_HOST],
CONF_FILE_PATH: user_input[CONF_FILE_PATH],
},
)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
async def async_step_import(self, user_input):
"""Handle import."""
self.importing = True
return await self.async_step_user(user_input)
def _url_already_configured(self, url):
"""See if we already have a UPB PIM matching user input configured."""
existing_hosts = {
urlparse(entry.data[CONF_HOST]).hostname
for entry in self._async_current_entries()
}
return urlparse(url).hostname in existing_hosts
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidUpbFile(exceptions.HomeAssistantError):
"""Error to indicate there is invalid or missing UPB config file."""
|
from async_timeout import timeout
from homeassistant.components.websocket_api import const
from homeassistant.components.websocket_api.auth import (
TYPE_AUTH,
TYPE_AUTH_OK,
TYPE_AUTH_REQUIRED,
)
from homeassistant.components.websocket_api.const import URL
from homeassistant.core import Context, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity
from homeassistant.loader import async_get_integration
from homeassistant.setup import async_setup_component
from tests.common import MockEntity, MockEntityPlatform, async_mock_service
async def test_call_service(hass, websocket_client):
"""Test call service command."""
calls = []
@callback
def service_call(call):
calls.append(call)
hass.services.async_register("domain_test", "test_service", service_call)
await websocket_client.send_json(
{
"id": 5,
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(calls) == 1
call = calls[0]
assert call.domain == "domain_test"
assert call.service == "test_service"
assert call.data == {"hello": "world"}
async def test_call_service_not_found(hass, websocket_client):
"""Test call service command."""
await websocket_client.send_json(
{
"id": 5,
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_NOT_FOUND
async def test_call_service_child_not_found(hass, websocket_client):
"""Test not reporting not found errors if it's not the called service."""
async def serv_handler(call):
await hass.services.async_call("non", "existing")
hass.services.async_register("domain_test", "test_service", serv_handler)
await websocket_client.send_json(
{
"id": 5,
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_HOME_ASSISTANT_ERROR
async def test_call_service_error(hass, websocket_client):
"""Test call service command with error."""
@callback
def ha_error_call(_):
raise HomeAssistantError("error_message")
hass.services.async_register("domain_test", "ha_error", ha_error_call)
async def unknown_error_call(_):
raise ValueError("value_error")
hass.services.async_register("domain_test", "unknown_error", unknown_error_call)
await websocket_client.send_json(
{
"id": 5,
"type": "call_service",
"domain": "domain_test",
"service": "ha_error",
}
)
msg = await websocket_client.receive_json()
print(msg)
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"] is False
assert msg["error"]["code"] == "home_assistant_error"
assert msg["error"]["message"] == "error_message"
await websocket_client.send_json(
{
"id": 6,
"type": "call_service",
"domain": "domain_test",
"service": "unknown_error",
}
)
msg = await websocket_client.receive_json()
print(msg)
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"] is False
assert msg["error"]["code"] == "unknown_error"
assert msg["error"]["message"] == "value_error"
async def test_subscribe_unsubscribe_events(hass, websocket_client):
"""Test subscribe/unsubscribe events command."""
init_count = sum(hass.bus.async_listeners().values())
await websocket_client.send_json(
{"id": 5, "type": "subscribe_events", "event_type": "test_event"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Verify we have a new listener
assert sum(hass.bus.async_listeners().values()) == init_count + 1
hass.bus.async_fire("ignore_event")
hass.bus.async_fire("test_event", {"hello": "world"})
hass.bus.async_fire("ignore_event")
with timeout(3):
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event["event_type"] == "test_event"
assert event["data"] == {"hello": "world"}
assert event["origin"] == "LOCAL"
await websocket_client.send_json(
{"id": 6, "type": "unsubscribe_events", "subscription": 5}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Check our listener got unsubscribed
assert sum(hass.bus.async_listeners().values()) == init_count
async def test_get_states(hass, websocket_client):
"""Test get_states command."""
hass.states.async_set("greeting.hello", "world")
hass.states.async_set("greeting.bye", "universe")
await websocket_client.send_json({"id": 5, "type": "get_states"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
states = []
for state in hass.states.async_all():
states.append(state.as_dict())
assert msg["result"] == states
async def test_get_services(hass, websocket_client):
"""Test get_services command."""
await websocket_client.send_json({"id": 5, "type": "get_services"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == hass.services.async_services()
async def test_get_config(hass, websocket_client):
"""Test get_config command."""
await websocket_client.send_json({"id": 5, "type": "get_config"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
if "components" in msg["result"]:
msg["result"]["components"] = set(msg["result"]["components"])
if "whitelist_external_dirs" in msg["result"]:
msg["result"]["whitelist_external_dirs"] = set(
msg["result"]["whitelist_external_dirs"]
)
if "allowlist_external_dirs" in msg["result"]:
msg["result"]["allowlist_external_dirs"] = set(
msg["result"]["allowlist_external_dirs"]
)
if "allowlist_external_urls" in msg["result"]:
msg["result"]["allowlist_external_urls"] = set(
msg["result"]["allowlist_external_urls"]
)
assert msg["result"] == hass.config.as_dict()
async def test_ping(websocket_client):
"""Test get_panels command."""
await websocket_client.send_json({"id": 5, "type": "ping"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "pong"
async def test_call_service_context_with_user(hass, aiohttp_client, hass_access_token):
"""Test that the user is set in the service call context."""
assert await async_setup_component(hass, "websocket_api", {})
calls = async_mock_service(hass, "domain_test", "test_service")
client = await aiohttp_client(hass.http.app)
async with client.ws_connect(URL) as ws:
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_REQUIRED
await ws.send_json({"type": TYPE_AUTH, "access_token": hass_access_token})
auth_msg = await ws.receive_json()
assert auth_msg["type"] == TYPE_AUTH_OK
await ws.send_json(
{
"id": 5,
"type": "call_service",
"domain": "domain_test",
"service": "test_service",
"service_data": {"hello": "world"},
}
)
msg = await ws.receive_json()
assert msg["success"]
refresh_token = await hass.auth.async_validate_access_token(hass_access_token)
assert len(calls) == 1
call = calls[0]
assert call.domain == "domain_test"
assert call.service == "test_service"
assert call.data == {"hello": "world"}
assert call.context.user_id == refresh_token.user.id
async def test_subscribe_requires_admin(websocket_client, hass_admin_user):
"""Test subscribing events without being admin."""
hass_admin_user.groups = []
await websocket_client.send_json(
{"id": 5, "type": "subscribe_events", "event_type": "test_event"}
)
msg = await websocket_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNAUTHORIZED
async def test_states_filters_visible(hass, hass_admin_user, websocket_client):
"""Test we only get entities that we're allowed to see."""
hass_admin_user.mock_policy({"entities": {"entity_ids": {"test.entity": True}}})
hass.states.async_set("test.entity", "hello")
hass.states.async_set("test.not_visible_entity", "invisible")
await websocket_client.send_json({"id": 5, "type": "get_states"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert len(msg["result"]) == 1
assert msg["result"][0]["entity_id"] == "test.entity"
async def test_get_states_not_allows_nan(hass, websocket_client):
"""Test get_states command not allows NaN floats."""
hass.states.async_set("greeting.hello", "world", {"hello": float("NaN")})
await websocket_client.send_json({"id": 5, "type": "get_states"})
msg = await websocket_client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNKNOWN_ERROR
async def test_subscribe_unsubscribe_events_whitelist(
hass, websocket_client, hass_admin_user
):
"""Test subscribe/unsubscribe events on whitelist."""
hass_admin_user.groups = []
await websocket_client.send_json(
{"id": 5, "type": "subscribe_events", "event_type": "not-in-whitelist"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == "unauthorized"
await websocket_client.send_json(
{"id": 6, "type": "subscribe_events", "event_type": "themes_updated"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
hass.bus.async_fire("themes_updated")
with timeout(3):
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == "event"
event = msg["event"]
assert event["event_type"] == "themes_updated"
assert event["origin"] == "LOCAL"
async def test_subscribe_unsubscribe_events_state_changed(
hass, websocket_client, hass_admin_user
):
"""Test subscribe/unsubscribe state_changed events."""
hass_admin_user.groups = []
hass_admin_user.mock_policy({"entities": {"entity_ids": {"light.permitted": True}}})
await websocket_client.send_json(
{"id": 7, "type": "subscribe_events", "event_type": "state_changed"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 7
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
hass.states.async_set("light.not_permitted", "on")
hass.states.async_set("light.permitted", "on")
msg = await websocket_client.receive_json()
assert msg["id"] == 7
assert msg["type"] == "event"
assert msg["event"]["event_type"] == "state_changed"
assert msg["event"]["data"]["entity_id"] == "light.permitted"
async def test_render_template_renders_template(hass, websocket_client):
"""Test simple template is rendered and updated."""
hass.states.async_set("light.test", "on")
await websocket_client.send_json(
{
"id": 5,
"type": "render_template",
"template": "State is: {{ states('light.test') }}",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event == {
"result": "State is: on",
"listeners": {
"all": False,
"domains": [],
"entities": ["light.test"],
"time": False,
},
}
hass.states.async_set("light.test", "off")
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event == {
"result": "State is: off",
"listeners": {
"all": False,
"domains": [],
"entities": ["light.test"],
"time": False,
},
}
async def test_render_template_manual_entity_ids_no_longer_needed(
hass, websocket_client
):
"""Test that updates to specified entity ids cause a template rerender."""
hass.states.async_set("light.test", "on")
await websocket_client.send_json(
{
"id": 5,
"type": "render_template",
"template": "State is: {{ states('light.test') }}",
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event == {
"result": "State is: on",
"listeners": {
"all": False,
"domains": [],
"entities": ["light.test"],
"time": False,
},
}
hass.states.async_set("light.test", "off")
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event == {
"result": "State is: off",
"listeners": {
"all": False,
"domains": [],
"entities": ["light.test"],
"time": False,
},
}
async def test_render_template_with_error(hass, websocket_client, caplog):
"""Test a template with an error."""
await websocket_client.send_json(
{"id": 5, "type": "render_template", "template": "{{ my_unknown_var() + 1 }}"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_TEMPLATE_ERROR
assert "TemplateError" not in caplog.text
async def test_render_template_with_timeout_and_error(hass, websocket_client, caplog):
"""Test a template with an error with a timeout."""
await websocket_client.send_json(
{
"id": 5,
"type": "render_template",
"template": "{{ now() | rando }}",
"timeout": 5,
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_TEMPLATE_ERROR
assert "TemplateError" not in caplog.text
async def test_render_template_error_in_template_code(hass, websocket_client, caplog):
"""Test a template that will throw in template.py."""
await websocket_client.send_json(
{"id": 5, "type": "render_template", "template": "{{ now() | random }}"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_TEMPLATE_ERROR
assert "TemplateError" not in caplog.text
async def test_render_template_with_delayed_error(hass, websocket_client, caplog):
"""Test a template with an error that only happens after a state change."""
hass.states.async_set("sensor.test", "on")
await hass.async_block_till_done()
template_str = """
{% if states.sensor.test.state %}
on
{% else %}
{{ explode + 1 }}
{% endif %}
"""
await websocket_client.send_json(
{"id": 5, "type": "render_template", "template": template_str}
)
await hass.async_block_till_done()
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
hass.states.async_remove("sensor.test")
await hass.async_block_till_done()
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
event = msg["event"]
assert event == {
"result": "on",
"listeners": {
"all": False,
"domains": [],
"entities": ["sensor.test"],
"time": False,
},
}
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_TEMPLATE_ERROR
assert "TemplateError" not in caplog.text
async def test_render_template_with_timeout(hass, websocket_client, caplog):
"""Test a template that will timeout."""
slow_template_str = """
{% for var in range(1000) -%}
{% for var in range(1000) -%}
{{ var }}
{%- endfor %}
{%- endfor %}
"""
await websocket_client.send_json(
{
"id": 5,
"type": "render_template",
"timeout": 0.000001,
"template": slow_template_str,
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_TEMPLATE_ERROR
assert "TemplateError" not in caplog.text
async def test_render_template_returns_with_match_all(hass, websocket_client):
"""Test that a template that would match with all entities still return success."""
await websocket_client.send_json(
{"id": 5, "type": "render_template", "template": "State is: {{ 42 }}"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
async def test_manifest_list(hass, websocket_client):
"""Test loading manifests."""
http = await async_get_integration(hass, "http")
websocket_api = await async_get_integration(hass, "websocket_api")
await websocket_client.send_json({"id": 5, "type": "manifest/list"})
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert sorted(msg["result"], key=lambda manifest: manifest["domain"]) == [
http.manifest,
websocket_api.manifest,
]
async def test_manifest_get(hass, websocket_client):
"""Test getting a manifest."""
hue = await async_get_integration(hass, "hue")
await websocket_client.send_json(
{"id": 6, "type": "manifest/get", "integration": "hue"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == hue.manifest
# Non existing
await websocket_client.send_json(
{"id": 7, "type": "manifest/get", "integration": "non_existing"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 7
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
async def test_entity_source_admin(hass, websocket_client, hass_admin_user):
"""Check that we fetch sources correctly."""
platform = MockEntityPlatform(hass)
await platform.async_add_entities(
[MockEntity(name="Entity 1"), MockEntity(name="Entity 2")]
)
# Fetch all
await websocket_client.send_json({"id": 6, "type": "entity/source"})
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == {
"test_domain.entity_1": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
"test_domain.entity_2": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
}
# Fetch one
await websocket_client.send_json(
{"id": 7, "type": "entity/source", "entity_id": ["test_domain.entity_2"]}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 7
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == {
"test_domain.entity_2": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
}
# Fetch two
await websocket_client.send_json(
{
"id": 8,
"type": "entity/source",
"entity_id": ["test_domain.entity_2", "test_domain.entity_1"],
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 8
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == {
"test_domain.entity_1": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
"test_domain.entity_2": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
}
# Fetch non existing
await websocket_client.send_json(
{
"id": 9,
"type": "entity/source",
"entity_id": ["test_domain.entity_2", "test_domain.non_existing"],
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 9
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_NOT_FOUND
# Mock policy
hass_admin_user.groups = []
hass_admin_user.mock_policy(
{"entities": {"entity_ids": {"test_domain.entity_2": True}}}
)
# Fetch all
await websocket_client.send_json({"id": 10, "type": "entity/source"})
msg = await websocket_client.receive_json()
assert msg["id"] == 10
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"] == {
"test_domain.entity_2": {
"source": entity.SOURCE_PLATFORM_CONFIG,
"domain": "test_platform",
},
}
# Fetch unauthorized
await websocket_client.send_json(
{"id": 11, "type": "entity/source", "entity_id": ["test_domain.entity_1"]}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 11
assert msg["type"] == const.TYPE_RESULT
assert not msg["success"]
assert msg["error"]["code"] == const.ERR_UNAUTHORIZED
async def test_subscribe_trigger(hass, websocket_client):
"""Test subscribing to a trigger."""
init_count = sum(hass.bus.async_listeners().values())
await websocket_client.send_json(
{
"id": 5,
"type": "subscribe_trigger",
"trigger": {"platform": "event", "event_type": "test_event"},
"variables": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Verify we have a new listener
assert sum(hass.bus.async_listeners().values()) == init_count + 1
context = Context()
hass.bus.async_fire("ignore_event")
hass.bus.async_fire("test_event", {"hello": "world"}, context=context)
hass.bus.async_fire("ignore_event")
with timeout(3):
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == "event"
assert msg["event"]["context"]["id"] == context.id
assert msg["event"]["variables"]["trigger"]["platform"] == "event"
event = msg["event"]["variables"]["trigger"]["event"]
assert event["event_type"] == "test_event"
assert event["data"] == {"hello": "world"}
assert event["origin"] == "LOCAL"
await websocket_client.send_json(
{"id": 6, "type": "unsubscribe_events", "subscription": 5}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
# Check our listener got unsubscribed
assert sum(hass.bus.async_listeners().values()) == init_count
async def test_test_condition(hass, websocket_client):
"""Test testing a condition."""
hass.states.async_set("hello.world", "paulus")
await websocket_client.send_json(
{
"id": 5,
"type": "test_condition",
"condition": {
"condition": "state",
"entity_id": "hello.world",
"state": "paulus",
},
"variables": {"hello": "world"},
}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 5
assert msg["type"] == const.TYPE_RESULT
assert msg["success"]
assert msg["result"]["result"] is True
|
from __future__ import print_function
import sys
import argparse
_stash = globals()['_stash']
def main(args):
ap = argparse.ArgumentParser()
ap.add_argument('name', nargs='?', help='variable name')
ap.add_argument('value', nargs='?', type=int, help='variable value')
ap.add_argument('-l', '--list', action='store_true', help='list all config variables and their values')
ns = ap.parse_args(args)
config = {
'py_traceback': _stash.runtime,
'py_pdb': _stash.runtime,
'input_encoding_utf8': _stash.runtime,
'ipython_style_history_search': _stash.runtime.history,
"enable_styles": _stash,
"colored_errors": _stash.runtime,
}
if ns.list:
for name in sorted(config.keys()):
print('%s=%s' % (name, config[name].__dict__[name]))
else:
try:
if ns.name is not None and ns.value is not None:
config[ns.name].__dict__[ns.name] = ns.value
elif ns.name is not None:
print('%s=%s' % (ns.name, config[ns.name].__dict__[ns.name]))
else:
ap.print_help()
except KeyError:
print('%s: invalid config option name' % ns.name)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1:])
|
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
import ssl
import pytest
import kombu.utils.url
from kombu.utils.url import as_url, parse_url, maybe_sanitize_url
from kombu.utils.url import parse_ssl_cert_reqs
def test_parse_url():
assert parse_url('amqp://user:pass@localhost:5672/my/vhost') == {
'transport': 'amqp',
'userid': 'user',
'password': 'pass',
'hostname': 'localhost',
'port': 5672,
'virtual_host': 'my/vhost',
}
@pytest.mark.parametrize('urltuple,expected', [
(('https',), 'https:///'),
(('https', 'e.com'), 'https://e.com/'),
(('https', 'e.com', 80), 'https://e.com:80/'),
(('https', 'e.com', 80, 'u'), 'https://[email protected]:80/'),
(('https', 'e.com', 80, 'u', 'p'), 'https://u:[email protected]:80/'),
(('https', 'e.com', 80, None, 'p'), 'https://:[email protected]:80/'),
(('https', 'e.com', 80, None, 'p', '/foo'), 'https://:[email protected]:80//foo'),
])
def test_as_url(urltuple, expected):
assert as_url(*urltuple) == expected
@pytest.mark.parametrize('url,expected', [
('foo', 'foo'),
('http://u:[email protected]//foo', 'http://u:**@e.com//foo'),
])
def test_maybe_sanitize_url(url, expected):
assert maybe_sanitize_url(url) == expected
assert (maybe_sanitize_url('http://u:[email protected]//foo') ==
'http://u:**@e.com//foo')
def test_ssl_parameters():
url = 'rediss://user:password@host:6379/0?'
querystring = urlencode({
'ssl_cert_reqs': 'required',
'ssl_ca_certs': '/var/ssl/myca.pem',
'ssl_certfile': '/var/ssl/server-cert.pem',
'ssl_keyfile': '/var/ssl/priv/worker-key.pem',
})
kwargs = parse_url(url + querystring)
assert kwargs['transport'] == 'rediss'
assert kwargs['ssl']['ssl_cert_reqs'] == ssl.CERT_REQUIRED
assert kwargs['ssl']['ssl_ca_certs'] == '/var/ssl/myca.pem'
assert kwargs['ssl']['ssl_certfile'] == '/var/ssl/server-cert.pem'
assert kwargs['ssl']['ssl_keyfile'] == '/var/ssl/priv/worker-key.pem'
kombu.utils.url.ssl_available = False
kwargs = parse_url(url + querystring)
assert kwargs['ssl']['ssl_cert_reqs'] is None
kombu.utils.url.ssl_available = True
@pytest.mark.parametrize('query_param,ssl_available,expected', [
('CERT_REQUIRED', True, ssl.CERT_REQUIRED),
('CERT_OPTIONAL', True, ssl.CERT_OPTIONAL),
('CERT_NONE', True, ssl.CERT_NONE),
('required', True, ssl.CERT_REQUIRED),
('optional', True, ssl.CERT_OPTIONAL),
('none', True, ssl.CERT_NONE),
('CERT_REQUIRED', None, None),
])
def test_parse_ssl_cert_reqs(query_param, ssl_available, expected):
kombu.utils.url.ssl_available = ssl_available
result = parse_ssl_cert_reqs(query_param)
kombu.utils.url.ssl_available = True
assert result == expected
def test_parse_ssl_cert_reqs_bad_value():
with pytest.raises(KeyError):
parse_ssl_cert_reqs('badvalue')
|
from pyownet import protocol
from homeassistant.components.onewire.const import (
CONF_MOUNT_DIR,
CONF_TYPE_OWSERVER,
CONF_TYPE_SYSBUS,
DEFAULT_OWSERVER_PORT,
DEFAULT_SYSBUS_MOUNT_DIR,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from . import setup_onewire_owserver_integration, setup_onewire_sysbus_integration
from tests.async_mock import patch
async def test_user_owserver(hass):
"""Test OWServer user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_TYPE: CONF_TYPE_OWSERVER},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "owserver"
assert not result["errors"]
# Invalid server
with patch(
"homeassistant.components.onewire.onewirehub.protocol.proxy",
side_effect=protocol.ConnError,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "owserver"
assert result["errors"] == {"base": "cannot_connect"}
# Valid server
with patch("homeassistant.components.onewire.onewirehub.protocol.proxy",), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "1.2.3.4"
assert result["data"] == {
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: "1.2.3.4",
CONF_PORT: 1234,
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_user_owserver_duplicate(hass):
"""Test OWServer flow."""
with patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
await setup_onewire_owserver_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_TYPE: CONF_TYPE_OWSERVER},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "owserver"
assert not result["errors"]
# Duplicate server
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_user_sysbus(hass):
"""Test SysBus flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_TYPE: CONF_TYPE_SYSBUS},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "mount_dir"
assert not result["errors"]
# Invalid path
with patch(
"homeassistant.components.onewire.onewirehub.os.path.isdir",
return_value=False,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_MOUNT_DIR: "/sys/bus/invalid_directory"},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "mount_dir"
assert result["errors"] == {"base": "invalid_path"}
# Valid path
with patch(
"homeassistant.components.onewire.onewirehub.os.path.isdir",
return_value=True,
), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_MOUNT_DIR: "/sys/bus/directory"},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "/sys/bus/directory"
assert result["data"] == {
CONF_TYPE: CONF_TYPE_SYSBUS,
CONF_MOUNT_DIR: "/sys/bus/directory",
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_user_sysbus_duplicate(hass):
"""Test SysBus duplicate flow."""
with patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
await setup_onewire_sysbus_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_TYPE: CONF_TYPE_SYSBUS},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "mount_dir"
assert not result["errors"]
# Valid path
with patch(
"homeassistant.components.onewire.onewirehub.os.path.isdir",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_MOUNT_DIR: DEFAULT_SYSBUS_MOUNT_DIR},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_sysbus(hass):
"""Test import step."""
with patch(
"homeassistant.components.onewire.onewirehub.os.path.isdir",
return_value=True,
), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_TYPE: CONF_TYPE_SYSBUS},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == DEFAULT_SYSBUS_MOUNT_DIR
assert result["data"] == {
CONF_TYPE: CONF_TYPE_SYSBUS,
CONF_MOUNT_DIR: DEFAULT_SYSBUS_MOUNT_DIR,
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_sysbus_with_mount_dir(hass):
"""Test import step."""
with patch(
"homeassistant.components.onewire.onewirehub.os.path.isdir",
return_value=True,
), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_TYPE: CONF_TYPE_SYSBUS,
CONF_MOUNT_DIR: DEFAULT_SYSBUS_MOUNT_DIR,
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == DEFAULT_SYSBUS_MOUNT_DIR
assert result["data"] == {
CONF_TYPE: CONF_TYPE_SYSBUS,
CONF_MOUNT_DIR: DEFAULT_SYSBUS_MOUNT_DIR,
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_owserver(hass):
"""Test import step."""
with patch("homeassistant.components.onewire.onewirehub.protocol.proxy",), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: "1.2.3.4",
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "1.2.3.4"
assert result["data"] == {
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: "1.2.3.4",
CONF_PORT: DEFAULT_OWSERVER_PORT,
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_owserver_with_port(hass):
"""Test import step."""
with patch("homeassistant.components.onewire.onewirehub.protocol.proxy",), patch(
"homeassistant.components.onewire.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.onewire.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: "1.2.3.4",
CONF_PORT: "1234",
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "1.2.3.4"
assert result["data"] == {
CONF_TYPE: CONF_TYPE_OWSERVER,
CONF_HOST: "1.2.3.4",
CONF_PORT: "1234",
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
|
import json
import logging
import pytest
import voluptuous as vol
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.mqtt import MQTT_PUBLISH_SCHEMA
import homeassistant.components.snips as snips
from homeassistant.helpers.intent import ServiceIntentHandler, async_register
from tests.common import async_fire_mqtt_message, async_mock_intent, async_mock_service
async def test_snips_config(hass, mqtt_mock):
"""Test Snips Config."""
result = await async_setup_component(
hass,
"snips",
{
"snips": {
"feedback_sounds": True,
"probability_threshold": 0.5,
"site_ids": ["default", "remote"],
}
},
)
assert result
async def test_snips_bad_config(hass, mqtt_mock):
"""Test Snips bad config."""
result = await async_setup_component(
hass,
"snips",
{
"snips": {
"feedback_sounds": "on",
"probability": "none",
"site_ids": "default",
}
},
)
assert not result
async def test_snips_config_feedback_on(hass, mqtt_mock):
"""Test Snips Config."""
calls = async_mock_service(hass, "mqtt", "publish", MQTT_PUBLISH_SCHEMA)
result = await async_setup_component(
hass, "snips", {"snips": {"feedback_sounds": True}}
)
assert result
await hass.async_block_till_done()
assert len(calls) == 2
topic = calls[0].data["topic"]
assert topic == "hermes/feedback/sound/toggleOn"
topic = calls[1].data["topic"]
assert topic == "hermes/feedback/sound/toggleOn"
assert calls[1].data["qos"] == 1
assert calls[1].data["retain"]
async def test_snips_config_feedback_off(hass, mqtt_mock):
"""Test Snips Config."""
calls = async_mock_service(hass, "mqtt", "publish", MQTT_PUBLISH_SCHEMA)
result = await async_setup_component(
hass, "snips", {"snips": {"feedback_sounds": False}}
)
assert result
await hass.async_block_till_done()
assert len(calls) == 2
topic = calls[0].data["topic"]
assert topic == "hermes/feedback/sound/toggleOn"
topic = calls[1].data["topic"]
assert topic == "hermes/feedback/sound/toggleOff"
assert calls[1].data["qos"] == 0
assert not calls[1].data["retain"]
async def test_snips_config_no_feedback(hass, mqtt_mock):
"""Test Snips Config."""
calls = async_mock_service(hass, "snips", "say")
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
await hass.async_block_till_done()
assert len(calls) == 0
async def test_snips_intent(hass, mqtt_mock):
"""Test intent via Snips."""
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"siteId": "default",
"sessionId": "1234567890ABCDEF",
"input": "turn the lights green",
"intent": {
"intentName": "Lights",
"confidenceScore": 1
},
"slots": [
{
"slotName": "light_color",
"value": {
"kind": "Custom",
"value": "green"
},
"rawValue": "green"
}
]
}
"""
intents = async_mock_intent(hass, "Lights")
async_fire_mqtt_message(hass, "hermes/intent/Lights", payload)
await hass.async_block_till_done()
assert len(intents) == 1
intent = intents[0]
assert intent.platform == "snips"
assert intent.intent_type == "Lights"
assert intent
assert intent.slots == {
"light_color": {"value": "green"},
"light_color_raw": {"value": "green"},
"confidenceScore": {"value": 1},
"site_id": {"value": "default"},
"session_id": {"value": "1234567890ABCDEF"},
}
assert intent.text_input == "turn the lights green"
async def test_snips_service_intent(hass, mqtt_mock):
"""Test ServiceIntentHandler via Snips."""
hass.states.async_set("light.kitchen", "off")
calls = async_mock_service(hass, "light", "turn_on")
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"input": "turn the light on",
"intent": {
"intentName": "Lights",
"confidenceScore": 0.85
},
"siteId": "default",
"slots": [
{
"slotName": "name",
"value": {
"kind": "Custom",
"value": "kitchen"
},
"rawValue": "green"
}
]
}
"""
async_register(
hass, ServiceIntentHandler("Lights", "light", "turn_on", "Turned {} on")
)
async_fire_mqtt_message(hass, "hermes/intent/Lights", payload)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "light"
assert calls[0].service == "turn_on"
assert calls[0].data["entity_id"] == "light.kitchen"
assert "confidenceScore" not in calls[0].data
assert "site_id" not in calls[0].data
async def test_snips_intent_with_duration(hass, mqtt_mock):
"""Test intent with Snips duration."""
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"input": "set a timer of five minutes",
"intent": {
"intentName": "SetTimer",
"confidenceScore": 1
},
"slots": [
{
"rawValue": "five minutes",
"value": {
"kind": "Duration",
"years": 0,
"quarters": 0,
"months": 0,
"weeks": 0,
"days": 0,
"hours": 0,
"minutes": 5,
"seconds": 0,
"precision": "Exact"
},
"range": {
"start": 15,
"end": 27
},
"entity": "snips/duration",
"slotName": "timer_duration"
}
]
}
"""
intents = async_mock_intent(hass, "SetTimer")
async_fire_mqtt_message(hass, "hermes/intent/SetTimer", payload)
await hass.async_block_till_done()
assert len(intents) == 1
intent = intents[0]
assert intent.platform == "snips"
assert intent.intent_type == "SetTimer"
assert intent.slots == {
"confidenceScore": {"value": 1},
"site_id": {"value": None},
"session_id": {"value": None},
"timer_duration": {"value": 300},
"timer_duration_raw": {"value": "five minutes"},
}
async def test_intent_speech_response(hass, mqtt_mock):
"""Test intent speech response via Snips."""
calls = async_mock_service(hass, "mqtt", "publish", MQTT_PUBLISH_SCHEMA)
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
result = await async_setup_component(
hass,
"intent_script",
{
"intent_script": {
"spokenIntent": {
"speech": {"type": "plain", "text": "I am speaking to you"}
}
}
},
)
assert result
payload = """
{
"input": "speak to me",
"sessionId": "abcdef0123456789",
"intent": {
"intentName": "spokenIntent",
"confidenceScore": 1
},
"slots": []
}
"""
async_fire_mqtt_message(hass, "hermes/intent/spokenIntent", payload)
await hass.async_block_till_done()
assert len(calls) == 1
payload = json.loads(calls[0].data["payload"])
topic = calls[0].data["topic"]
assert payload["sessionId"] == "abcdef0123456789"
assert payload["text"] == "I am speaking to you"
assert topic == "hermes/dialogueManager/endSession"
async def test_unknown_intent(hass, caplog, mqtt_mock):
"""Test unknown intent."""
caplog.set_level(logging.WARNING)
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"input": "I don't know what I am supposed to do",
"sessionId": "abcdef1234567890",
"intent": {
"intentName": "unknownIntent",
"confidenceScore": 1
},
"slots": []
}
"""
async_fire_mqtt_message(hass, "hermes/intent/unknownIntent", payload)
await hass.async_block_till_done()
assert "Received unknown intent unknownIntent" in caplog.text
async def test_snips_intent_user(hass, mqtt_mock):
"""Test intentName format user_XXX__intentName."""
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"input": "what to do",
"intent": {
"intentName": "user_ABCDEF123__Lights",
"confidenceScore": 1
},
"slots": []
}
"""
intents = async_mock_intent(hass, "Lights")
async_fire_mqtt_message(hass, "hermes/intent/user_ABCDEF123__Lights", payload)
await hass.async_block_till_done()
assert len(intents) == 1
intent = intents[0]
assert intent.platform == "snips"
assert intent.intent_type == "Lights"
async def test_snips_intent_username(hass, mqtt_mock):
"""Test intentName format username:intentName."""
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
payload = """
{
"input": "what to do",
"intent": {
"intentName": "username:Lights",
"confidenceScore": 1
},
"slots": []
}
"""
intents = async_mock_intent(hass, "Lights")
async_fire_mqtt_message(hass, "hermes/intent/username:Lights", payload)
await hass.async_block_till_done()
assert len(intents) == 1
intent = intents[0]
assert intent.platform == "snips"
assert intent.intent_type == "Lights"
async def test_snips_low_probability(hass, caplog, mqtt_mock):
"""Test intent via Snips."""
caplog.set_level(logging.WARNING)
result = await async_setup_component(
hass, "snips", {"snips": {"probability_threshold": 0.5}}
)
assert result
payload = """
{
"input": "I am not sure what to say",
"intent": {
"intentName": "LightsMaybe",
"confidenceScore": 0.49
},
"slots": []
}
"""
async_mock_intent(hass, "LightsMaybe")
async_fire_mqtt_message(hass, "hermes/intent/LightsMaybe", payload)
await hass.async_block_till_done()
assert "Intent below probaility threshold 0.49 < 0.5" in caplog.text
async def test_intent_special_slots(hass, mqtt_mock):
"""Test intent special slot values via Snips."""
calls = async_mock_service(hass, "light", "turn_on")
result = await async_setup_component(hass, "snips", {"snips": {}})
assert result
result = await async_setup_component(
hass,
"intent_script",
{
"intent_script": {
"Lights": {
"action": {
"service": "light.turn_on",
"data_template": {
"confidenceScore": "{{ confidenceScore }}",
"site_id": "{{ site_id }}",
},
}
}
}
},
)
assert result
payload = """
{
"input": "turn the light on",
"intent": {
"intentName": "Lights",
"confidenceScore": 0.85
},
"siteId": "default",
"slots": []
}
"""
async_fire_mqtt_message(hass, "hermes/intent/Lights", payload)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "light"
assert calls[0].service == "turn_on"
assert calls[0].data["confidenceScore"] == 0.85
assert calls[0].data["site_id"] == "default"
async def test_snips_say(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(hass, "snips", "say", snips.SERVICE_SCHEMA_SAY)
data = {"text": "Hello"}
await hass.services.async_call("snips", "say", data)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "snips"
assert calls[0].service == "say"
assert calls[0].data["text"] == "Hello"
async def test_snips_say_action(hass):
"""Test snips say_action with invalid config."""
calls = async_mock_service(
hass, "snips", "say_action", snips.SERVICE_SCHEMA_SAY_ACTION
)
data = {"text": "Hello", "intent_filter": ["myIntent"]}
await hass.services.async_call("snips", "say_action", data)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "snips"
assert calls[0].service == "say_action"
assert calls[0].data["text"] == "Hello"
assert calls[0].data["intent_filter"] == ["myIntent"]
async def test_snips_say_invalid_config(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(hass, "snips", "say", snips.SERVICE_SCHEMA_SAY)
data = {"text": "Hello", "badKey": "boo"}
with pytest.raises(vol.Invalid):
await hass.services.async_call("snips", "say", data)
await hass.async_block_till_done()
assert len(calls) == 0
async def test_snips_say_action_invalid(hass):
"""Test snips say_action with invalid config."""
calls = async_mock_service(
hass, "snips", "say_action", snips.SERVICE_SCHEMA_SAY_ACTION
)
data = {"text": "Hello", "can_be_enqueued": "notabool"}
with pytest.raises(vol.Invalid):
await hass.services.async_call("snips", "say_action", data)
await hass.async_block_till_done()
assert len(calls) == 0
async def test_snips_feedback_on(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(
hass, "snips", "feedback_on", snips.SERVICE_SCHEMA_FEEDBACK
)
data = {"site_id": "remote"}
await hass.services.async_call("snips", "feedback_on", data)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "snips"
assert calls[0].service == "feedback_on"
assert calls[0].data["site_id"] == "remote"
async def test_snips_feedback_off(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(
hass, "snips", "feedback_off", snips.SERVICE_SCHEMA_FEEDBACK
)
data = {"site_id": "remote"}
await hass.services.async_call("snips", "feedback_off", data)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].domain == "snips"
assert calls[0].service == "feedback_off"
assert calls[0].data["site_id"] == "remote"
async def test_snips_feedback_config(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(
hass, "snips", "feedback_on", snips.SERVICE_SCHEMA_FEEDBACK
)
data = {"site_id": "remote", "test": "test"}
with pytest.raises(vol.Invalid):
await hass.services.async_call("snips", "feedback_on", data)
await hass.async_block_till_done()
assert len(calls) == 0
|
from homeassistant.components.conversation.util import create_matcher
def test_create_matcher():
"""Test the create matcher method."""
# Basic sentence
pattern = create_matcher("Hello world")
assert pattern.match("Hello world") is not None
# Match a part
pattern = create_matcher("Hello {name}")
match = pattern.match("hello world")
assert match is not None
assert match.groupdict()["name"] == "world"
no_match = pattern.match("Hello world, how are you?")
assert no_match is None
# Optional and matching part
pattern = create_matcher("Turn on [the] {name}")
match = pattern.match("turn on the kitchen lights")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
match = pattern.match("turn on kitchen lights")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
match = pattern.match("turn off kitchen lights")
assert match is None
# Two different optional parts, 1 matching part
pattern = create_matcher("Turn on [the] [a] {name}")
match = pattern.match("turn on the kitchen lights")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
match = pattern.match("turn on kitchen lights")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
match = pattern.match("turn on a kitchen light")
assert match is not None
assert match.groupdict()["name"] == "kitchen light"
# Strip plural
pattern = create_matcher("Turn {name}[s] on")
match = pattern.match("turn kitchen lights on")
assert match is not None
assert match.groupdict()["name"] == "kitchen light"
# Optional 2 words
pattern = create_matcher("Turn [the great] {name} on")
match = pattern.match("turn the great kitchen lights on")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
match = pattern.match("turn kitchen lights on")
assert match is not None
assert match.groupdict()["name"] == "kitchen lights"
|
import factory.fuzzy
import pytest
from pytest_factoryboy import register
from importlib import import_module
from cms.api import create_page
from django import VERSION as DJANGO_VERSION
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AnonymousUser
from post_office.models import EmailTemplate
from rest_framework.test import APIClient, APIRequestFactory
from shop.models.cart import CartModel
from shop.models.address import ISO_3166_CODES
from shop.models.defaults.customer import Customer
from shop.models.defaults.address import ShippingAddress, BillingAddress
from shop.models.notification import Notification
from shop.models.related import ProductPageModel
from shop.money import Money
from testshop.models import Commodity
@pytest.fixture
def session():
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session.create()
return session
@pytest.fixture
def api_client():
api_client = APIClient()
return api_client
@pytest.fixture
def api_rf():
api_rf = APIRequestFactory()
return api_rf
@register
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = get_user_model()
@classmethod
def create(cls, **kwargs):
user = super(UserFactory, cls).create(**kwargs)
assert isinstance(user, get_user_model())
if DJANGO_VERSION < (2,):
assert user.is_authenticated() is True
else:
assert user.is_authenticated is True
return user
username = factory.Sequence(lambda n: 'uid-{}'.format(n))
password = 'secret'
@register
class CustomerFactory(factory.django.DjangoModelFactory):
class Meta:
model = Customer
@classmethod
def create(cls, **kwargs):
customer = super(CustomerFactory, cls).create(**kwargs)
assert isinstance(customer, Customer)
assert isinstance(customer.user, get_user_model())
assert customer.is_authenticated is True
assert customer.is_registered is True
return customer
user = factory.SubFactory(UserFactory)
@pytest.fixture
def registered_customer():
user = UserFactory(email='[email protected]', password=make_password('secret'), is_active=True)
customer = CustomerFactory(user=user)
assert customer.is_registered is True
assert isinstance(customer.user, get_user_model())
return customer
@pytest.fixture()
def admin_user(db, django_user_model, django_username_field):
user = UserFactory(email='[email protected]', password=make_password('secret'),
is_active=True, is_staff=True, is_superuser=True)
return user
@pytest.fixture()
def admin_client(db, admin_user):
from django.test.client import Client
client = Client()
client.login(username=admin_user.username, password='secret')
return client
@register
class CommodityFactory(factory.django.DjangoModelFactory):
class Meta:
model = Commodity
product_name = factory.fuzzy.FuzzyText(prefix='Product-')
product_code = factory.Sequence(lambda n: 'article-{}'.format(n + 1))
unit_price = Money(factory.fuzzy.FuzzyDecimal(1, 100).fuzz())
slug = factory.fuzzy.FuzzyText(length=7)
order = factory.Sequence(lambda n: n)
quantity = 5
@classmethod
def create(cls, **kwargs):
product = super(CommodityFactory, cls).create(**kwargs)
page = create_page("Catalog", 'page.html', 'en')
ProductPageModel.objects.create(page=page, product=product)
return product
@pytest.fixture
def empty_cart(rf, api_client):
request = rf.get('/my-cart')
request.session = api_client.session
request.user = AnonymousUser()
request.customer = Customer.objects.get_or_create_from_request(request)
request.customer.email = '[email protected]'
request.customer.save()
cart = CartModel.objects.get_from_request(request)
cart.update(request)
assert cart.is_empty
assert cart.subtotal == Money(0)
return cart
@register
class ShippingAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = ShippingAddress
priority = factory.Sequence(lambda n: n + 1)
name = factory.fuzzy.FuzzyText()
address1 = factory.fuzzy.FuzzyText()
zip_code = factory.fuzzy.FuzzyText()
city = factory.fuzzy.FuzzyText()
country = factory.fuzzy.FuzzyChoice(choices=dict(ISO_3166_CODES).keys())
@register
class BillingAddressFactory(factory.django.DjangoModelFactory):
class Meta:
model = BillingAddress
@register
class EmailTemplateFactory(factory.django.DjangoModelFactory):
class Meta:
model = EmailTemplate
subject = 'Order {{ order.number }}'
content = '{% extends "shop/email/order-detail.txt" %}'
@register
class NotificationFactory(factory.django.DjangoModelFactory):
class Meta:
model = Notification
mail_template = factory.SubFactory(EmailTemplateFactory)
|
import os
import os.path as op
from collections import OrderedDict
from datetime import datetime, timezone
import numpy as np
from ..base import BaseRaw
from ..constants import FIFF
from ..meas_info import create_info
from ..utils import _mult_cal_one
from ...annotations import Annotations
from ...utils import logger, verbose, fill_doc, warn
@fill_doc
def read_raw_persyst(fname, preload=False, verbose=None):
"""Reader for a Persyst (.lay/.dat) recording.
Parameters
----------
fname : str
Path to the Persyst header (.lay) file.
%(preload)s
%(verbose)s
Returns
-------
raw : instance of RawPersyst
A Raw object containing Persyst data.
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
return RawPersyst(fname, preload, verbose)
@fill_doc
class RawPersyst(BaseRaw):
"""Raw object from a Persyst file.
Parameters
----------
fname : str
Path to the Persyst header (.lay) file.
%(preload)s
%(verbose)s
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
@verbose
def __init__(self, fname, preload=False, verbose=None):
logger.info('Loading %s' % fname)
if not fname.endswith('.lay'):
fname = fname + '.lay'
curr_path, lay_fname = op.dirname(fname), op.basename(fname)
if not op.exists(fname):
raise FileNotFoundError(f'The path you specified, '
f'"{lay_fname}",does not exist.')
# sections and subsections currently unused
keys, data, sections = _read_lay_contents(fname)
# these are the section headers in the Persyst file layout
# Note: We do not make use of "SampleTimes" yet
fileinfo_dict = OrderedDict()
channelmap_dict = OrderedDict()
patient_dict = OrderedDict()
comments_dict = OrderedDict()
# loop through each line in the lay file
for key, val, section in zip(keys, data, sections):
if key == '':
continue
# make sure key are lowercase for everything, but electrodes
if key is not None and section != 'channelmap':
key = key.lower()
# FileInfo
if section == 'fileinfo':
# extract the .dat file name
if key == 'file':
dat_fname = val
dat_path = op.dirname(dat_fname)
dat_fpath = op.join(curr_path, op.basename(dat_fname))
# determine if .dat file exists where it should
error_msg = f'The data path you specified ' \
f'does not exist for the lay path, {lay_fname}'
if op.isabs(dat_path) and not op.exists(dat_fname):
raise FileNotFoundError(error_msg)
if not op.exists(dat_fpath):
raise FileNotFoundError(error_msg)
fileinfo_dict[key] = val
# ChannelMap
elif section == 'channelmap':
# channel map has <channel_name>=<number> for <key>=<val>
channelmap_dict[key] = val
# Patient (All optional)
elif section == 'patient':
patient_dict[key] = val
elif section == 'comments':
comments_dict[key] = val
# get numerical metadata
# datatype is either 7 for 32 bit, or 0 for 16 bit
datatype = fileinfo_dict.get('datatype')
cal = float(fileinfo_dict.get('calibration'))
n_chs = int(fileinfo_dict.get('waveformcount'))
# Store subject information from lay file in mne format
# Note: Persyst also records "Physician", "Technician",
# "Medications", "History", and "Comments1" and "Comments2"
# and this information is currently discarded
subject_info = _get_subjectinfo(patient_dict)
# set measurement date
testdate = patient_dict.get('testdate')
if testdate is not None:
# TODO: Persyst may change its internal date schemas
# without notice
# These are the 3 "so far" possible datatime storage
# formats in Persyst .lay
if '/' in testdate:
testdate = datetime.strptime(testdate, '%m/%d/%Y')
elif '-' in testdate:
testdate = datetime.strptime(testdate, '%d-%m-%Y')
elif '.' in testdate:
testdate = datetime.strptime(testdate, '%Y.%m.%d')
if not isinstance(testdate, datetime):
warn('Cannot read in the measurement date due '
'to incompatible format. Please set manually '
'for %s ' % lay_fname)
meas_date = None
else:
testtime = datetime.strptime(patient_dict.get('testtime'),
'%H:%M:%S')
meas_date = datetime(
year=testdate.year, month=testdate.month,
day=testdate.day, hour=testtime.hour,
minute=testtime.minute, second=testtime.second,
tzinfo=timezone.utc)
# Create mne structure
ch_names = list(channelmap_dict.keys())
if n_chs != len(ch_names):
raise RuntimeError('Channels in lay file do not '
'match the number of channels '
'in the .dat file.') # noqa
# get rid of the "-Ref" in channel names
ch_names = [ch.upper().split('-REF')[0] for ch in ch_names]
# get the sampling rate and default channel types to EEG
sfreq = fileinfo_dict.get('samplingrate')
ch_types = 'eeg'
info = create_info(ch_names, sfreq, ch_types=ch_types)
info.update(subject_info=subject_info)
for idx in range(n_chs):
# calibration brings to uV then 1e-6 brings to V
info['chs'][idx]['cal'] = cal * 1.0e-6
info['meas_date'] = meas_date
# determine number of samples in file
# Note: We do not use the lay file to do this
# because clips in time may be generated by Persyst that
# DO NOT modify the "SampleTimes" section
with open(dat_fpath, 'rb') as f:
# determine the precision
if int(datatype) == 7:
# 32 bit
dtype = np.dtype('i4')
elif int(datatype) == 0:
# 16 bit
dtype = np.dtype('i2')
else:
raise RuntimeError(f'Unknown format: {datatype}')
# allow offset to occur
f.seek(0, os.SEEK_END)
n_samples = f.tell()
n_samples = n_samples // (dtype.itemsize * n_chs)
logger.debug(f'Loaded {n_samples} samples '
f'for {n_chs} channels.')
raw_extras = {
'dtype': dtype,
'n_chs': n_chs,
'n_samples': n_samples
}
# create Raw object
super(RawPersyst, self).__init__(
info, preload, filenames=[dat_fpath],
last_samps=[n_samples - 1],
raw_extras=[raw_extras], verbose=verbose)
# set annotations based on the comments read in
num_comments = len(comments_dict)
onset = np.zeros(num_comments, float)
duration = np.zeros(num_comments, float)
description = [''] * num_comments
for t_idx, (_description, (_onset, _duration)) in \
enumerate(comments_dict.items()):
# extract the onset, duration, description to
# create an Annotations object
onset[t_idx] = _onset
duration[t_idx] = _duration
description[t_idx] = _description
annot = Annotations(onset, duration, description)
self.set_annotations(annot)
def _read_segment_file(self, data, idx, fi, start, stop, cals, mult):
"""Read a segment of data from a file.
The Persyst software records raw data in either 16 or 32 bit
binary files. In addition, it stores the calibration to convert
data to uV in the lay file.
"""
dtype = self._raw_extras[fi]['dtype']
n_chs = self._raw_extras[fi]['n_chs']
dat_fname = self._filenames[fi]
# compute samples count based on start and stop
time_length_samps = stop - start
# read data from .dat file into array of correct size, then calibrate
# records = recnum rows x inf columns
count = time_length_samps * n_chs
# seek the dat file
with open(dat_fname, 'rb') as dat_file_ID:
# allow offset to occur
dat_file_ID.seek(n_chs * dtype.itemsize * start, 1)
# read in the actual record starting at possibly offset
record = np.fromfile(dat_file_ID, dtype=dtype,
count=count)
# chs * rows
# cast as float32; more than enough precision
record = np.reshape(record, (n_chs, -1), 'F').astype(np.float32)
# calibrate to convert to V and handle mult
_mult_cal_one(data, record, idx, cals, mult)
def _get_subjectinfo(patient_dict):
# attempt to parse out the birthdate, but if it doesn't
# meet spec, then it will set to None
birthdate = patient_dict.get('birthdate')
if '/' in birthdate:
try:
birthdate = datetime.strptime(birthdate, '%m/%d/%y')
except ValueError:
birthdate = None
print('Unable to process birthdate of %s ' % birthdate)
elif '-' in birthdate:
try:
birthdate = datetime.strptime(birthdate, '%d-%m-%y')
except ValueError:
birthdate = None
print('Unable to process birthdate of %s ' % birthdate)
subject_info = {
'first_name': patient_dict.get('first'),
'middle_name': patient_dict.get('middle'),
'last_name': patient_dict.get('last'),
'sex': patient_dict.get('sex'),
'hand': patient_dict.get('hand'),
'his_id': patient_dict.get('id'),
'birthday': birthdate,
}
# Recode sex values
sex_dict = dict(
m=FIFF.FIFFV_SUBJ_SEX_MALE,
male=FIFF.FIFFV_SUBJ_SEX_MALE,
f=FIFF.FIFFV_SUBJ_SEX_FEMALE,
female=FIFF.FIFFV_SUBJ_SEX_FEMALE,
)
subject_info['sex'] = sex_dict.get(subject_info['sex'],
FIFF.FIFFV_SUBJ_SEX_UNKNOWN)
# Recode hand values
hand_dict = dict(
r=FIFF.FIFFV_SUBJ_HAND_RIGHT,
right=FIFF.FIFFV_SUBJ_HAND_RIGHT,
l=FIFF.FIFFV_SUBJ_HAND_LEFT,
left=FIFF.FIFFV_SUBJ_HAND_LEFT,
a=FIFF.FIFFV_SUBJ_HAND_AMBI,
ambidextrous=FIFF.FIFFV_SUBJ_HAND_AMBI,
ambi=FIFF.FIFFV_SUBJ_HAND_AMBI,
)
# no handedness is set when unknown
try:
subject_info['hand'] = hand_dict[subject_info['hand']]
except KeyError:
subject_info.pop('hand')
return subject_info
def _read_lay_contents(fname):
"""Lay file are laid out like a INI file."""
# keep track of sections, keys and data
sections = []
keys, data = [], []
# initialize all section to empty str
section = ''
with open(fname, 'r') as fin:
for line in fin:
# break a line into a status, key and value
status, key, val = _process_lay_line(line, section)
# handle keys and values if they are
# Section, Subsections, or Line items
if status == 1: # Section was found
section = val.lower()
continue
# keep track of all sections, subsections,
# keys and the data of the file
sections.append(section)
data.append(val)
keys.append(key)
return keys, data, sections
def _process_lay_line(line, section):
"""Process a line read from the Lay (INI) file.
Each line in the .lay file will be processed
into a structured ``status``, ``key`` and ``value``.
Parameters
----------
line : str
The actual line in the Lay file.
section : str
The section in the Lay file.
Returns
-------
status : int
Returns the following integers based on status.
-1 => unknown string found
0 => empty line found
1 => section found
2 => key-value pair found
key : str
The string before the ``'='`` character. If section is "Comments",
then returns the text comment description.
value : str
The string from the line after the ``'='`` character. If section is
"Comments", then returns the onset and duration as a tuple.
"""
key = '' # default; only return value possibly not set
line = line.strip() # remove leading and trailing spaces
end_idx = len(line) - 1 # get the last index of the line
# empty sequence evaluates to false
if not line:
status = 0
key = ''
value = ''
return status, key, value
# section found
elif (line[0] == '[') and (line[end_idx] == ']') \
and (end_idx + 1 >= 3):
status = 1
value = line[1:end_idx].lower()
# key found
else:
# handle Comments section differently from all other sections
# TODO: utilize state and var_type in code.
# Currently not used
if section == 'comments':
# Persyst Comments output 5 variables "," separated
time_sec, duration, state, var_type, text = line.split(',')
status = 2
key = text
value = (time_sec, duration)
# all other sections
else:
if '=' not in line:
raise RuntimeError('The line %s does not conform '
'to the standards. Please check the '
'.lay file.' % line) # noqa
pos = line.index('=')
status = 2
# the line now is composed of a
# <key>=<value>
key = line[0:pos]
key.strip()
value = line[pos + 1:end_idx + 1]
value.strip()
return status, key, value
|
import posixpath
import re
from perfkitbenchmarker import errors
from perfkitbenchmarker import linux_packages
PACKAGE_NAME = 'glibc'
GLIBC_DIR = '%s/glibc' % linux_packages.INSTALL_DIR
GLIBC_VERSION = '2.31'
GLIBC_TAR = 'glibc-{}.tar.xz'.format(GLIBC_VERSION)
BINUTILS_DIR = '%s/binutils' % linux_packages.INSTALL_DIR
BINUTILS_VERSION = '2.34'
BINUTILS_TAR = 'binutils-{}.tar.gz'.format(BINUTILS_VERSION)
PREPROVISIONED_DATA = {
BINUTILS_TAR:
'53537d334820be13eeb8acb326d01c7c81418772d626715c7ae927a7d401cab3',
GLIBC_TAR:
'9246fe44f68feeec8c666bb87973d590ce0137cca145df014c72ec95be9ffd17'
}
PACKAGE_DATA_URL = {
BINUTILS_TAR: posixpath.join(
'https://ftp.gnu.org/gnu/binutils', BINUTILS_TAR),
GLIBC_TAR: posixpath.join(
'https://ftp.gnu.org/gnu/libc', GLIBC_TAR)
}
_GCC_VERSION_RE = re.compile(r'gcc\ version\ (.*?)\ ')
def GetGccVersion(vm):
"""Get the currently installed gcc version."""
_, stderr = vm.RemoteCommand('gcc -v')
match = _GCC_VERSION_RE.search(stderr)
if not match:
raise errors.Benchmarks.RunError('Invalid gcc version %s' % stderr)
return match.group(1)
def _Install(vm):
"""Installs the Glibc Benchmark package on the VM."""
# The included version of gcc-7.4 in Ubuntu 1804 does not work out of the box
# without gcc-snapshot.
vm.InstallPackages('gcc-snapshot')
GetGccVersion(vm)
vm.Install('build_tools')
# bison and texinfo are required for compiling newer versions of glibc > 2.27.
vm.InstallPackages('bison texinfo')
vm.RemoteCommand('cd {0} && mkdir binutils'.format(
linux_packages.INSTALL_DIR))
vm.InstallPreprovisionedPackageData(
PACKAGE_NAME, [BINUTILS_TAR], BINUTILS_DIR)
vm.RemoteCommand('cd {0} && tar xvf {1}'.format(BINUTILS_DIR, BINUTILS_TAR))
vm.RemoteCommand('cd {0} && mkdir binutils-build && '
'cd binutils-build/ && '
'../binutils-{1}/configure --prefix=/opt/binutils && '
'make -j 4 && sudo make install'.format(
BINUTILS_DIR, BINUTILS_VERSION))
vm.RemoteCommand('cd {0} && mkdir glibc'.format(linux_packages.INSTALL_DIR))
vm.InstallPreprovisionedPackageData(
PACKAGE_NAME, [GLIBC_TAR], GLIBC_DIR)
vm.RemoteCommand('cd {0} && tar xvf {1}'.format(GLIBC_DIR, GLIBC_TAR))
vm.RemoteCommand(
'cd {0} && mkdir glibc-build && cd glibc-build && '
'../glibc-{1}/configure --prefix=/usr/local/glibc --disable-profile '
'--enable-add-ons --with-headers=/usr/include '
'--with-binutils=/opt/binutils/bin && make && sudo make install'.format(
GLIBC_DIR, GLIBC_VERSION))
def YumInstall(vm):
"""Installs the Glibc Benchmark package on the VM."""
_Install(vm)
def AptInstall(vm):
"""Installs the Glibc Benchmark package on the VM."""
_Install(vm)
|
import os
from coverage.plugin import FileReporter
from coverage.python import PythonFileReporter
from tests.coveragetest import CoverageTest, UsingModulesMixin
# pylint: disable=import-error
# Unable to import 'aa' (No module named aa)
def native(filename):
"""Make `filename` into a native form."""
return filename.replace("/", os.sep)
class FileReporterTest(UsingModulesMixin, CoverageTest):
"""Tests for FileReporter classes."""
run_in_temp_dir = False
def test_filenames(self):
acu = PythonFileReporter("aa/afile.py")
bcu = PythonFileReporter("aa/bb/bfile.py")
ccu = PythonFileReporter("aa/bb/cc/cfile.py")
self.assertEqual(acu.relative_filename(), "aa/afile.py")
self.assertEqual(bcu.relative_filename(), "aa/bb/bfile.py")
self.assertEqual(ccu.relative_filename(), "aa/bb/cc/cfile.py")
self.assertEqual(acu.source(), "# afile.py\n")
self.assertEqual(bcu.source(), "# bfile.py\n")
self.assertEqual(ccu.source(), "# cfile.py\n")
def test_odd_filenames(self):
acu = PythonFileReporter("aa/afile.odd.py")
bcu = PythonFileReporter("aa/bb/bfile.odd.py")
b2cu = PythonFileReporter("aa/bb.odd/bfile.py")
self.assertEqual(acu.relative_filename(), "aa/afile.odd.py")
self.assertEqual(bcu.relative_filename(), "aa/bb/bfile.odd.py")
self.assertEqual(b2cu.relative_filename(), "aa/bb.odd/bfile.py")
self.assertEqual(acu.source(), "# afile.odd.py\n")
self.assertEqual(bcu.source(), "# bfile.odd.py\n")
self.assertEqual(b2cu.source(), "# bfile.py\n")
def test_modules(self):
import aa
import aa.bb
import aa.bb.cc
acu = PythonFileReporter(aa)
bcu = PythonFileReporter(aa.bb)
ccu = PythonFileReporter(aa.bb.cc)
self.assertEqual(acu.relative_filename(), native("aa/__init__.py"))
self.assertEqual(bcu.relative_filename(), native("aa/bb/__init__.py"))
self.assertEqual(ccu.relative_filename(), native("aa/bb/cc/__init__.py"))
self.assertEqual(acu.source(), "# aa\n")
self.assertEqual(bcu.source(), "# bb\n")
self.assertEqual(ccu.source(), "") # yes, empty
def test_module_files(self):
import aa.afile
import aa.bb.bfile
import aa.bb.cc.cfile
acu = PythonFileReporter(aa.afile)
bcu = PythonFileReporter(aa.bb.bfile)
ccu = PythonFileReporter(aa.bb.cc.cfile)
self.assertEqual(acu.relative_filename(), native("aa/afile.py"))
self.assertEqual(bcu.relative_filename(), native("aa/bb/bfile.py"))
self.assertEqual(ccu.relative_filename(), native("aa/bb/cc/cfile.py"))
self.assertEqual(acu.source(), "# afile.py\n")
self.assertEqual(bcu.source(), "# bfile.py\n")
self.assertEqual(ccu.source(), "# cfile.py\n")
def test_comparison(self):
acu = FileReporter("aa/afile.py")
acu2 = FileReporter("aa/afile.py")
zcu = FileReporter("aa/zfile.py")
bcu = FileReporter("aa/bb/bfile.py")
assert acu == acu2 and acu <= acu2 and acu >= acu2 # pylint: disable=chained-comparison
assert acu < zcu and acu <= zcu and acu != zcu
assert zcu > acu and zcu >= acu and zcu != acu
assert acu < bcu and acu <= bcu and acu != bcu
assert bcu > acu and bcu >= acu and bcu != acu
def test_egg(self):
# Test that we can get files out of eggs, and read their source files.
# The egg1 module is installed by an action in igor.py.
import egg1
import egg1.egg1
# Verify that we really imported from an egg. If we did, then the
# __file__ won't be an actual file, because one of the "directories"
# in the path is actually the .egg zip file.
self.assert_doesnt_exist(egg1.__file__)
ecu = PythonFileReporter(egg1)
eecu = PythonFileReporter(egg1.egg1)
self.assertEqual(ecu.source(), u"")
self.assertIn(u"# My egg file!", eecu.source().splitlines())
|
import unittest
from kalliope.core.SignalModule import MissingParameter
from kalliope.core.Models import Brain
from kalliope.core.Models import Neuron
from kalliope.core.Models import Synapse
from kalliope.core.Models.Signal import Signal
from kalliope.signals.geolocation.geolocation import Geolocation
class Test_Geolocation(unittest.TestCase):
def test_check_geolocation_valid(self):
expected_parameters = ["latitude", "longitude", "radius"]
self.assertTrue(Geolocation.check_parameters(expected_parameters))
def test_check_geolocation_valid_with_other(self):
expected_parameters = ["latitude", "longitude", "radius", "kalliope", "random"]
self.assertTrue(Geolocation.check_parameters(expected_parameters))
def test_check_geolocation_no_radius(self):
expected_parameters = ["latitude", "longitude", "kalliope", "random"]
self.assertFalse(Geolocation.check_parameters(expected_parameters))
def test_check_geolocation_no_latitude(self):
expected_parameters = ["longitude", "radius", "kalliope", "random"]
self.assertFalse(Geolocation.check_parameters(expected_parameters))
def test_check_geolocation_no_longitude(self):
expected_parameters = ["latitude", "radius", "kalliope", "random"]
self.assertFalse(Geolocation.check_parameters(expected_parameters))
def test_get_list_synapse_with_geolocation(self):
# Init
neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3'})
neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
fake_geolocation_parameters = {
"latitude": 66,
"longitude": 66,
"radius": 66,
}
signal1 = Signal(name="geolocation", parameters=fake_geolocation_parameters)
signal2 = Signal(name="order", parameters="this is the second sentence")
synapse1 = Synapse(name="Synapse1", neurons=[neuron1, neuron2], signals=[signal1])
synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
synapses_list = [synapse1, synapse2]
br = Brain(synapses=synapses_list)
expected_list = [synapse1]
# Stubbing the Geolocation Signal with the brain
geo = Geolocation()
geo.brain = br
geo.run()
self.assertEqual(expected_list, geo.list_synapses_with_geolocalion)
def test_get_list_synapse_with_raise_missing_parameters(self):
# Init
neuron1 = Neuron(name='neurone1', parameters={'var1': 'val1'})
neuron2 = Neuron(name='neurone2', parameters={'var2': 'val2'})
neuron3 = Neuron(name='neurone3', parameters={'var3': 'val3'})
neuron4 = Neuron(name='neurone4', parameters={'var4': 'val4'})
fake_geolocation_parameters = {
"longitude": 66,
"radius": 66,
}
signal1 = Signal(name="geolocation", parameters=fake_geolocation_parameters)
signal2 = Signal(name="order", parameters="this is the second sentence")
synapse1 = Synapse(name="Synapse1", neurons=[neuron1, neuron2], signals=[signal1])
synapse2 = Synapse(name="Synapse2", neurons=[neuron3, neuron4], signals=[signal2])
synapses_list = [synapse1, synapse2]
br = Brain(synapses=synapses_list)
# Stubbing the Geolocation Signal with the brain
geo = Geolocation()
geo.brain = br
with self.assertRaises(MissingParameter):
geo.run()
if __name__ == '__main__':
unittest.main()
|
import unittest
from absl import flags
import mock
from perfkitbenchmarker import providers
from perfkitbenchmarker import requirements
from perfkitbenchmarker.configs import benchmark_config_spec
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
class LoadProvidersTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(LoadProvidersTestCase, self).setUp()
FLAGS.ignore_package_requirements = True
p = mock.patch.object(providers, '_imported_providers', new=set())
p.start()
self.addCleanup(p.stop)
# TODO(user): See if this can be fixed.
@unittest.skip('This fails because modules are being imported multiple '
'times in the instance of this process. Not sure how this '
'ever worked.')
def testImportAllProviders(self):
# Test that all modules can be imported successfully, but mock out the
# import of CloudStack's csapi.
with mock.patch.dict('sys.modules', csapi=mock.Mock()):
for cloud in providers.VALID_CLOUDS:
providers.LoadProvider(cloud)
def testLoadInvalidProvider(self):
with self.assertRaises(ImportError):
providers.LoadProvider('InvalidCloud')
def testLoadProviderChecksRequirements(self):
with mock.patch(requirements.__name__ + '.CheckProviderRequirements'):
providers.LoadProvider('GCP', ignore_package_requirements=False)
requirements.CheckProviderRequirements.assert_called_once_with('gcp')
def testLoadProviderIgnoresRequirements(self):
with mock.patch(requirements.__name__ + '.CheckProviderRequirements'):
providers.LoadProvider('GCP')
requirements.CheckProviderRequirements.assert_not_called()
def testBenchmarkConfigSpecLoadsProvider(self):
p = mock.patch(providers.__name__ + '.LoadProvider')
p.start()
self.addCleanup(p.stop)
config = {
'vm_groups': {
'group1': {
'cloud': 'AWS',
'os_type': 'ubuntu1804',
'vm_count': 0,
'vm_spec': {'AWS': {}}
}
}
}
benchmark_config_spec.BenchmarkConfigSpec(
'name', flag_values=FLAGS, **config)
providers.LoadProvider.assert_called_with('AWS', True)
if __name__ == '__main__':
unittest.main()
|
from vcr.serializers import compat
from vcr.request import Request
import yaml
# version 1 cassettes started with VCR 1.0.x.
# Before 1.0.x, there was no versioning.
CASSETTE_FORMAT_VERSION = 1
"""
Just a general note on the serialization philosophy here:
I prefer cassettes to be human-readable if possible. Yaml serializes
bytestrings to !!binary, which isn't readable, so I would like to serialize to
strings and from strings, which yaml will encode as utf-8 automatically.
All the internal HTTP stuff expects bytestrings, so this whole serialization
process feels backwards.
Serializing: bytestring -> string (yaml persists to utf-8)
Deserializing: string (yaml converts from utf-8) -> bytestring
"""
def _looks_like_an_old_cassette(data):
return isinstance(data, list) and len(data) and "request" in data[0]
def _warn_about_old_cassette_format():
raise ValueError(
"Your cassette files were generated in an older version "
"of VCR. Delete your cassettes or run the migration script."
"See http://git.io/mHhLBg for more details."
)
def deserialize(cassette_string, serializer):
try:
data = serializer.deserialize(cassette_string)
# Old cassettes used to use yaml object thingy so I have to
# check for some fairly stupid exceptions here
except (ImportError, yaml.constructor.ConstructorError):
_warn_about_old_cassette_format()
if _looks_like_an_old_cassette(data):
_warn_about_old_cassette_format()
requests = [Request._from_dict(r["request"]) for r in data["interactions"]]
responses = [compat.convert_to_bytes(r["response"]) for r in data["interactions"]]
return requests, responses
def serialize(cassette_dict, serializer):
interactions = [
{
"request": compat.convert_to_unicode(request._to_dict()),
"response": compat.convert_to_unicode(response),
}
for request, response in zip(cassette_dict["requests"], cassette_dict["responses"])
]
data = {"version": CASSETTE_FORMAT_VERSION, "interactions": interactions}
return serializer.serialize(data)
|
from unittest.mock import Mock
from homeassistant.components.slack.notify import SlackNotificationService
from tests.async_mock import AsyncMock
async def test_message_includes_default_emoji():
"""Tests that default icon is used when no message icon is given."""
mock_client = Mock()
mock_client.chat_postMessage = AsyncMock()
expected_icon = ":robot_face:"
service = SlackNotificationService(None, mock_client, "_", "_", expected_icon)
await service.async_send_message("test")
mock_fn = mock_client.chat_postMessage
mock_fn.assert_called_once()
_, kwargs = mock_fn.call_args
assert kwargs["icon_emoji"] == expected_icon
async def test_message_emoji_overrides_default():
"""Tests that overriding the default icon emoji when sending a message works."""
mock_client = Mock()
mock_client.chat_postMessage = AsyncMock()
service = SlackNotificationService(None, mock_client, "_", "_", "default_icon")
expected_icon = ":new:"
await service.async_send_message("test", data={"icon": expected_icon})
mock_fn = mock_client.chat_postMessage
mock_fn.assert_called_once()
_, kwargs = mock_fn.call_args
assert kwargs["icon_emoji"] == expected_icon
async def test_message_includes_default_icon_url():
"""Tests that overriding the default icon url when sending a message works."""
mock_client = Mock()
mock_client.chat_postMessage = AsyncMock()
expected_icon = "https://example.com/hass.png"
service = SlackNotificationService(None, mock_client, "_", "_", expected_icon)
await service.async_send_message("test")
mock_fn = mock_client.chat_postMessage
mock_fn.assert_called_once()
_, kwargs = mock_fn.call_args
assert kwargs["icon_url"] == expected_icon
async def test_message_icon_url_overrides_default():
"""Tests that overriding the default icon url when sending a message works."""
mock_client = Mock()
mock_client.chat_postMessage = AsyncMock()
service = SlackNotificationService(None, mock_client, "_", "_", "default_icon")
expected_icon = "https://example.com/hass.png"
await service.async_send_message("test", data={"icon": expected_icon})
mock_fn = mock_client.chat_postMessage
mock_fn.assert_called_once()
_, kwargs = mock_fn.call_args
assert kwargs["icon_url"] == expected_icon
|
import datetime
import logging
import hypothesis
from hypothesis import strategies
import pytest
from qutebrowser.misc import sql
from qutebrowser.completion.models import histcategory
from qutebrowser.utils import usertypes
@pytest.fixture
def hist(init_sql, config_stub):
config_stub.val.completion.timestamp_format = '%Y-%m-%d'
config_stub.val.completion.web_history.max_items = -1
return sql.SqlTable('CompletionHistory', ['url', 'title', 'last_atime'])
@pytest.mark.parametrize('pattern, before, after', [
('foo',
[('foo', ''), ('bar', ''), ('aafobbb', '')],
[('foo',)]),
('FOO',
[('foo', ''), ('bar', ''), ('aafobbb', '')],
[('foo',)]),
('foo',
[('FOO', ''), ('BAR', ''), ('AAFOBBB', '')],
[('FOO',)]),
('foo',
[('baz', 'bar'), ('foo', ''), ('bar', 'foo')],
[('foo', ''), ('bar', 'foo')]),
('foo',
[('fooa', ''), ('foob', ''), ('fooc', '')],
[('fooa', ''), ('foob', ''), ('fooc', '')]),
('foo',
[('foo', 'bar'), ('bar', 'foo'), ('biz', 'baz')],
[('foo', 'bar'), ('bar', 'foo')]),
('foo bar',
[('foo', ''), ('bar foo', ''), ('xfooyybarz', '')],
[('bar foo', ''), ('xfooyybarz', '')]),
('foo%bar',
[('foo%bar', ''), ('foo bar', ''), ('foobar', '')],
[('foo%bar', '')]),
('_',
[('a_b', ''), ('__a', ''), ('abc', '')],
[('a_b', ''), ('__a', '')]),
('%',
[('\\foo', '\\bar')],
[]),
("can't",
[("can't touch this", ''), ('a', '')],
[("can't touch this", '')]),
("ample itle",
[('example.com', 'title'), ('example.com', 'nope')],
[('example.com', 'title')]),
# https://github.com/qutebrowser/qutebrowser/issues/4411
("mlfreq",
[('https://qutebrowser.org/FAQ.html', 'Frequently Asked Questions')],
[]),
("ml freq",
[('https://qutebrowser.org/FAQ.html', 'Frequently Asked Questions')],
[('https://qutebrowser.org/FAQ.html', 'Frequently Asked Questions')]),
])
def test_set_pattern(pattern, before, after, model_validator, hist):
"""Validate the filtering and sorting results of set_pattern."""
for row in before:
hist.insert({'url': row[0], 'title': row[1], 'last_atime': 1})
cat = histcategory.HistoryCategory()
model_validator.set_model(cat)
cat.set_pattern(pattern)
model_validator.validate(after)
def test_set_pattern_repeated(model_validator, hist):
"""Validate multiple subsequent calls to set_pattern."""
hist.insert({'url': 'example.com/foo', 'title': 'title1', 'last_atime': 1})
hist.insert({'url': 'example.com/bar', 'title': 'title2', 'last_atime': 1})
hist.insert({'url': 'example.com/baz', 'title': 'title3', 'last_atime': 1})
cat = histcategory.HistoryCategory()
model_validator.set_model(cat)
cat.set_pattern('b')
model_validator.validate([
('example.com/bar', 'title2'),
('example.com/baz', 'title3'),
])
cat.set_pattern('ba')
model_validator.validate([
('example.com/bar', 'title2'),
('example.com/baz', 'title3'),
])
cat.set_pattern('ba ')
model_validator.validate([
('example.com/bar', 'title2'),
('example.com/baz', 'title3'),
])
cat.set_pattern('ba z')
model_validator.validate([
('example.com/baz', 'title3'),
])
@pytest.mark.parametrize('pattern', [
' '.join(map(str, range(10000))),
'x' * 50000,
], ids=['numbers', 'characters'])
def test_set_pattern_long(hist, message_mock, caplog, pattern):
hist.insert({'url': 'example.com/foo', 'title': 'title1', 'last_atime': 1})
cat = histcategory.HistoryCategory()
with caplog.at_level(logging.ERROR):
cat.set_pattern(pattern)
msg = message_mock.getmsg(usertypes.MessageLevel.error)
assert msg.text.startswith("Error with SQL query:")
@hypothesis.given(pat=strategies.text())
def test_set_pattern_hypothesis(hist, pat, caplog):
hist.insert({'url': 'example.com/foo', 'title': 'title1', 'last_atime': 1})
cat = histcategory.HistoryCategory()
with caplog.at_level(logging.ERROR):
cat.set_pattern(pat)
@pytest.mark.parametrize('max_items, before, after', [
(-1, [
('a', 'a', '2017-04-16'),
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
], [
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
('a', 'a', '2017-04-16'),
]),
(3, [
('a', 'a', '2017-04-16'),
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
], [
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
('a', 'a', '2017-04-16'),
]),
(2 ** 63 - 1, [ # Maximum value sqlite can handle for LIMIT
('a', 'a', '2017-04-16'),
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
], [
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
('a', 'a', '2017-04-16'),
]),
(2, [
('a', 'a', '2017-04-16'),
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
], [
('b', 'b', '2017-06-16'),
('c', 'c', '2017-05-16'),
]),
(1, [], []), # issue 2849 (crash with empty history)
])
def test_sorting(max_items, before, after, model_validator, hist, config_stub):
"""Validate the filtering and sorting results of set_pattern."""
config_stub.val.completion.web_history.max_items = max_items
for url, title, atime in before:
timestamp = datetime.datetime.strptime(atime, '%Y-%m-%d').timestamp()
hist.insert({'url': url, 'title': title, 'last_atime': timestamp})
cat = histcategory.HistoryCategory()
model_validator.set_model(cat)
cat.set_pattern('')
model_validator.validate(after)
def test_remove_rows(hist, model_validator):
hist.insert({'url': 'foo', 'title': 'Foo', 'last_atime': 0})
hist.insert({'url': 'bar', 'title': 'Bar', 'last_atime': 0})
cat = histcategory.HistoryCategory()
model_validator.set_model(cat)
cat.set_pattern('')
hist.delete('url', 'foo')
cat.removeRows(0, 1)
model_validator.validate([('bar', 'Bar')])
def test_remove_rows_fetch(hist):
"""removeRows should fetch enough data to make the current index valid."""
# we cannot use model_validator as it will fetch everything up front
hist.insert_batch({
'url': [str(i) for i in range(300)],
'title': [str(i) for i in range(300)],
'last_atime': [0] * 300,
})
cat = histcategory.HistoryCategory()
cat.set_pattern('')
# sanity check that we didn't fetch everything up front
assert cat.rowCount() < 300
cat.fetchMore()
assert cat.rowCount() == 300
hist.delete('url', '298')
cat.removeRows(297, 1)
assert cat.rowCount() == 299
@pytest.mark.parametrize('fmt, expected', [
('%Y-%m-%d', '2018-02-27'),
('%m/%d/%Y %H:%M', '02/27/2018 08:30'),
('', ''),
])
def test_timestamp_fmt(fmt, expected, model_validator, config_stub, init_sql):
"""Validate the filtering and sorting results of set_pattern."""
config_stub.val.completion.timestamp_format = fmt
hist = sql.SqlTable('CompletionHistory', ['url', 'title', 'last_atime'])
atime = datetime.datetime(2018, 2, 27, 8, 30)
hist.insert({'url': 'foo', 'title': '', 'last_atime': atime.timestamp()})
cat = histcategory.HistoryCategory()
model_validator.set_model(cat)
cat.set_pattern('')
model_validator.validate([('foo', '', expected)])
def test_skip_duplicate_set(message_mock, caplog, hist):
cat = histcategory.HistoryCategory()
cat.set_pattern('foo')
cat.set_pattern('foobarbaz')
msg = caplog.messages[-1]
assert msg.startswith(
"Skipping query on foobarbaz due to prefix foo returning nothing.")
|
from rest_framework import serializers
from shop.conf import app_settings
from shop.models.cart import CartModel, CartItemModel
from shop.rest.money import MoneyField
from shop.models.fields import ChoiceEnum
class ExtraCartRow(serializers.Serializer):
"""
This data structure holds extra information for each item, or for the whole cart, while
processing the cart using their modifiers.
"""
label = serializers.CharField(
read_only=True,
help_text="A short description of this row in a natural language.",
)
amount = MoneyField(
help_text="The price difference, if applied.",
)
class ExtraCartRowList(serializers.Serializer):
"""
Represent the OrderedDict used for cart.extra_rows and cart_item.extra_rows.
Additionally add the modifiers identifier to each element.
"""
def to_representation(self, obj):
return [dict(ecr.data, modifier=modifier) for modifier, ecr in obj.items()]
class BaseItemSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(lookup_field='pk', view_name='shop:cart-detail')
unit_price = MoneyField()
line_total = MoneyField()
summary = serializers.SerializerMethodField(
help_text="Sub-serializer for fields to be shown in the product's summary.")
extra_rows = ExtraCartRowList(read_only=True)
class Meta:
model = CartItemModel
def create(self, validated_data):
assert 'cart' in validated_data
cart_item, _ = CartItemModel.objects.get_or_create(**validated_data)
cart_item.save()
return cart_item
def to_representation(self, cart_item):
cart_item.update(self.context['request'])
representation = super().to_representation(cart_item)
return representation
def validate_product(self, product):
if not product.active:
msg = "Product `{}` is inactive, and can not be added to the cart."
raise serializers.ValidationError(msg.format(product))
return product
def get_summary(self, cart_item):
serializer_class = app_settings.PRODUCT_SUMMARY_SERIALIZER
serializer = serializer_class(cart_item.product, context=self.context,
read_only=True, label=self.root.label)
return serializer.data
class CartItemSerializer(BaseItemSerializer):
class Meta(BaseItemSerializer.Meta):
exclude = ['cart', 'id']
def create(self, validated_data):
validated_data['cart'] = CartModel.objects.get_or_create_from_request(self.context['request'])
return super().create(validated_data)
class WatchItemSerializer(BaseItemSerializer):
class Meta(BaseItemSerializer.Meta):
fields = ['product', 'product_code', 'url', 'summary', 'quantity', 'extra']
def create(self, validated_data):
cart = CartModel.objects.get_or_create_from_request(self.context['request'])
validated_data.update(cart=cart, quantity=0)
return super().create(validated_data)
class CartItems(ChoiceEnum):
without = False
unsorted = 1
arranged = 2
class BaseCartSerializer(serializers.ModelSerializer):
subtotal = MoneyField()
total = MoneyField()
extra_rows = ExtraCartRowList(read_only=True)
class Meta:
model = CartModel
fields = ['subtotal', 'total', 'extra_rows']
def to_representation(self, cart):
cart.update(self.context['request'])
representation = super().to_representation(cart)
if self.with_items:
items = self.represent_items(cart)
representation.update(items=items)
return representation
def represent_items(self, cart):
raise NotImplementedError("{} must implement method `represent_items()`.".format(self.__class__))
class CartSerializer(BaseCartSerializer):
total_quantity = serializers.IntegerField()
num_items = serializers.IntegerField()
class Meta(BaseCartSerializer.Meta):
fields = ['total_quantity', 'num_items'] + BaseCartSerializer.Meta.fields
def __init__(self, *args, **kwargs):
self.with_items = kwargs.pop('with_items', CartItems.without)
super().__init__(*args, **kwargs)
def represent_items(self, cart):
if self.with_items == CartItems.unsorted:
items = CartItemModel.objects.filter(cart=cart, quantity__gt=0).order_by('-updated_at')
else:
items = CartItemModel.objects.filter_cart_items(cart, self.context['request'])
serializer = CartItemSerializer(items, context=self.context, label=self.label, many=True)
return serializer.data
class WatchSerializer(BaseCartSerializer):
num_items = serializers.IntegerField()
class Meta(BaseCartSerializer.Meta):
fields = ['num_items']
def __init__(self, *args, **kwargs):
self.with_items = kwargs.pop('with_items', CartItems.arranged)
super().__init__(*args, **kwargs)
def represent_items(self, cart):
if self.with_items == CartItems.unsorted:
items = CartItemModel.objects.filter(cart=cart, quantity=0).order_by('-updated_at')
else:
items = CartItemModel.objects.filter_watch_items(cart, self.context['request'])
serializer = WatchItemSerializer(items, context=self.context, label=self.label, many=True)
return serializer.data
|
import fcntl
import os
import signal
import struct
import sys
import termios
import click
import pexpect
from molecule import logger
from molecule import scenarios
from molecule import util
from molecule.command import base
LOG = logger.get_logger(__name__)
class Login(base.Base):
"""
.. program:: molecule login
.. option:: molecule login
Target the default scenario.
.. program:: molecule login --scenario-name foo
.. option:: molecule login --scenario-name foo
Targeting a specific scenario.
.. program:: molecule login --host hostname
.. option:: molecule login --host hostname
Targeting a specific running host.
.. program:: molecule login --host hostname --scenario-name foo
.. option:: molecule login --host hostname --scenario-name foo
Targeting a specific running host and scenario.
.. program:: molecule --debug login
.. option:: molecule --debug login
Executing with `debug`.
.. program:: molecule --base-config base.yml login
.. option:: molecule --base-config base.yml login
Executing with a `base-config`.
.. program:: molecule --env-file foo.yml login
.. option:: molecule --env-file foo.yml login
Load an env file to read variables from when rendering
molecule.yml.
"""
def __init__(self, c):
super(Login, self).__init__(c)
self._pt = None
def execute(self):
"""
Execute the actions necessary to perform a `molecule login` and
returns None.
:return: None
"""
c = self._config
if ((not c.state.created) and c.driver.managed):
msg = 'Instances not created. Please create instances first.'
util.sysexit_with_message(msg)
hosts = [d['name'] for d in self._config.platforms.instances]
hostname = self._get_hostname(hosts)
self._get_login(hostname)
def _get_hostname(self, hosts):
hostname = self._config.command_args.get('host')
if hostname is None:
if len(hosts) == 1:
hostname = hosts[0]
else:
msg = ('There are {} running hosts. Please specify '
'which with --host.\n\n'
'Available hosts:\n{}'.format(
len(hosts), '\n'.join(sorted(hosts))))
util.sysexit_with_message(msg)
match = [x for x in hosts if x.startswith(hostname)]
if len(match) == 0:
msg = ("There are no hosts that match '{}'. You "
'can only login to valid hosts.').format(hostname)
util.sysexit_with_message(msg)
elif len(match) != 1:
# If there are multiple matches, but one of them is an exact string
# match, assume this is the one they're looking for and use it.
if hostname in match:
match = [
hostname,
]
else:
msg = ("There are {} hosts that match '{}'. You "
'can only login to one at a time.\n\n'
'Available hosts:\n{}'.format(
len(match), hostname, '\n'.join(sorted(hosts))))
util.sysexit_with_message(msg)
return match[0]
def _get_login(self, hostname): # pragma: no cover
lines, columns = os.popen('stty size', 'r').read().split()
login_options = self._config.driver.login_options(hostname)
login_options['columns'] = columns
login_options['lines'] = lines
login_cmd = self._config.driver.login_cmd_template.format(
**login_options)
dimensions = (int(lines), int(columns))
cmd = '/usr/bin/env {}'.format(login_cmd)
self._pt = pexpect.spawn(cmd, dimensions=dimensions)
signal.signal(signal.SIGWINCH, self._sigwinch_passthrough)
self._pt.interact()
def _sigwinch_passthrough(self, sig, data): # pragma: no cover
tiocgwinsz = 1074295912 # assume
if 'TIOCGWINSZ' in dir(termios):
tiocgwinsz = termios.TIOCGWINSZ
s = struct.pack('HHHH', 0, 0, 0, 0)
a = struct.unpack('HHHH',
fcntl.ioctl(sys.stdout.fileno(), tiocgwinsz, s))
self._pt.setwinsize(a[0], a[1])
@click.command()
@click.pass_context
@click.option('--host', '-h', help='Host to access.')
@click.option(
'--scenario-name',
'-s',
default=base.MOLECULE_DEFAULT_SCENARIO_NAME,
help='Name of the scenario to target. ({})'.format(
base.MOLECULE_DEFAULT_SCENARIO_NAME))
def login(ctx, host, scenario_name): # pragma: no cover
""" Log in to one instance. """
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'host': host,
}
s = scenarios.Scenarios(
base.get_configs(args, command_args), scenario_name)
for scenario in s.all:
base.execute_subcommand(scenario.config, subcommand)
|
from datetime import timedelta
import schiene
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util
CONF_DESTINATION = "to"
CONF_START = "from"
CONF_OFFSET = "offset"
DEFAULT_OFFSET = timedelta(minutes=0)
CONF_ONLY_DIRECT = "only_direct"
DEFAULT_ONLY_DIRECT = False
ICON = "mdi:train"
SCAN_INTERVAL = timedelta(minutes=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
vol.Optional(CONF_OFFSET, default=DEFAULT_OFFSET): cv.time_period,
vol.Optional(CONF_ONLY_DIRECT, default=DEFAULT_ONLY_DIRECT): cv.boolean,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Deutsche Bahn Sensor."""
start = config.get(CONF_START)
destination = config[CONF_DESTINATION]
offset = config[CONF_OFFSET]
only_direct = config[CONF_ONLY_DIRECT]
add_entities([DeutscheBahnSensor(start, destination, offset, only_direct)], True)
class DeutscheBahnSensor(Entity):
"""Implementation of a Deutsche Bahn sensor."""
def __init__(self, start, goal, offset, only_direct):
"""Initialize the sensor."""
self._name = f"{start} to {goal}"
self.data = SchieneData(start, goal, offset, only_direct)
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def icon(self):
"""Return the icon for the frontend."""
return ICON
@property
def state(self):
"""Return the departure time of the next train."""
return self._state
@property
def device_state_attributes(self):
"""Return the state attributes."""
connections = self.data.connections[0]
if len(self.data.connections) > 1:
connections["next"] = self.data.connections[1]["departure"]
if len(self.data.connections) > 2:
connections["next_on"] = self.data.connections[2]["departure"]
return connections
def update(self):
"""Get the latest delay from bahn.de and updates the state."""
self.data.update()
self._state = self.data.connections[0].get("departure", "Unknown")
if self.data.connections[0].get("delay", 0) != 0:
self._state += f" + {self.data.connections[0]['delay']}"
class SchieneData:
"""Pull data from the bahn.de web page."""
def __init__(self, start, goal, offset, only_direct):
"""Initialize the sensor."""
self.start = start
self.goal = goal
self.offset = offset
self.only_direct = only_direct
self.schiene = schiene.Schiene()
self.connections = [{}]
def update(self):
"""Update the connection data."""
self.connections = self.schiene.connections(
self.start,
self.goal,
dt_util.as_local(dt_util.utcnow() + self.offset),
self.only_direct,
)
if not self.connections:
self.connections = [{}]
for con in self.connections:
# Detail info is not useful. Having a more consistent interface
# simplifies usage of template sensors.
if "details" in con:
con.pop("details")
delay = con.get("delay", {"delay_departure": 0, "delay_arrival": 0})
con["delay"] = delay["delay_departure"]
con["delay_arrival"] = delay["delay_arrival"]
con["ontime"] = con.get("ontime", False)
|
import functools
import logging
import os
import posixpath
import re
from absl import flags
from perfkitbenchmarker import data
from perfkitbenchmarker import linux_packages
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.linux_packages import hadoop
FLAGS = flags.FLAGS
flags.DEFINE_string('hbase_version', '1.3.5', 'HBase version.')
flags.DEFINE_string('hbase_bin_url', None,
'Specify to override url from HBASE_URL_BASE.')
HBASE_URL_BASE = 'https://www-us.apache.org/dist/hbase'
HBASE_PATTERN = r'>(hbase-([\d\.]+)-bin.tar.gz)<'
HBASE_VERSION_PATTERN = re.compile('HBase (.*)$', re.IGNORECASE | re.MULTILINE)
DATA_FILES = ['hbase/hbase-site.xml.j2', 'hbase/regionservers.j2',
'hbase/hbase-env.sh.j2']
HBASE_DIR = posixpath.join(linux_packages.INSTALL_DIR, 'hbase')
HBASE_BIN = posixpath.join(HBASE_DIR, 'bin')
HBASE_CONF_DIR = posixpath.join(HBASE_DIR, 'conf')
def _GetHBaseURL():
"""Gets the HBase download url based on flags.
The default is to look for the version `--hbase_version` to download.
If `--hbase_use_stable` is set will look for the latest stable version.
Returns:
The HBase download url.
"""
return '{0}/{1}/hbase-{1}-bin.tar.gz'.format(
HBASE_URL_BASE, FLAGS.hbase_version)
def GetHBaseVersion(vm):
txt, _ = vm.RemoteCommand(posixpath.join(HBASE_BIN, 'hbase') + ' version')
m = HBASE_VERSION_PATTERN.search(txt)
if m:
return m.group(1)
else:
# log as an warning, don't throw exception so as to continue on
logging.warn('Could not find HBase version from %s', txt)
return None
def CheckPrerequisites():
"""Verifies that the required resources are present.
Raises:
perfkitbenchmarker.data.ResourceNotFound: On missing resource.
"""
for resource in DATA_FILES:
data.ResourcePath(resource)
def _Install(vm):
vm.Install('hadoop')
vm.Install('curl')
hbase_url = FLAGS.hbase_bin_url or _GetHBaseURL()
vm.RemoteCommand(('mkdir {0} && curl -L {1} | '
'tar -C {0} --strip-components=1 -xzf -').format(
HBASE_DIR, hbase_url))
def YumInstall(vm):
"""Installs HBase on the VM."""
_Install(vm)
def AptInstall(vm):
"""Installs HBase on the VM."""
_Install(vm)
def _RenderConfig(vm, master_ip, zk_ips, regionserver_ips):
# Use the same heap configuration as Cassandra
memory_mb = vm.total_memory_kb // 1024
hbase_memory_mb = max(min(memory_mb // 2, 1024),
min(memory_mb // 4, 8192))
context = {
'master_ip': master_ip,
'worker_ips': regionserver_ips,
'zk_quorum_ips': zk_ips,
'hadoop_private_key': hadoop.HADOOP_PRIVATE_KEY,
'hbase_memory_mb': hbase_memory_mb,
'scratch_dir': vm.GetScratchDir(),
}
for file_name in DATA_FILES:
file_path = data.ResourcePath(file_name)
remote_path = posixpath.join(HBASE_CONF_DIR,
os.path.basename(file_name))
if file_name.endswith('.j2'):
vm.RenderTemplate(file_path, os.path.splitext(remote_path)[0], context)
else:
vm.RemoteCopy(file_path, remote_path)
def ConfigureAndStart(master, regionservers, zk_nodes):
"""Configure HBase on a cluster.
Args:
master: VM. Master VM.
regionservers: List of VMs.
"""
vms = [master] + regionservers
def LinkNativeLibraries(vm):
vm.RemoteCommand(('mkdir {0}/lib/native && '
'ln -s {1} {0}/lib/native/Linux-amd64-64').format(
HBASE_DIR,
posixpath.join(hadoop.HADOOP_DIR, 'lib', 'native')))
vm_util.RunThreaded(LinkNativeLibraries, vms)
fn = functools.partial(_RenderConfig, master_ip=master.internal_ip,
zk_ips=[vm.internal_ip for vm in zk_nodes],
regionserver_ips=[regionserver.internal_ip
for regionserver in regionservers])
vm_util.RunThreaded(fn, vms)
master.RemoteCommand('{0} dfs -mkdir /hbase'.format(
posixpath.join(hadoop.HADOOP_BIN, 'hdfs')))
master.RemoteCommand(posixpath.join(HBASE_BIN, 'start-hbase.sh'))
def Stop(master):
"""Stop HBase.
Args:
master: VM. Master VM.
"""
master.RemoteCommand(posixpath.join(HBASE_BIN, 'stop-hbase.sh'))
|
from service_configuration_lib import DEFAULT_SOA_DIR
from paasta_tools.cli.utils import list_paasta_services
from paasta_tools.cli.utils import list_service_instances
from paasta_tools.utils import list_services
from paasta_tools.utils import SPACER
def add_subparser(subparsers):
list_parser = subparsers.add_parser(
"list",
help="Display a list of PaaSTA services",
description=(
"'paasta list' inspects the soa-configs directory and lists all of the "
"PaaSTA services that are declared."
),
)
list_parser.add_argument(
"-a",
"--all",
action="store_true",
help="Display all services, even if not on PaaSTA.",
)
list_parser.add_argument(
"-i",
"--print-instances",
action="store_true",
help="Display all service%sinstance values, which only PaaSTA services have."
% SPACER,
)
list_parser.add_argument(
"-y",
"--yelpsoa-config-root",
dest="soa_dir",
help="A directory from which yelpsoa-configs should be read from",
default=DEFAULT_SOA_DIR,
)
list_parser.set_defaults(command=paasta_list)
def paasta_list(args):
"""Print a list of Yelp services currently running
:param args: argparse.Namespace obj created from sys.args by cli"""
if args.print_instances:
services = list_service_instances(args.soa_dir)
elif args.all:
services = list_services(args.soa_dir)
else:
services = list_paasta_services(args.soa_dir)
for service in services:
print(service)
|
import codecs
import sys
import json
from lark import Lark
from lark.grammar import RuleOptions, Rule
from lark.lexer import TerminalDef
from lark.tools import lalr_argparser, build_lalr
import argparse
argparser = argparse.ArgumentParser(prog='python -m lark.tools.serialize', parents=[lalr_argparser],
description="Lark Serialization Tool - Stores Lark's internal state & LALR analysis as a JSON file",
epilog='Look at the Lark documentation for more info on the options')
def serialize(lark_inst, outfile):
data, memo = lark_inst.memo_serialize([TerminalDef, Rule])
outfile.write('{\n')
outfile.write(' "data": %s,\n' % json.dumps(data))
outfile.write(' "memo": %s\n' % json.dumps(memo))
outfile.write('}\n')
def main():
ns = argparser.parse_args()
serialize(*build_lalr(ns))
if __name__ == '__main__':
main()
|
from homeassistant.components import geonetnz_volcano
from homeassistant.components.geo_location import ATTR_DISTANCE
from homeassistant.components.geonetnz_volcano import DEFAULT_SCAN_INTERVAL
from homeassistant.components.geonetnz_volcano.const import (
ATTR_ACTIVITY,
ATTR_EXTERNAL_ID,
ATTR_HAZARDS,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_FRIENDLY_NAME,
ATTR_ICON,
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_UNIT_OF_MEASUREMENT,
CONF_RADIUS,
EVENT_HOMEASSISTANT_START,
)
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from homeassistant.util.unit_system import IMPERIAL_SYSTEM
from tests.async_mock import AsyncMock, patch
from tests.common import async_fire_time_changed
from tests.components.geonetnz_volcano import _generate_mock_feed_entry
CONFIG = {geonetnz_volcano.DOMAIN: {CONF_RADIUS: 200}}
async def test_setup(hass, legacy_patchable_time):
"""Test the general setup of the integration."""
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry(
"1234",
"Title 1",
1,
15.5,
(38.0, -3.0),
attribution="Attribution 1",
activity="Activity 1",
hazards="Hazards 1",
)
mock_entry_2 = _generate_mock_feed_entry("2345", "Title 2", 0, 20.5, (38.1, -3.1))
mock_entry_3 = _generate_mock_feed_entry("3456", "Title 3", 2, 25.5, (38.2, -3.2))
mock_entry_4 = _generate_mock_feed_entry("4567", "Title 4", 1, 12.5, (38.3, -3.3))
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
) as mock_feed_update:
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
all_states = hass.states.async_all()
# 3 sensor entities
assert len(all_states) == 3
state = hass.states.get("sensor.volcano_title_1")
assert state is not None
assert state.name == "Volcano Title 1"
assert int(state.state) == 1
assert state.attributes[ATTR_EXTERNAL_ID] == "1234"
assert state.attributes[ATTR_LATITUDE] == 38.0
assert state.attributes[ATTR_LONGITUDE] == -3.0
assert state.attributes[ATTR_DISTANCE] == 15.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 1"
assert state.attributes[ATTR_ATTRIBUTION] == "Attribution 1"
assert state.attributes[ATTR_ACTIVITY] == "Activity 1"
assert state.attributes[ATTR_HAZARDS] == "Hazards 1"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "alert level"
assert state.attributes[ATTR_ICON] == "mdi:image-filter-hdr"
state = hass.states.get("sensor.volcano_title_2")
assert state is not None
assert state.name == "Volcano Title 2"
assert int(state.state) == 0
assert state.attributes[ATTR_EXTERNAL_ID] == "2345"
assert state.attributes[ATTR_LATITUDE] == 38.1
assert state.attributes[ATTR_LONGITUDE] == -3.1
assert state.attributes[ATTR_DISTANCE] == 20.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 2"
state = hass.states.get("sensor.volcano_title_3")
assert state is not None
assert state.name == "Volcano Title 3"
assert int(state.state) == 2
assert state.attributes[ATTR_EXTERNAL_ID] == "3456"
assert state.attributes[ATTR_LATITUDE] == 38.2
assert state.attributes[ATTR_LONGITUDE] == -3.2
assert state.attributes[ATTR_DISTANCE] == 25.5
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 3"
# Simulate an update - two existing, one new entry, one outdated entry
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_4, mock_entry_3]
async_fire_time_changed(hass, utcnow + DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - empty data, but successful update,
# so no changes to entities.
mock_feed_update.return_value = "OK_NO_DATA", None
async_fire_time_changed(hass, utcnow + 2 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - empty data, keep all entities
mock_feed_update.return_value = "ERROR", None
async_fire_time_changed(hass, utcnow + 3 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
# Simulate an update - regular data for 3 entries
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
async_fire_time_changed(hass, utcnow + 4 * DEFAULT_SCAN_INTERVAL)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 4
async def test_setup_imperial(hass):
"""Test the setup of the integration using imperial unit system."""
hass.config.units = IMPERIAL_SYSTEM
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry("1234", "Title 1", 1, 15.5, (38.0, -3.0))
# Patching 'utcnow' to gain more control over the timed update.
utcnow = dt_util.utcnow()
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock
) as mock_feed_update, patch(
"aio_geojson_client.feed.GeoJsonFeed.__init__"
) as mock_feed_init:
mock_feed_update.return_value = "OK", [mock_entry_1]
assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG)
# Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
all_states = hass.states.async_all()
assert len(all_states) == 1
# Test conversion of 200 miles to kilometers.
assert mock_feed_init.call_args[1].get("filter_radius") == 321.8688
state = hass.states.get("sensor.volcano_title_1")
assert state is not None
assert state.name == "Volcano Title 1"
assert int(state.state) == 1
assert state.attributes[ATTR_EXTERNAL_ID] == "1234"
assert state.attributes[ATTR_LATITUDE] == 38.0
assert state.attributes[ATTR_LONGITUDE] == -3.0
assert state.attributes[ATTR_DISTANCE] == 9.6
assert state.attributes[ATTR_FRIENDLY_NAME] == "Volcano Title 1"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "alert level"
assert state.attributes[ATTR_ICON] == "mdi:image-filter-hdr"
|
import os
import sys
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path
sys.path = [os.path.abspath(os.path.dirname(os.path.dirname(__file__)))] + sys.path
os.environ['is_test_suite'] = 'True'
from auto_ml import Predictor
import dill
from nose.tools import assert_equal, assert_not_equal, with_setup
import numpy as np
from sklearn.model_selection import train_test_split
import utils_testing as utils
def test_calibrate_final_model_classification():
np.random.seed(0)
df_titanic_train, df_titanic_test = utils.get_titanic_binary_classification_dataset()
# Take a third of our test data (a tenth of our overall data) for calibration
df_titanic_test, df_titanic_calibration = train_test_split(df_titanic_test, test_size=0.33, random_state=42)
column_descriptions = {
'survived': 'output'
, 'sex': 'categorical'
, 'embarked': 'categorical'
, 'pclass': 'categorical'
}
ml_predictor = Predictor(type_of_estimator='classifier', column_descriptions=column_descriptions)
ml_predictor.train(df_titanic_train, calibrate_final_model=True, X_test=df_titanic_calibration, y_test=df_titanic_calibration.survived)
test_score = ml_predictor.score(df_titanic_test, df_titanic_test.survived)
print('test_score')
print(test_score)
assert -0.14 < test_score < -0.12
def test_calibrate_final_model_missing_X_test_y_test_classification():
np.random.seed(0)
df_titanic_train, df_titanic_test = utils.get_titanic_binary_classification_dataset()
# Take a third of our test data (a tenth of our overall data) for calibration
df_titanic_test, df_titanic_calibration = train_test_split(df_titanic_test, test_size=0.33, random_state=42)
column_descriptions = {
'survived': 'output'
, 'sex': 'categorical'
, 'embarked': 'categorical'
, 'pclass': 'categorical'
}
ml_predictor = Predictor(type_of_estimator='classifier', column_descriptions=column_descriptions)
# This should still work, just with warning printed
ml_predictor.train(df_titanic_train, calibrate_final_model=True)
test_score = ml_predictor.score(df_titanic_test, df_titanic_test.survived)
print('test_score')
print(test_score)
assert -0.14 < test_score < -0.12
|
from homeassistant.const import CONF_HOST, CONF_NAME
from tests.async_mock import AsyncMock, patch
HOST = "1.2.3.4"
NAME = "Yeti"
CONF_DATA = {
CONF_HOST: HOST,
CONF_NAME: NAME,
}
CONF_CONFIG_FLOW = {
CONF_HOST: HOST,
CONF_NAME: NAME,
}
async def _create_mocked_yeti(raise_exception=False):
mocked_yeti = AsyncMock()
mocked_yeti.get_state = AsyncMock()
return mocked_yeti
def _patch_init_yeti(mocked_yeti):
return patch("homeassistant.components.goalzero.Yeti", return_value=mocked_yeti)
def _patch_config_flow_yeti(mocked_yeti):
return patch(
"homeassistant.components.goalzero.config_flow.Yeti",
return_value=mocked_yeti,
)
|
import mock
from paasta_tools import list_marathon_service_instances
from paasta_tools.marathon_tools import MarathonClients
from paasta_tools.mesos.exceptions import NoSlavesAvailableError
def test_get_desired_marathon_configs():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_services_for_cluster",
autospec=True,
) as mock_get_services_for_cluster, mock.patch(
"paasta_tools.list_marathon_service_instances.load_marathon_service_config",
autospec=True,
) as mock_load_marathon_service_config, mock.patch(
"paasta_tools.list_marathon_service_instances.load_system_paasta_config",
autospec=True,
), mock.patch(
"paasta_tools.list_marathon_service_instances._log", autospec=True
):
mock_app_dict = {"id": "/service.instance.git.configs"}
mock_app = mock.MagicMock(
format_marathon_app_dict=mock.MagicMock(return_value=mock_app_dict)
)
mock_app_2 = mock.MagicMock(
format_marathon_app_dict=mock.MagicMock(side_effect=[Exception])
)
mock_get_services_for_cluster.return_value = [
("service", "instance"),
("service", "broken_instance"),
]
mock_load_marathon_service_config.side_effect = [mock_app, mock_app_2]
assert list_marathon_service_instances.get_desired_marathon_configs(
"/fake/soa/dir"
) == (
{"service.instance.git.configs": mock_app_dict},
{"service.instance.git.configs": mock_app},
)
def test_get_desired_marathon_configs_handles_no_slaves():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_services_for_cluster",
autospec=True,
), mock.patch(
"paasta_tools.list_marathon_service_instances.load_marathon_service_config",
autospec=True,
), mock.patch(
"paasta_tools.list_marathon_service_instances.load_system_paasta_config",
autospec=True,
) as mock_load_marathon_service_config:
mock_load_marathon_service_config.return_value = mock.MagicMock(
format_marathon_app_dict=mock.MagicMock(
side_effect=NoSlavesAvailableError()
)
)
assert list_marathon_service_instances.get_desired_marathon_configs(
"/fake/soadir/"
) == ({}, {})
def test_get_service_instances_that_need_bouncing():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_desired_marathon_configs",
autospec=True,
) as mock_get_desired_marathon_configs, mock.patch(
"paasta_tools.list_marathon_service_instances.get_num_at_risk_tasks",
autospec=True,
) as mock_get_num_at_risk_tasks, mock.patch(
"paasta_tools.list_marathon_service_instances.get_draining_hosts", autospec=True
):
mock_get_desired_marathon_configs.return_value = (
{
"fake--service.fake--instance.sha.config": {"instances": 5},
"fake--service2.fake--instance.sha.config": {"instances": 5},
},
{
"fake--service.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
),
"fake--service2.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
),
},
)
fake_apps = [
mock.MagicMock(instances=5, id="/fake--service.fake--instance.sha.config2"),
mock.MagicMock(instances=5, id="/fake--service2.fake--instance.sha.config"),
]
mock_client = mock.MagicMock(list_apps=mock.MagicMock(return_value=fake_apps))
fake_clients = MarathonClients(current=[mock_client], previous=[mock_client])
mock_get_num_at_risk_tasks.return_value = 0
assert set(
list_marathon_service_instances.get_service_instances_that_need_bouncing(
marathon_clients=fake_clients, soa_dir="/fake/soa/dir"
)
) == {"fake_service.fake_instance"}
def test_get_service_instances_that_need_bouncing_two_existing_services():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_desired_marathon_configs",
autospec=True,
) as mock_get_desired_marathon_configs, mock.patch(
"paasta_tools.list_marathon_service_instances.get_num_at_risk_tasks",
autospec=True,
) as mock_get_num_at_risk_tasks, mock.patch(
"paasta_tools.list_marathon_service_instances.get_draining_hosts", autospec=True
):
mock_get_desired_marathon_configs.return_value = (
{"fake--service.fake--instance.sha.config": {"instances": 5}},
{
"fake--service.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
)
},
)
fake_apps = [
mock.MagicMock(instances=5, id="/fake--service.fake--instance.sha.config"),
mock.MagicMock(instances=5, id="/fake--service.fake--instance.sha.config2"),
]
mock_client = mock.MagicMock(list_apps=mock.MagicMock(return_value=fake_apps))
fake_clients = MarathonClients(current=[mock_client], previous=[mock_client])
mock_get_num_at_risk_tasks.return_value = 0
assert set(
list_marathon_service_instances.get_service_instances_that_need_bouncing(
marathon_clients=fake_clients, soa_dir="/fake/soa/dir"
)
) == {"fake_service.fake_instance"}
def test_get_service_instances_that_need_bouncing_no_difference():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_desired_marathon_configs",
autospec=True,
) as mock_get_desired_marathon_configs, mock.patch(
"paasta_tools.list_marathon_service_instances.get_num_at_risk_tasks",
autospec=True,
) as mock_get_num_at_risk_tasks, mock.patch(
"paasta_tools.list_marathon_service_instances.get_draining_hosts", autospec=True
):
mock_get_desired_marathon_configs.return_value = (
{"fake--service.fake--instance.sha.config": {"instances": 5}},
{
"fake--service.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
)
},
)
fake_apps = [
mock.MagicMock(instances=5, id="/fake--service.fake--instance.sha.config")
]
mock_client = mock.MagicMock(list_apps=mock.MagicMock(return_value=fake_apps))
fake_clients = MarathonClients(current=[mock_client], previous=[mock_client])
mock_get_num_at_risk_tasks.return_value = 0
assert (
set(
list_marathon_service_instances.get_service_instances_that_need_bouncing(
marathon_clients=fake_clients, soa_dir="/fake/soa/dir"
)
)
== set()
)
def test_get_service_instances_that_need_bouncing_instances_difference():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_desired_marathon_configs",
autospec=True,
) as mock_get_desired_marathon_configs, mock.patch(
"paasta_tools.list_marathon_service_instances.get_num_at_risk_tasks",
autospec=True,
) as mock_get_num_at_risk_tasks, mock.patch(
"paasta_tools.list_marathon_service_instances.get_draining_hosts", autospec=True
):
mock_get_desired_marathon_configs.return_value = (
{"fake--service.fake--instance.sha.config": {"instances": 5}},
{
"fake--service.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
)
},
)
fake_apps = [
mock.MagicMock(instances=4, id="/fake--service.fake--instance.sha.config")
]
mock_client = mock.MagicMock(list_apps=mock.MagicMock(return_value=fake_apps))
fake_clients = MarathonClients(current=[mock_client], previous=[mock_client])
mock_get_num_at_risk_tasks.return_value = 0
assert set(
list_marathon_service_instances.get_service_instances_that_need_bouncing(
marathon_clients=fake_clients, soa_dir="/fake/soa/dir"
)
) == {"fake_service.fake_instance"}
def test_get_service_instances_that_need_bouncing_at_risk():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_desired_marathon_configs",
autospec=True,
) as mock_get_desired_marathon_configs, mock.patch(
"paasta_tools.list_marathon_service_instances.get_num_at_risk_tasks",
autospec=True,
) as mock_get_num_at_risk_tasks, mock.patch(
"paasta_tools.list_marathon_service_instances.get_draining_hosts", autospec=True
):
mock_get_desired_marathon_configs.return_value = (
{"fake--service.fake--instance.sha.config": {"instances": 5}},
{
"fake--service.fake--instance.sha.config": mock.Mock(
get_marathon_shard=mock.Mock(return_value=None)
)
},
)
fake_apps = [
mock.MagicMock(instances=5, id="/fake--service.fake--instance.sha.config")
]
mock_client = mock.MagicMock(list_apps=mock.MagicMock(return_value=fake_apps))
fake_clients = MarathonClients(current=[mock_client], previous=[mock_client])
mock_get_num_at_risk_tasks.return_value = 1
assert set(
list_marathon_service_instances.get_service_instances_that_need_bouncing(
marathon_clients=fake_clients, soa_dir="/fake/soa/dir"
)
) == {"fake_service.fake_instance"}
def test_exceptions_logged_with_debug():
with mock.patch(
"paasta_tools.list_marathon_service_instances.get_services_for_cluster",
autospec=True,
) as mock_get_services_for_cluster, mock.patch(
"paasta_tools.list_marathon_service_instances.load_marathon_service_config",
autospec=True,
) as mock_load_marathon_service_config, mock.patch(
"paasta_tools.list_marathon_service_instances.load_system_paasta_config",
autospec=True,
), mock.patch(
"paasta_tools.list_marathon_service_instances._log", autospec=True
) as mock_log:
mock_app = mock.MagicMock(
format_marathon_app_dict=mock.MagicMock(side_effect=[Exception])
)
mock_get_services_for_cluster.return_value = [("service", "broken_instance")]
mock_load_marathon_service_config.side_effect = [mock_app]
list_marathon_service_instances.get_desired_marathon_configs("/fake/soa/dir")
mock_log.assert_called_once_with(
service="service",
line=mock.ANY,
component="deploy",
level="debug",
cluster=mock.ANY,
instance="broken_instance",
)
|
from ... import app, event
from . import Widget
app.assets.associate_asset(__name__, 'https://cdn.plot.ly/plotly-latest.min.js')
class PlotlyWidget(Widget):
""" A widget that shows a Plotly visualization.
"""
data = event.ListProp(settable=True, doc="""
The data (list of dicts) that describes the plot.
This can e.g. be the output of the Python plotly API call.
""")
layout = event.DictProp(settable=True, doc="""
The layout dict to style the plot.
""")
config = event.DictProp(settable=True, doc="""
The config for the plot.
""")
@event.reaction
def __relayout(self):
global Plotly
w, h = self.size
if len(self.node.children) > 0:
Plotly.relayout(self.node, dict(width=w, height=h))
@event.reaction
def _init_plot(self):
# https://plot.ly/javascript/plotlyjs-function-reference/#plotlynewplot
# Overwrites an existing plot
global Plotly
Plotly.newPlot(self.node, self.data, self.layout, self.config)
|
from ipaddress import ip_network
from aiohttp import web
from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO
import pytest
from homeassistant.components.http.forwarded import async_setup_forwarded
async def mock_handler(request):
"""Return the real IP as text."""
return web.Response(text=request.remote)
async def test_x_forwarded_for_without_trusted_proxy(aiohttp_client, caplog):
"""Test that we get the IP from the transport."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
assert (
"Received X-Forwarded-For header from untrusted proxy 127.0.0.1, headers not processed"
in caplog.text
)
@pytest.mark.parametrize(
"trusted_proxies,x_forwarded_for,remote",
[
(
["127.0.0.0/24", "1.1.1.1", "10.10.10.0/24"],
"10.10.10.10, 1.1.1.1",
"10.10.10.10",
),
(["127.0.0.0/24", "1.1.1.1"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "2.2.2.2"),
(["127.0.0.0/24", "1.1.1.1"], "123.123.123.123,2.2.2.2,1.1.1.1", "2.2.2.2"),
(["127.0.0.0/24"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "1.1.1.1"),
(["127.0.0.0/24"], "127.0.0.1", "127.0.0.1"),
(["127.0.0.1", "1.1.1.1"], "123.123.123.123, 1.1.1.1", "123.123.123.123"),
(["127.0.0.1", "1.1.1.1"], "123.123.123.123, 2.2.2.2, 1.1.1.1", "2.2.2.2"),
(["127.0.0.1"], "255.255.255.255", "255.255.255.255"),
],
)
async def test_x_forwarded_for_with_trusted_proxy(
trusted_proxies, x_forwarded_for, remote, aiohttp_client
):
"""Test that we get the IP from the forwarded for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == remote
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(
app, [ip_network(trusted_proxy) for trusted_proxy in trusted_proxies]
)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 200
async def test_x_forwarded_for_with_untrusted_proxy(aiohttp_client):
"""Test that we get the IP from transport with untrusted proxy."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("1.1.1.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
async def test_x_forwarded_for_with_spoofed_header(aiohttp_client):
"""Test that we get the IP from the transport with a spoofed header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"}
)
assert resp.status == 200
@pytest.mark.parametrize(
"x_forwarded_for",
[
"This value is invalid",
"1.1.1.1, , 1.2.3.4",
"1.1.1.1,,1.2.3.4",
"1.1.1.1, batman, 1.2.3.4",
"192.168.0.0/24",
"192.168.0.0/24, 1.1.1.1",
",",
"",
],
)
async def test_x_forwarded_for_with_malformed_header(
x_forwarded_for, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with a malformed header."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 400
assert "Invalid IP address in X-Forwarded-For" in caplog.text
async def test_x_forwarded_for_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_FOR, "123.123.123.123"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forwarded-For" in caplog.text
async def test_x_forwarded_proto_without_trusted_proxy(aiohttp_client):
"""Test that proto header is ignored when untrusted."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_PROTO: "https"}
)
assert resp.status == 200
@pytest.mark.parametrize(
"x_forwarded_for,remote,x_forwarded_proto,secure",
[
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https, http, http", True),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https,http,http", True),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "http", False),
(
"10.10.10.10, 127.0.0.1, 127.0.0.2",
"10.10.10.10",
"http, https, https",
False,
),
("10.10.10.10, 127.0.0.1, 127.0.0.2", "10.10.10.10", "https", True),
(
"255.255.255.255, 10.10.10.10, 127.0.0.1",
"10.10.10.10",
"http, https, http",
True,
),
(
"255.255.255.255, 10.10.10.10, 127.0.0.1",
"10.10.10.10",
"https, http, https",
False,
),
("255.255.255.255, 10.10.10.10, 127.0.0.1", "10.10.10.10", "https", True),
],
)
async def test_x_forwarded_proto_with_trusted_proxy(
x_forwarded_for, remote, x_forwarded_proto, secure, aiohttp_client
):
"""Test that we get the proto header if proxy is trusted."""
async def handler(request):
assert request.remote == remote
assert request.scheme == ("https" if secure else "http")
assert request.secure == secure
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == 200
async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(aiohttp_client):
"""Test that we get the proto with 1 element in the proto, multiple in the for."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "https"
assert request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: "255.255.255.255, 127.0.0.1, 127.0.0.2",
X_FORWARDED_PROTO: "https",
},
)
assert resp.status == 200
async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client):
"""Test that proto header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_PROTO: "https"})
assert resp.status == 200
async def test_x_forwarded_proto_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_PROTO, "https"),
(X_FORWARDED_PROTO, "http"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forward-Proto" in caplog.text
@pytest.mark.parametrize(
"x_forwarded_proto",
["", ",", "https, , https", "https, https, "],
)
async def test_x_forwarded_proto_empty_element(
x_forwarded_proto, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with empty proto."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "1.1.1.1", X_FORWARDED_PROTO: x_forwarded_proto},
)
assert resp.status == 400
assert "Empty item received in X-Forward-Proto header" in caplog.text
@pytest.mark.parametrize(
"x_forwarded_for,x_forwarded_proto,expected,got",
[
("1.1.1.1, 2.2.2.2", "https, https, https", 2, 3),
("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4", "https, https, https", 4, 3),
],
)
async def test_x_forwarded_proto_incorrect_number_of_elements(
x_forwarded_for, x_forwarded_proto, expected, got, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with incorrect number of elements."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == 400
assert (
f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}"
in caplog.text
)
async def test_x_forwarded_host_without_trusted_proxy(aiohttp_client):
"""Test that host header is ignored when untrusted."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
)
assert resp.status == 200
async def test_x_forwarded_host_with_trusted_proxy(aiohttp_client):
"""Test that we get the host header if proxy is trusted."""
async def handler(request):
assert request.host == "example.com"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
)
assert resp.status == 200
async def test_x_forwarded_host_not_processed_without_for(aiohttp_client):
"""Test that host header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_HOST: "example.com"})
assert resp.status == 200
async def test_x_forwarded_host_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_HOST, "example.com"),
(X_FORWARDED_HOST, "example.spoof"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forwarded-Host" in caplog.text
async def test_x_forwarded_host_with_empty_header(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with empty host value."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""}
)
assert resp.status == 400
assert "Empty value received in X-Forward-Host header" in caplog.text
|
from homeassistant.components.water_heater import (
_LOGGER,
ATTR_AWAY_MODE,
ATTR_OPERATION_MODE,
DOMAIN,
SERVICE_SET_AWAY_MODE,
SERVICE_SET_OPERATION_MODE,
SERVICE_SET_TEMPERATURE,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, ENTITY_MATCH_ALL
async def async_set_away_mode(hass, away_mode, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified water_heater devices away mode on."""
data = {ATTR_AWAY_MODE: away_mode}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
await hass.services.async_call(DOMAIN, SERVICE_SET_AWAY_MODE, data, blocking=True)
async def async_set_temperature(
hass, temperature=None, entity_id=ENTITY_MATCH_ALL, operation_mode=None
):
"""Set new target temperature."""
kwargs = {
key: value
for key, value in [
(ATTR_TEMPERATURE, temperature),
(ATTR_ENTITY_ID, entity_id),
(ATTR_OPERATION_MODE, operation_mode),
]
if value is not None
}
_LOGGER.debug("set_temperature start data=%s", kwargs)
await hass.services.async_call(
DOMAIN, SERVICE_SET_TEMPERATURE, kwargs, blocking=True
)
async def async_set_operation_mode(hass, operation_mode, entity_id=ENTITY_MATCH_ALL):
"""Set new target operation mode."""
data = {ATTR_OPERATION_MODE: operation_mode}
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
await hass.services.async_call(
DOMAIN, SERVICE_SET_OPERATION_MODE, data, blocking=True
)
|
import warnings
from ..utils import tight_layout
from ...fixes import nullcontext
class MplCanvas(object):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, brain, width, height, dpi):
from PyQt5 import QtWidgets
from matplotlib import rc_context
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
if brain.separate_canvas:
parent = None
else:
parent = brain.window
# prefer constrained layout here but live with tight_layout otherwise
context = nullcontext
extra_events = ('resize',)
try:
context = rc_context({'figure.constrained_layout.use': True})
extra_events = ()
except KeyError:
pass
with context:
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.canvas = FigureCanvasQTAgg(self.fig)
self.axes = self.fig.add_subplot(111)
self.axes.set(xlabel='Time (sec)', ylabel='Activation (AU)')
self.canvas.setParent(parent)
FigureCanvasQTAgg.setSizePolicy(
self.canvas,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding
)
FigureCanvasQTAgg.updateGeometry(self.canvas)
self.brain = brain
self.time_func = brain.callbacks["time"]
for event in ('button_press', 'motion_notify') + extra_events:
self.canvas.mpl_connect(
event + '_event', getattr(self, 'on_' + event))
def plot(self, x, y, label, **kwargs):
"""Plot a curve."""
line, = self.axes.plot(
x, y, label=label, **kwargs)
self.update_plot()
return line
def plot_time_line(self, x, label, **kwargs):
"""Plot the vertical line."""
line = self.axes.axvline(x, label=label, **kwargs)
self.update_plot()
return line
def update_plot(self):
"""Update the plot."""
leg = self.axes.legend(
prop={'family': 'monospace', 'size': 'small'},
framealpha=0.5, handlelength=1.,
facecolor=self.brain._bg_color)
for text in leg.get_texts():
text.set_color(self.brain._fg_color)
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', 'constrained_layout')
self.canvas.draw()
def set_color(self, bg_color, fg_color):
"""Set the widget colors."""
self.axes.set_facecolor(bg_color)
self.axes.xaxis.label.set_color(fg_color)
self.axes.yaxis.label.set_color(fg_color)
self.axes.spines['top'].set_color(fg_color)
self.axes.spines['bottom'].set_color(fg_color)
self.axes.spines['left'].set_color(fg_color)
self.axes.spines['right'].set_color(fg_color)
self.axes.tick_params(axis='x', colors=fg_color)
self.axes.tick_params(axis='y', colors=fg_color)
self.fig.patch.set_facecolor(bg_color)
def show(self):
"""Show the canvas."""
self.canvas.show()
def close(self):
"""Close the canvas."""
self.canvas.close()
def on_button_press(self, event):
"""Handle button presses."""
# left click (and maybe drag) in progress in axes
if (event.inaxes != self.axes or
event.button != 1):
return
self.time_func(
event.xdata, update_widget=True, time_as_index=False)
def clear(self):
"""Clear internal variables."""
self.close()
self.axes.clear()
self.fig.clear()
self.brain = None
self.canvas = None
on_motion_notify = on_button_press # for now they can be the same
def on_resize(self, event):
"""Handle resize events."""
tight_layout(fig=self.axes.figure)
|
from test import CollectorTestCase
from test import get_collector_config
from mysql55 import MySQLPerfCollector
class TestMySQLPerfCollector(CollectorTestCase):
def setUp(self, allowed_names=None):
if not allowed_names:
allowed_names = []
config = get_collector_config('MySQLPerfCollector', {
'allowed_names': allowed_names,
'interval': 1
})
self.collector = MySQLPerfCollector(config, None)
def test_import(self):
self.assertTrue(MySQLPerfCollector)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.