input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tabular models. Tabular models of any dimension can be created using `tabular_model`. For convenience `Tabular1D` and `Tabular2D` are provided. Examples -------- >>> table = np.array([[ 3., 0., 0.], ... [ 0., 2., 0.], ... [ 0., 0., 0.]]) >>> points = ([1, 2, 3], [1, 2, 3]) >>> t2 = Tabular2D(points, lookup_table=table, bounds_error=False, ... fill_value=None, method='nearest') """ # pylint: disable=invalid-name import abc import numpy as np from astropy import units as u from .core import Model try: from scipy.interpolate import interpn has_scipy = True except ImportError: has_scipy = False __all__ = ['tabular_model', 'Tabular1D', 'Tabular2D'] __doctest_requires__ = {('tabular_model'): ['scipy']} class _Tabular(Model): """ Returns an interpolated lookup table value. Parameters ---------- points : tuple of ndarray of float, optional The points defining the regular grid in n dimensions. ndarray must have shapes (m1, ), ..., (mn, ), lookup_table : array-like The data on a regular grid in n dimensions. Must have shapes (m1, ..., mn, ...) method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest", and "splinef2d". "splinef2d" is only supported for 2-dimensional data. Default is "linear". bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then ``fill_value`` is used. fill_value : float or `~astropy.units.Quantity`, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Extrapolation is not supported by method "splinef2d". If Quantity is given, it will be converted to the unit of ``lookup_table``, if applicable. Returns ------- value : ndarray Interpolated values at input coordinates. Raises ------ ImportError Scipy is not installed. Notes ----- Uses `scipy.interpolate.interpn`. """ linear = False fittable = False standard_broadcasting = False @property @abc.abstractmethod def lookup_table(self): pass _is_dynamic = True _id = 0 def __init__(self, points=None, lookup_table=None, method='linear', bounds_error=True, fill_value=np.nan, **kwargs): n_models = kwargs.get('n_models', 1) if n_models > 1: raise NotImplementedError('Only n_models=1 is supported.') super().__init__(**kwargs) self.outputs = ("y",) if lookup_table is None: raise ValueError('Must provide a lookup table.') if not isinstance(lookup_table, u.Quantity): lookup_table = np.asarray(lookup_table) if self.lookup_table.ndim != lookup_table.ndim: raise ValueError("lookup_table should be an array with " "{} dimensions.".format(self.lookup_table.ndim)) if points is None: points = tuple(np.arange(x, dtype=float) for x in lookup_table.shape) else: if lookup_table.ndim == 1 and not isinstance(points, tuple): points = (points,) npts = len(points) if npts != lookup_table.ndim: raise ValueError( "Expected grid points in " "{} directions, got {}.".format(lookup_table.ndim, npts)) if (npts > 1 and isinstance(points[0], u.Quantity) and len(set([getattr(p, 'unit', None) for p in points])) > 1): raise ValueError('points must all have the same unit.') if isinstance(fill_value, u.Quantity): if not isinstance(lookup_table, u.Quantity): raise ValueError('fill value is in {} but expected to be ' 'unitless.'.format(fill_value.unit)) fill_value = fill_value.to(lookup_table.unit).value self.points = points self.lookup_table = lookup_table self.bounds_error = bounds_error self.method = method self.fill_value = fill_value def __repr__(self): fmt = "<{}(points={}, lookup_table={})>".format( self.__class__.__name__, self.points, self.lookup_table) return fmt def __str__(self): default_keywords = [ ('Model', self.__class__.__name__), ('Name', self.name), ('N_inputs', self.n_inputs), ('N_outputs', self.n_outputs), ('Parameters', ""), (' points', self.points), (' lookup_table', self.lookup_table), (' method', self.method), (' fill_value', self.fill_value), (' bounds_error', self.bounds_error) ] parts = [f'{keyword}: {value}' for keyword, value in default_keywords if value is not None] return '\n'.join(parts) @property def input_units(self): pts = self.points[0] if not isinstance(pts, u.Quantity): return None return dict([(x, pts.unit) for x in self.inputs]) @property def return_units(self): if not isinstance(self.lookup_table, u.Quantity): return None return {self.outputs[0]: self.lookup_table.unit} @property def bounding_box(self): """ Tuple defining the default ``bounding_box`` limits, ``(points_low, points_high)``. Examples -------- >>> from astropy.modeling.models import Tabular1D, Tabular2D >>> t1 = Tabular1D(points=[1, 2, 3], lookup_table=[10, 20, 30]) >>> t1.bounding_box (1, 3) >>> t2 = Tabular2D(points=[[1, 2, 3], [2, 3, 4]], ... lookup_table=[[10, 20, 30], [20, 30, 40]]) >>> t2.bounding_box ((2, 4), (1, 3)) """ bbox = [(min(p), max(p)) for p in self.points][::-1] if len(bbox) == 1: bbox = bbox[0] return tuple(bbox) def evaluate(self, *inputs): """ Return the interpolated values at the input coordinates. Parameters ---------- inputs : list of scalar or list of ndarray Input coordinates. The number of inputs must be equal to the dimensions of the lookup table. """ inputs = np.broadcast_arrays(*inputs) if isinstance(inputs, u.Quantity): inputs = inputs.value shape = inputs[0].shape inputs = [inp.flatten() for inp in inputs[: self.n_inputs]] inputs = np.array(inputs).T if not has_scipy: # pragma: no cover raise ImportError("Tabular model requires scipy.") result = interpn(self.points, self.lookup_table, inputs, method=self.method, bounds_error=self.bounds_error, fill_value=self.fill_value) # return_units not respected when points has no units if (isinstance(self.lookup_table, u.Quantity) and not isinstance(self.points[0], u.Quantity)): result = result * self.lookup_table.unit if self.n_outputs == 1: result = result.reshape(shape) else: result = [r.reshape(shape) for r in result] return result @property def inverse(self): if self.n_inputs == 1: # If the wavelength array is decending instead of ascending, both # points and lookup_table need to be reversed in the inverse transform # for scipy.interpolate to work properly if np.all(np.diff(self.lookup_table) > 0): # ascending case points = self.lookup_table lookup_table = self.points[0] elif np.all(np.diff(self.lookup_table) < 0): # descending case, reverse order points = self.lookup_table[::-1] lookup_table = self.points[0][::-1] else: # equal-valued or double-valued lookup_table raise NotImplementedError return Tabular1D(points=points, lookup_table=lookup_table, method=self.method, bounds_error=self.bounds_error, fill_value=self.fill_value) raise NotImplementedError("An analytical inverse transform " "has not been implemented for this model.") def tabular_model(dim, name=None): """ Make a ``Tabular`` model where ``n_inputs`` is based on the dimension of the lookup_table. This model has to be further initialized and when evaluated returns the interpolated values. Parameters ---------- dim : int Dimensions of the lookup table. name : str Name for the class. Examples -------- >>> table = np.array([[3., 0., 0.], ... [0., 2., 0.], ... [0., 0., 0.]]) >>> tab = tabular_model(2, name='Tabular2D') >>> print(tab) <class 'astropy.modeling.tabular.Tabular2D'> Name: Tabular2D N_inputs: 2 N_outputs: 1 >>> points = ([1, 2, 3], [1, 2, 3]) Setting fill_value to None, allows extrapolation. >>> m = tab(points, lookup_table=table, name='my_table', ... bounds_error=False, fill_value=None, method='nearest') >>> xinterp = [0, 1, 1.5, 2.72, 3.14] >>> m(xinterp, xinterp) # doctest: +FLOAT_CMP array([3., 3., 3., 0., 0.]) """ if dim < 1: raise ValueError('Lookup table must have at least one dimension.') table = np.zeros([2] * dim) members = {'lookup_table': table, 'n_inputs': dim, 'n_outputs': 1} if dim == 1: members['_separable'] = True else: members['_separable'] = False if name is None: model_id = _Tabular._id _Tabular._id += 1 name = f'Tabular{model_id}' model_class = type(str(name), (_Tabular,), members) model_class.__module__ = 'astropy.modeling.tabular' return model_class Tabular1D = tabular_model(1, name='Tabular1D') Tabular2D = tabular_model(2, name='Tabular2D') _tab_docs = """ method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest", and "splinef2d". "splinef2d" is only supported for 2-dimensional data. Default is "linear". bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then ``fill_value`` is used. fill_value : float, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Extrapolation is not supported by method "splinef2d". Returns ------- value : ndarray Interpolated values at input coordinates. Raises ------ ImportError Scipy is not installed. Notes ----- Uses `scipy.interpolate.interpn`. """ Tabular1D.__doc__ = """ Tabular model in 1D. Returns an interpolated lookup table value. Parameters ---------- points : array-like of float of ndim=1. The points defining the regular grid in n dimensions. lookup_table : array-like, of ndim=1. The data in one dimensions. """ + _tab_docs Tabular2D.__doc__ = """ Tabular model in 2D. Returns an interpolated lookup table value. Parameters ---------- points : tuple of ndarray of float, optional The points defining the regular grid in n dimensions. ndarray with shapes (m1, m2). lookup_table : array-like The data on a regular grid in 2 dimensions. Shape (m1, m2). """ + _tab_docs
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import pytest asdf = pytest.importorskip('asdf') import io from astropy import units as u from asdf.tests import helpers # TODO: Implement defunit def test_unit(): yaml = """ unit: !unit/unit-1.0.0 "2.1798721 10-18kg m2 s-2" """ buff = helpers.yaml_to_asdf(yaml) with asdf.open(buff) as ff: assert ff.tree['unit'].is_equivalent(u.Ry) buff2 = io.BytesIO() ff.write_to(buff2) buff2.seek(0) with asdf.open(buff2) as ff: assert ff.tree['unit'].is_equivalent(u.Ry)
mhvk/astropy
astropy/io/misc/asdf/tags/unit/tests/test_unit.py
astropy/modeling/tabular.py
""" implement the TimedeltaIndex """ from datetime import timedelta import numpy as np from pandas.core.dtypes.common import ( _TD_DTYPE, is_integer, is_float, is_bool_dtype, is_list_like, is_scalar, is_timedelta64_dtype, is_timedelta64_ns_dtype, pandas_dtype, _ensure_int64) from pandas.core.dtypes.missing import isna from pandas.core.dtypes.generic import ABCSeries from pandas.core.common import _maybe_box, _values_from_object from pandas.core.indexes.base import Index from pandas.core.indexes.numeric import Int64Index import pandas.compat as compat from pandas.compat import u from pandas.tseries.frequencies import to_offset from pandas.core.algorithms import checked_add_with_arr from pandas.core.base import _shared_docs from pandas.core.indexes.base import _index_shared_docs import pandas.core.common as com import pandas.core.dtypes.concat as _concat from pandas.util._decorators import Appender, Substitution, deprecate_kwarg from pandas.core.indexes.datetimelike import TimelikeOps, DatetimeIndexOpsMixin from pandas.core.tools.timedeltas import ( to_timedelta, _coerce_scalar_to_timedelta_type) from pandas.tseries.offsets import Tick, DateOffset from pandas._libs import (lib, index as libindex, tslib as libts, join as libjoin, Timedelta, NaT, iNaT) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._libs.tslibs.fields import get_timedelta_field def _field_accessor(name, alias, docstring=None): def f(self): values = self.asi8 result = get_timedelta_field(values, alias) if self.hasnans: result = self._maybe_mask_results(result, convert='float64') return Index(result, name=self.name) f.__name__ = name f.__doc__ = docstring return property(f) def _td_index_cmp(opname, cls, nat_result=False): """ Wrap comparison operations to convert timedelta-like to timedelta64 """ def wrapper(self, other): msg = "cannot compare a TimedeltaIndex with type {0}" func = getattr(super(TimedeltaIndex, self), opname) if _is_convertible_to_td(other) or other is NaT: try: other = _to_m8(other) except ValueError: # failed to parse as timedelta raise TypeError(msg.format(type(other))) result = func(other) if isna(other): result.fill(nat_result) else: if not is_list_like(other): raise TypeError(msg.format(type(other))) other = TimedeltaIndex(other).values result = func(other) result = _values_from_object(result) if isinstance(other, Index): o_mask = other.values.view('i8') == iNaT else: o_mask = other.view('i8') == iNaT if o_mask.any(): result[o_mask] = nat_result if self.hasnans: result[self._isnan] = nat_result # support of bool dtype indexers if is_bool_dtype(result): return result return Index(result) return compat.set_function_name(wrapper, opname, cls) class TimedeltaIndex(DatetimeIndexOpsMixin, TimelikeOps, Int64Index): """ Immutable ndarray of timedelta64 data, represented internally as int64, and which can be boxed to timedelta objects Parameters ---------- data : array-like (1-dimensional), optional Optional timedelta-like data to construct index with unit: unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional which is an integer/float number freq: a frequency for the index, optional copy : bool Make a copy of input ndarray start : starting value, timedelta-like, optional If data is None, start is used as the start point in generating regular timedelta data. periods : int, optional, > 0 Number of periods to generate, if generating index. Takes precedence over end argument end : end time, timedelta-like, optional If periods is none, generated index will extend to first conforming time on or just past end argument closed : string or None, default None Make the interval closed with respect to the given frequency to the 'left', 'right', or both sides (None) name : object Name to be stored in the index Notes ----- To learn more about the frequency strings, please see `this link <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__. See Also --------- Index : The base pandas Index type Timedelta : Represents a duration between two dates or times. DatetimeIndex : Index of datetime64 data PeriodIndex : Index of Period data Attributes ---------- days seconds microseconds nanoseconds components inferred_freq Methods ------- to_pytimedelta to_series round floor ceil to_frame """ _typ = 'timedeltaindex' _join_precedence = 10 def _join_i8_wrapper(joinf, **kwargs): return DatetimeIndexOpsMixin._join_i8_wrapper( joinf, dtype='m8[ns]', **kwargs) _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer_int64) _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer_int64) _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer_int64) _left_indexer_unique = _join_i8_wrapper( libjoin.left_join_indexer_unique_int64, with_indexers=False) _arrmap = None # define my properties & methods for delegation _other_ops = [] _bool_ops = [] _object_ops = ['freq'] _field_ops = ['days', 'seconds', 'microseconds', 'nanoseconds'] _datetimelike_ops = _field_ops + _object_ops + _bool_ops _datetimelike_methods = ["to_pytimedelta", "total_seconds", "round", "floor", "ceil"] @classmethod def _add_comparison_methods(cls): """ add in comparison methods """ cls.__eq__ = _td_index_cmp('__eq__', cls) cls.__ne__ = _td_index_cmp('__ne__', cls, nat_result=True) cls.__lt__ = _td_index_cmp('__lt__', cls) cls.__gt__ = _td_index_cmp('__gt__', cls) cls.__le__ = _td_index_cmp('__le__', cls) cls.__ge__ = _td_index_cmp('__ge__', cls) _engine_type = libindex.TimedeltaEngine _comparables = ['name', 'freq'] _attributes = ['name', 'freq'] _is_numeric_dtype = True _infer_as_myclass = True freq = None def __new__(cls, data=None, unit=None, freq=None, start=None, end=None, periods=None, copy=False, name=None, closed=None, verify_integrity=True, **kwargs): if isinstance(data, TimedeltaIndex) and freq is None and name is None: if copy: return data.copy() else: return data._shallow_copy() freq_infer = False if not isinstance(freq, DateOffset): # if a passed freq is None, don't infer automatically if freq != 'infer': freq = to_offset(freq) else: freq_infer = True freq = None if periods is not None: if is_float(periods): periods = int(periods) elif not is_integer(periods): msg = 'periods must be a number, got {periods}' raise TypeError(msg.format(periods=periods)) if data is None and freq is None: raise ValueError("Must provide freq argument if no data is " "supplied") if data is None: return cls._generate(start, end, periods, name, freq, closed=closed) if unit is not None: data = to_timedelta(data, unit=unit, box=False) if not isinstance(data, (np.ndarray, Index, ABCSeries)): if is_scalar(data): raise ValueError('TimedeltaIndex() must be called with a ' 'collection of some kind, %s was passed' % repr(data)) # convert if not already if getattr(data, 'dtype', None) != _TD_DTYPE: data = to_timedelta(data, unit=unit, box=False) elif copy: data = np.array(data, copy=True) # check that we are matching freqs if verify_integrity and len(data) > 0: if freq is not None and not freq_infer: index = cls._simple_new(data, name=name) inferred = index.inferred_freq if inferred != freq.freqstr: on_freq = cls._generate( index[0], None, len(index), name, freq) if not np.array_equal(index.asi8, on_freq.asi8): raise ValueError('Inferred frequency {0} from passed ' 'timedeltas does not conform to ' 'passed frequency {1}' .format(inferred, freq.freqstr)) index.freq = freq return index if freq_infer: index = cls._simple_new(data, name=name) inferred = index.inferred_freq if inferred: index.freq = to_offset(inferred) return index return cls._simple_new(data, name=name, freq=freq) @classmethod def _generate(cls, start, end, periods, name, offset, closed=None): if com._count_not_none(start, end, periods) != 2: raise ValueError('Of the three parameters: start, end, and ' 'periods, exactly two must be specified') if start is not None: start = Timedelta(start) if end is not None: end = Timedelta(end) left_closed = False right_closed = False if start is None and end is None: if closed is not None: raise ValueError("Closed has to be None if not both of start" "and end are defined") if closed is None: left_closed = True right_closed = True elif closed == "left": left_closed = True elif closed == "right": right_closed = True else: raise ValueError("Closed has to be either 'left', 'right' or None") index = _generate_regular_range(start, end, periods, offset) index = cls._simple_new(index, name=name, freq=offset) if not left_closed: index = index[1:] if not right_closed: index = index[:-1] return index @property def _box_func(self): return lambda x: Timedelta(x, unit='ns') @classmethod def _simple_new(cls, values, name=None, freq=None, **kwargs): values = np.array(values, copy=False) if values.dtype == np.object_: values = array_to_timedelta64(values) if values.dtype != _TD_DTYPE: values = _ensure_int64(values).view(_TD_DTYPE) result = object.__new__(cls) result._data = values result.name = name result.freq = freq result._reset_identity() return result @property def _formatter_func(self): from pandas.io.formats.format import _get_format_timedelta64 return _get_format_timedelta64(self, box=True) def __setstate__(self, state): """Necessary for making this object picklable""" if isinstance(state, dict): super(TimedeltaIndex, self).__setstate__(state) else: raise Exception("invalid pickle state") _unpickle_compat = __setstate__ def _maybe_update_attributes(self, attrs): """ Update Index attributes (e.g. freq) depending on op """ freq = attrs.get('freq', None) if freq is not None: # no need to infer if freq is None attrs['freq'] = 'infer' return attrs def _add_delta(self, delta): if isinstance(delta, (Tick, timedelta, np.timedelta64)): new_values = self._add_delta_td(delta) name = self.name elif isinstance(delta, TimedeltaIndex): new_values = self._add_delta_tdi(delta) # update name when delta is index name = com._maybe_match_name(self, delta) else: raise ValueError("cannot add the type {0} to a TimedeltaIndex" .format(type(delta))) result = TimedeltaIndex(new_values, freq='infer', name=name) return result def _evaluate_with_timedelta_like(self, other, op, opstr): # allow division by a timedelta if opstr in ['__div__', '__truediv__', '__floordiv__']: if _is_convertible_to_td(other): other = Timedelta(other) if isna(other): raise NotImplementedError( "division by pd.NaT not implemented") i8 = self.asi8 if opstr in ['__floordiv__']: result = i8 // other.value else: result = op(i8, float(other.value)) result = self._maybe_mask_results(result, convert='float64') return Index(result, name=self.name, copy=False) return NotImplemented def _add_datelike(self, other): # adding a timedeltaindex to a datetimelike from pandas import Timestamp, DatetimeIndex if other is NaT: result = self._nat_new(box=False) else: other = Timestamp(other) i8 = self.asi8 result = checked_add_with_arr(i8, other.value, arr_mask=self._isnan) result = self._maybe_mask_results(result, fill_value=iNaT) return DatetimeIndex(result, name=self.name, copy=False) def _sub_datelike(self, other): from pandas import DatetimeIndex if other is NaT: result = self._nat_new(box=False) else: raise TypeError("cannot subtract a datelike from a TimedeltaIndex") return DatetimeIndex(result, name=self.name, copy=False) def _format_native_types(self, na_rep=u('NaT'), date_format=None, **kwargs): from pandas.io.formats.format import Timedelta64Formatter return Timedelta64Formatter(values=self, nat_rep=na_rep, justify='all').get_result() days = _field_accessor("days", "days", " Number of days for each element. ") seconds = _field_accessor("seconds", "seconds", " Number of seconds (>= 0 and less than 1 day) " "for each element. ") microseconds = _field_accessor("microseconds", "microseconds", "\nNumber of microseconds (>= 0 and less " "than 1 second) for each\nelement. ") nanoseconds = _field_accessor("nanoseconds", "nanoseconds", "\nNumber of nanoseconds (>= 0 and less " "than 1 microsecond) for each\nelement.\n") @property def components(self): """ Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame """ from pandas import DataFrame columns = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'] hasnans = self.hasnans if hasnans: def f(x): if isna(x): return [np.nan] * len(columns) return x.components else: def f(x): return x.components result = DataFrame([f(x) for x in self]) result.columns = columns if not hasnans: result = result.astype('int64') return result def total_seconds(self): """ Total duration of each element expressed in seconds. """ return Index(self._maybe_mask_results(1e-9 * self.asi8), name=self.name) def to_pytimedelta(self): """ Return TimedeltaIndex as object ndarray of datetime.timedelta objects Returns ------- datetimes : ndarray """ return libts.ints_to_pytimedelta(self.asi8) @Appender(_index_shared_docs['astype']) def astype(self, dtype, copy=True): dtype = pandas_dtype(dtype) if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype): # return an index (essentially this is division) result = self.values.astype(dtype, copy=copy) if self.hasnans: values = self._maybe_mask_results(result, convert='float64') return Index(values, name=self.name) return Index(result.astype('i8'), name=self.name) return super(TimedeltaIndex, self).astype(dtype, copy=copy) def union(self, other): """ Specialized union for TimedeltaIndex objects. If combine overlapping ranges with the same DateOffset, will be much faster than Index.union Parameters ---------- other : TimedeltaIndex or array-like Returns ------- y : Index or TimedeltaIndex """ self._assert_can_do_setop(other) if not isinstance(other, TimedeltaIndex): try: other = TimedeltaIndex(other) except (TypeError, ValueError): pass this, other = self, other if this._can_fast_union(other): return this._fast_union(other) else: result = Index.union(this, other) if isinstance(result, TimedeltaIndex): if result.freq is None: result.freq = to_offset(result.inferred_freq) return result def join(self, other, how='left', level=None, return_indexers=False, sort=False): """ See Index.join """ if _is_convertible_to_index(other): try: other = TimedeltaIndex(other) except (TypeError, ValueError): pass return Index.join(self, other, how=how, level=level, return_indexers=return_indexers, sort=sort) def _wrap_joined_index(self, joined, other): name = self.name if self.name == other.name else None if (isinstance(other, TimedeltaIndex) and self.freq == other.freq and self._can_fast_union(other)): joined = self._shallow_copy(joined, name=name) return joined else: return self._simple_new(joined, name) def _can_fast_union(self, other): if not isinstance(other, TimedeltaIndex): return False freq = self.freq if freq is None or freq != other.freq: return False if not self.is_monotonic or not other.is_monotonic: return False if len(self) == 0 or len(other) == 0: return True # to make our life easier, "sort" the two ranges if self[0] <= other[0]: left, right = self, other else: left, right = other, self right_start = right[0] left_end = left[-1] # Only need to "adjoin", not overlap return (right_start == left_end + freq) or right_start in left def _fast_union(self, other): if len(other) == 0: return self.view(type(self)) if len(self) == 0: return other.view(type(self)) # to make our life easier, "sort" the two ranges if self[0] <= other[0]: left, right = self, other else: left, right = other, self left_end = left[-1] right_end = right[-1] # concatenate if left_end < right_end: loc = right.searchsorted(left_end, side='right') right_chunk = right.values[loc:] dates = _concat._concat_compat((left.values, right_chunk)) return self._shallow_copy(dates) else: return left def _wrap_union_result(self, other, result): name = self.name if self.name == other.name else None return self._simple_new(result, name=name, freq=None) def intersection(self, other): """ Specialized intersection for TimedeltaIndex objects. May be much faster than Index.intersection Parameters ---------- other : TimedeltaIndex or array-like Returns ------- y : Index or TimedeltaIndex """ self._assert_can_do_setop(other) if not isinstance(other, TimedeltaIndex): try: other = TimedeltaIndex(other) except (TypeError, ValueError): pass result = Index.intersection(self, other) return result if len(self) == 0: return self if len(other) == 0: return other # to make our life easier, "sort" the two ranges if self[0] <= other[0]: left, right = self, other else: left, right = other, self end = min(left[-1], right[-1]) start = right[0] if end < start: return type(self)(data=[]) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left.values[lslice] return self._shallow_copy(left_chunk) def _maybe_promote(self, other): if other.inferred_type == 'timedelta': other = TimedeltaIndex(other) return self, other def get_value(self, series, key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ if _is_convertible_to_td(key): key = Timedelta(key) return self.get_value_maybe_box(series, key) try: return _maybe_box(self, Index.get_value(self, series, key), series, key) except KeyError: try: loc = self._get_string_slice(key) return series[loc] except (TypeError, ValueError, KeyError): pass try: return self.get_value_maybe_box(series, key) except (TypeError, ValueError, KeyError): raise KeyError(key) def get_value_maybe_box(self, series, key): if not isinstance(key, Timedelta): key = Timedelta(key) values = self._engine.get_value(_values_from_object(series), key) return _maybe_box(self, values, series, key) def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label Returns ------- loc : int """ if is_list_like(key): raise TypeError if isna(key): key = NaT if tolerance is not None: # try converting tolerance now, so errors don't get swallowed by # the try/except clauses below tolerance = self._convert_tolerance(tolerance, np.asarray(key)) if _is_convertible_to_td(key): key = Timedelta(key) return Index.get_loc(self, key, method, tolerance) try: return Index.get_loc(self, key, method, tolerance) except (KeyError, ValueError, TypeError): try: return self._get_string_slice(key) except (TypeError, KeyError, ValueError): pass try: stamp = Timedelta(key) return Index.get_loc(self, stamp, method, tolerance) except (KeyError, ValueError): raise KeyError(key) def _maybe_cast_slice_bound(self, label, side, kind): """ If label is a string, cast it to timedelta according to resolution. Parameters ---------- label : object side : {'left', 'right'} kind : {'ix', 'loc', 'getitem'} Returns ------- label : object """ assert kind in ['ix', 'loc', 'getitem', None] if isinstance(label, compat.string_types): parsed = _coerce_scalar_to_timedelta_type(label, box=True) lbound = parsed.round(parsed.resolution) if side == 'left': return lbound else: return (lbound + to_offset(parsed.resolution) - Timedelta(1, 'ns')) elif is_integer(label) or is_float(label): self._invalid_indexer('slice', label) return label def _get_string_slice(self, key, use_lhs=True, use_rhs=True): freq = getattr(self, 'freqstr', getattr(self, 'inferred_freq', None)) if is_integer(key) or is_float(key) or key is NaT: self._invalid_indexer('slice', key) loc = self._partial_td_slice(key, freq, use_lhs=use_lhs, use_rhs=use_rhs) return loc def _partial_td_slice(self, key, freq, use_lhs=True, use_rhs=True): # given a key, try to figure out a location for a partial slice if not isinstance(key, compat.string_types): return key raise NotImplementedError # TODO(wesm): dead code # parsed = _coerce_scalar_to_timedelta_type(key, box=True) # is_monotonic = self.is_monotonic # # figure out the resolution of the passed td # # and round to it # # t1 = parsed.round(reso) # t2 = t1 + to_offset(parsed.resolution) - Timedelta(1, 'ns') # stamps = self.asi8 # if is_monotonic: # # we are out of range # if (len(stamps) and ((use_lhs and t1.value < stamps[0] and # t2.value < stamps[0]) or # ((use_rhs and t1.value > stamps[-1] and # t2.value > stamps[-1])))): # raise KeyError # # a monotonic (sorted) series can be sliced # left = (stamps.searchsorted(t1.value, side='left') # if use_lhs else None) # right = (stamps.searchsorted(t2.value, side='right') # if use_rhs else None) # return slice(left, right) # lhs_mask = (stamps >= t1.value) if use_lhs else True # rhs_mask = (stamps <= t2.value) if use_rhs else True # # try to find a the dates # return (lhs_mask & rhs_mask).nonzero()[0] @Substitution(klass='TimedeltaIndex') @Appender(_shared_docs['searchsorted']) @deprecate_kwarg(old_arg_name='key', new_arg_name='value') def searchsorted(self, value, side='left', sorter=None): if isinstance(value, (np.ndarray, Index)): value = np.array(value, dtype=_TD_DTYPE, copy=False) else: value = _to_m8(value) return self.values.searchsorted(value, side=side, sorter=sorter) def is_type_compatible(self, typ): return typ == self.inferred_type or typ == 'timedelta' @property def inferred_type(self): return 'timedelta64' @property def dtype(self): return _TD_DTYPE @property def is_all_dates(self): return True def insert(self, loc, item): """ Make new Index inserting new item at location Parameters ---------- loc : int item : object if not either a Python datetime or a numpy integer-like, returned Index dtype will be object rather than datetime. Returns ------- new_index : Index """ # try to convert if possible if _is_convertible_to_td(item): try: item = Timedelta(item) except Exception: pass elif is_scalar(item) and isna(item): # GH 18295 item = self._na_value freq = None if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)): # check freq can be preserved on edge cases if self.freq is not None: if ((loc == 0 or loc == -len(self)) and item + self.freq == self[0]): freq = self.freq elif (loc == len(self)) and item - self.freq == self[-1]: freq = self.freq item = _to_m8(item) try: new_tds = np.concatenate((self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)) return TimedeltaIndex(new_tds, name=self.name, freq=freq) except (AttributeError, TypeError): # fall back to object index if isinstance(item, compat.string_types): return self.astype(object).insert(loc, item) raise TypeError( "cannot insert TimedeltaIndex with incompatible label") def delete(self, loc): """ Make a new DatetimeIndex with passed location(s) deleted. Parameters ---------- loc: int, slice or array of ints Indicate which sub-arrays to remove. Returns ------- new_index : TimedeltaIndex """ new_tds = np.delete(self.asi8, loc) freq = 'infer' if is_integer(loc): if loc in (0, -len(self), -1, len(self) - 1): freq = self.freq else: if is_list_like(loc): loc = lib.maybe_indices_to_slice( _ensure_int64(np.array(loc)), len(self)) if isinstance(loc, slice) and loc.step in (1, None): if (loc.start in (0, None) or loc.stop in (len(self), None)): freq = self.freq return TimedeltaIndex(new_tds, name=self.name, freq=freq) TimedeltaIndex._add_comparison_methods() TimedeltaIndex._add_numeric_methods() TimedeltaIndex._add_logical_methods_disabled() TimedeltaIndex._add_datetimelike_methods() def _is_convertible_to_index(other): """ return a boolean whether I can attempt conversion to a TimedeltaIndex """ if isinstance(other, TimedeltaIndex): return True elif (len(other) > 0 and other.inferred_type not in ('floating', 'mixed-integer', 'integer', 'mixed-integer-float', 'mixed')): return True return False def _is_convertible_to_td(key): return isinstance(key, (DateOffset, timedelta, Timedelta, np.timedelta64, compat.string_types)) def _to_m8(key): """ Timedelta-like => dt64 """ if not isinstance(key, Timedelta): # this also converts strings key = Timedelta(key) # return an type that can be compared return np.int64(key.value).view(_TD_DTYPE) def _generate_regular_range(start, end, periods, offset): stride = offset.nanos if periods is None: b = Timedelta(start).value e = Timedelta(end).value e += stride - e % stride elif start is not None: b = Timedelta(start).value e = b + periods * stride elif end is not None: e = Timedelta(end).value + stride b = e - periods * stride else: raise ValueError("at least 'start' or 'end' should be specified " "if a 'period' is given.") data = np.arange(b, e, stride, dtype=np.int64) data = TimedeltaIndex._simple_new(data, None) return data def timedelta_range(start=None, end=None, periods=None, freq='D', name=None, closed=None): """ Return a fixed frequency TimedeltaIndex, with day as the default frequency Parameters ---------- start : string or timedelta-like, default None Left bound for generating timedeltas end : string or timedelta-like, default None Right bound for generating timedeltas periods : integer, default None Number of periods to generate freq : string or DateOffset, default 'D' (calendar daily) Frequency strings can have multiples, e.g. '5H' name : string, default None Name of the resulting TimedeltaIndex closed : string, default None Make the interval closed with respect to the given frequency to the 'left', 'right', or both sides (None) Returns ------- rng : TimedeltaIndex Notes ----- Of the three parameters: ``start``, ``end``, and ``periods``, exactly two must be specified. To learn more about the frequency strings, please see `this link <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`__. Examples -------- >>> pd.timedelta_range(start='1 day', periods=4) TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq='D') The ``closed`` parameter specifies which endpoint is included. The default behavior is to include both endpoints. >>> pd.timedelta_range(start='1 day', periods=4, closed='right') TimedeltaIndex(['2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq='D') The ``freq`` parameter specifies the frequency of the TimedeltaIndex. Only fixed frequencies can be passed, non-fixed frequencies such as 'M' (month end) will raise. >>> pd.timedelta_range(start='1 day', end='2 days', freq='6H') TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00', '1 days 18:00:00', '2 days 00:00:00'], dtype='timedelta64[ns]', freq='6H') """ return TimedeltaIndex(start=start, end=end, periods=periods, freq=freq, name=name, closed=closed)
# -*- coding: utf-8 -*- from __future__ import print_function import pytest from datetime import datetime from numpy import random import numpy as np from pandas.compat import lrange, lzip, u from pandas import (compat, DataFrame, Series, Index, MultiIndex, date_range, isna) import pandas as pd from pandas.util.testing import assert_frame_equal from pandas.errors import PerformanceWarning import pandas.util.testing as tm from pandas.tests.frame.common import TestData class TestDataFrameSelectReindex(TestData): # These are specific reindex-based tests; other indexing tests should go in # test_indexing def test_drop_names(self): df = DataFrame([[1, 2, 3], [3, 4, 5], [5, 6, 7]], index=['a', 'b', 'c'], columns=['d', 'e', 'f']) df.index.name, df.columns.name = 'first', 'second' df_dropped_b = df.drop('b') df_dropped_e = df.drop('e', axis=1) df_inplace_b, df_inplace_e = df.copy(), df.copy() df_inplace_b.drop('b', inplace=True) df_inplace_e.drop('e', axis=1, inplace=True) for obj in (df_dropped_b, df_dropped_e, df_inplace_b, df_inplace_e): assert obj.index.name == 'first' assert obj.columns.name == 'second' assert list(df.columns) == ['d', 'e', 'f'] pytest.raises(ValueError, df.drop, ['g']) pytest.raises(ValueError, df.drop, ['g'], 1) # errors = 'ignore' dropped = df.drop(['g'], errors='ignore') expected = Index(['a', 'b', 'c'], name='first') tm.assert_index_equal(dropped.index, expected) dropped = df.drop(['b', 'g'], errors='ignore') expected = Index(['a', 'c'], name='first') tm.assert_index_equal(dropped.index, expected) dropped = df.drop(['g'], axis=1, errors='ignore') expected = Index(['d', 'e', 'f'], name='second') tm.assert_index_equal(dropped.columns, expected) dropped = df.drop(['d', 'g'], axis=1, errors='ignore') expected = Index(['e', 'f'], name='second') tm.assert_index_equal(dropped.columns, expected) # GH 16398 dropped = df.drop([], errors='ignore') expected = Index(['a', 'b', 'c'], name='first') tm.assert_index_equal(dropped.index, expected) def test_drop_col_still_multiindex(self): arrays = [['a', 'b', 'c', 'top'], ['', '', '', 'OD'], ['', '', '', 'wx']] tuples = sorted(zip(*arrays)) index = MultiIndex.from_tuples(tuples) df = DataFrame(np.random.randn(3, 4), columns=index) del df[('a', '', '')] assert(isinstance(df.columns, MultiIndex)) def test_drop(self): simple = DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}) assert_frame_equal(simple.drop("A", axis=1), simple[['B']]) assert_frame_equal(simple.drop(["A", "B"], axis='columns'), simple[[]]) assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :]) assert_frame_equal(simple.drop( [0, 3], axis='index'), simple.loc[[1, 2], :]) pytest.raises(ValueError, simple.drop, 5) pytest.raises(ValueError, simple.drop, 'C', 1) pytest.raises(ValueError, simple.drop, [1, 5]) pytest.raises(ValueError, simple.drop, ['A', 'C'], 1) # errors = 'ignore' assert_frame_equal(simple.drop(5, errors='ignore'), simple) assert_frame_equal(simple.drop([0, 5], errors='ignore'), simple.loc[[1, 2, 3], :]) assert_frame_equal(simple.drop('C', axis=1, errors='ignore'), simple) assert_frame_equal(simple.drop(['A', 'C'], axis=1, errors='ignore'), simple[['B']]) # non-unique - wheee! nu_df = DataFrame(lzip(range(3), range(-3, 1), list('abc')), columns=['a', 'a', 'b']) assert_frame_equal(nu_df.drop('a', axis=1), nu_df[['b']]) assert_frame_equal(nu_df.drop('b', axis='columns'), nu_df['a']) assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 nu_df = nu_df.set_index(pd.Index(['X', 'Y', 'X'])) nu_df.columns = list('abc') assert_frame_equal(nu_df.drop('X', axis='rows'), nu_df.loc[["Y"], :]) assert_frame_equal(nu_df.drop(['X', 'Y'], axis=0), nu_df.loc[[], :]) # inplace cache issue # GH 5628 df = pd.DataFrame(np.random.randn(10, 3), columns=list('abc')) expected = df[~(df.b > 0)] df.drop(labels=df[df.b > 0].index, inplace=True) assert_frame_equal(df, expected) def test_drop_multiindex_not_lexsorted(self): # GH 11640 # define the lexsorted version lexsorted_mi = MultiIndex.from_tuples( [('a', ''), ('b1', 'c1'), ('b2', 'c2')], names=['b', 'c']) lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) assert lexsorted_df.columns.is_lexsorted() # define the non-lexsorted version not_lexsorted_df = DataFrame(columns=['a', 'b', 'c', 'd'], data=[[1, 'b1', 'c1', 3], [1, 'b2', 'c2', 4]]) not_lexsorted_df = not_lexsorted_df.pivot_table( index='a', columns=['b', 'c'], values='d') not_lexsorted_df = not_lexsorted_df.reset_index() assert not not_lexsorted_df.columns.is_lexsorted() # compare the results tm.assert_frame_equal(lexsorted_df, not_lexsorted_df) expected = lexsorted_df.drop('a', axis=1) with tm.assert_produces_warning(PerformanceWarning): result = not_lexsorted_df.drop('a', axis=1) tm.assert_frame_equal(result, expected) def test_drop_api_equivalence(self): # equivalence of the labels/axis and index/columns API's (GH12392) df = DataFrame([[1, 2, 3], [3, 4, 5], [5, 6, 7]], index=['a', 'b', 'c'], columns=['d', 'e', 'f']) res1 = df.drop('a') res2 = df.drop(index='a') tm.assert_frame_equal(res1, res2) res1 = df.drop('d', 1) res2 = df.drop(columns='d') tm.assert_frame_equal(res1, res2) res1 = df.drop(labels='e', axis=1) res2 = df.drop(columns='e') tm.assert_frame_equal(res1, res2) res1 = df.drop(['a'], axis=0) res2 = df.drop(index=['a']) tm.assert_frame_equal(res1, res2) res1 = df.drop(['a'], axis=0).drop(['d'], axis=1) res2 = df.drop(index=['a'], columns=['d']) tm.assert_frame_equal(res1, res2) with pytest.raises(ValueError): df.drop(labels='a', index='b') with pytest.raises(ValueError): df.drop(labels='a', columns='b') with pytest.raises(ValueError): df.drop(axis=1) def test_merge_join_different_levels(self): # GH 9455 # first dataframe df1 = DataFrame(columns=['a', 'b'], data=[[1, 11], [0, 22]]) # second dataframe columns = MultiIndex.from_tuples([('a', ''), ('c', 'c1')]) df2 = DataFrame(columns=columns, data=[[1, 33], [0, 44]]) # merge columns = ['a', 'b', ('c', 'c1')] expected = DataFrame(columns=columns, data=[[1, 11, 33], [0, 22, 44]]) with tm.assert_produces_warning(UserWarning): result = pd.merge(df1, df2, on='a') tm.assert_frame_equal(result, expected) # join, see discussion in GH 12219 columns = ['a', 'b', ('a', ''), ('c', 'c1')] expected = DataFrame(columns=columns, data=[[1, 11, 0, 44], [0, 22, 1, 33]]) with tm.assert_produces_warning(UserWarning): result = df1.join(df2, on='a') tm.assert_frame_equal(result, expected) def test_reindex(self): newFrame = self.frame.reindex(self.ts1.index) for col in newFrame.columns: for idx, val in compat.iteritems(newFrame[col]): if idx in self.frame.index: if np.isnan(val): assert np.isnan(self.frame[col][idx]) else: assert val == self.frame[col][idx] else: assert np.isnan(val) for col, series in compat.iteritems(newFrame): assert tm.equalContents(series.index, newFrame.index) emptyFrame = self.frame.reindex(Index([])) assert len(emptyFrame.index) == 0 # Cython code should be unit-tested directly nonContigFrame = self.frame.reindex(self.ts1.index[::2]) for col in nonContigFrame.columns: for idx, val in compat.iteritems(nonContigFrame[col]): if idx in self.frame.index: if np.isnan(val): assert np.isnan(self.frame[col][idx]) else: assert val == self.frame[col][idx] else: assert np.isnan(val) for col, series in compat.iteritems(nonContigFrame): assert tm.equalContents(series.index, nonContigFrame.index) # corner cases # Same index, copies values but not index if copy=False newFrame = self.frame.reindex(self.frame.index, copy=False) assert newFrame.index is self.frame.index # length zero newFrame = self.frame.reindex([]) assert newFrame.empty assert len(newFrame.columns) == len(self.frame.columns) # length zero with columns reindexed with non-empty index newFrame = self.frame.reindex([]) newFrame = newFrame.reindex(self.frame.index) assert len(newFrame.index) == len(self.frame.index) assert len(newFrame.columns) == len(self.frame.columns) # pass non-Index newFrame = self.frame.reindex(list(self.ts1.index)) tm.assert_index_equal(newFrame.index, self.ts1.index) # copy with no axes result = self.frame.reindex() assert_frame_equal(result, self.frame) assert result is not self.frame def test_reindex_nan(self): df = pd.DataFrame([[1, 2], [3, 5], [7, 11], [9, 23]], index=[2, np.nan, 1, 5], columns=['joe', 'jim']) i, j = [np.nan, 5, 5, np.nan, 1, 2, np.nan], [1, 3, 3, 1, 2, 0, 1] assert_frame_equal(df.reindex(i), df.iloc[j]) df.index = df.index.astype('object') assert_frame_equal(df.reindex(i), df.iloc[j], check_index_type=False) # GH10388 df = pd.DataFrame({'other': ['a', 'b', np.nan, 'c'], 'date': ['2015-03-22', np.nan, '2012-01-08', np.nan], 'amount': [2, 3, 4, 5]}) df['date'] = pd.to_datetime(df.date) df['delta'] = (pd.to_datetime('2015-06-18') - df['date']).shift(1) left = df.set_index(['delta', 'other', 'date']).reset_index() right = df.reindex(columns=['delta', 'other', 'date', 'amount']) assert_frame_equal(left, right) def test_reindex_name_remains(self): s = Series(random.rand(10)) df = DataFrame(s, index=np.arange(len(s))) i = Series(np.arange(10), name='iname') df = df.reindex(i) assert df.index.name == 'iname' df = df.reindex(Index(np.arange(10), name='tmpname')) assert df.index.name == 'tmpname' s = Series(random.rand(10)) df = DataFrame(s.T, index=np.arange(len(s))) i = Series(np.arange(10), name='iname') df = df.reindex(columns=i) assert df.columns.name == 'iname' def test_reindex_int(self): smaller = self.intframe.reindex(self.intframe.index[::2]) assert smaller['A'].dtype == np.int64 bigger = smaller.reindex(self.intframe.index) assert bigger['A'].dtype == np.float64 smaller = self.intframe.reindex(columns=['A', 'B']) assert smaller['A'].dtype == np.int64 def test_reindex_like(self): other = self.frame.reindex(index=self.frame.index[:10], columns=['C', 'B']) assert_frame_equal(other, self.frame.reindex_like(other)) def test_reindex_columns(self): new_frame = self.frame.reindex(columns=['A', 'B', 'E']) tm.assert_series_equal(new_frame['B'], self.frame['B']) assert np.isnan(new_frame['E']).all() assert 'C' not in new_frame # Length zero new_frame = self.frame.reindex(columns=[]) assert new_frame.empty def test_reindex_columns_method(self): # GH 14992, reindexing over columns ignored method df = DataFrame(data=[[11, 12, 13], [21, 22, 23], [31, 32, 33]], index=[1, 2, 4], columns=[1, 2, 4], dtype=float) # default method result = df.reindex(columns=range(6)) expected = DataFrame(data=[[np.nan, 11, 12, np.nan, 13, np.nan], [np.nan, 21, 22, np.nan, 23, np.nan], [np.nan, 31, 32, np.nan, 33, np.nan]], index=[1, 2, 4], columns=range(6), dtype=float) assert_frame_equal(result, expected) # method='ffill' result = df.reindex(columns=range(6), method='ffill') expected = DataFrame(data=[[np.nan, 11, 12, 12, 13, 13], [np.nan, 21, 22, 22, 23, 23], [np.nan, 31, 32, 32, 33, 33]], index=[1, 2, 4], columns=range(6), dtype=float) assert_frame_equal(result, expected) # method='bfill' result = df.reindex(columns=range(6), method='bfill') expected = DataFrame(data=[[11, 11, 12, 13, 13, np.nan], [21, 21, 22, 23, 23, np.nan], [31, 31, 32, 33, 33, np.nan]], index=[1, 2, 4], columns=range(6), dtype=float) assert_frame_equal(result, expected) def test_reindex_axes(self): # GH 3317, reindexing by both axes loses freq of the index df = DataFrame(np.ones((3, 3)), index=[datetime(2012, 1, 1), datetime(2012, 1, 2), datetime(2012, 1, 3)], columns=['a', 'b', 'c']) time_freq = date_range('2012-01-01', '2012-01-03', freq='d') some_cols = ['a', 'b'] index_freq = df.reindex(index=time_freq).index.freq both_freq = df.reindex(index=time_freq, columns=some_cols).index.freq seq_freq = df.reindex(index=time_freq).reindex( columns=some_cols).index.freq assert index_freq == both_freq assert index_freq == seq_freq def test_reindex_fill_value(self): df = DataFrame(np.random.randn(10, 4)) # axis=0 result = df.reindex(lrange(15)) assert np.isnan(result.values[-5:]).all() result = df.reindex(lrange(15), fill_value=0) expected = df.reindex(lrange(15)).fillna(0) assert_frame_equal(result, expected) # axis=1 result = df.reindex(columns=lrange(5), fill_value=0.) expected = df.copy() expected[4] = 0. assert_frame_equal(result, expected) result = df.reindex(columns=lrange(5), fill_value=0) expected = df.copy() expected[4] = 0 assert_frame_equal(result, expected) result = df.reindex(columns=lrange(5), fill_value='foo') expected = df.copy() expected[4] = 'foo' assert_frame_equal(result, expected) # reindex_axis with tm.assert_produces_warning(FutureWarning): result = df.reindex_axis(lrange(15), fill_value=0., axis=0) expected = df.reindex(lrange(15)).fillna(0) assert_frame_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = df.reindex_axis(lrange(5), fill_value=0., axis=1) expected = df.reindex(columns=lrange(5)).fillna(0) assert_frame_equal(result, expected) # other dtypes df['foo'] = 'foo' result = df.reindex(lrange(15), fill_value=0) expected = df.reindex(lrange(15)).fillna(0) assert_frame_equal(result, expected) def test_reindex_dups(self): # GH4746, reindex on duplicate index error messages arr = np.random.randn(10) df = DataFrame(arr, index=[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]) # set index is ok result = df.copy() result.index = list(range(len(df))) expected = DataFrame(arr, index=list(range(len(df)))) assert_frame_equal(result, expected) # reindex fails pytest.raises(ValueError, df.reindex, index=list(range(len(df)))) def test_reindex_axis_style(self): # https://github.com/pandas-dev/pandas/issues/12392 df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) expected = pd.DataFrame({"A": [1, 2, np.nan], "B": [4, 5, np.nan]}, index=[0, 1, 3]) result = df.reindex([0, 1, 3]) assert_frame_equal(result, expected) result = df.reindex([0, 1, 3], axis=0) assert_frame_equal(result, expected) result = df.reindex([0, 1, 3], axis='index') assert_frame_equal(result, expected) def test_reindex_positional_warns(self): # https://github.com/pandas-dev/pandas/issues/12392 df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) expected = pd.DataFrame({"A": [1., 2], 'B': [4., 5], "C": [np.nan, np.nan]}) with tm.assert_produces_warning(FutureWarning): result = df.reindex([0, 1], ['A', 'B', 'C']) assert_frame_equal(result, expected) def test_reindex_axis_style_raises(self): # https://github.com/pandas-dev/pandas/issues/12392 df = pd.DataFrame({"A": [1, 2, 3], 'B': [4, 5, 6]}) with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex([0, 1], ['A'], axis=1) with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex([0, 1], ['A'], axis='index') with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(index=[0, 1], axis='index') with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(index=[0, 1], axis='columns') with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(columns=[0, 1], axis='columns') with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(index=[0, 1], columns=[0, 1], axis='columns') with tm.assert_raises_regex(TypeError, 'Cannot specify all'): df.reindex([0, 1], [0], ['A']) # Mixing styles with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(index=[0, 1], axis='index') with tm.assert_raises_regex(TypeError, "Cannot specify both 'axis'"): df.reindex(index=[0, 1], axis='columns') # Duplicates with tm.assert_raises_regex(TypeError, "multiple values"): df.reindex([0, 1], labels=[0, 1]) def test_reindex_single_named_indexer(self): # https://github.com/pandas-dev/pandas/issues/12392 df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}) result = df.reindex([0, 1], columns=['A']) expected = pd.DataFrame({"A": [1, 2]}) assert_frame_equal(result, expected) def test_reindex_api_equivalence(self): # https://github.com/pandas-dev/pandas/issues/12392 # equivalence of the labels/axis and index/columns API's df = DataFrame([[1, 2, 3], [3, 4, 5], [5, 6, 7]], index=['a', 'b', 'c'], columns=['d', 'e', 'f']) res1 = df.reindex(['b', 'a']) res2 = df.reindex(index=['b', 'a']) res3 = df.reindex(labels=['b', 'a']) res4 = df.reindex(labels=['b', 'a'], axis=0) res5 = df.reindex(['b', 'a'], axis=0) for res in [res2, res3, res4, res5]: tm.assert_frame_equal(res1, res) res1 = df.reindex(columns=['e', 'd']) res2 = df.reindex(['e', 'd'], axis=1) res3 = df.reindex(labels=['e', 'd'], axis=1) for res in [res2, res3]: tm.assert_frame_equal(res1, res) with tm.assert_produces_warning(FutureWarning) as m: res1 = df.reindex(['b', 'a'], ['e', 'd']) assert 'reindex' in str(m[0].message) res2 = df.reindex(columns=['e', 'd'], index=['b', 'a']) res3 = df.reindex(labels=['b', 'a'], axis=0).reindex(labels=['e', 'd'], axis=1) for res in [res2, res3]: tm.assert_frame_equal(res1, res) def test_align(self): af, bf = self.frame.align(self.frame) assert af._data is not self.frame._data af, bf = self.frame.align(self.frame, copy=False) assert af._data is self.frame._data # axis = 0 other = self.frame.iloc[:-5, :3] af, bf = self.frame.align(other, axis=0, fill_value=-1) tm.assert_index_equal(bf.columns, other.columns) # test fill value join_idx = self.frame.index.join(other.index) diff_a = self.frame.index.difference(join_idx) diff_b = other.index.difference(join_idx) diff_a_vals = af.reindex(diff_a).values diff_b_vals = bf.reindex(diff_b).values assert (diff_a_vals == -1).all() af, bf = self.frame.align(other, join='right', axis=0) tm.assert_index_equal(bf.columns, other.columns) tm.assert_index_equal(bf.index, other.index) tm.assert_index_equal(af.index, other.index) # axis = 1 other = self.frame.iloc[:-5, :3].copy() af, bf = self.frame.align(other, axis=1) tm.assert_index_equal(bf.columns, self.frame.columns) tm.assert_index_equal(bf.index, other.index) # test fill value join_idx = self.frame.index.join(other.index) diff_a = self.frame.index.difference(join_idx) diff_b = other.index.difference(join_idx) diff_a_vals = af.reindex(diff_a).values # TODO(wesm): unused? diff_b_vals = bf.reindex(diff_b).values # noqa assert (diff_a_vals == -1).all() af, bf = self.frame.align(other, join='inner', axis=1) tm.assert_index_equal(bf.columns, other.columns) af, bf = self.frame.align(other, join='inner', axis=1, method='pad') tm.assert_index_equal(bf.columns, other.columns) # test other non-float types af, bf = self.intframe.align(other, join='inner', axis=1, method='pad') tm.assert_index_equal(bf.columns, other.columns) af, bf = self.mixed_frame.align(self.mixed_frame, join='inner', axis=1, method='pad') tm.assert_index_equal(bf.columns, self.mixed_frame.columns) af, bf = self.frame.align(other.iloc[:, 0], join='inner', axis=1, method=None, fill_value=None) tm.assert_index_equal(bf.index, Index([])) af, bf = self.frame.align(other.iloc[:, 0], join='inner', axis=1, method=None, fill_value=0) tm.assert_index_equal(bf.index, Index([])) # mixed floats/ints af, bf = self.mixed_float.align(other.iloc[:, 0], join='inner', axis=1, method=None, fill_value=0) tm.assert_index_equal(bf.index, Index([])) af, bf = self.mixed_int.align(other.iloc[:, 0], join='inner', axis=1, method=None, fill_value=0) tm.assert_index_equal(bf.index, Index([])) # Try to align DataFrame to Series along bad axis with pytest.raises(ValueError): self.frame.align(af.iloc[0, :3], join='inner', axis=2) # align dataframe to series with broadcast or not idx = self.frame.index s = Series(range(len(idx)), index=idx) left, right = self.frame.align(s, axis=0) tm.assert_index_equal(left.index, self.frame.index) tm.assert_index_equal(right.index, self.frame.index) assert isinstance(right, Series) left, right = self.frame.align(s, broadcast_axis=1) tm.assert_index_equal(left.index, self.frame.index) expected = {} for c in self.frame.columns: expected[c] = s expected = DataFrame(expected, index=self.frame.index, columns=self.frame.columns) tm.assert_frame_equal(right, expected) # see gh-9558 df = DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) result = df[df['a'] == 2] expected = DataFrame([[2, 5]], index=[1], columns=['a', 'b']) tm.assert_frame_equal(result, expected) result = df.where(df['a'] == 2, 0) expected = DataFrame({'a': [0, 2, 0], 'b': [0, 5, 0]}) tm.assert_frame_equal(result, expected) def _check_align(self, a, b, axis, fill_axis, how, method, limit=None): aa, ab = a.align(b, axis=axis, join=how, method=method, limit=limit, fill_axis=fill_axis) join_index, join_columns = None, None ea, eb = a, b if axis is None or axis == 0: join_index = a.index.join(b.index, how=how) ea = ea.reindex(index=join_index) eb = eb.reindex(index=join_index) if axis is None or axis == 1: join_columns = a.columns.join(b.columns, how=how) ea = ea.reindex(columns=join_columns) eb = eb.reindex(columns=join_columns) ea = ea.fillna(axis=fill_axis, method=method, limit=limit) eb = eb.fillna(axis=fill_axis, method=method, limit=limit) assert_frame_equal(aa, ea) assert_frame_equal(ab, eb) def test_align_fill_method_inner(self): for meth in ['pad', 'bfill']: for ax in [0, 1, None]: for fax in [0, 1]: self._check_align_fill('inner', meth, ax, fax) def test_align_fill_method_outer(self): for meth in ['pad', 'bfill']: for ax in [0, 1, None]: for fax in [0, 1]: self._check_align_fill('outer', meth, ax, fax) def test_align_fill_method_left(self): for meth in ['pad', 'bfill']: for ax in [0, 1, None]: for fax in [0, 1]: self._check_align_fill('left', meth, ax, fax) def test_align_fill_method_right(self): for meth in ['pad', 'bfill']: for ax in [0, 1, None]: for fax in [0, 1]: self._check_align_fill('right', meth, ax, fax) def _check_align_fill(self, kind, meth, ax, fax): left = self.frame.iloc[0:4, :10] right = self.frame.iloc[2:, 6:] empty = self.frame.iloc[:0, :0] self._check_align(left, right, axis=ax, fill_axis=fax, how=kind, method=meth) self._check_align(left, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1) # empty left self._check_align(empty, right, axis=ax, fill_axis=fax, how=kind, method=meth) self._check_align(empty, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1) # empty right self._check_align(left, empty, axis=ax, fill_axis=fax, how=kind, method=meth) self._check_align(left, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1) # both empty self._check_align(empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth) self._check_align(empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1) def test_align_int_fill_bug(self): # GH #910 X = np.arange(10 * 10, dtype='float64').reshape(10, 10) Y = np.ones((10, 1), dtype=int) df1 = DataFrame(X) df1['0.X'] = Y.squeeze() df2 = df1.astype(float) result = df1 - df1.mean() expected = df2 - df2.mean() assert_frame_equal(result, expected) def test_align_multiindex(self): # GH 10665 # same test cases as test_align_multiindex in test_series.py midx = pd.MultiIndex.from_product([range(2), range(3), range(2)], names=('a', 'b', 'c')) idx = pd.Index(range(2), name='b') df1 = pd.DataFrame(np.arange(12, dtype='int64'), index=midx) df2 = pd.DataFrame(np.arange(2, dtype='int64'), index=idx) # these must be the same results (but flipped) res1l, res1r = df1.align(df2, join='left') res2l, res2r = df2.align(df1, join='right') expl = df1 assert_frame_equal(expl, res1l) assert_frame_equal(expl, res2r) expr = pd.DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx) assert_frame_equal(expr, res1r) assert_frame_equal(expr, res2l) res1l, res1r = df1.align(df2, join='right') res2l, res2r = df2.align(df1, join='left') exp_idx = pd.MultiIndex.from_product([range(2), range(2), range(2)], names=('a', 'b', 'c')) expl = pd.DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx) assert_frame_equal(expl, res1l) assert_frame_equal(expl, res2r) expr = pd.DataFrame([0, 0, 1, 1] * 2, index=exp_idx) assert_frame_equal(expr, res1r) assert_frame_equal(expr, res2l) def test_align_series_combinations(self): df = pd.DataFrame({'a': [1, 3, 5], 'b': [1, 3, 5]}, index=list('ACE')) s = pd.Series([1, 2, 4], index=list('ABD'), name='x') # frame + series res1, res2 = df.align(s, axis=0) exp1 = pd.DataFrame({'a': [1, np.nan, 3, np.nan, 5], 'b': [1, np.nan, 3, np.nan, 5]}, index=list('ABCDE')) exp2 = pd.Series([1, 2, np.nan, 4, np.nan], index=list('ABCDE'), name='x') tm.assert_frame_equal(res1, exp1) tm.assert_series_equal(res2, exp2) # series + frame res1, res2 = s.align(df) tm.assert_series_equal(res1, exp2) tm.assert_frame_equal(res2, exp1) def test_filter(self): # Items filtered = self.frame.filter(['A', 'B', 'E']) assert len(filtered.columns) == 2 assert 'E' not in filtered filtered = self.frame.filter(['A', 'B', 'E'], axis='columns') assert len(filtered.columns) == 2 assert 'E' not in filtered # Other axis idx = self.frame.index[0:4] filtered = self.frame.filter(idx, axis='index') expected = self.frame.reindex(index=idx) tm.assert_frame_equal(filtered, expected) # like fcopy = self.frame.copy() fcopy['AA'] = 1 filtered = fcopy.filter(like='A') assert len(filtered.columns) == 2 assert 'AA' in filtered # like with ints in column names df = DataFrame(0., index=[0, 1, 2], columns=[0, 1, '_A', '_B']) filtered = df.filter(like='_') assert len(filtered.columns) == 2 # regex with ints in column names # from PR #10384 df = DataFrame(0., index=[0, 1, 2], columns=['A1', 1, 'B', 2, 'C']) expected = DataFrame( 0., index=[0, 1, 2], columns=pd.Index([1, 2], dtype=object)) filtered = df.filter(regex='^[0-9]+$') tm.assert_frame_equal(filtered, expected) expected = DataFrame(0., index=[0, 1, 2], columns=[0, '0', 1, '1']) # shouldn't remove anything filtered = expected.filter(regex='^[0-9]+$') tm.assert_frame_equal(filtered, expected) # pass in None with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter() with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter(items=None) with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter(axis=1) # test mutually exclusive arguments with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', like='bbi') with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', axis=1) with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$') with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi', axis=0) with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi') # objects filtered = self.mixed_frame.filter(like='foo') assert 'foo' in filtered # unicode columns, won't ascii-encode df = self.frame.rename(columns={'B': u('\u2202')}) filtered = df.filter(like='C') assert 'C' in filtered def test_filter_regex_search(self): fcopy = self.frame.copy() fcopy['AA'] = 1 # regex filtered = fcopy.filter(regex='[A]+') assert len(filtered.columns) == 2 assert 'AA' in filtered # doesn't have to be at beginning df = DataFrame({'aBBa': [1, 2], 'BBaBB': [1, 2], 'aCCa': [1, 2], 'aCCaBB': [1, 2]}) result = df.filter(regex='BB') exp = df[[x for x in df.columns if 'BB' in x]] assert_frame_equal(result, exp) @pytest.mark.parametrize('name,expected', [ ('a', DataFrame({u'a': [1, 2]})), (u'a', DataFrame({u'a': [1, 2]})), (u'あ', DataFrame({u'あ': [3, 4]})) ]) def test_filter_unicode(self, name, expected): # GH13101 df = DataFrame({u'a': [1, 2], u'あ': [3, 4]}) assert_frame_equal(df.filter(like=name), expected) assert_frame_equal(df.filter(regex=name), expected) @pytest.mark.parametrize('name', ['a', u'a']) def test_filter_bytestring(self, name): # GH13101 df = DataFrame({b'a': [1, 2], b'b': [3, 4]}) expected = DataFrame({b'a': [1, 2]}) assert_frame_equal(df.filter(like=name), expected) assert_frame_equal(df.filter(regex=name), expected) def test_filter_corner(self): empty = DataFrame() result = empty.filter([]) assert_frame_equal(result, empty) result = empty.filter(like='foo') assert_frame_equal(result, empty) def test_select(self): # deprecated: gh-12410 f = lambda x: x.weekday() == 2 index = self.tsframe.index[[f(x) for x in self.tsframe.index]] expected_weekdays = self.tsframe.reindex(index=index) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = self.tsframe.select(f, axis=0) assert_frame_equal(result, expected_weekdays) result = self.frame.select(lambda x: x in ('B', 'D'), axis=1) expected = self.frame.reindex(columns=['B', 'D']) assert_frame_equal(result, expected, check_names=False) # replacement f = lambda x: x.weekday == 2 result = self.tsframe.loc(axis=0)[f(self.tsframe.index)] assert_frame_equal(result, expected_weekdays) crit = lambda x: x in ['B', 'D'] result = self.frame.loc(axis=1)[(self.frame.columns.map(crit))] expected = self.frame.reindex(columns=['B', 'D']) assert_frame_equal(result, expected, check_names=False) # doc example df = DataFrame({'A': [1, 2, 3]}, index=['foo', 'bar', 'baz']) crit = lambda x: x in ['bar', 'baz'] with tm.assert_produces_warning(FutureWarning): expected = df.select(crit) result = df.loc[df.index.map(crit)] assert_frame_equal(result, expected, check_names=False) def test_take(self): # homogeneous order = [3, 1, 2, 0] for df in [self.frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ['D', 'B', 'C', 'A']] assert_frame_equal(result, expected, check_names=False) # negative indices order = [2, 1, -1] for df in [self.frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) assert_frame_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = df.take(order, convert=True, axis=0) assert_frame_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = df.take(order, convert=False, axis=0) assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ['C', 'B', 'D']] assert_frame_equal(result, expected, check_names=False) # illegal indices pytest.raises(IndexError, df.take, [3, 1, 2, 30], axis=0) pytest.raises(IndexError, df.take, [3, 1, 2, -31], axis=0) pytest.raises(IndexError, df.take, [3, 1, 2, 5], axis=1) pytest.raises(IndexError, df.take, [3, 1, 2, -5], axis=1) # mixed-dtype order = [4, 1, 2, 0, 3] for df in [self.mixed_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ['foo', 'B', 'C', 'A', 'D']] assert_frame_equal(result, expected) # negative indices order = [4, 1, -2] for df in [self.mixed_frame]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ['foo', 'B', 'D']] assert_frame_equal(result, expected) # by dtype order = [1, 2, 0, 3] for df in [self.mixed_float, self.mixed_int]: result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ['B', 'C', 'A', 'D']] assert_frame_equal(result, expected) def test_reindex_boolean(self): frame = DataFrame(np.ones((10, 2), dtype=bool), index=np.arange(0, 20, 2), columns=[0, 2]) reindexed = frame.reindex(np.arange(10)) assert reindexed.values.dtype == np.object_ assert isna(reindexed[0][1]) reindexed = frame.reindex(columns=lrange(3)) assert reindexed.values.dtype == np.object_ assert isna(reindexed[1]).all() def test_reindex_objects(self): reindexed = self.mixed_frame.reindex(columns=['foo', 'A', 'B']) assert 'foo' in reindexed reindexed = self.mixed_frame.reindex(columns=['A', 'B']) assert 'foo' not in reindexed def test_reindex_corner(self): index = Index(['a', 'b', 'c']) dm = self.empty.reindex(index=[1, 2, 3]) reindexed = dm.reindex(columns=index) tm.assert_index_equal(reindexed.columns, index) # ints are weird smaller = self.intframe.reindex(columns=['A', 'B', 'E']) assert smaller['E'].dtype == np.float64 def test_reindex_axis(self): cols = ['A', 'B', 'E'] with tm.assert_produces_warning(FutureWarning) as m: reindexed1 = self.intframe.reindex_axis(cols, axis=1) assert 'reindex' in str(m[0].message) reindexed2 = self.intframe.reindex(columns=cols) assert_frame_equal(reindexed1, reindexed2) rows = self.intframe.index[0:5] with tm.assert_produces_warning(FutureWarning) as m: reindexed1 = self.intframe.reindex_axis(rows, axis=0) assert 'reindex' in str(m[0].message) reindexed2 = self.intframe.reindex(index=rows) assert_frame_equal(reindexed1, reindexed2) pytest.raises(ValueError, self.intframe.reindex_axis, rows, axis=2) # no-op case cols = self.frame.columns.copy() with tm.assert_produces_warning(FutureWarning) as m: newFrame = self.frame.reindex_axis(cols, axis=1) assert 'reindex' in str(m[0].message) assert_frame_equal(newFrame, self.frame) def test_reindex_with_nans(self): df = DataFrame([[1, 2], [3, 4], [np.nan, np.nan], [7, 8], [9, 10]], columns=['a', 'b'], index=[100.0, 101.0, np.nan, 102.0, 103.0]) result = df.reindex(index=[101.0, 102.0, 103.0]) expected = df.iloc[[1, 3, 4]] assert_frame_equal(result, expected) result = df.reindex(index=[103.0]) expected = df.iloc[[4]] assert_frame_equal(result, expected) result = df.reindex(index=[101.0]) expected = df.iloc[[1]] assert_frame_equal(result, expected) def test_reindex_multi(self): df = DataFrame(np.random.randn(3, 3)) result = df.reindex(index=lrange(4), columns=lrange(4)) expected = df.reindex(lrange(4)).reindex(columns=lrange(4)) assert_frame_equal(result, expected) df = DataFrame(np.random.randint(0, 10, (3, 3))) result = df.reindex(index=lrange(4), columns=lrange(4)) expected = df.reindex(lrange(4)).reindex(columns=lrange(4)) assert_frame_equal(result, expected) df = DataFrame(np.random.randint(0, 10, (3, 3))) result = df.reindex(index=lrange(2), columns=lrange(2)) expected = df.reindex(lrange(2)).reindex(columns=lrange(2)) assert_frame_equal(result, expected) df = DataFrame(np.random.randn(5, 3) + 1j, columns=['a', 'b', 'c']) result = df.reindex(index=[0, 1], columns=['a', 'b']) expected = df.reindex([0, 1]).reindex(columns=['a', 'b']) assert_frame_equal(result, expected)
zfrenchee/pandas
pandas/tests/frame/test_axis_select_reindex.py
pandas/core/indexes/timedeltas.py
import atexit import os import re import subprocess import threading from contextlib import contextmanager from functools import partial import diaper from cached_property import cached_property from werkzeug.local import LocalProxy # import diaper for backward compatibility on_rtd = os.environ.get('READTHEDOCS') == 'True' class TriesExceeded(Exception): """Default exception raised when tries() method doesn't catch a func exception""" pass class FakeObject: def __init__(self, **kwargs): self.__dict__ = kwargs def fakeobject_or_object(obj, attr, default=None): if isinstance(obj, str): return FakeObject(**{attr: obj}) elif not obj: return FakeObject(**{attr: default}) else: return obj def clear_property_cache(obj, *names): """ clear a cached property regardess of if it was cached priority """ if isinstance(obj, LocalProxy): obj = obj._get_current_object() for name in names: assert isinstance(getattr(type(obj), name), cached_property) obj.__dict__.pop(name, None) class _classproperty(property): """Subclass property to make classmethod properties possible""" def __get__(self, cls, owner): return self.fget.__get__(None, owner)() def classproperty(f): """Enables properties for whole classes: Usage: >>> class Foo(object): ... @classproperty ... def bar(cls): ... return "bar" ... >>> print(Foo.bar) baz """ return _classproperty(classmethod(f)) def at_exit(f, *args, **kwargs): """Diaper-protected atexit handler registering. Same syntax as atexit.register()""" return atexit.register(lambda: diaper(f, *args, **kwargs)) def _prenormalize_text(text): """Makes the text lowercase and removes all characters that are not digits, alphas, or spaces""" # _'s represent spaces so convert those to spaces too return re.sub(r"[^a-z0-9 ]", "", text.strip().lower().replace('_', ' ')) def _replace_spaces_with(text, delim): """Contracts spaces into one character and replaces it with a custom character.""" return re.sub(r"\s+", delim, text) def normalize_text(text): """Converts a string to a lowercase string containing only letters, digits and spaces. The space is always one character long if it is present. """ return _replace_spaces_with(_prenormalize_text(text), ' ') def attributize_string(text): """Converts a string to a lowercase string containing only letters, digits and underscores. Usable for eg. generating object key names. The underscore is always one character long if it is present. """ return _replace_spaces_with(_prenormalize_text(text), '_') def normalize_space(text): """Works in accordance with the XPath's normalize-space() operator. `Description <https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/normalize-space>`_: *The normalize-space function strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string.* """ return _replace_spaces_with(text.strip(), ' ') def tries(num_tries, exceptions, f, *args, **kwargs): """ Tries to call the function multiple times if specific exceptions occur. Args: num_tries: How many times to try if exception is raised exceptions: Tuple (or just single one) of exceptions that should be treated as repeat. f: Callable to be called. *args: Arguments to be passed through to the callable **kwargs: Keyword arguments to be passed through to the callable Returns: What ``f`` returns. Raises: What ``f`` raises if the try count is exceeded. """ caught_exception = TriesExceeded('Tries were exhausted without a func exception') tries = 0 while tries < num_tries: tries += 1 try: return f(*args, **kwargs) except exceptions as e: caught_exception = e pass else: raise caught_exception # There are some environment variables that get smuggled in anyway. # If there is yet another one that will be possibly smuggled in, update this entry. READ_ENV_UNWANTED = {'SHLVL', '_', 'PWD'} def read_env(file): """Given a :py:class:`py.path.Local` file name, return a dict of exported shell vars and their values. Args: file: A :py:class:`py.path.Local` instance. Note: This will only include shell variables that are exported from the file being parsed Returns: A :py:class:`dict` of key/value pairs. If the file does not exist or bash could not parse the file, this dict will be empty. """ env_vars = {} if file.check(): # parse the file with bash, since it's pretty good at it, and dump the env # Use env -i to clean up the env (except the very few variables provider by bash itself) command = ['env', '-i', 'bash', '-c', f'source {file.strpath} && env'] proc = subprocess.Popen(command, stdout=subprocess.PIPE, bufsize=1) # filter out the remaining unwanted things for line in iter(proc.stdout.readline, b''): try: key, value = line.split("=", 1) except ValueError: continue if key not in READ_ENV_UNWANTED: try: value = int(value.strip()) except (ValueError, TypeError): value = value.strip() env_vars[key] = value stdout, stderr = proc.communicate() return env_vars def safe_string(o): """This will make string out of ANYTHING without having to worry about the stupid Unicode errors This function tries to make str/unicode out of ``o`` unless it already is one of those and then it processes it so in the end there is a harmless ascii string. Args: o: Anything. """ if not isinstance(o, str): o = str(o) if isinstance(o, bytes): o = o.decode('utf-8', "ignore") if not isinstance(o, str): o = o.encode("ascii", "xmlcharrefreplace") else: o = o.encode("ascii", "xmlcharrefreplace").decode('ascii') return o def process_pytest_path(path): # Processes the path elements with regards to [] path = path.lstrip("/") if len(path) == 0: return [] try: seg_end = path.index("/") except ValueError: seg_end = None try: param_start = path.index("[") except ValueError: param_start = None try: param_end = path.index("]") except ValueError: param_end = None if seg_end is None: # Definitely a final segment return [path] else: if (param_start is not None and param_end is not None and seg_end > param_start and seg_end < param_end): # The / inside [] segment = path[:param_end + 1] rest = path[param_end + 1:] return [segment] + process_pytest_path(rest) else: # The / that is not inside [] segment = path[:seg_end] rest = path[seg_end + 1:] return [segment] + process_pytest_path(rest) def process_shell_output(value): """This function allows you to unify the behaviour when you putput some values to stdout. You can check the code of the function how exactly does it behave for the particular types of variables. If no output is expected, it returns None. Args: value: Value to be outputted. Returns: A tuple consisting of returncode and the output to be printed. """ result_lines = [] exit = 0 if isinstance(value, (list, tuple, set)): for entry in sorted(value): result_lines.append(entry) elif isinstance(value, dict): for key, value in value.items(): result_lines.append(f'{key}={value}') elif isinstance(value, str): result_lines.append(value) elif isinstance(value, bool): # 'True' result becomes flipped exit 0, and vice versa for False exit = int(not value) else: # Unknown type, print it result_lines.append(str(value)) return exit, '\n'.join(result_lines) if result_lines else None def iterate_pairs(iterable): """Iterates over iterable, always taking two items at time. Eg. ``[1, 2, 3, 4, 5, 6]`` will yield ``(1, 2)``, then ``(3, 4)`` ... Must have even number of items. Args: iterable: An iterable with even number of items to be iterated over. """ if len(iterable) % 2 != 0: raise ValueError('Iterable must have even number of items.') it = iter(iterable) for i in it: yield i, next(it) def icastmap(t, i, *args, **kwargs): """Works like the map() but is made specially to map classes on iterables. A generator version. This function only applies the ``t`` to the item of ``i`` if it is not of that type. Args: t: The class that you want all the yielded items to be type of. i: Iterable with items to be cast. Returns: A generator. """ for item in i: if isinstance(item, t): yield item else: yield t(item, *args, **kwargs) def castmap(t, i, *args, **kwargs): """Works like the map() but is made specially to map classes on iterables. This function only applies the ``t`` to the item of ``i`` if it is not of that type. Args: t: The class that you want all theitems in the list to be type of. i: Iterable with items to be cast. Returns: A list. """ return list(icastmap(t, i, *args, **kwargs)) class InstanceClassMethod: """ Decorator-descriptor that enables you to use any method both as class and instance one Usage: .. code-block:: python class SomeClass(object): @InstanceClassMethod def a_method(self): the_instance_variant() @a_method.classmethod def a_method(cls): the_class_variant() i = SomeClass() i.a_method() SomeClass.a_method() # Both are possible If you don't pass ``classmethod`` the "instance" method, the one that was passed first will be called for both kinds of invocation. """ def __init__(self, instance_or_class_method): self.instance_or_class_method = instance_or_class_method self.class_method = None def classmethod(self, class_method): self.class_method = class_method return self def __get__(self, o, t): if o is None: # classmethod return partial(self.class_method or self.instance_or_class_method, t) else: # instancemethod return partial(self.instance_or_class_method, o) class ParamClassName: """ ParamClassName is a Descriptor to help when using classes and instances as parameters Note: This descriptor is a hack until collections are implemented everywhere Usage: .. code-block:: python class Provider(object): _param_name = ParamClassName('name') def __init__(self, name): self.name = name When accessing the ``_param_name`` on the class object it will return the ``__name__`` of the class by default. When accessing the ``_param_name`` on an instance of the class, it will return the attribute that is passed in. """ def __init__(self, instance_attr, class_attr='__name__'): self.instance_attr = instance_attr self.class_attr = class_attr def __get__(self, instance, owner): if instance: return getattr(instance, self.instance_attr) else: return getattr(owner, self.class_attr) @contextmanager def periodic_call(period_seconds, call, args=None, kwargs=None): timer = None args = args or [] kwargs = kwargs or {} def timer_event(): call(*args, **kwargs) reschedule() def reschedule(): nonlocal timer timer = threading.Timer(period_seconds, timer_event) timer.start() reschedule() try: yield finally: timer.cancel()
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/utils/__init__.py
# Common stuff for custom button testing from widgetastic.widget import ParametrizedLocator from widgetastic.widget import ParametrizedView from widgetastic.widget import Text from widgetastic.widget import TextInput from widgetastic.widget import View from widgetastic_patternfly import BootstrapSelect from widgetastic_patternfly import Button from widgetastic_patternfly import Dropdown OBJ_TYPE = [ "AZONE", "CLOUD_NETWORK", "CLOUD_OBJECT_STORE_CONTAINER", "CLOUD_SUBNET", "CLOUD_TENANT", "CLOUD_VOLUME", "CLUSTERS", "CONTAINER_IMAGES", "CONTAINER_NODES", "CONTAINER_PODS", "CONTAINER_PROJECTS", "CONTAINER_TEMPLATES", "CONTAINER_VOLUMES", "DATASTORES", "GROUP", "USER", "GENERIC", "HOSTS", "LOAD_BALANCER", "ROUTER", "ORCHESTRATION_STACK", "PROVIDER", "SECURITY_GROUP", "SERVICE", "SWITCH", "TENANT", "TEMPLATE_IMAGE", "VM_INSTANCE", ] CLASS_MAP = { "AZONE": {"ui": "Availability Zone", "rest": "AvailabilityZone"}, "CLOUD_NETWORK": {"ui": "Cloud Network", "rest": "CloudNetwork"}, "CLOUD_OBJECT_STORE_CONTAINER": { "ui": "Cloud Object Store Container", "rest": "CloudObjectStoreContainer", }, "CLOUD_SUBNET": {"ui": "Cloud Subnet", "rest": "CloudSubnet"}, "CLOUD_TENANT": {"ui": "Cloud Tenant", "rest": "CloudTenant"}, "CLOUD_VOLUME": {"ui": "Cloud Volume", "rest": "CloudVolume"}, "CLUSTERS": {"ui": "Cluster / Deployment Role", "rest": "EmsCluster"}, "CONTAINER_IMAGES": {"ui": "Container Image", "rest": "ContainerImage"}, "CONTAINER_NODES": {"ui": "Container Node", "rest": "ContainerNode"}, "CONTAINER_PODS": {"ui": "Container Pod", "rest": "ContainerGroup"}, "CONTAINER_PROJECTS": {"ui": "Container Project", "rest": "ContainerProject"}, "CONTAINER_TEMPLATES": {"ui": "Container Template", "rest": "ContainerTemplate"}, "CONTAINER_VOLUMES": {"ui": "Container Volume", "rest": "ContainerVolume"}, "DATASTORES": {"ui": "Datastore", "rest": "Storage"}, "GROUP": {"ui": "Group", "rest": "MiqGroup"}, "USER": {"ui": "User", "rest": "User"}, "GENERIC": {"ui": "Generic Object", "rest": "GenericObject"}, "HOSTS": {"ui": "Host / Node", "rest": "Host"}, "LOAD_BALANCER": {"ui": "Load Balancer", "rest": "LoadBalancer"}, "ROUTER": {"ui": "Network Router", "rest": "NetworkRouter"}, "ORCHESTRATION_STACK": {"ui": "Orchestration Stack", "rest": "OrchestrationStack"}, "PROVIDER": {"ui": "Provider", "rest": "ExtManagementSystem"}, "SECURITY_GROUP": {"ui": "Security Group", "rest": "SecurityGroup"}, "SERVICE": {"ui": "Service", "rest": "Service"}, "SWITCH": {"ui": "Virtual Infra Switch", "rest": "Switch"}, "TENANT": {"ui": "Tenant", "rest": "Tenant"}, "TEMPLATE_IMAGE": {"ui": "VM Template and Image", "rest": "MiqTemplate"}, "VM_INSTANCE": {"ui": "VM and Instance", "rest": "Vm"}, } def check_log_requests_count(appliance, parse_str=None): """ Method for checking number of requests count in automation log Args: appliance: an appliance for ssh parse_str: string check-in automation log Return: requests string count """ if not parse_str: parse_str = "Attributes - Begin" count = appliance.ssh_client.run_command( f"grep -c -w '{parse_str}' /var/www/miq/vmdb/log/automation.log" ) return int(count.output) def log_request_check(appliance, expected_count): """ Method for checking expected request count in automation log Args: appliance: an appliance for ssh expected_count: expected request count in automation log """ return check_log_requests_count(appliance=appliance) == expected_count class TextInputDialogView(View): """ This is view comes on different custom button objects for dialog execution""" title = Text("#explorer_title_text") service_name = TextInput(id="service_name") submit = Button("Submit") cancel = Button("Cancel") @property def is_displayed(self): # This is only for wait for view return self.submit.is_displayed and self.service_name.is_displayed class TextInputAutomateView(View): """This is view comes on clicking custom button""" title = Text("#explorer_title_text") text_box1 = TextInput(id="text_box_1") text_box2 = TextInput(id="text_box_2") submit = Button("Submit") cancel = Button("Cancel") @property def is_displayed(self): return (self.submit.is_displayed and self.text_box1.is_displayed and self.text_box2.is_displayed) class CredsHostsDialogView(View): """This view for custom button default ansible playbook dialog""" machine_credential = BootstrapSelect(locator=".//select[@id='credential']//parent::div") hosts = TextInput(id="hosts") submit = Button("Submit") cancel = Button("Cancel") @property def is_displayed(self): return self.submit.is_displayed and self.machine_credential.is_displayed class TextInputDialogSSUIView(TextInputDialogView): """ This is view comes on SSUI custom button dialog execution""" submit = Button("Submit Request") class DropdownDialogView(ParametrizedView): """ This is custom view for custom button dropdown dialog execution""" title = Text("#explorer_title_text") class service_name(ParametrizedView): # noqa PARAMETERS = ("dialog_id",) dropdown = BootstrapSelect( locator=ParametrizedLocator("//select[@id={dialog_id|quote}]/..") ) submit = Button("Submit") submit_request = Button("Submit Request") cancel = Button("Cancel") class CustomButtonSSUIDropdwon(Dropdown): """This is workaround for custom button Dropdown in SSUI item_enabled method""" def item_enabled(self, item): self._verify_enabled() el = self.item_element(item) return "disabled" not in self.browser.classes(el)
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/tests/automate/custom_button/__init__.py
"""A model of an Infrastructure PhysicalServer in CFME.""" import attr from cached_property import cached_property from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from varmeth import variable from wrapanapi.systems import LenovoSystem from cfme.common import PolicyProfileAssignable from cfme.common import Taggable from cfme.common.physical_server_views import PhysicalServerDetailsView from cfme.common.physical_server_views import PhysicalServerEditTagsView from cfme.common.physical_server_views import PhysicalServerManagePoliciesView from cfme.common.physical_server_views import PhysicalServerNetworkDevicesView from cfme.common.physical_server_views import PhysicalServerProvisionView from cfme.common.physical_server_views import PhysicalServerStorageDevicesView from cfme.common.physical_server_views import PhysicalServersView from cfme.common.physical_server_views import PhysicalServerTimelinesView from cfme.exceptions import HostStatsNotContains from cfme.exceptions import ItemNotFound from cfme.exceptions import ProviderHasNoProperty from cfme.exceptions import StatsDoNotMatch from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.log import logger from cfme.utils.pretty import Pretty from cfme.utils.providers import get_crud_by_name from cfme.utils.update import Updateable from cfme.utils.wait import wait_for @attr.s class PhysicalServer(BaseEntity, Updateable, Pretty, PolicyProfileAssignable, Taggable): """Model of an Physical Server in cfme. Args: name: Name of the physical server. hostname: hostname of the physical server. ip_address: The IP address as a string. custom_ident: The custom identifiter. Usage: myhost = PhysicalServer(name='vmware') myhost.create() """ pretty_attrs = ['name', 'hostname', 'ip_address', 'custom_ident'] name = attr.ib() ems_ref = attr.ib(default=None) provider = attr.ib(default=None) hostname = attr.ib(default=None) ip_address = attr.ib(default=None) custom_ident = attr.ib(default=None) db_id = None mgmt_class = LenovoSystem INVENTORY_TO_MATCH = ['power_state'] STATS_TO_MATCH = ['cores_capacity', 'memory_capacity', 'num_network_devices', 'num_storage_devices'] def load_details(self, refresh=False): """To be compatible with the Taggable and PolicyProfileAssignable mixins. Args: refresh (bool): Whether to perform the page refresh, defaults to False """ view = navigate_to(self, "Details") if refresh: view.browser.refresh() view.flush_widget_cache() def _execute_button(self, button, option, handle_alert=False): view = navigate_to(self, "Details") view.toolbar.custom_button(button).item_select(option, handle_alert=handle_alert) return view def _execute_action_button(self, button, option, handle_alert=True, **kwargs): target = kwargs.get("target", None) provider = kwargs.get("provider", None) desired_state = kwargs.get("desired_state", None) view = self._execute_button(button, option, handle_alert=handle_alert) if desired_state: self._wait_for_state_change(desired_state, target, provider, view) elif handle_alert: wait_for( lambda: view.flash.is_displayed, message="Wait for the handle alert to appear...", num_sec=5, delay=2 ) def power_on(self, **kwargs): self._execute_action_button("Power", "Power On", **kwargs) def power_off(self, **kwargs): self._execute_action_button("Power", "Power Off", **kwargs) def power_off_immediately(self, **kwargs): self._execute_action_button("Power", "Power Off Immediately", **kwargs) def restart(self, **kwargs): self._execute_action_button("Power", "Restart", **kwargs) def restart_immediately(self, **kwargs): self._execute_action_button("Power", "Restart Immediately", **kwargs) def refresh(self, provider, handle_alert=False): last_refresh = provider.last_refresh_date() self._execute_button("Configuration", "Refresh Relationships and Power States", handle_alert) wait_for( lambda: last_refresh != provider.last_refresh_date(), message="Wait for the server to be refreshed...", num_sec=300, delay=5 ) def turn_on_led(self, **kwargs): self._execute_action_button('Identify', 'Turn On LED', **kwargs) def turn_off_led(self, **kwargs): self._execute_action_button('Identify', 'Turn Off LED', **kwargs) def turn_blink_led(self, **kwargs): self._execute_action_button('Identify', 'Blink LED', **kwargs) @variable(alias='ui') def power_state(self): view = navigate_to(self, "Details") return view.entities.power_management.get_text_of("Power State") @variable(alias='ui') def cores_capacity(self): view = navigate_to(self, "Details") return view.entities.properties.get_text_of("CPU total cores") @variable(alias='ui') def memory_capacity(self): view = navigate_to(self, "Details") return view.entities.properties.get_text_of("Total memory (mb)") @variable(alias='ui') def num_network_devices(self): view = navigate_to(self, "Details") return view.entities.properties.get_text_of("Network Devices") @variable(alias='ui') def num_storage_devices(self): view = navigate_to(self, "Details") return view.entities.properties.get_text_of("Storage Devices") def _wait_for_state_change(self, desired_state, target, provider, view, timeout=300, delay=10): """Wait for PhysicalServer to come to desired state. This function waits just the needed amount of time thanks to wait_for. Args: desired_state (str): 'on' or 'off' target (str): The name of the method that most be used to compare with the desired_state view (object): The view that most be refreshed to verify if the value was changed provider (object): 'LenovoProvider' timeout (int): Specify amount of time (in seconds) to wait until TimedOutError is raised delay (int): Specify amount of time (in seconds) to repeat each time. """ def _is_state_changed(): self.refresh(provider, handle_alert=True) return desired_state == getattr(self, target)() wait_for(_is_state_changed, fail_func=view.browser.refresh, num_sec=timeout, delay=delay) @property def exists(self): """Checks if the physical_server exists in the UI. Returns: :py:class:`bool` """ view = navigate_to(self.parent, "All") try: view.entities.get_entity(name=self.name, surf_pages=True) except ItemNotFound: return False else: return True @cached_property def get_db_id(self): if self.db_id is None: self.db_id = self.appliance.physical_server_id(self.name) return self.db_id else: return self.db_id def wait_to_appear(self): """Waits for the server to appear in the UI.""" view = navigate_to(self.parent, "All") logger.info("Waiting for the server to appear...") wait_for( lambda: self.exists, message="Wait for the server to appear", num_sec=1000, fail_func=view.browser.refresh ) def wait_for_delete(self): """Waits for the server to remove from the UI.""" view = navigate_to(self.parent, "All") logger.info("Waiting for the server to delete...") wait_for( lambda: not self.exists, message="Wait for the server to disappear", num_sec=500, fail_func=view.browser.refresh ) def validate_stats(self, ui=False): """ Validates that the detail page matches the physical server's information. This method logs into the provider using the mgmt_system interface and collects a set of statistics to be matched against the UI. An exception will be raised if the stats retrieved from the UI do not match those retrieved from wrapanapi. """ # Make sure we are on the physical server detail page if ui: self.load_details() # Retrieve the client and the stats and inventory to match client = self.provider.mgmt stats_to_match = self.STATS_TO_MATCH inventory_to_match = self.INVENTORY_TO_MATCH # Retrieve the stats and inventory from wrapanapi server_stats = client.server_stats(self, stats_to_match) server_inventory = client.server_inventory(self, inventory_to_match) # Refresh the browser if ui: self.browser.selenium.refresh() # Verify that the stats retrieved from wrapanapi match those retrieved # from the UI for stat in stats_to_match: try: cfme_stat = int(getattr(self, stat)(method='ui' if ui else None)) server_stat = int(server_stats[stat]) if server_stat != cfme_stat: msg = "The {} stat does not match. (server: {}, server stat: {}, cfme stat: {})" raise StatsDoNotMatch(msg.format(stat, self.name, server_stat, cfme_stat)) except KeyError: raise HostStatsNotContains( f"Server stats information does not contain '{stat}'") except AttributeError: raise ProviderHasNoProperty(f"Provider does not know how to get '{stat}'") # Verify that the inventory retrieved from wrapanapi match those retrieved # from the UI for inventory in inventory_to_match: try: cfme_inventory = getattr(self, inventory)(method='ui' if ui else None) server_inventory = server_inventory[inventory] if server_inventory != cfme_inventory: msg = "The {} inventory does not match. (server: {}, server inventory: {}, " \ "cfme inventory: {})" raise StatsDoNotMatch(msg.format(inventory, self.name, server_inventory, cfme_inventory)) except KeyError: raise HostStatsNotContains( f"Server inventory information does not contain '{inventory}'") except AttributeError: msg = "Provider does not know how to get '{}'" raise ProviderHasNoProperty(msg.format(inventory)) @attr.s class PhysicalServerCollection(BaseCollection): """Collection object for the :py:class:`cfme.infrastructure.host.PhysicalServer`.""" ENTITY = PhysicalServer def select_entity_rows(self, physical_servers): """ Select all physical server objects """ physical_servers = list(physical_servers) checked_physical_servers = list() view = navigate_to(self, 'All') for physical_server in physical_servers: view.entities.get_entity(name=physical_server.name, surf_pages=True).ensure_checked() checked_physical_servers.append(physical_server) return view def all(self, provider): """returning all physical_servers objects""" physical_server_table = self.appliance.db.client['physical_servers'] ems_table = self.appliance.db.client['ext_management_systems'] physical_server_query = ( self.appliance.db.client.session .query(physical_server_table.name, physical_server_table.ems_ref, ems_table.name) .join(ems_table, physical_server_table.ems_id == ems_table.id)) provider = None if self.filters.get('provider'): provider = self.filters.get('provider') physical_server_query = physical_server_query.filter(ems_table.name == provider.name) physical_servers = [] for name, ems_ref, ems_name in physical_server_query.all(): physical_servers.append(self.instantiate(name=name, ems_ref=ems_ref, provider=provider or get_crud_by_name(ems_name))) return physical_servers def find_by(self, provider, ph_name): """returning all physical_servers objects""" physical_server_table = self.appliance.db.client['physical_servers'] ems_table = self.appliance.db.client['ext_management_systems'] physical_server_query = ( self.appliance.db.client.session .query(physical_server_table.name, ems_table.name) .join(ems_table, physical_server_table.ems_id == ems_table.id)) provider = None if self.filters.get('provider'): provider = self.filters.get('provider') physical_server_query = physical_server_query.filter(ems_table.name == provider.name) for name, ems_name in physical_server_query.all(): if ph_name == name: return self.instantiate(name=name, provider=provider or get_crud_by_name(ems_name)) def power_on(self, *physical_servers): view = self.select_entity_rows(physical_servers) view.toolbar.power.item_select("Power On", handle_alert=True) def power_off(self, *physical_servers): view = self.select_entity_rows(physical_servers) view.toolbar.power.item_select("Power Off", handle_alert=True) def custom_button_action(self, button, option, physical_servers, handle_alert=True): view = self.select_entity_rows(physical_servers) view.toolbar.custom_button(button).item_select(option, handle_alert=handle_alert) @navigator.register(PhysicalServerCollection) class All(CFMENavigateStep): VIEW = PhysicalServersView prerequisite = NavigateToAttribute("appliance.server", "LoggedIn") def step(self, *args, **kwargs): self.prerequisite_view.navigation.select("Compute", "Physical Infrastructure", "Servers") @navigator.register(PhysicalServerCollection) class ManagePoliciesCollection(CFMENavigateStep): VIEW = PhysicalServerManagePoliciesView prerequisite = NavigateToSibling("All") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.policy.item_select("Manage Policies") @navigator.register(PhysicalServerCollection) class EditTagsCollection(CFMENavigateStep): VIEW = PhysicalServerEditTagsView prerequisite = NavigateToSibling("All") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.policy.item_select("Edit Tags") @navigator.register(PhysicalServerCollection) class ProvisionCollection(CFMENavigateStep): VIEW = PhysicalServerProvisionView prerequisite = NavigateToSibling("All") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.lifecycle.item_select("Provision Physical Server") @navigator.register(PhysicalServer) class Details(CFMENavigateStep): VIEW = PhysicalServerDetailsView prerequisite = NavigateToAttribute("parent", "All") def step(self, *args, **kwargs): self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True).click() @navigator.register(PhysicalServer) class ManagePolicies(CFMENavigateStep): VIEW = PhysicalServerManagePoliciesView prerequisite = NavigateToSibling("Details") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.policy.item_select("Manage Policies") @navigator.register(PhysicalServer) class Provision(CFMENavigateStep): VIEW = PhysicalServerProvisionView prerequisite = NavigateToSibling("Details") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.lifecycle.item_select("Provision Physical Server") @navigator.register(PhysicalServer) class Timelines(CFMENavigateStep): VIEW = PhysicalServerTimelinesView prerequisite = NavigateToSibling("Details") def step(self, *args, **kwargs): self.prerequisite_view.toolbar.monitoring.item_select("Timelines") @navigator.register(PhysicalServer) class NetworkDevices(CFMENavigateStep): VIEW = PhysicalServerNetworkDevicesView prerequisite = NavigateToSibling("Details") def step(self, *args, **kwargs): self.prerequisite_view.entities.properties.click_at("Network Devices") @navigator.register(PhysicalServer) class StorageDevices(CFMENavigateStep): VIEW = PhysicalServerStorageDevicesView prerequisite = NavigateToSibling("Details") def step(self, *args, **kwargs): self.prerequisite_view.entities.properties.click_at("Storage Devices")
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/physical/physical_server.py
import attr from cached_property import cached_property from navmazing import NavigateToAttribute from cfme.automate.dialogs import AddBoxView from cfme.automate.dialogs import BoxForm from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.modeling.base import parent_of_type from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator class EditBoxView(BoxForm): """EditBox View.""" @property def is_displayed(self): return ( self.in_customization and self.title.text == f"Editing Dialog {self.box_label} [Box Information]" ) @attr.s class Box(BaseEntity): """A class representing one Box of dialog.""" box_label = attr.ib() box_desc = attr.ib(default=None) from cfme.automate.dialogs.dialog_element import ElementCollection _collections = {'elements': ElementCollection} @cached_property def elements(self): return self.collections.elements @property def tree_path(self): return self.parent.tree_path + [self.box_label] @property def tab(self): from cfme.automate.dialogs.dialog_tab import Tab return parent_of_type(self, Tab) @attr.s class BoxCollection(BaseCollection): ENTITY = Box @property def tree_path(self): return self.parent.tree_path def create(self, box_label=None, box_desc=None): """Create box method. Args: box_label and box_description. """ view = navigate_to(self, "Add") view.new_box.click() view.edit_box.click() view.fill({'box_label': box_label, 'box_desc': box_desc}) view.save_button.click() return self.instantiate(box_label=box_label, box_desc=box_desc) @navigator.register(BoxCollection) class Add(CFMENavigateStep): VIEW = AddBoxView prerequisite = NavigateToAttribute('parent.parent', 'Add') def step(self, *args, **kwargs): self.prerequisite_view.add_section.click()
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/automate/dialogs/dialog_box.py
from lxml.html import document_fromstring from widgetastic.utils import Parameter from widgetastic.widget import ParametrizedView from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import Accordion from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patternfly import Dropdown from cfme.common import BaseLoggedInPage from cfme.common import TimelinesView from widgetastic_manageiq import BaseEntitiesView from widgetastic_manageiq import BaseNonInteractiveEntitiesView from widgetastic_manageiq import BootstrapTreeview from widgetastic_manageiq import Button from widgetastic_manageiq import ItemsToolBarViewSelector from widgetastic_manageiq import JSBaseEntity from widgetastic_manageiq import ManageIQTree from widgetastic_manageiq import Search from widgetastic_manageiq import SummaryTable class ComputePhysicalInfrastructureServersView(BaseLoggedInPage): """Common parts for server views.""" title = Text('.//div[@id="center_div" or @id="main-content"]//h1') @property def in_compute_physical_infrastructure_servers(self): return (self.logged_in_as_current_user and self.navigation.currently_selected == ["Compute", "Physical Infrastructure", "Servers"]) class PhysicalServerEntity(JSBaseEntity): @property def data(self): data_dict = super().data if 'quadicon' in data_dict and data_dict['quadicon']: quad_data = document_fromstring(data_dict['quadicon']) data_dict['no_host'] = int(quad_data.xpath(self.QUADRANT.format(pos="a"))[0].text) data_dict['state'] = quad_data.xpath(self.QUADRANT.format(pos="b"))[0].get('style') data_dict['vendor'] = quad_data.xpath(self.QUADRANT.format(pos="c"))[0].get('alt') data_dict['creds'] = quad_data.xpath(self.QUADRANT.format(pos="d"))[0].get('alt') return data_dict class PhysicalServerDetailsToolbar(View): """Represents physical toolbar and its controls.""" monitoring = Dropdown(text="Monitoring") configuration = Dropdown(text="Configuration") policy = Dropdown(text="Policy") power = Dropdown(text="Power") identify = Dropdown(text="Identify") lifecycle = Dropdown(text="Lifecycle") @ParametrizedView.nested class custom_button(ParametrizedView): # noqa PARAMETERS = ("button_group", ) _dropdown = Dropdown(text=Parameter("button_group")) def item_select(self, button, handle_alert=False): self._dropdown.item_select(button, handle_alert=handle_alert) class PhysicalServerDetailsEntities(View): """Represents Details page.""" properties = SummaryTable(title="Properties") networks = SummaryTable(title="Networks") relationships = SummaryTable(title="Relationships") power_management = SummaryTable(title="Power Management") assets = SummaryTable(title="Assets") firmware = SummaryTable(title="Firmware") network_devices = SummaryTable(title="Network Devices") smart = SummaryTable(title="Smart Management") class PhysicalServerDetailsView(ComputePhysicalInfrastructureServersView): """Main PhysicalServer details page.""" breadcrumb = BreadCrumb(locator='.//ol[@class="breadcrumb"]') toolbar = View.nested(PhysicalServerDetailsToolbar) entities = View.nested(PhysicalServerDetailsEntities) @property def is_displayed(self): title = "{name} (Summary)".format(name=self.context["object"].name) return (self.in_compute_physical_infrastructure_servers and self.breadcrumb.active_location == title) class PhysicalServerTimelinesView(TimelinesView, ComputePhysicalInfrastructureServersView): """Represents a PhysicalServer Timelines page.""" pass class PhysicalServerProvisionView(BaseLoggedInPage): """Represents the Provision Physical Server page.""" breadcrumb = BreadCrumb(locator='.//ol[@class="breadcrumb"]') @property def is_displayed(self): title = "Add PhysicalServer" return self.breadcrumb.active_location == title class PhysicalServerManagePoliciesView(BaseLoggedInPage): """PhysicalServer's Manage Policies view.""" policies = BootstrapTreeview("protectbox") entities = View.nested(BaseNonInteractiveEntitiesView) save = Button("Save") reset = Button("Reset") cancel = Button("Cancel") breadcrumb = BreadCrumb(locator='.//ol[@class="breadcrumb"]') @property def is_displayed(self): title = "'Physical Server' Policy Assignment" return self.breadcrumb.active_location == title class PhysicalServerEditTagsView(BaseLoggedInPage): """PhysicalServer's EditTags view.""" policies = BootstrapTreeview("protectbox") entities = View.nested(BaseNonInteractiveEntitiesView) breadcrumb = BreadCrumb(locator='.//ol[@class="breadcrumb"]') @property def is_displayed(self): title = "Tag Assignment" return self.breadcrumb.active_location == title class PhysicalServersToolbar(View): """Represents hosts toolbar and its controls.""" configuration = Dropdown(text="Configuration") policy = Dropdown(text="Policy") lifecycle = Dropdown(text="Lifecycle") monitoring = Dropdown(text="Monitoring") power = Dropdown(text="Power") identify = Dropdown(text="Identify") view_selector = View.nested(ItemsToolBarViewSelector) @ParametrizedView.nested class custom_button(ParametrizedView): # noqa PARAMETERS = ("button_group",) _dropdown = Dropdown(text=Parameter("button_group")) def item_select(self, button, handle_alert=False): self._dropdown.item_select(button, handle_alert=handle_alert) class PhysicalServerSideBar(View): """Represents left side bar. It usually contains navigation, filters, etc.""" @View.nested class filters(Accordion): # noqa tree = ManageIQTree() class PhysicalServerEntitiesView(BaseEntitiesView): """Represents the view with different items like hosts.""" @property def entity_class(self): return PhysicalServerEntity class PhysicalServersView(ComputePhysicalInfrastructureServersView): toolbar = View.nested(PhysicalServersToolbar) sidebar = View.nested(PhysicalServerSideBar) search = View.nested(Search) including_entities = View.include(PhysicalServerEntitiesView, use_parent=True) @property def is_displayed(self): return (self.in_compute_physical_infrastructure_servers and self.title.text == "Physical Servers") @View.nested class my_filters(Accordion): # noqa ACCORDION_NAME = "My Filters" navigation = BootstrapNav('.//div/ul') tree = ManageIQTree() class PhysicalServerNetworkDevicesView(ComputePhysicalInfrastructureServersView): """Represents the Network Devices page""" @property def is_displayed(self): return ("Network Devices" in self.title.text and self.in_compute_physical_infrastructure_servers) class PhysicalServerStorageDevicesView(ComputePhysicalInfrastructureServersView): """Represents the Storage Devices page""" @property def is_displayed(self): return ("Storage Devices" in self.title.text and self.in_compute_physical_infrastructure_servers)
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/common/physical_server_views.py
""" A model of a PXE Server in CFME """ import attr from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from selenium.common.exceptions import NoSuchElementException from varmeth import variable from widgetastic.widget import Checkbox from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import Accordion from widgetastic_patternfly import BootstrapSelect from widgetastic_patternfly import Button from widgetastic_patternfly import Dropdown from cfme.base import BaseCollection from cfme.base import BaseEntity from cfme.common import BaseLoggedInPage from cfme.exceptions import displayed_not_implemented from cfme.utils import conf from cfme.utils import ParamClassName from cfme.utils.appliance import Navigatable from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.datafile import load_data_file from cfme.utils.path import project_path from cfme.utils.pretty import Pretty from cfme.utils.update import Updateable from cfme.utils.wait import wait_for from widgetastic_manageiq import Input from widgetastic_manageiq import ManageIQTree from widgetastic_manageiq import ScriptBox from widgetastic_manageiq import SummaryTable from widgetastic_manageiq import Table class PXEToolBar(View): """ represents PXE toolbar and its controls """ # todo: add back button later configuration = Dropdown(text='Configuration') class PXESideBar(View): """ represents left side bar. it usually contains navigation, filters, etc """ @View.nested class servers(Accordion): # noqa ACCORDION_NAME = "PXE Servers" tree = ManageIQTree() @View.nested class templates(Accordion): # noqa ACCORDION_NAME = "Customization Templates" tree = ManageIQTree() @View.nested class image_types(Accordion): # noqa ACCORDION_NAME = "System Image Types" tree = ManageIQTree() @View.nested class datastores(Accordion): # noqa ACCORDION_NAME = "ISO Datastores" tree = ManageIQTree() class PXEMainView(BaseLoggedInPage): """ represents whole All PXE Servers page """ toolbar = View.nested(PXEToolBar) sidebar = View.nested(PXESideBar) title = Text('//div[@id="main-content"]//h1') entities = Table(locator='.//div[@id="records_div" or @id="main_div"]//table') @property def is_displayed(self): return self.navigation.currently_selected == ['Compute', 'Infrastructure', 'PXE'] class PXEServersView(PXEMainView): """ represents whole All PXE Servers page """ @property def is_displayed(self): return (super().is_displayed and self.title.text == 'All PXE Servers') class PXEDetailsToolBar(PXEToolBar): """ represents the toolbar which appears when any pxe entity is clicked """ reload = Button(title='Refresh this page') class PXEServerDetailsView(PXEMainView): """ represents Server Details view """ toolbar = View.nested(PXEDetailsToolBar) @View.nested class entities(View): # noqa basic_information = SummaryTable(title="Basic Information") pxe_image_menus = SummaryTable(title='PXE Image Menus') is_displayed = displayed_not_implemented class PXEServerForm(View): title = Text('//div[@id="main-content"]//h1') # common fields name = Input(id='name') depot_type = BootstrapSelect(id='log_protocol') access_url = Input(id='access_url') pxe_dir = Input(id='pxe_directory') windows_images_dir = Input(id='windows_images_directory') customization_dir = Input(id='customization_directory') filename = Input(id='pxemenu_0') uri = Input(id='uri') # both NFS and Samba # Samba only username = Input(id='log_userid') password = Input(id='log_password') confirm_password = Input(id='log_verify') validate = Button('Validate the credentials by logging into the Server') is_displayed = displayed_not_implemented class PXEServerAddView(PXEServerForm): """ represents Add New PXE Server view """ add = Button('Add') cancel = Button('Cancel') class PXEServerEditView(PXEServerForm): """ represents PXE Server Edit view """ save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') class PXEImageEditView(View): """ it can be found when some image is clicked in PXE Server Tree """ title = Text('//div[@id="main-content"]//h1') default_for_windows = Checkbox(id='default_for_windows') type = BootstrapSelect(id='image_typ') save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') is_displayed = displayed_not_implemented class PXEServer(Updateable, Pretty, Navigatable): """Model of a PXE Server object in CFME Args: name: Name of PXE server. depot_type: Depot type, either Samba or Network File System. uri: The Depot URI. userid: The Samba username. password: The Samba password. access_url: HTTP access path for PXE server. pxe_dir: The PXE dir for accessing configuration. windows_dir: Windows source directory. customize_dir: Customization directory for templates. menu_filename: Menu filename for iPXE/syslinux menu. """ pretty_attrs = ['name', 'uri', 'access_url'] _param_name = ParamClassName('name') def __init__(self, name=None, depot_type=None, uri=None, userid=None, password=None, access_url=None, pxe_dir=None, windows_dir=None, customize_dir=None, menu_filename=None, appliance=None): Navigatable.__init__(self, appliance=appliance) self.name = name self.depot_type = depot_type self.uri = uri self.userid = userid # todo: turn into Credentials class self.password = password self.access_url = access_url self.pxe_dir = pxe_dir self.windows_dir = windows_dir self.customize_dir = customize_dir self.menu_filename = menu_filename def create(self, cancel=False, refresh=True, refresh_timeout=120): """ Creates a PXE server object Args: cancel (boolean): Whether to cancel out of the creation. The cancel is done after all the information present in the PXE Server has been filled in the UI. refresh (boolean): Whether to run the refresh operation on the PXE server after the add has been completed. """ view = navigate_to(self, 'Add') view.fill({'name': self.name, 'depot_type': self.depot_type, 'access_url': self.access_url, 'pxe_dir': self.pxe_dir, 'windows_images_dir': self.windows_dir, 'customization_dir': self.customize_dir, 'filename': self.menu_filename, 'uri': self.uri, # Samba only 'username': self.userid, 'password': self.password, 'confirm_password': self.password}) if self.depot_type == 'Samba' and self.userid and self.password: view.validate.click() main_view = self.create_view(PXEServersView) if cancel: view.cancel.click() main_view.flash.assert_success_message('Add of new PXE Server ' 'was cancelled by the user') else: view.add.click() main_view.flash.assert_no_error() if refresh: self.refresh(timeout=refresh_timeout) @variable(alias="db") def exists(self): """ Checks if the PXE server already exists """ dbs = self.appliance.db.client candidates = list(dbs.session.query(dbs["pxe_servers"])) return self.name in [s.name for s in candidates] @exists.variant('ui') def exists_ui(self): """ Checks if the PXE server already exists """ try: navigate_to(self, 'Details') return True except NoSuchElementException: return False def update(self, updates, cancel=False): """ Updates a PXE server in the UI. Better to use utils.update.update context manager than call this directly. Args: updates (dict): fields that are changing. cancel (boolean): whether to cancel out of the update. """ view = navigate_to(self, 'Edit') view.fill(updates) if updates.get('userid') or updates.get('password'): view.validate.click() name = updates.get('name') or self.name main_view = self.create_view(PXEServersView, override=updates) if cancel: view.cancel.click() main_view.flash.assert_success_message('Edit of PXE Server "{}" was ' 'cancelled by the user'.format(name)) else: view.save.click() main_view.flash.assert_no_error() def delete(self, cancel=True): """ Deletes a PXE server from CFME Args: cancel: Whether to cancel the deletion, defaults to True """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Remove this PXE Server from Inventory', handle_alert=not cancel) if not cancel: main_view = self.create_view(PXEServersView) main_view.flash.assert_no_error() else: navigate_to(self, 'Details') def refresh(self, wait=True, timeout=120): """ Refreshes the PXE relationships and waits for it to be updated """ view = navigate_to(self, 'Details') last_time = view.entities.basic_information.get_text_of('Last Refreshed On') view.toolbar.configuration.item_select('Refresh Relationships', handle_alert=True) view.flash.assert_success_message('PXE Server "{}": Refresh Relationships ' 'successfully initiated'.format(self.name)) if wait: basic_info = view.entities.basic_information wait_for(lambda lt: lt != basic_info.get_text_of('Last Refreshed On'), func_args=[last_time], fail_func=view.toolbar.reload.click, num_sec=timeout, message="pxe refresh") @variable(alias='db') def get_pxe_image_type(self, image_name): pxe_i = self.appliance.db.client["pxe_images"] pxe_s = self.appliance.db.client["pxe_servers"] pxe_t = self.appliance.db.client["pxe_image_types"] hosts = list(self.appliance.db.client.session.query(pxe_t.name) .join(pxe_i, pxe_i.pxe_image_type_id == pxe_t.id) .join(pxe_s, pxe_i.pxe_server_id == pxe_s.id) .filter(pxe_s.name == self.name) .filter(pxe_i.name == image_name)) if hosts: return hosts[0][0] else: return None @get_pxe_image_type.variant('ui') def get_pxe_image_type_ui(self, image_name): view = navigate_to(self, 'Details') view.sidebar.servers.tree.click_path('All PXE Servers', self.name, 'PXE Images', image_name) details_view = self.create_view(PXESystemImageTypeDetailsView) return details_view.entities.basic_information.get_text_of('Type') def set_pxe_image_type(self, image_name, image_type): """ Function to set the image type of a PXE image """ # todo: maybe create appropriate navmazing destinations instead ? if self.get_pxe_image_type(image_name) != image_type: view = navigate_to(self, 'Details') view.sidebar.servers.tree.click_path('All PXE Servers', self.name, 'PXE Images', image_name) details_view = self.create_view(PXESystemImageTypeDetailsView) details_view.toolbar.configuration.item_select('Edit this PXE Image') edit_view = self.create_view(PXEImageEditView) edit_view.fill({'type': image_type}) edit_view.save.click() @navigator.register(PXEServer, 'All') class PXEServerAll(CFMENavigateStep): VIEW = PXEServersView prerequisite = NavigateToSibling('PXEMainPage') def step(self, *args, **kwargs): self.view.sidebar.servers.tree.click_path('All PXE Servers') @navigator.register(PXEServer, 'Add') class PXEServerAdd(CFMENavigateStep): VIEW = PXEServerAddView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Add a New PXE Server') @navigator.register(PXEServer, 'Details') class PXEServerDetails(CFMENavigateStep): VIEW = PXEServerDetailsView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.sidebar.servers.tree.click_path('All PXE Servers', self.obj.name) @navigator.register(PXEServer, 'Edit') class PXEServerEdit(CFMENavigateStep): VIEW = PXEServerEditView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Edit this PXE Server') class PXECustomizationTemplatesView(PXEMainView): """ represents Customization Template Groups page """ entities = Table(locator='.//div[@id="template_folders_div"]/table') table = Table("//div[@id='main_div']//table") @property def is_displayed(self): return (super().is_displayed and self.title.text == 'All Customization Templates - System Image Types') class PXECustomizationTemplateDetailsView(PXEMainView): """ represents some certain Customization Template Details page """ toolbar = View.nested(PXEDetailsToolBar) @View.nested class entities(View): # noqa basic_information = SummaryTable(title="Basic Information") script = ScriptBox(locator='//textarea[contains(@id, "script_data")]') @property def is_displayed(self): if getattr(self.context['object'], 'name'): title = 'Customization Template "{name}"'.format(name=self.context['object'].name) return (super().is_displayed and self.title.text == title) else: return False class PXECustomizationTemplateForm(View): title = Text('//div[@id="main-content"]//h1') name = Input(id='name') description = Input(id='description') image_type = BootstrapSelect(id='img_typ') type = BootstrapSelect(id='typ') script = ScriptBox(locator='//textarea[contains(@id, "script_data")]') is_displayed = displayed_not_implemented class PXECustomizationTemplateAddView(PXECustomizationTemplateForm): add = Button('Add') cancel = Button('Cancel') class PXECustomizationTemplateEditView(PXECustomizationTemplateForm): save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') class PXECustomizationTemplateCopyView(PXECustomizationTemplateForm): toolbar = View.nested(PXEDetailsToolBar) add = Button('Add') cancel = Button('Cancel') @attr.s class CustomizationTemplate(Updateable, Pretty, BaseEntity): """ Model of a Customization Template in CFME """ pretty_attrs = ['name', 'image_type'] name = attr.ib(default=None) description = attr.ib(default=None) script_data = attr.ib(default=None) image_type = attr.ib(default=None) script_type = attr.ib(default=None) @variable(alias='db') def exists(self): """ Checks if the Customization template already exists """ dbs = self.appliance.db.client candidates = list(dbs.session.query(dbs["customization_templates"])) return self.name in [s.name for s in candidates] @exists.variant('ui') def exists_ui(self): """ Checks if the Customization template already exists """ try: navigate_to(self, 'Details') return True except NoSuchElementException: return False def update(self, updates, cancel=False): """ Updates a Customization Template server in the UI. Better to use utils.update.update context manager than call this directly. Args: updates (dict): fields that are changing. cancel (boolean): whether to cancel out of the update. """ if 'image_type' in updates and updates['image_type'] is None: updates['image_type'] = '<Choose>' elif 'script_type' in updates and updates['script_type'] is None: updates['script_type'] = '<Choose>' view = navigate_to(self, 'Edit') view.fill(updates) main_view = self.create_view(PXECustomizationTemplatesView, override=updates) if cancel: view.cancel.click() else: view.save.click() main_view.flash.assert_no_error() def copy(self, name=None, description=None, cancel=False): """ This method is used to copy a Customization Template server via UI. Args: name (str): This field contains the name of the newly copied Customization Template. description (str) : This field contains the description of the newly copied Customization Template. cancel (bool): It's used for flag to cancel or not the copy operation. """ view = navigate_to(self, 'Copy') name = name or f'Copy of {self.name}' description = description or f'Copy of {self.description}' view.fill({'name': name, 'description': description}) customization_template = self.parent.instantiate(name, description, self.script_data, self.image_type, self.script_type) if cancel: view.cancel.click() else: view.add.click() main_view = self.create_view(PXECustomizationTemplatesView) main_view.flash.assert_no_error() return customization_template @attr.s class CustomizationTemplateCollection(BaseCollection): """Collection class for CustomizationTemplate""" ENTITY = CustomizationTemplate def create(self, name, description, image_type, script_type, script_data, cancel=False): """ Creates a Customization Template object Args: cancel (boolean): Whether to cancel out of the creation. The cancel is done after all the information present in the CT has been filled in the UI. name: Name of CT description:description: The description field of CT. image_type: Image type of the CT. script_data: Contains the script data. script_type: It specifies the script_type of the script. """ customization_templates = self.instantiate(name, description, script_data, image_type, script_type) view = navigate_to(self, 'Add') view.fill({'name': name, 'description': description, 'image_type': image_type, 'type': script_type, 'script': script_data}) main_view = self.create_view(PXECustomizationTemplatesView) if cancel: view.cancel.click() else: view.add.click() main_view.flash.assert_no_error() return customization_templates def delete(self, cancel=False, *ct_objs): """ Deletes a Customization Template server from CFME Args: ct_objs: It's a Customization Template object cancel: Whether to cancel the deletion, defaults to True """ for ct_obj in ct_objs: view = navigate_to(ct_obj, 'Details') view.toolbar.configuration.item_select('Remove this Customization Template', handle_alert=not cancel) view = ct_obj.create_view(PXECustomizationTemplatesView) view.flash.assert_no_error() @navigator.register(CustomizationTemplateCollection, 'All') class CustomizationTemplateAll(CFMENavigateStep): VIEW = PXECustomizationTemplatesView prerequisite = NavigateToSibling('PXEMainPage') def step(self, *args, **kwargs): self.view.sidebar.templates.tree.click_path( 'All Customization Templates - System Image Types' ) @navigator.register(CustomizationTemplateCollection, 'Add') class CustomizationTemplateAdd(CFMENavigateStep): VIEW = PXECustomizationTemplateAddView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Add a New Customization Template') @navigator.register(CustomizationTemplate, 'Details') class CustomizationTemplateDetails(CFMENavigateStep): VIEW = PXECustomizationTemplateDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self, *args, **kwargs): tree = self.view.sidebar.templates.tree tree.click_path('All Customization Templates - System Image Types', self.obj.image_type, self.obj.name) @navigator.register(CustomizationTemplate, 'Copy') class CustomizationTemplateCopy(CFMENavigateStep): VIEW = PXECustomizationTemplateCopyView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.view.toolbar.configuration.item_select("Copy this Customization Template") @navigator.register(CustomizationTemplate, 'Edit') class CustomizationTemplateEdit(CFMENavigateStep): VIEW = PXECustomizationTemplateEditView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Edit this Customization Template') class PXESystemImageTypesView(PXEMainView): """ represents whole All System Image Types page """ @property def is_displayed(self): return (super().is_displayed and self.title.text == 'All System Image Types') class PXESystemImageTypeDetailsView(PXEMainView): toolbar = View.nested(PXEDetailsToolBar) @View.nested class entities(View): # noqa basic_information = SummaryTable(title="Basic Information") is_displayed = displayed_not_implemented class PXESystemImageTypeForm(View): title = Text('//div[@id="main-content"]//h1') name = Input(id='name') type = BootstrapSelect(id='provision_type') is_displayed = displayed_not_implemented class PXESystemImageTypeAddView(PXESystemImageTypeForm): add = Button('Add') cancel = Button('Cancel') class PXESystemImageTypeEditView(PXESystemImageTypeForm): save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') @attr.s class SystemImage(Updateable, BaseEntity): """Model of an ISO System Image in CFME. Args: name: The name of the System Image. It's the same as ISO filename in ISO domain image_type: SystemImageType object datastore: ISODatastore object """ name = attr.ib(default=None) image_type = attr.ib(default=None) datastore = attr.ib(default=None) def set_image_type(self): """Changes the Type field in Basic Information table for System Image in UI.""" view = navigate_to(self, 'Edit') changed = view.image_type.fill_with(self.image_type.name) if changed: view.save.click() else: view.cancel.click() @attr.s class SystemImageCollection(BaseCollection): ENTITY = SystemImage class PXESystemImageDeatilsView(PXEMainView): @property def is_displayed(self): return self.sidebar.datastores.tree.read()[-1] == self.context['object'].name @View.nested class entities(View): # noqa basic_information = SummaryTable(title="Basic Information") class PXESystemImageEditView(PXEMainView): is_displayed = displayed_not_implemented image_type = BootstrapSelect(id='image_typ') save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') @navigator.register(SystemImage, 'Details') class SystemImageDetails(CFMENavigateStep): VIEW = PXESystemImageDeatilsView prerequisite = NavigateToSibling('PXEMainPage') def step(self, *args, **kwargs): self.view.sidebar.datastores.tree.click_path( 'All ISO Datastores', self.view.context['object'].datastore.provider, 'ISO Images', self.view.context['object'].name) @navigator.register(SystemImage, 'Edit') class SystemImageEdit(CFMENavigateStep): VIEW = PXESystemImageEditView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.view.toolbar.configuration.item_select('Edit this ISO Image') @attr.s class SystemImageType(Updateable, Pretty, BaseEntity): """Model of a System Image Type in CFME. Args: name: The name of the System Image Type. provision_type: The provision type, either Vm or Host. """ pretty_attrs = ['name', 'provision_type'] VM_OR_INSTANCE = "VM and Instance" HOST_OR_NODE = "Host / Node" name = attr.ib(default=None) provision_type = attr.ib(default=None) def update(self, updates, cancel=False): """ Updates a System Image Type in the UI. Better to use utils.update.update context manager than call this directly. Args: updates (dict): fields that are changing. cancel (boolean): whether to cancel out of the update. """ view = navigate_to(self, 'Edit') view.fill({'name': updates.get('name'), 'type': updates.get('provision_type')}) if cancel: view.cancel.click() else: view.save.click() # No flash message def delete(self, cancel=True): """ Deletes a System Image Type from CFME Args: cancel: Whether to cancel the deletion, defaults to True """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Remove this System Image Type', handle_alert=not cancel) if not cancel: main_view = self.create_view(PXESystemImageTypesView) msg = f'System Image Type "{self.name}": Delete successful' main_view.flash.assert_success_message(msg) else: navigate_to(self, 'Details') @attr.s class SystemImageTypeCollection(BaseCollection): """ Collection class for SystemImageType. """ ENTITY = SystemImageType def create(self, name, provision_type, cancel=False): """ Creates a System Image Type object Args: name: It contains name of the System Image Type provision_type: Type on Image. i.e Vm and Instance or Host cancel (boolean): Whether to cancel out of the creation. The cancel is done after all the information present in the SIT has been filled in the UI. """ system_image_type = self.instantiate(name, provision_type) view = navigate_to(self, 'Add') view.fill({'name': name, 'type': provision_type}) if cancel: view.cancel.click() msg = 'Add of new System Image Type was cancelled by the user' else: view.add.click() msg = f'System Image Type "{name}" was added' main_view = self.create_view(PXESystemImageTypesView) main_view.flash.assert_success_message(msg) return system_image_type def delete(self, cancel=False, *sys_objs): """ This methods deletes the System Image Type using select option, hence can be used for multiple delete. Args: cancel: This is the boolean argument required for handle_alert sys_objs: It's System Image Types object """ view = navigate_to(self, 'All') for sys_obj in sys_objs: view.entities.row(Name=sys_obj.name)[0].click() view.toolbar.configuration.item_select("Remove System Image Types", handle_alert=not cancel) main_view = self.create_view(PXESystemImageTypesView) main_view.flash.assert_no_error() @navigator.register(SystemImageTypeCollection, 'All') class SystemImageTypeAll(CFMENavigateStep): VIEW = PXESystemImageTypesView prerequisite = NavigateToSibling('PXEMainPage') def step(self, *args, **kwargs): self.view.sidebar.image_types.tree.click_path('All System Image Types') @navigator.register(SystemImageTypeCollection, 'Add') class SystemImageTypeAdd(CFMENavigateStep): VIEW = PXESystemImageTypeAddView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Add a new System Image Type') @navigator.register(SystemImageType, 'Details') class SystemImageTypeDetails(CFMENavigateStep): VIEW = PXESystemImageTypeDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self, *args, **kwargs): self.prerequisite_view.sidebar.image_types.tree.click_path('All System Image Types', self.obj.name) @navigator.register(SystemImageType, 'Edit') class SystemImageTypeEdit(CFMENavigateStep): VIEW = PXESystemImageTypeEditView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Edit this System Image Type') class PXEDatastoresView(PXEMainView): """ represents whole All ISO Datastores page """ @property def is_displayed(self): return (super().is_displayed and self.title.text == 'All ISO Datastores') class PXEDatastoreDetailsView(PXEMainView): toolbar = View.nested(PXEDetailsToolBar) @View.nested class entities(View): # noqa basic_information = SummaryTable(title="Basic Information") is_displayed = displayed_not_implemented class PXEDatastoreForm(View): title = Text('//div[@id="main-content"]//h1') provider = BootstrapSelect(id='ems_id') is_displayed = displayed_not_implemented class PXEDatastoreAddView(PXEDatastoreForm): add = Button('Add') cancel = Button('Cancel') class PXEDatastoreEditView(PXEDatastoreForm): save = Button('Save') reset = Button('Reset') cancel = Button('Cancel') class ISODatastore(Updateable, Pretty, Navigatable): """Model of a PXE Server object in CFME Args: provider: Provider name. """ _param_name = ParamClassName('ds_name') pretty_attrs = ['provider'] def __init__(self, provider=None, appliance=None): Navigatable.__init__(self, appliance=appliance) self.provider = provider def create(self, cancel=False, refresh=True, refresh_timeout=120): """ Creates an ISO datastore object Args: cancel (boolean): Whether to cancel out of the creation. The cancel is done after all the information present in the ISO datastore has been filled in the UI. refresh (boolean): Whether to run the refresh operation on the ISO datastore after the add has been completed. """ view = navigate_to(self, 'Add') view.fill({'provider': self.provider}) main_view = self.create_view(PXEDatastoresView) if cancel: view.cancel.click() msg = 'Add of new ISO Datastore was cancelled by the user' else: view.add.click() msg = f'ISO Datastore "{self.provider}" was added' main_view.flash.assert_success_message(msg) if refresh: self.refresh(timeout=refresh_timeout) @variable(alias='db') def exists(self): """ Checks if the ISO Datastore already exists via db """ iso = self.appliance.db.client['iso_datastores'] ems = self.appliance.db.client['ext_management_systems'] name = self.provider iso_ds = list(self.appliance.db.client.session.query(iso.id) .join(ems, iso.ems_id == ems.id) .filter(ems.name == name)) if iso_ds: return True else: return False @exists.variant('ui') def exists_ui(self): """ Checks if the ISO Datastore already exists via UI """ try: navigate_to(self, 'Details') return True except NoSuchElementException: return False def delete(self, cancel=True): """ Deletes an ISO Datastore from CFME Args: cancel: Whether to cancel the deletion, defaults to True """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Remove this ISO Datastore from Inventory', handle_alert=not cancel) if not cancel: main_view = self.create_view(PXEDatastoresView) main_view.flash.assert_success_message('ISO Datastore "{}": Delete successful' .format(self.provider)) else: navigate_to(self, 'Details') def refresh(self, wait=True, timeout=120): """ Refreshes the PXE relationships and waits for it to be updated """ view = navigate_to(self, 'Details') basic_info = view.entities.basic_information last_time = basic_info.get_text_of('Last Refreshed On') view.toolbar.configuration.item_select('Refresh Relationships', handle_alert=True) view.flash.assert_success_message( f'ISO Datastore "{self.provider}": Refresh Relationships successfully initiated' ) if wait: wait_for(lambda lt: lt != basic_info.get_text_of('Last Refreshed On'), func_args=[last_time], fail_func=view.toolbar.reload.click, num_sec=timeout, message="iso refresh") def set_iso_image_type(self, image_name, image_type): """ Function to set the image type of a PXE image """ view = navigate_to(self, 'All') view.sidebar.datastores.tree.click_path('All ISO Datastores', self.provider, 'ISO Images', image_name) view.toolbar.configuration.item_select('Edit this ISO Image') view = view.browser.create_view(PXEImageEditView) changed = view.fill({'type': image_type}) # Click save if enabled else click Cancel if changed: view.save.click() else: view.cancel.click() @navigator.register(ISODatastore, 'All') class ISODatastoreAll(CFMENavigateStep): VIEW = PXEDatastoresView prerequisite = NavigateToSibling('PXEMainPage') def step(self, *args, **kwargs): self.view.sidebar.datastores.tree.click_path("All ISO Datastores") @navigator.register(ISODatastore, 'Add') class ISODatastoreAdd(CFMENavigateStep): VIEW = PXEDatastoreAddView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.configuration.item_select('Add a New ISO Datastore') @navigator.register(ISODatastore, 'Details') class ISODatastoreDetails(CFMENavigateStep): VIEW = PXEDatastoreDetailsView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.view.sidebar.datastores.tree.click_path("All ISO Datastores", self.obj.provider) @navigator.register(SystemImage, 'PXEMainPage') @navigator.register(PXEServer, 'PXEMainPage') @navigator.register(CustomizationTemplateCollection, 'PXEMainPage') @navigator.register(SystemImageTypeCollection, 'PXEMainPage') @navigator.register(ISODatastore, 'PXEMainPage') class PXEMainPage(CFMENavigateStep): prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') def step(self, *args, **kwargs): self.prerequisite_view.navigation.select('Compute', 'Infrastructure', 'PXE') def get_template_from_config(template_config_name, create=False, appliance=None): """ Convenience function to grab the details for a template from the yamls and create template. """ assert appliance is not None template_config = conf.cfme_data.get('customization_templates', {})[template_config_name] script_data = load_data_file(str(project_path.join(template_config['script_file'])), replacements=template_config['replacements']) script_data = script_data.read() collection = appliance.collections.customization_templates kwargs = { 'name': template_config['name'], 'description': template_config['description'], 'image_type': template_config['image_type'], 'script_type': template_config['script_type'], 'script_data': script_data } customization_template = collection.instantiate(**kwargs) if create and not customization_template.exists(): return collection.create(**kwargs) return customization_template def get_pxe_server_from_config(pxe_config_name, appliance): """ Convenience function to grab the details for a pxe server fomr the yamls. """ pxe_config = conf.cfme_data.get('pxe_servers', {})[pxe_config_name] return PXEServer(name=pxe_config['name'], depot_type=pxe_config['depot_type'], uri=pxe_config['uri'], userid=pxe_config.get('userid') or None, password=pxe_config.get('password') or None, access_url=pxe_config['access_url'], pxe_dir=pxe_config['pxe_dir'], windows_dir=pxe_config['windows_dir'], customize_dir=pxe_config['customize_dir'], menu_filename=pxe_config['menu_filename'], appliance=appliance) def remove_all_pxe_servers(): """ Convenience function to remove all PXE servers """ view = navigate_to(PXEServer, 'All') if view.entities.is_displayed: for entity in view.entities.rows(): entity[0].ensure_checked() view.toolbar.configuration.item_select('Remove PXE Servers', handle_alert=True)
import pytest from cfme import test_requirements from cfme.infrastructure.provider.virtualcenter import VMwareProvider @test_requirements.vmrc @pytest.mark.provider([VMwareProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) def test_vmrc_console(request, appliance, setup_provider, provider, configure_console_vmrc): """ Test VMRC console can be opened for the VMware provider. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" & select "VMware VMRC Plugin"(Applicable to versions older than CFME 5.11). 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few seconds for the VMRC console. """ vms_collections = appliance.collections.infra_vms vm = vms_collections.instantiate(name='cu-24x7', provider=provider) if not vm.exists_on_provider: pytest.skip("Skipping test, cu-24x7 VM does not exist") if appliance.version < '5.11': vm.open_console(console='VM Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) else: vm.open_console(console='VMRC Console', invokes_alert=True) assert vm.vm_console, 'VMConsole object should be created' request.addfinalizer(vm.vm_console.close_console_window) request.addfinalizer(appliance.server.logout) @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['edge', 'internet_explorer']) @pytest.mark.parametrize('operating_system', ['windows7', 'windows10', 'windows_server2012', 'windows_server2016']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_windows(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @test_requirements.vmrc @pytest.mark.manual("manualonly") @pytest.mark.parametrize('browser', ['chrome_latest', 'firefox_latest']) @pytest.mark.parametrize('operating_system', ['fedora_latest', 'rhel8.x', 'rhel7.x', 'rhel6.x']) @pytest.mark.provider([VMwareProvider]) def test_vmrc_console_linux(browser, operating_system, provider): """ This testcase is here to reflect testing matrix for vmrc consoles. Combinations listed are being tested manually. Originally, there was one testcase for every combination, this approach reduces number of needed testcases. Polarion: assignee: apagac casecomponent: Infra caseimportance: high initialEstimate: 2h setup: 1. Login to CFME Appliance as admin. 2. Navigate to Configuration 3. Under VMware Console Support section and click on Dropdown in front of "Use" and select "VMware VMRC Plugin". 4. Click save at the bottom of the page. 5. Provision a testing VM. testSteps: 1. Navigtate to testing VM 2. Launch the console by Access -> VM Console 3. Make sure the console accepts commands 4. Make sure the characters are visible expectedResults: 1. VM Details displayed 2. You should see a Pop-up being Blocked, Please allow it to open (always allow pop-ups for this site) and then a new tab will open and then in few secs, you will see a prompt asking you if you would like to open VMRC, click Yes. Once done, VMRC Window will open(apart from browser) and it will ask you if you would like to View Certificate or Connect anyway or Cancel, please click Connect Anyway. Finally, you should see VM in this window and should be able to interact with it using mouse/keyboard. 3. Console accepts characters 4. Characters not garbled; no visual defect """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_novmrccredsinprovider(): """ Leave the VMRC Creds blank in the provider add/edit dialog and observe behavior trying to launch console. It should fail. Also observe the message in VMRC Console Creds tab about what will happen if creds left blank. Bugzilla: 1550612 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical caseposneg: negative initialEstimate: 1/2h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_addremovevmwarecreds(): """ Add VMware VMRC Console Credentials to a VMware Provider and then Remove it. Bugzilla: 1559957 Polarion: assignee: apagac casecomponent: Appliance initialEstimate: 1/4h startsin: 5.8 testSteps: 1. Compute->Infrastructure->Provider, Add VMware Provider with VMRC Console Creds 2. Edit provider, remove VMware VMRC Console Creds and Save expectedResults: 1. Provider added 2. Provider can be Saved without VMRC Console Creds """ pass @pytest.mark.manual("manualonly") @test_requirements.vmrc @pytest.mark.tier(2) def test_vmrc_console_usecredwithlimitedvmrcaccess(): """ Add Provider in VMware now has a new VMRC Console Tab for adding credentials which will be used to initiate VMRC Connections and these credentials could be less privileged as compared to Admin user but needs to have Console Access. In current VMware env we have "user_interact@vsphere.local" for this purpose. It is setup on vSphere65(NVC) and has no permissions to add network device, suspend vm, install vmware tools or reconfigure floppy. So if you can see your VMRC Console can"t do these operations with user_interact, mark this test as passed. As the sole purpose of this test is to validate correct user and permissions are being used. Bugzilla: 1479840 Polarion: assignee: apagac casecomponent: Appliance caseimportance: critical initialEstimate: 1/2h startsin: 5.8 """ pass
ManageIQ/integration_tests
cfme/tests/infrastructure/test_vmrc_console.py
cfme/infrastructure/pxe.py
# flake8: noqa from pandas.core.reshape.concat import concat from pandas.core.reshape.melt import lreshape, melt, wide_to_long from pandas.core.reshape.merge import merge, merge_asof, merge_ordered from pandas.core.reshape.pivot import crosstab, pivot, pivot_table from pandas.core.reshape.reshape import get_dummies from pandas.core.reshape.tile import cut, qcut
import numpy as np import pytest import pandas.util._test_decorators as td from pandas import Categorical, DataFrame, MultiIndex, Series, date_range import pandas._testing as tm class TestDataFrameToXArray: @pytest.fixture def df(self): return DataFrame( { "a": list("abc"), "b": list(range(1, 4)), "c": np.arange(3, 6).astype("u1"), "d": np.arange(4.0, 7.0, dtype="float64"), "e": [True, False, True], "f": Categorical(list("abc")), "g": date_range("20130101", periods=3), "h": date_range("20130101", periods=3, tz="US/Eastern"), } ) @td.skip_if_no("xarray", "0.10.0") def test_to_xarray_index_types(self, index, df): if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") if len(index) == 0: pytest.skip("Test doesn't make sense for empty index") from xarray import Dataset df.index = index[:3] df.index.name = "foo" df.columns.name = "bar" result = df.to_xarray() assert result.dims["foo"] == 3 assert len(result.coords) == 1 assert len(result.data_vars) == 8 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, Dataset) # idempotency # datetimes w/tz are preserved # column names are lost expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None tm.assert_frame_equal(result.to_dataframe(), expected) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_empty(self, df): from xarray import Dataset df.index.name = "foo" result = df[0:0].to_xarray() assert result.dims["foo"] == 0 assert isinstance(result, Dataset) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_with_multiindex(self, df): from xarray import Dataset # available in 0.7.1 # MultiIndex df.index = MultiIndex.from_product([["a"], range(3)], names=["one", "two"]) result = df.to_xarray() assert result.dims["one"] == 1 assert result.dims["two"] == 3 assert len(result.coords) == 2 assert len(result.data_vars) == 8 tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, Dataset) result = result.to_dataframe() expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None tm.assert_frame_equal(result, expected) class TestSeriesToXArray: @td.skip_if_no("xarray", "0.10.0") def test_to_xarray_index_types(self, index): if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") from xarray import DataArray ser = Series(range(len(index)), index=index, dtype="int64") ser.index.name = "foo" result = ser.to_xarray() repr(result) assert len(result) == len(index) assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) # idempotency tm.assert_series_equal(result.to_series(), ser) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_empty(self): from xarray import DataArray ser = Series([], dtype=object) ser.index.name = "foo" result = ser.to_xarray() assert len(result) == 0 assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_with_multiindex(self): from xarray import DataArray mi = MultiIndex.from_product([["a", "b"], range(3)], names=["one", "two"]) ser = Series(range(6), dtype="int64", index=mi) result = ser.to_xarray() assert len(result) == 2 tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, DataArray) res = result.to_series() tm.assert_series_equal(res, ser)
gfyoung/pandas
pandas/tests/generic/test_to_xarray.py
pandas/core/reshape/api.py
from pandas.core.arrays.base import ( ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin, ) from pandas.core.arrays.boolean import BooleanArray from pandas.core.arrays.categorical import Categorical from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.floating import FloatingArray from pandas.core.arrays.integer import IntegerArray from pandas.core.arrays.interval import IntervalArray from pandas.core.arrays.masked import BaseMaskedArray from pandas.core.arrays.numpy_ import PandasArray, PandasDtype from pandas.core.arrays.period import PeriodArray, period_array from pandas.core.arrays.sparse import SparseArray from pandas.core.arrays.string_ import StringArray from pandas.core.arrays.timedeltas import TimedeltaArray __all__ = [ "ExtensionArray", "ExtensionOpsMixin", "ExtensionScalarOpsMixin", "BaseMaskedArray", "BooleanArray", "Categorical", "DatetimeArray", "FloatingArray", "IntegerArray", "IntervalArray", "PandasArray", "PandasDtype", "PeriodArray", "period_array", "SparseArray", "StringArray", "TimedeltaArray", ]
import numpy as np import pytest import pandas.util._test_decorators as td from pandas import Categorical, DataFrame, MultiIndex, Series, date_range import pandas._testing as tm class TestDataFrameToXArray: @pytest.fixture def df(self): return DataFrame( { "a": list("abc"), "b": list(range(1, 4)), "c": np.arange(3, 6).astype("u1"), "d": np.arange(4.0, 7.0, dtype="float64"), "e": [True, False, True], "f": Categorical(list("abc")), "g": date_range("20130101", periods=3), "h": date_range("20130101", periods=3, tz="US/Eastern"), } ) @td.skip_if_no("xarray", "0.10.0") def test_to_xarray_index_types(self, index, df): if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") if len(index) == 0: pytest.skip("Test doesn't make sense for empty index") from xarray import Dataset df.index = index[:3] df.index.name = "foo" df.columns.name = "bar" result = df.to_xarray() assert result.dims["foo"] == 3 assert len(result.coords) == 1 assert len(result.data_vars) == 8 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, Dataset) # idempotency # datetimes w/tz are preserved # column names are lost expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None tm.assert_frame_equal(result.to_dataframe(), expected) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_empty(self, df): from xarray import Dataset df.index.name = "foo" result = df[0:0].to_xarray() assert result.dims["foo"] == 0 assert isinstance(result, Dataset) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_with_multiindex(self, df): from xarray import Dataset # available in 0.7.1 # MultiIndex df.index = MultiIndex.from_product([["a"], range(3)], names=["one", "two"]) result = df.to_xarray() assert result.dims["one"] == 1 assert result.dims["two"] == 3 assert len(result.coords) == 2 assert len(result.data_vars) == 8 tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, Dataset) result = result.to_dataframe() expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None tm.assert_frame_equal(result, expected) class TestSeriesToXArray: @td.skip_if_no("xarray", "0.10.0") def test_to_xarray_index_types(self, index): if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") from xarray import DataArray ser = Series(range(len(index)), index=index, dtype="int64") ser.index.name = "foo" result = ser.to_xarray() repr(result) assert len(result) == len(index) assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) # idempotency tm.assert_series_equal(result.to_series(), ser) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_empty(self): from xarray import DataArray ser = Series([], dtype=object) ser.index.name = "foo" result = ser.to_xarray() assert len(result) == 0 assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray_with_multiindex(self): from xarray import DataArray mi = MultiIndex.from_product([["a", "b"], range(3)], names=["one", "two"]) ser = Series(range(6), dtype="int64", index=mi) result = ser.to_xarray() assert len(result) == 2 tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, DataArray) res = result.to_series() tm.assert_series_equal(res, ser)
gfyoung/pandas
pandas/tests/generic/test_to_xarray.py
pandas/core/arrays/__init__.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import with_statement from decimal import Decimal from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from parler.models import TranslatableModel, TranslatedFields from shuup.core.fields import InternalIdentifierField from shuup.utils.numbers import bankers_round, parse_decimal_string __all__ = ("SalesUnit",) @python_2_unicode_compatible class SalesUnit(TranslatableModel): identifier = InternalIdentifierField(unique=True) decimals = models.PositiveSmallIntegerField(default=0, verbose_name=_(u"allowed decimals")) translations = TranslatedFields( name=models.CharField(max_length=128, verbose_name=_('name')), short_name=models.CharField(max_length=128, verbose_name=_('short name')), ) class Meta: verbose_name = _('sales unit') verbose_name_plural = _('sales units') def __str__(self): return self.safe_translation_getter("name", default=None) @property def allow_fractions(self): return self.decimals > 0 @cached_property def quantity_step(self): """ Get the quantity increment for the amount of decimals this unit allows. For 0 decimals, this will be 1; for 1 decimal, 0.1; etc. :return: Decimal in (0..1] :rtype: Decimal """ # This particular syntax (`10 ^ -n`) is the same that `bankers_round` uses # to figure out the quantizer. return Decimal(10) ** (-int(self.decimals)) def round(self, value): return bankers_round(parse_decimal_string(value), self.decimals)
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest import random from shuup.admin.modules.products.views.edit import ProductEditView from shuup.core.models import StockBehavior, Supplier from shuup.simple_supplier.admin_module.forms import SimpleSupplierForm from shuup.simple_supplier.admin_module.views import ( process_alert_limit, process_stock_adjustment ) from shuup.simple_supplier.models import StockCount from shuup.testing.factories import ( create_order_with_product, create_product, get_default_shop ) from shuup_tests.simple_supplier.utils import get_simple_supplier @pytest.mark.django_db def test_simple_supplier(rf): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop) ss = supplier.get_stock_status(product.pk) assert ss.product == product assert ss.logical_count == 0 num = random.randint(100, 500) supplier.adjust_stock(product.pk, +num) assert supplier.get_stock_status(product.pk).logical_count == num # Create order ... order = create_order_with_product(product, supplier, 10, 3, shop=shop) quantities = order.get_product_ids_and_quantities() pss = supplier.get_stock_status(product.pk) assert pss.logical_count == (num - quantities[product.pk]) assert pss.physical_count == num # Create shipment ... order.create_shipment_of_all_products(supplier) pss = supplier.get_stock_status(product.pk) assert pss.physical_count == (num - quantities[product.pk]) # Cancel order... order.set_canceled() pss = supplier.get_stock_status(product.pk) assert pss.logical_count == (num) @pytest.mark.django_db def test_supplier_with_stock_counts(rf): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) quantity = random.randint(100, 600) supplier.adjust_stock(product.pk, quantity) assert supplier.get_stock_statuses([product.id])[product.id].logical_count == quantity # No orderability errors since product is not stocked assert not list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity+1, customer=None)) product.stock_behavior = StockBehavior.STOCKED # Make product stocked product.save() assert not list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity, customer=None)) # Now since product is stocked we get orderability error with quantity + 1 assert list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity+1, customer=None)) @pytest.mark.django_db def test_supplier_with_stock_counts(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) quantity = random.randint(100, 600) supplier.adjust_stock(product.pk, quantity) adjust_quantity = random.randint(100, 600) request = rf.get("/") request.user = admin_user request.POST = { "purchase_price": decimal.Decimal(32.00), "delta": adjust_quantity } response = process_stock_adjustment(request, supplier.id, product.id) assert response.status_code == 400 # Only POST is allowed request.method = "POST" response = process_stock_adjustment(request, supplier.id, product.id) assert response.status_code == 200 pss = supplier.get_stock_status(product.pk) # Product stock values should be adjusted assert pss.logical_count == (quantity + adjust_quantity) @pytest.mark.django_db def test_admin_form(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) request = rf.get("/") request.user = admin_user frm = SimpleSupplierForm(product=product, request=request) # Form contains 1 product even if the product is not stocked assert len(frm.products) == 1 assert not frm.products[0].is_stocked() product.stock_behavior = StockBehavior.STOCKED # Make product stocked product.save() # Now since product is stocked it should be in the form frm = SimpleSupplierForm(product=product, request=request) assert len(frm.products) == 1 # Add stocked children for product child_product = create_product("child-test-product", shop, supplier) child_product.stock_behavior = StockBehavior.STOCKED child_product.save() child_product.link_to_parent(product) # Admin form should now contain only child products for product frm = SimpleSupplierForm(product=product, request=request) assert len(frm.products) == 1 assert frm.products[0] == child_product @pytest.mark.django_db def test_new_product_admin_form_renders(rf, client, admin_user): """ Make sure that no exceptions are raised when creating a new product with simple supplier enabled """ request = rf.get("/") request.user = admin_user request.session = client.session view = ProductEditView.as_view() shop = get_default_shop() supplier = get_simple_supplier() supplier.stock_managed = True supplier.save() # This should not raise an exception view(request).render() supplier.stock_managed = False supplier.save() # Nor should this view(request).render() def test_alert_limit_view(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) sc = StockCount.objects.get(supplier=supplier, product=product) assert not sc.alert_limit test_alert_limit = decimal.Decimal(10) request = rf.get("/") request.user = admin_user request.method = "POST" request.POST = { "alert_limit": test_alert_limit, } response = process_alert_limit(request, supplier.id, product.id) assert response.status_code == 200 sc = StockCount.objects.get(supplier=supplier, product=product) assert sc.alert_limit == test_alert_limit
hrayr-artunyan/shuup
shuup_tests/simple_supplier/test_simple_supplier.py
shuup/core/models/_units.py
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import decimal from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import ugettext_lazy as _ from enumfields import Enum from parler.models import TranslatableModel, TranslatedField, TranslatedFields from shuup.core.fields import MeasurementField, MoneyValueField from ._service_base import ( ServiceBehaviorComponent, ServiceCost, TranslatableServiceBehaviorComponent ) class FixedCostBehaviorComponent(TranslatableServiceBehaviorComponent): name = _("Fixed cost") help_text = _("Add fixed cost to price of the service.") price_value = MoneyValueField() description = TranslatedField(any_language=True) translations = TranslatedFields( description=models.CharField(max_length=100, blank=True, verbose_name=_("description")), ) def get_costs(self, service, source): price = source.create_price(self.price_value) description = self.safe_translation_getter('description') yield ServiceCost(price, description) class WaivingCostBehaviorComponent(TranslatableServiceBehaviorComponent): name = _("Waiving cost") help_text = _( "Add cost to price of the service if total price " "of products is less than a waive limit.") price_value = MoneyValueField() waive_limit_value = MoneyValueField() description = TranslatedField(any_language=True) translations = TranslatedFields( description=models.CharField(max_length=100, blank=True, verbose_name=_("description")), ) def get_costs(self, service, source): waive_limit = source.create_price(self.waive_limit_value) product_total = source.total_price_of_products price = source.create_price(self.price_value) description = self.safe_translation_getter('description') zero_price = source.create_price(0) if product_total and product_total >= waive_limit: yield ServiceCost(zero_price, description, base_price=price) else: yield ServiceCost(price, description) class WeightLimitsBehaviorComponent(ServiceBehaviorComponent): name = _("Weight limits") help_text = _( "Limit availability of the service based on " "total weight of products.") min_weight = models.DecimalField( max_digits=36, decimal_places=6, blank=True, null=True, verbose_name=_("minimum weight")) max_weight = models.DecimalField( max_digits=36, decimal_places=6, blank=True, null=True, verbose_name=_("maximum weight")) def get_unavailability_reasons(self, service, source): weight = sum(((x.get("weight") or 0) for x in source.get_lines()), 0) if self.min_weight: if weight < self.min_weight: yield ValidationError(_("Minimum weight not met."), code="min_weight") if self.max_weight: if weight > self.max_weight: yield ValidationError(_("Maximum weight exceeded."), code="max_weight") class WeightBasedPriceRange(TranslatableModel): component = models.ForeignKey( "WeightBasedPricingBehaviorComponent", related_name="ranges", on_delete=models.CASCADE ) min_value = MeasurementField(unit="g", verbose_name=_("min weight"), blank=True, null=True) max_value = MeasurementField(unit="g", verbose_name=_("max weight"), blank=True, null=True) price_value = MoneyValueField() description = TranslatedField(any_language=True) translations = TranslatedFields( description=models.CharField(max_length=100, blank=True, verbose_name=_("description")), ) def matches_to_value(self, value): return _is_in_range(value, self.min_value, self.max_value) def _is_in_range(value, min_value, max_value): """ Help function to check if the ``WeightBasedPriceRange`` matches If min_value is None the max_value determines if the range matches. None as a max_value represents infinity. Min value is counted in range only when it's zero. Max value is always part of the range. :type value: decimal.Decimal :type min_value: MeasurementField :type max_value: MeasurementField :rtype: bool """ if value is None: return False if (not (min_value or max_value)) or (min_value == max_value == value): return True if (not min_value or value > min_value) and (max_value is None or value <= max_value): return True return False class WeightBasedPricingBehaviorComponent(ServiceBehaviorComponent): name = _("Weight-based pricing") help_text = _( "Define price based on basket weight. " "Range minimums is counted in range only as zero.") def _get_matching_range_with_lowest_price(self, source): total_gross_weight = source.total_gross_weight matching_ranges = [range for range in self.ranges.all() if range.matches_to_value(total_gross_weight)] if not matching_ranges: return return min(matching_ranges, key=lambda x: x.price_value) def get_costs(self, service, source): range = self._get_matching_range_with_lowest_price(source) if range: price = source.create_price(range.price_value) description = range.safe_translation_getter('description') yield ServiceCost(price, description) def get_unavailability_reasons(self, service, source): range = self._get_matching_range_with_lowest_price(source) if not range: yield ValidationError(_("Weight does not match with any range."), code="out_of_range") class GroupAvailabilityBehaviorComponent(ServiceBehaviorComponent): name = _("Contact group availability") help_text = _("Limit service availability for specific contact groups.") groups = models.ManyToManyField("ContactGroup", verbose_name=_("groups")) def get_unavailability_reasons(self, service, source): if source.customer and not source.customer.pk: yield ValidationError(_("Customer does not belong to any group.")) return customer_groups = set(source.customer.groups.all().values_list("pk", flat=True)) groups_to_match = set(self.groups.all().values_list("pk", flat=True)) if not bool(customer_groups & groups_to_match): yield ValidationError(_("Service is not available for any of the customers groups.")) class StaffOnlyBehaviorComponent(ServiceBehaviorComponent): name = _("Staff only availability") help_text = _("Limit service availability to staff only") def get_unavailability_reasons(self, service, source): if not source.creator or not source.creator.is_staff: yield ValidationError(_("Service is only available for staff")) class RoundingMode(Enum): ROUND_HALF_UP = decimal.ROUND_HALF_UP ROUND_HALF_DOWN = decimal.ROUND_HALF_DOWN ROUND_UP = decimal.ROUND_UP ROUND_DOWN = decimal.ROUND_DOWN class Labels: ROUND_HALF_UP = _("round to nearest with ties going away from zero") ROUND_HALF_DOWN = _("round to nearest with ties going towards zero") ROUND_UP = _("round away from zero") ROUND_DOWN = _("round towards zero")
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest import random from shuup.admin.modules.products.views.edit import ProductEditView from shuup.core.models import StockBehavior, Supplier from shuup.simple_supplier.admin_module.forms import SimpleSupplierForm from shuup.simple_supplier.admin_module.views import ( process_alert_limit, process_stock_adjustment ) from shuup.simple_supplier.models import StockCount from shuup.testing.factories import ( create_order_with_product, create_product, get_default_shop ) from shuup_tests.simple_supplier.utils import get_simple_supplier @pytest.mark.django_db def test_simple_supplier(rf): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop) ss = supplier.get_stock_status(product.pk) assert ss.product == product assert ss.logical_count == 0 num = random.randint(100, 500) supplier.adjust_stock(product.pk, +num) assert supplier.get_stock_status(product.pk).logical_count == num # Create order ... order = create_order_with_product(product, supplier, 10, 3, shop=shop) quantities = order.get_product_ids_and_quantities() pss = supplier.get_stock_status(product.pk) assert pss.logical_count == (num - quantities[product.pk]) assert pss.physical_count == num # Create shipment ... order.create_shipment_of_all_products(supplier) pss = supplier.get_stock_status(product.pk) assert pss.physical_count == (num - quantities[product.pk]) # Cancel order... order.set_canceled() pss = supplier.get_stock_status(product.pk) assert pss.logical_count == (num) @pytest.mark.django_db def test_supplier_with_stock_counts(rf): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) quantity = random.randint(100, 600) supplier.adjust_stock(product.pk, quantity) assert supplier.get_stock_statuses([product.id])[product.id].logical_count == quantity # No orderability errors since product is not stocked assert not list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity+1, customer=None)) product.stock_behavior = StockBehavior.STOCKED # Make product stocked product.save() assert not list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity, customer=None)) # Now since product is stocked we get orderability error with quantity + 1 assert list(supplier.get_orderability_errors(product.get_shop_instance(shop), quantity+1, customer=None)) @pytest.mark.django_db def test_supplier_with_stock_counts(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) quantity = random.randint(100, 600) supplier.adjust_stock(product.pk, quantity) adjust_quantity = random.randint(100, 600) request = rf.get("/") request.user = admin_user request.POST = { "purchase_price": decimal.Decimal(32.00), "delta": adjust_quantity } response = process_stock_adjustment(request, supplier.id, product.id) assert response.status_code == 400 # Only POST is allowed request.method = "POST" response = process_stock_adjustment(request, supplier.id, product.id) assert response.status_code == 200 pss = supplier.get_stock_status(product.pk) # Product stock values should be adjusted assert pss.logical_count == (quantity + adjust_quantity) @pytest.mark.django_db def test_admin_form(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) request = rf.get("/") request.user = admin_user frm = SimpleSupplierForm(product=product, request=request) # Form contains 1 product even if the product is not stocked assert len(frm.products) == 1 assert not frm.products[0].is_stocked() product.stock_behavior = StockBehavior.STOCKED # Make product stocked product.save() # Now since product is stocked it should be in the form frm = SimpleSupplierForm(product=product, request=request) assert len(frm.products) == 1 # Add stocked children for product child_product = create_product("child-test-product", shop, supplier) child_product.stock_behavior = StockBehavior.STOCKED child_product.save() child_product.link_to_parent(product) # Admin form should now contain only child products for product frm = SimpleSupplierForm(product=product, request=request) assert len(frm.products) == 1 assert frm.products[0] == child_product @pytest.mark.django_db def test_new_product_admin_form_renders(rf, client, admin_user): """ Make sure that no exceptions are raised when creating a new product with simple supplier enabled """ request = rf.get("/") request.user = admin_user request.session = client.session view = ProductEditView.as_view() shop = get_default_shop() supplier = get_simple_supplier() supplier.stock_managed = True supplier.save() # This should not raise an exception view(request).render() supplier.stock_managed = False supplier.save() # Nor should this view(request).render() def test_alert_limit_view(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) sc = StockCount.objects.get(supplier=supplier, product=product) assert not sc.alert_limit test_alert_limit = decimal.Decimal(10) request = rf.get("/") request.user = admin_user request.method = "POST" request.POST = { "alert_limit": test_alert_limit, } response = process_alert_limit(request, supplier.id, product.id) assert response.status_code == 200 sc = StockCount.objects.get(supplier=supplier, product=product) assert sc.alert_limit == test_alert_limit
hrayr-artunyan/shuup
shuup_tests/simple_supplier/test_simple_supplier.py
shuup/core/models/_service_behavior.py
"""All methods needed to bootstrap a Home Assistant instance.""" import asyncio import logging.handlers from timeit import default_timer as timer from types import ModuleType from typing import Optional, Dict, List from homeassistant import requirements, core, loader, config as conf_util from homeassistant.config import async_notify_setup_error from homeassistant.const import EVENT_COMPONENT_LOADED, PLATFORM_FORMAT from homeassistant.exceptions import HomeAssistantError from homeassistant.util.async_ import run_coroutine_threadsafe _LOGGER = logging.getLogger(__name__) ATTR_COMPONENT = 'component' DATA_SETUP = 'setup_tasks' DATA_DEPS_REQS = 'deps_reqs_processed' SLOW_SETUP_WARNING = 10 def setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict] = None) -> bool: """Set up a component and all its dependencies.""" return run_coroutine_threadsafe( # type: ignore async_setup_component(hass, domain, config), loop=hass.loop).result() async def async_setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict] = None) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.get(DATA_SETUP) if setup_tasks is not None and domain in setup_tasks: return await setup_tasks[domain] # type: ignore if config is None: config = {} if setup_tasks is None: setup_tasks = hass.data[DATA_SETUP] = {} task = setup_tasks[domain] = hass.async_create_task( _async_setup_component(hass, domain, config)) return await task # type: ignore async def _async_process_dependencies( hass: core.HomeAssistant, config: Dict, name: str, dependencies: List[str]) -> bool: """Ensure all dependencies are set up.""" blacklisted = [dep for dep in dependencies if dep in loader.DEPENDENCY_BLACKLIST] if blacklisted: _LOGGER.error("Unable to set up dependencies of %s: " "found blacklisted dependencies: %s", name, ', '.join(blacklisted)) return False tasks = [async_setup_component(hass, dep, config) for dep in dependencies] if not tasks: return True results = await asyncio.gather(*tasks, loop=hass.loop) failed = [dependencies[idx] for idx, res in enumerate(results) if not res] if failed: _LOGGER.error("Unable to set up dependencies of %s. " "Setup failed for dependencies: %s", name, ', '.join(failed)) return False return True async def _async_setup_component(hass: core.HomeAssistant, domain: str, config: Dict) -> bool: """Set up a component for Home Assistant. This method is a coroutine. """ def log_error(msg: str, link: bool = True) -> None: """Log helper.""" _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) component = loader.get_component(hass, domain) if not component: log_error("Component not found.", False) return False # Validate no circular dependencies components = loader.load_order_component(hass, domain) # OrderedSet is empty if component or dependencies could not be resolved if not components: log_error("Unable to resolve component or dependencies.") return False processed_config = \ conf_util.async_process_component_config(hass, config, domain) if processed_config is None: log_error("Invalid config.") return False try: await async_process_deps_reqs(hass, config, domain, component) except HomeAssistantError as err: log_error(str(err)) return False start = timer() _LOGGER.info("Setting up %s", domain) if hasattr(component, 'PLATFORM_SCHEMA'): # Entity components have their own warning warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING) try: if hasattr(component, 'async_setup'): result = await component.async_setup( # type: ignore hass, processed_config) else: result = await hass.async_add_executor_job( component.setup, hass, processed_config) # type: ignore except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, True) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds.", domain, end - start) if result is False: log_error("Component failed to initialize.") return False if result is not True: log_error("Component did not return boolean if setup was successful. " "Disabling component.") loader.set_component(hass, domain, None) return False if hass.config_entries: for entry in hass.config_entries.async_entries(domain): await entry.async_setup(hass, component=component) hass.config.components.add(component.DOMAIN) # type: ignore # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire( EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN} # type: ignore ) return True async def async_prepare_setup_platform(hass: core.HomeAssistant, config: Dict, domain: str, platform_name: str) \ -> Optional[ModuleType]: """Load a platform and makes sure dependencies are setup. This method is a coroutine. """ platform_path = PLATFORM_FORMAT.format(domain, platform_name) def log_error(msg: str) -> None: """Log helper.""" _LOGGER.error("Unable to prepare setup for platform %s: %s", platform_path, msg) async_notify_setup_error(hass, platform_path) platform = loader.get_platform(hass, domain, platform_name) # Not found if platform is None: log_error("Platform not found.") return None # Already loaded if platform_path in hass.config.components: return platform try: await async_process_deps_reqs( hass, config, platform_path, platform) except HomeAssistantError as err: log_error(str(err)) return None return platform async def async_process_deps_reqs( hass: core.HomeAssistant, config: Dict, name: str, module: ModuleType) -> None: """Process all dependencies and requirements for a module. Module is a Python module of either a component or platform. """ processed = hass.data.get(DATA_DEPS_REQS) if processed is None: processed = hass.data[DATA_DEPS_REQS] = set() elif name in processed: return if hasattr(module, 'DEPENDENCIES'): dep_success = await _async_process_dependencies( hass, config, name, module.DEPENDENCIES) # type: ignore if not dep_success: raise HomeAssistantError("Could not set up all dependencies.") if not hass.config.skip_pip and hasattr(module, 'REQUIREMENTS'): req_success = await requirements.async_process_requirements( hass, name, module.REQUIREMENTS) # type: ignore if not req_success: raise HomeAssistantError("Could not install all requirements.") processed.add(name)
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/setup.py
""" Integration with the Rachio Iro sprinkler system controller. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.rachio/ """ from abc import abstractmethod import logging from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.components.rachio import (DOMAIN as DOMAIN_RACHIO, KEY_DEVICE_ID, KEY_STATUS, KEY_SUBTYPE, SIGNAL_RACHIO_CONTROLLER_UPDATE, STATUS_OFFLINE, STATUS_ONLINE, SUBTYPE_OFFLINE, SUBTYPE_ONLINE,) from homeassistant.helpers.dispatcher import dispatcher_connect DEPENDENCIES = ['rachio'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Rachio binary sensors.""" devices = [] for controller in hass.data[DOMAIN_RACHIO].controllers: devices.append(RachioControllerOnlineBinarySensor(hass, controller)) add_entities(devices) _LOGGER.info("%d Rachio binary sensor(s) added", len(devices)) class RachioControllerBinarySensor(BinarySensorDevice): """Represent a binary sensor that reflects a Rachio state.""" def __init__(self, hass, controller, poll=True): """Set up a new Rachio controller binary sensor.""" self._controller = controller if poll: self._state = self._poll_update() else: self._state = None dispatcher_connect(hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._handle_any_update) @property def should_poll(self) -> bool: """Declare that this entity pushes its state to HA.""" return False @property def is_on(self) -> bool: """Return whether the sensor has a 'true' value.""" return self._state def _handle_any_update(self, *args, **kwargs) -> None: """Determine whether an update event applies to this device.""" if args[0][KEY_DEVICE_ID] != self._controller.controller_id: # For another device return # For this device self._handle_update() @abstractmethod def _poll_update(self, data=None) -> bool: """Request the state from the API.""" pass @abstractmethod def _handle_update(self, *args, **kwargs) -> None: """Handle an update to the state of this sensor.""" pass class RachioControllerOnlineBinarySensor(RachioControllerBinarySensor): """Represent a binary sensor that reflects if the controller is online.""" def __init__(self, hass, controller): """Set up a new Rachio controller online binary sensor.""" super().__init__(hass, controller, poll=False) self._state = self._poll_update(controller.init_data) @property def name(self) -> str: """Return the name of this sensor including the controller name.""" return "{} online".format(self._controller.name) @property def unique_id(self) -> str: """Return a unique id for this entity.""" return "{}-online".format(self._controller.controller_id) @property def device_class(self) -> str: """Return the class of this device, from component DEVICE_CLASSES.""" return 'connectivity' @property def icon(self) -> str: """Return the name of an icon for this sensor.""" return 'mdi:wifi-strength-4' if self.is_on\ else 'mdi:wifi-strength-off-outline' def _poll_update(self, data=None) -> bool: """Request the state from the API.""" if data is None: data = self._controller.rachio.device.get( self._controller.controller_id)[1] if data[KEY_STATUS] == STATUS_ONLINE: return True if data[KEY_STATUS] == STATUS_OFFLINE: return False _LOGGER.warning('"%s" reported in unknown state "%s"', self.name, data[KEY_STATUS]) def _handle_update(self, *args, **kwargs) -> None: """Handle an update to the state of this sensor.""" if args[0][KEY_SUBTYPE] == SUBTYPE_ONLINE: self._state = True elif args[0][KEY_SUBTYPE] == SUBTYPE_OFFLINE: self._state = False self.schedule_update_ha_state()
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/binary_sensor/rachio.py
""" Provide functionality to keep track of devices. For more details about this component, please refer to the documentation at https://home-assistant.io/components/device_tracker/ """ import asyncio from datetime import timedelta import logging from typing import Any, List, Sequence, Callable import voluptuous as vol from homeassistant.setup import async_prepare_setup_platform from homeassistant.core import callback from homeassistant.loader import bind_hass from homeassistant.components import group, zone from homeassistant.components.group import ( ATTR_ADD_ENTITIES, ATTR_ENTITIES, ATTR_OBJECT_ID, ATTR_VISIBLE, DOMAIN as DOMAIN_GROUP, SERVICE_SET) from homeassistant.components.zone.zone import async_active_zone from homeassistant.config import load_yaml_config_file, async_log_exception from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform, discovery from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.restore_state import async_get_last_state from homeassistant.helpers.typing import GPSType, ConfigType, HomeAssistantType import homeassistant.helpers.config_validation as cv from homeassistant import util from homeassistant.util.async_ import run_coroutine_threadsafe import homeassistant.util.dt as dt_util from homeassistant.util.yaml import dump from homeassistant.helpers.event import async_track_utc_time_change from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_GPS_ACCURACY, ATTR_ICON, ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_NAME, CONF_ICON, CONF_MAC, CONF_NAME, DEVICE_DEFAULT_NAME, STATE_NOT_HOME, STATE_HOME) _LOGGER = logging.getLogger(__name__) DOMAIN = 'device_tracker' DEPENDENCIES = ['zone', 'group'] GROUP_NAME_ALL_DEVICES = 'all devices' ENTITY_ID_ALL_DEVICES = group.ENTITY_ID_FORMAT.format('all_devices') ENTITY_ID_FORMAT = DOMAIN + '.{}' YAML_DEVICES = 'known_devices.yaml' CONF_TRACK_NEW = 'track_new_devices' DEFAULT_TRACK_NEW = True CONF_NEW_DEVICE_DEFAULTS = 'new_device_defaults' CONF_CONSIDER_HOME = 'consider_home' DEFAULT_CONSIDER_HOME = timedelta(seconds=180) CONF_SCAN_INTERVAL = 'interval_seconds' DEFAULT_SCAN_INTERVAL = timedelta(seconds=12) CONF_AWAY_HIDE = 'hide_if_away' DEFAULT_AWAY_HIDE = False EVENT_NEW_DEVICE = 'device_tracker_new_device' SERVICE_SEE = 'see' ATTR_ATTRIBUTES = 'attributes' ATTR_BATTERY = 'battery' ATTR_DEV_ID = 'dev_id' ATTR_GPS = 'gps' ATTR_HOST_NAME = 'host_name' ATTR_LOCATION_NAME = 'location_name' ATTR_MAC = 'mac' ATTR_SOURCE_TYPE = 'source_type' ATTR_CONSIDER_HOME = 'consider_home' SOURCE_TYPE_GPS = 'gps' SOURCE_TYPE_ROUTER = 'router' SOURCE_TYPE_BLUETOOTH = 'bluetooth' SOURCE_TYPE_BLUETOOTH_LE = 'bluetooth_le' SOURCE_TYPES = (SOURCE_TYPE_GPS, SOURCE_TYPE_ROUTER, SOURCE_TYPE_BLUETOOTH, SOURCE_TYPE_BLUETOOTH_LE) NEW_DEVICE_DEFAULTS_SCHEMA = vol.Any(None, vol.Schema({ vol.Optional(CONF_TRACK_NEW, default=DEFAULT_TRACK_NEW): cv.boolean, vol.Optional(CONF_AWAY_HIDE, default=DEFAULT_AWAY_HIDE): cv.boolean, })) PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend({ vol.Optional(CONF_SCAN_INTERVAL): cv.time_period, vol.Optional(CONF_TRACK_NEW): cv.boolean, vol.Optional(CONF_CONSIDER_HOME, default=DEFAULT_CONSIDER_HOME): vol.All( cv.time_period, cv.positive_timedelta), vol.Optional(CONF_NEW_DEVICE_DEFAULTS, default={}): NEW_DEVICE_DEFAULTS_SCHEMA }) SERVICE_SEE_PAYLOAD_SCHEMA = vol.Schema(vol.All( cv.has_at_least_one_key(ATTR_MAC, ATTR_DEV_ID), { ATTR_MAC: cv.string, ATTR_DEV_ID: cv.string, ATTR_HOST_NAME: cv.string, ATTR_LOCATION_NAME: cv.string, ATTR_GPS: cv.gps, ATTR_GPS_ACCURACY: cv.positive_int, ATTR_BATTERY: cv.positive_int, ATTR_ATTRIBUTES: dict, ATTR_SOURCE_TYPE: vol.In(SOURCE_TYPES), ATTR_CONSIDER_HOME: cv.time_period, # Temp workaround for iOS app introduced in 0.65 vol.Optional('battery_status'): str, vol.Optional('hostname'): str, })) @bind_hass def is_on(hass: HomeAssistantType, entity_id: str = None): """Return the state if any or a specified device is home.""" entity = entity_id or ENTITY_ID_ALL_DEVICES return hass.states.is_state(entity, STATE_HOME) def see(hass: HomeAssistantType, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy=None, battery: int = None, attributes: dict = None): """Call service to notify you see device.""" data = {key: value for key, value in ((ATTR_MAC, mac), (ATTR_DEV_ID, dev_id), (ATTR_HOST_NAME, host_name), (ATTR_LOCATION_NAME, location_name), (ATTR_GPS, gps), (ATTR_GPS_ACCURACY, gps_accuracy), (ATTR_BATTERY, battery)) if value is not None} if attributes: data[ATTR_ATTRIBUTES] = attributes hass.services.call(DOMAIN, SERVICE_SEE, data) async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {}) track_new = conf.get(CONF_TRACK_NEW) if track_new is None: track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = await async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker( hass, consider_home, track_new, defaults, devices) async def async_setup_platform(p_type, p_config, disc_info=None): """Set up a device tracker platform.""" platform = await async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = await platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = await hass.async_add_job( platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = await platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = await hass.async_add_job( platform.setup_scanner, hass, p_config, tracker.see, disc_info) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform( hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: await asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() async def async_platform_discovered(platform, info): """Load a platform.""" await async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change( hass, tracker.async_update_stale, second=range(0, 60, 5)) async def async_see_service(call): """Service to see a device.""" # Temp workaround for iOS, introduced in 0.65 data = dict(call.data) data.pop('hostname', None) data.pop('battery_status', None) await tracker.async_see(**data) hass.services.async_register( DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA) # restore await tracker.async_setup_tracked_device() return True class DeviceTracker: """Representation of a device tracker.""" def __init__(self, hass: HomeAssistantType, consider_home: timedelta, track_new: bool, defaults: dict, devices: Sequence) -> None: """Initialize a device tracker.""" self.hass = hass self.devices = {dev.dev_id: dev for dev in devices} self.mac_to_dev = {dev.mac: dev for dev in devices if dev.mac} self.consider_home = consider_home self.track_new = track_new if track_new is not None \ else defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) self.defaults = defaults self.group = None self._is_updating = asyncio.Lock(loop=hass.loop) for dev in devices: if self.devices[dev.dev_id] is not dev: _LOGGER.warning('Duplicate device IDs detected %s', dev.dev_id) if dev.mac and self.mac_to_dev[dev.mac] is not dev: _LOGGER.warning('Duplicate device MAC addresses detected %s', dev.mac) def see(self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None): """Notify the device tracker that you see a device.""" self.hass.add_job( self.async_see(mac, dev_id, host_name, location_name, gps, gps_accuracy, battery, attributes, source_type, picture, icon, consider_home) ) async def async_see( self, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy: int = None, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, picture: str = None, icon: str = None, consider_home: timedelta = None): """Notify the device tracker that you see a device. This method is a coroutine. """ if mac is None and dev_id is None: raise HomeAssistantError('Neither mac or device id passed in') elif mac is not None: mac = str(mac).upper() device = self.mac_to_dev.get(mac) if not device: dev_id = util.slugify(host_name or '') or util.slugify(mac) else: dev_id = cv.slug(str(dev_id).lower()) device = self.devices.get(dev_id) if device: await device.async_seen( host_name, location_name, gps, gps_accuracy, battery, attributes, source_type, consider_home) if device.track: await device.async_update_ha_state() return # If no device can be found, create it dev_id = util.ensure_unique_string(dev_id, self.devices.keys()) device = Device( self.hass, consider_home or self.consider_home, self.track_new, dev_id, mac, (host_name or dev_id).replace('_', ' '), picture=picture, icon=icon, hide_if_away=self.defaults.get(CONF_AWAY_HIDE, DEFAULT_AWAY_HIDE)) self.devices[dev_id] = device if mac is not None: self.mac_to_dev[mac] = device await device.async_seen( host_name, location_name, gps, gps_accuracy, battery, attributes, source_type) if device.track: await device.async_update_ha_state() # During init, we ignore the group if self.group and self.track_new: self.hass.async_create_task( self.hass.async_call( DOMAIN_GROUP, SERVICE_SET, { ATTR_OBJECT_ID: util.slugify(GROUP_NAME_ALL_DEVICES), ATTR_VISIBLE: False, ATTR_NAME: GROUP_NAME_ALL_DEVICES, ATTR_ADD_ENTITIES: [device.entity_id]})) self.hass.bus.async_fire(EVENT_NEW_DEVICE, { ATTR_ENTITY_ID: device.entity_id, ATTR_HOST_NAME: device.host_name, ATTR_MAC: device.mac, }) # update known_devices.yaml self.hass.async_create_task( self.async_update_config( self.hass.config.path(YAML_DEVICES), dev_id, device) ) async def async_update_config(self, path, dev_id, device): """Add device to YAML configuration file. This method is a coroutine. """ async with self._is_updating: await self.hass.async_add_executor_job( update_config, self.hass.config.path(YAML_DEVICES), dev_id, device) @callback def async_setup_group(self): """Initialize group for all tracked devices. This method must be run in the event loop. """ entity_ids = [dev.entity_id for dev in self.devices.values() if dev.track] self.hass.async_create_task( self.hass.services.async_call( DOMAIN_GROUP, SERVICE_SET, { ATTR_OBJECT_ID: util.slugify(GROUP_NAME_ALL_DEVICES), ATTR_VISIBLE: False, ATTR_NAME: GROUP_NAME_ALL_DEVICES, ATTR_ENTITIES: entity_ids})) @callback def async_update_stale(self, now: dt_util.dt.datetime): """Update stale devices. This method must be run in the event loop. """ for device in self.devices.values(): if (device.track and device.last_update_home) and \ device.stale(now): self.hass.async_create_task(device.async_update_ha_state(True)) async def async_setup_tracked_device(self): """Set up all not exists tracked devices. This method is a coroutine. """ async def async_init_single_device(dev): """Init a single device_tracker entity.""" await dev.async_added_to_hass() await dev.async_update_ha_state() tasks = [] for device in self.devices.values(): if device.track and not device.last_seen: tasks.append(self.hass.async_create_task( async_init_single_device(device))) if tasks: await asyncio.wait(tasks, loop=self.hass.loop) class Device(Entity): """Represent a tracked device.""" host_name = None # type: str location_name = None # type: str gps = None # type: GPSType gps_accuracy = 0 # type: int last_seen = None # type: dt_util.dt.datetime consider_home = None # type: dt_util.dt.timedelta battery = None # type: int attributes = None # type: dict icon = None # type: str # Track if the last update of this device was HOME. last_update_home = False _state = STATE_NOT_HOME def __init__(self, hass: HomeAssistantType, consider_home: timedelta, track: bool, dev_id: str, mac: str, name: str = None, picture: str = None, gravatar: str = None, icon: str = None, hide_if_away: bool = False) -> None: """Initialize a device.""" self.hass = hass self.entity_id = ENTITY_ID_FORMAT.format(dev_id) # Timedelta object how long we consider a device home if it is not # detected anymore. self.consider_home = consider_home # Device ID self.dev_id = dev_id self.mac = mac # If we should track this device self.track = track # Configured name self.config_name = name # Configured picture if gravatar is not None: self.config_picture = get_gravatar_for_email(gravatar) else: self.config_picture = picture self.icon = icon self.away_hide = hide_if_away self.source_type = None self._attributes = {} @property def name(self): """Return the name of the entity.""" return self.config_name or self.host_name or DEVICE_DEFAULT_NAME @property def state(self): """Return the state of the device.""" return self._state @property def entity_picture(self): """Return the picture of the device.""" return self.config_picture @property def state_attributes(self): """Return the device state attributes.""" attr = { ATTR_SOURCE_TYPE: self.source_type } if self.gps: attr[ATTR_LATITUDE] = self.gps[0] attr[ATTR_LONGITUDE] = self.gps[1] attr[ATTR_GPS_ACCURACY] = self.gps_accuracy if self.battery: attr[ATTR_BATTERY] = self.battery return attr @property def device_state_attributes(self): """Return device state attributes.""" return self._attributes @property def hidden(self): """If device should be hidden.""" return self.away_hide and self.state != STATE_HOME async def async_seen( self, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy=0, battery: int = None, attributes: dict = None, source_type: str = SOURCE_TYPE_GPS, consider_home: timedelta = None): """Mark the device as seen.""" self.source_type = source_type self.last_seen = dt_util.utcnow() self.host_name = host_name self.location_name = location_name self.consider_home = consider_home or self.consider_home if battery: self.battery = battery if attributes: self._attributes.update(attributes) self.gps = None if gps is not None: try: self.gps = float(gps[0]), float(gps[1]) self.gps_accuracy = gps_accuracy or 0 except (ValueError, TypeError, IndexError): self.gps = None self.gps_accuracy = 0 _LOGGER.warning( "Could not parse gps value for %s: %s", self.dev_id, gps) # pylint: disable=not-an-iterable await self.async_update() def stale(self, now: dt_util.dt.datetime = None): """Return if device state is stale. Async friendly. """ return self.last_seen and \ (now or dt_util.utcnow()) - self.last_seen > self.consider_home async def async_update(self): """Update state of entity. This method is a coroutine. """ if not self.last_seen: return if self.location_name: self._state = self.location_name elif self.gps is not None and self.source_type == SOURCE_TYPE_GPS: zone_state = async_active_zone( self.hass, self.gps[0], self.gps[1], self.gps_accuracy) if zone_state is None: self._state = STATE_NOT_HOME elif zone_state.entity_id == zone.ENTITY_ID_HOME: self._state = STATE_HOME else: self._state = zone_state.name elif self.stale(): self._state = STATE_NOT_HOME self.gps = None self.last_update_home = False else: self._state = STATE_HOME self.last_update_home = True async def async_added_to_hass(self): """Add an entity.""" state = await async_get_last_state(self.hass, self.entity_id) if not state: return self._state = state.state for attr, var in ( (ATTR_SOURCE_TYPE, 'source_type'), (ATTR_GPS_ACCURACY, 'gps_accuracy'), (ATTR_BATTERY, 'battery'), ): if attr in state.attributes: setattr(self, var, state.attributes[attr]) if ATTR_LONGITUDE in state.attributes: self.gps = (state.attributes[ATTR_LATITUDE], state.attributes[ATTR_LONGITUDE]) class DeviceScanner: """Device scanner object.""" hass = None # type: HomeAssistantType def scan_devices(self) -> List[str]: """Scan for devices.""" raise NotImplementedError() def async_scan_devices(self) -> Any: """Scan for devices. This method must be run in the event loop and returns a coroutine. """ return self.hass.async_add_job(self.scan_devices) def get_device_name(self, device: str) -> str: """Get the name of a device.""" raise NotImplementedError() def async_get_device_name(self, device: str) -> Any: """Get the name of a device. This method must be run in the event loop and returns a coroutine. """ return self.hass.async_add_job(self.get_device_name, device) def get_extra_attributes(self, device: str) -> dict: """Get the extra attributes of a device.""" raise NotImplementedError() def async_get_extra_attributes(self, device: str) -> Any: """Get the extra attributes of a device. This method must be run in the event loop and returns a coroutine. """ return self.hass.async_add_job(self.get_extra_attributes, device) def load_config(path: str, hass: HomeAssistantType, consider_home: timedelta): """Load devices from YAML configuration file.""" return run_coroutine_threadsafe( async_load_config(path, hass, consider_home), hass.loop).result() async def async_load_config(path: str, hass: HomeAssistantType, consider_home: timedelta): """Load devices from YAML configuration file. This method is a coroutine. """ dev_schema = vol.Schema({ vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_ICON, default=None): vol.Any(None, cv.icon), vol.Optional('track', default=False): cv.boolean, vol.Optional(CONF_MAC, default=None): vol.Any(None, vol.All(cv.string, vol.Upper)), vol.Optional(CONF_AWAY_HIDE, default=DEFAULT_AWAY_HIDE): cv.boolean, vol.Optional('gravatar', default=None): vol.Any(None, cv.string), vol.Optional('picture', default=None): vol.Any(None, cv.string), vol.Optional(CONF_CONSIDER_HOME, default=consider_home): vol.All( cv.time_period, cv.positive_timedelta), }) try: result = [] try: devices = await hass.async_add_job( load_yaml_config_file, path) except HomeAssistantError as err: _LOGGER.error("Unable to load %s: %s", path, str(err)) return [] for dev_id, device in devices.items(): # Deprecated option. We just ignore it to avoid breaking change device.pop('vendor', None) try: device = dev_schema(device) device['dev_id'] = cv.slugify(dev_id) except vol.Invalid as exp: async_log_exception(exp, dev_id, devices, hass) else: result.append(Device(hass, **device)) return result except (HomeAssistantError, FileNotFoundError): # When YAML file could not be loaded/did not contain a dict return [] @callback def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType, scanner: Any, async_see_device: Callable, platform: str): """Set up the connect scanner-based platform to device tracker. This method must be run in the event loop. """ interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) update_lock = asyncio.Lock(loop=hass.loop) scanner.hass = hass # Initial scan of each mac we also tell about host name for config seen = set() # type: Any async def async_device_tracker_scan(now: dt_util.dt.datetime): """Handle interval matches.""" if update_lock.locked(): _LOGGER.warning( "Updating device list from %s took longer than the scheduled " "scan interval %s", platform, interval) return async with update_lock: found_devices = await scanner.async_scan_devices() for mac in found_devices: if mac in seen: host_name = None else: host_name = await scanner.async_get_device_name(mac) seen.add(mac) try: extra_attributes = (await scanner.async_get_extra_attributes(mac)) except NotImplementedError: extra_attributes = dict() kwargs = { 'mac': mac, 'host_name': host_name, 'source_type': SOURCE_TYPE_ROUTER, 'attributes': { 'scanner': scanner.__class__.__name__, **extra_attributes } } zone_home = hass.states.get(zone.ENTITY_ID_HOME) if zone_home: kwargs['gps'] = [zone_home.attributes[ATTR_LATITUDE], zone_home.attributes[ATTR_LONGITUDE]] kwargs['gps_accuracy'] = 0 hass.async_create_task(async_see_device(**kwargs)) async_track_time_interval(hass, async_device_tracker_scan, interval) hass.async_create_task(async_device_tracker_scan(None)) def update_config(path: str, dev_id: str, device: Device): """Add device to YAML configuration file.""" with open(path, 'a') as out: device = {device.dev_id: { ATTR_NAME: device.name, ATTR_MAC: device.mac, ATTR_ICON: device.icon, 'picture': device.config_picture, 'track': device.track, CONF_AWAY_HIDE: device.away_hide, }} out.write('\n') out.write(dump(device)) def get_gravatar_for_email(email: str): """Return an 80px Gravatar for the given email address. Async friendly. """ import hashlib url = 'https://www.gravatar.com/avatar/{}.jpg?s=80&d=wavatar' return url.format(hashlib.md5(email.encode('utf-8').lower()).hexdigest())
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/device_tracker/__init__.py
"""Config flow to configure the HomematicIP Cloud component.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback from .const import DOMAIN as HMIPC_DOMAIN from .const import HMIPC_AUTHTOKEN, HMIPC_HAPID, HMIPC_NAME, HMIPC_PIN from .const import _LOGGER from .hap import HomematicipAuth @callback def configured_haps(hass): """Return a set of the configured access points.""" return set(entry.data[HMIPC_HAPID] for entry in hass.config_entries.async_entries(HMIPC_DOMAIN)) @config_entries.HANDLERS.register(HMIPC_DOMAIN) class HomematicipCloudFlowHandler(config_entries.ConfigFlow): """Config flow for the HomematicIP Cloud component.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_PUSH def __init__(self): """Initialize HomematicIP Cloud config flow.""" self.auth = None async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" return await self.async_step_init(user_input) async def async_step_init(self, user_input=None): """Handle a flow start.""" errors = {} if user_input is not None: user_input[HMIPC_HAPID] = \ user_input[HMIPC_HAPID].replace('-', '').upper() if user_input[HMIPC_HAPID] in configured_haps(self.hass): return self.async_abort(reason='already_configured') self.auth = HomematicipAuth(self.hass, user_input) connected = await self.auth.async_setup() if connected: _LOGGER.info("Connection to HomematicIP Cloud established") return await self.async_step_link() return self.async_show_form( step_id='init', data_schema=vol.Schema({ vol.Required(HMIPC_HAPID): str, vol.Optional(HMIPC_NAME): str, vol.Optional(HMIPC_PIN): str, }), errors=errors ) async def async_step_link(self, user_input=None): """Attempt to link with the HomematicIP Cloud access point.""" errors = {} pressed = await self.auth.async_checkbutton() if pressed: authtoken = await self.auth.async_register() if authtoken: _LOGGER.info("Write config entry for HomematicIP Cloud") return self.async_create_entry( title=self.auth.config.get(HMIPC_HAPID), data={ HMIPC_HAPID: self.auth.config.get(HMIPC_HAPID), HMIPC_AUTHTOKEN: authtoken, HMIPC_NAME: self.auth.config.get(HMIPC_NAME) }) return self.async_abort(reason='connection_aborted') errors['base'] = 'press_the_button' return self.async_show_form(step_id='link', errors=errors) async def async_step_import(self, import_info): """Import a new access point as a config entry.""" hapid = import_info[HMIPC_HAPID] authtoken = import_info[HMIPC_AUTHTOKEN] name = import_info[HMIPC_NAME] hapid = hapid.replace('-', '').upper() if hapid in configured_haps(self.hass): return self.async_abort(reason='already_configured') _LOGGER.info("Imported authentication for %s", hapid) return self.async_create_entry( title=hapid, data={ HMIPC_AUTHTOKEN: authtoken, HMIPC_HAPID: hapid, HMIPC_NAME: name, } )
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/homematicip_cloud/config_flow.py
""" Support for Rain Bird Irrigation system LNK WiFi Module. For more details about this component, please refer to the documentation at https://home-assistant.io/components/switch.rainbird/ """ import logging import voluptuous as vol from homeassistant.components.rainbird import DATA_RAINBIRD from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) from homeassistant.const import (CONF_SWITCHES, CONF_ZONE, CONF_FRIENDLY_NAME, CONF_TRIGGER_TIME, CONF_SCAN_INTERVAL) from homeassistant.helpers import config_validation as cv DEPENDENCIES = ['rainbird'] DOMAIN = 'rainbird' _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_SWITCHES, default={}): vol.Schema({ cv.string: { vol.Optional(CONF_FRIENDLY_NAME): cv.string, vol.Required(CONF_ZONE): cv.string, vol.Required(CONF_TRIGGER_TIME): cv.string, vol.Optional(CONF_SCAN_INTERVAL): cv.string, }, }), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Rain Bird switches over a Rain Bird controller.""" controller = hass.data[DATA_RAINBIRD] devices = [] for dev_id, switch in config.get(CONF_SWITCHES).items(): devices.append(RainBirdSwitch(controller, switch, dev_id)) add_entities(devices, True) class RainBirdSwitch(SwitchDevice): """Representation of a Rain Bird switch.""" def __init__(self, rb, dev, dev_id): """Initialize a Rain Bird Switch Device.""" self._rainbird = rb self._devid = dev_id self._zone = int(dev.get(CONF_ZONE)) self._name = dev.get(CONF_FRIENDLY_NAME, "Sprinkler {}".format(self._zone)) self._state = None self._duration = dev.get(CONF_TRIGGER_TIME) self._attributes = { "duration": self._duration, "zone": self._zone } @property def device_state_attributes(self): """Return state attributes.""" return self._attributes @property def name(self): """Get the name of the switch.""" return self._name def turn_on(self, **kwargs): """Turn the switch on.""" self._rainbird.startIrrigation(int(self._zone), int(self._duration)) def turn_off(self, **kwargs): """Turn the switch off.""" self._rainbird.stopIrrigation() def get_device_status(self): """Get the status of the switch from Rain Bird Controller.""" return self._rainbird.currentIrrigation() == self._zone def update(self): """Update switch status.""" self._state = self.get_device_status() @property def is_on(self): """Return true if switch is on.""" return self._state
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/switch/rainbird.py
"""Webhooks for Home Assistant. For more details about this component, please refer to the documentation at https://home-assistant.io/components/webhook/ """ import logging from aiohttp.web import Response from homeassistant.core import callback from homeassistant.loader import bind_hass from homeassistant.auth.util import generate_secret from homeassistant.components.http.view import HomeAssistantView DOMAIN = 'webhook' DEPENDENCIES = ['http'] _LOGGER = logging.getLogger(__name__) @callback @bind_hass def async_register(hass, webhook_id, handler): """Register a webhook.""" handlers = hass.data.setdefault(DOMAIN, {}) if webhook_id in handlers: raise ValueError('Handler is already defined!') handlers[webhook_id] = handler @callback @bind_hass def async_unregister(hass, webhook_id): """Remove a webhook.""" handlers = hass.data.setdefault(DOMAIN, {}) handlers.pop(webhook_id, None) @callback def async_generate_id(): """Generate a webhook_id.""" return generate_secret(entropy=32) @callback @bind_hass def async_generate_url(hass, webhook_id): """Generate a webhook_id.""" return "{}/api/webhook/{}".format(hass.config.api.base_url, webhook_id) async def async_setup(hass, config): """Initialize the webhook component.""" hass.http.register_view(WebhookView) return True class WebhookView(HomeAssistantView): """Handle incoming webhook requests.""" url = "/api/webhook/{webhook_id}" name = "api:webhook" requires_auth = False async def post(self, request, webhook_id): """Handle webhook call.""" hass = request.app['hass'] handlers = hass.data.setdefault(DOMAIN, {}) handler = handlers.get(webhook_id) # Always respond successfully to not give away if a hook exists or not. if handler is None: _LOGGER.warning( 'Received message for unregistered webhook %s', webhook_id) return Response(status=200) try: response = await handler(hass, webhook_id, request) if response is None: response = Response(status=200) return response except Exception: # pylint: disable=broad-except _LOGGER.exception("Error processing webhook %s", webhook_id) return Response(status=200)
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/webhook.py
""" Support for interfacing with Monoprice 6 zone home audio controller. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.monoprice/ """ import logging import voluptuous as vol from homeassistant.components.media_player import ( DOMAIN, MEDIA_PLAYER_SCHEMA, PLATFORM_SCHEMA, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, MediaPlayerDevice) from homeassistant.const import ( ATTR_ENTITY_ID, CONF_NAME, CONF_PORT, STATE_OFF, STATE_ON) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['pymonoprice==0.3'] _LOGGER = logging.getLogger(__name__) SUPPORT_MONOPRICE = SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET | \ SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | \ SUPPORT_TURN_OFF | SUPPORT_SELECT_SOURCE ZONE_SCHEMA = vol.Schema({ vol.Required(CONF_NAME): cv.string, }) SOURCE_SCHEMA = vol.Schema({ vol.Required(CONF_NAME): cv.string, }) CONF_ZONES = 'zones' CONF_SOURCES = 'sources' DATA_MONOPRICE = 'monoprice' SERVICE_SNAPSHOT = 'snapshot' SERVICE_RESTORE = 'restore' # Valid zone ids: 11-16 or 21-26 or 31-36 ZONE_IDS = vol.All(vol.Coerce(int), vol.Any( vol.Range(min=11, max=16), vol.Range(min=21, max=26), vol.Range(min=31, max=36))) # Valid source ids: 1-6 SOURCE_IDS = vol.All(vol.Coerce(int), vol.Range(min=1, max=6)) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_PORT): cv.string, vol.Required(CONF_ZONES): vol.Schema({ZONE_IDS: ZONE_SCHEMA}), vol.Required(CONF_SOURCES): vol.Schema({SOURCE_IDS: SOURCE_SCHEMA}), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Monoprice 6-zone amplifier platform.""" port = config.get(CONF_PORT) from serial import SerialException from pymonoprice import get_monoprice try: monoprice = get_monoprice(port) except SerialException: _LOGGER.error("Error connecting to Monoprice controller") return sources = {source_id: extra[CONF_NAME] for source_id, extra in config[CONF_SOURCES].items()} hass.data[DATA_MONOPRICE] = [] for zone_id, extra in config[CONF_ZONES].items(): _LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME]) hass.data[DATA_MONOPRICE].append(MonopriceZone( monoprice, sources, zone_id, extra[CONF_NAME])) add_entities(hass.data[DATA_MONOPRICE], True) def service_handle(service): """Handle for services.""" entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids: devices = [device for device in hass.data[DATA_MONOPRICE] if device.entity_id in entity_ids] else: devices = hass.data[DATA_MONOPRICE] for device in devices: if service.service == SERVICE_SNAPSHOT: device.snapshot() elif service.service == SERVICE_RESTORE: device.restore() hass.services.register( DOMAIN, SERVICE_SNAPSHOT, service_handle, schema=MEDIA_PLAYER_SCHEMA) hass.services.register( DOMAIN, SERVICE_RESTORE, service_handle, schema=MEDIA_PLAYER_SCHEMA) class MonopriceZone(MediaPlayerDevice): """Representation of a Monoprice amplifier zone.""" def __init__(self, monoprice, sources, zone_id, zone_name): """Initialize new zone.""" self._monoprice = monoprice # dict source_id -> source name self._source_id_name = sources # dict source name -> source_id self._source_name_id = {v: k for k, v in sources.items()} # ordered list of all source names self._source_names = sorted(self._source_name_id.keys(), key=lambda v: self._source_name_id[v]) self._zone_id = zone_id self._name = zone_name self._snapshot = None self._state = None self._volume = None self._source = None self._mute = None def update(self): """Retrieve latest state.""" state = self._monoprice.zone_status(self._zone_id) if not state: return False self._state = STATE_ON if state.power else STATE_OFF self._volume = state.volume self._mute = state.mute idx = state.source if idx in self._source_id_name: self._source = self._source_id_name[idx] else: self._source = None return True @property def name(self): """Return the name of the zone.""" return self._name @property def state(self): """Return the state of the zone.""" return self._state @property def volume_level(self): """Volume level of the media player (0..1).""" if self._volume is None: return None return self._volume / 38.0 @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._mute @property def supported_features(self): """Return flag of media commands that are supported.""" return SUPPORT_MONOPRICE @property def media_title(self): """Return the current source as medial title.""" return self._source @property def source(self): """Return the current input source of the device.""" return self._source @property def source_list(self): """List of available input sources.""" return self._source_names def snapshot(self): """Save zone's current state.""" self._snapshot = self._monoprice.zone_status(self._zone_id) def restore(self): """Restore saved state.""" if self._snapshot: self._monoprice.restore_zone(self._snapshot) self.schedule_update_ha_state(True) def select_source(self, source): """Set input source.""" if source not in self._source_name_id: return idx = self._source_name_id[source] self._monoprice.set_source(self._zone_id, idx) def turn_on(self): """Turn the media player on.""" self._monoprice.set_power(self._zone_id, True) def turn_off(self): """Turn the media player off.""" self._monoprice.set_power(self._zone_id, False) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self._monoprice.set_mute(self._zone_id, mute) def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._monoprice.set_volume(self._zone_id, int(volume * 38)) def volume_up(self): """Volume up the media player.""" if self._volume is None: return self._monoprice.set_volume(self._zone_id, min(self._volume + 1, 38)) def volume_down(self): """Volume down media player.""" if self._volume is None: return self._monoprice.set_volume(self._zone_id, max(self._volume - 1, 0))
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/media_player/monoprice.py
""" Support for Ring Doorbell/Chimes. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/ring/ """ import logging from requests.exceptions import HTTPError, ConnectTimeout import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_USERNAME, CONF_PASSWORD REQUIREMENTS = ['ring_doorbell==0.2.1'] _LOGGER = logging.getLogger(__name__) CONF_ATTRIBUTION = "Data provided by Ring.com" NOTIFICATION_ID = 'ring_notification' NOTIFICATION_TITLE = 'Ring Setup' DATA_RING = 'ring' DOMAIN = 'ring' DEFAULT_CACHEDB = '.ring_cache.pickle' DEFAULT_ENTITY_NAMESPACE = 'ring' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, }), }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up the Ring component.""" conf = config[DOMAIN] username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] try: from ring_doorbell import Ring cache = hass.config.path(DEFAULT_CACHEDB) ring = Ring(username=username, password=password, cache_file=cache) if not ring.is_connected: return False hass.data['ring'] = ring except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Ring service: %s", str(ex)) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False return True
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/ring.py
""" Support for Tahoma scenes. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/scene.tahoma/ """ import logging from homeassistant.components.scene import Scene from homeassistant.components.tahoma import ( DOMAIN as TAHOMA_DOMAIN) DEPENDENCIES = ['tahoma'] _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tahoma scenes.""" controller = hass.data[TAHOMA_DOMAIN]['controller'] scenes = [] for scene in hass.data[TAHOMA_DOMAIN]['scenes']: scenes.append(TahomaScene(scene, controller)) add_entities(scenes, True) class TahomaScene(Scene): """Representation of a Tahoma scene entity.""" def __init__(self, tahoma_scene, controller): """Initialize the scene.""" self.tahoma_scene = tahoma_scene self.controller = controller self._name = self.tahoma_scene.name def activate(self): """Activate the scene.""" self.controller.launch_action_group(self.tahoma_scene.oid) @property def name(self): """Return the name of the scene.""" return self._name @property def device_state_attributes(self): """Return the state attributes of the scene.""" return {'tahoma_scene_oid': self.tahoma_scene.oid}
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/scene/tahoma.py
""" Support for the Opple light. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.opple/ """ import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, Light) from homeassistant.const import CONF_HOST, CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.util.color import \ color_temperature_kelvin_to_mired as kelvin_to_mired from homeassistant.util.color import \ color_temperature_mired_to_kelvin as mired_to_kelvin REQUIREMENTS = ['pyoppleio==1.0.5'] _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "opple light" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Opple light platform.""" name = config[CONF_NAME] host = config[CONF_HOST] entity = OppleLight(name, host) add_entities([entity]) _LOGGER.debug("Init light %s %s", host, entity.unique_id) class OppleLight(Light): """Opple light device.""" def __init__(self, name, host): """Initialize an Opple light.""" from pyoppleio.OppleLightDevice import OppleLightDevice self._device = OppleLightDevice(host) self._name = name self._is_on = None self._brightness = None self._color_temp = None @property def available(self): """Return True if light is available.""" return self._device.is_online @property def unique_id(self): """Return unique ID for light.""" return self._device.mac @property def name(self): """Return the display name of this light.""" return self._name @property def is_on(self): """Return true if light is on.""" return self._is_on @property def brightness(self): """Return the brightness of the light.""" return self._brightness @property def color_temp(self): """Return the color temperature of this light.""" return kelvin_to_mired(self._color_temp) @property def min_mireds(self): """Return minimum supported color temperature.""" return 175 @property def max_mireds(self): """Return maximum supported color temperature.""" return 333 @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP def turn_on(self, **kwargs): """Instruct the light to turn on.""" _LOGGER.debug("Turn on light %s %s", self._device.ip, kwargs) if not self.is_on: self._device.power_on = True if ATTR_BRIGHTNESS in kwargs and \ self.brightness != kwargs[ATTR_BRIGHTNESS]: self._device.brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_COLOR_TEMP in kwargs and \ self.color_temp != kwargs[ATTR_COLOR_TEMP]: color_temp = mired_to_kelvin(kwargs[ATTR_COLOR_TEMP]) self._device.color_temperature = color_temp def turn_off(self, **kwargs): """Instruct the light to turn off.""" self._device.power_on = False _LOGGER.debug("Turn off light %s", self._device.ip) def update(self): """Synchronize state with light.""" prev_available = self.available self._device.update() if prev_available == self.available and \ self._is_on == self._device.power_on and \ self._brightness == self._device.brightness and \ self._color_temp == self._device.color_temperature: return if not self.available: _LOGGER.debug("Light %s is offline", self._device.ip) return self._is_on = self._device.power_on self._brightness = self._device.brightness self._color_temp = self._device.color_temperature if not self.is_on: _LOGGER.debug("Update light %s success: power off", self._device.ip) else: _LOGGER.debug("Update light %s success: power on brightness %s " "color temperature %s", self._device.ip, self._brightness, self._color_temp)
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/light/opple.py
""" Support for Logi Circle cameras. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/logi_circle/ """ import logging import asyncio import voluptuous as vol import async_timeout import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_USERNAME, CONF_PASSWORD REQUIREMENTS = ['logi_circle==0.1.7'] _LOGGER = logging.getLogger(__name__) _TIMEOUT = 15 # seconds CONF_ATTRIBUTION = "Data provided by circle.logi.com" NOTIFICATION_ID = 'logi_notification' NOTIFICATION_TITLE = 'Logi Circle Setup' DOMAIN = 'logi_circle' DEFAULT_CACHEDB = '.logi_cache.pickle' DEFAULT_ENTITY_NAMESPACE = 'logi_circle' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, }), }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the Logi Circle component.""" conf = config[DOMAIN] username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] try: from logi_circle import Logi from logi_circle.exception import BadLogin from aiohttp.client_exceptions import ClientResponseError cache = hass.config.path(DEFAULT_CACHEDB) logi = Logi(username=username, password=password, cache_file=cache) with async_timeout.timeout(_TIMEOUT, loop=hass.loop): await logi.login() hass.data[DOMAIN] = await logi.cameras if not logi.is_connected: return False except (BadLogin, ClientResponseError) as ex: _LOGGER.error('Unable to connect to Logi Circle API: %s', str(ex)) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False except asyncio.TimeoutError: # The TimeoutError exception object returns nothing when casted to a # string, so we'll handle it separately. err = '{}s timeout exceeded when connecting to Logi Circle API'.format( _TIMEOUT) _LOGGER.error(err) hass.components.persistent_notification.create( 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(err), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False return True
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/logi_circle.py
"""View to accept incoming websocket connection.""" import asyncio from contextlib import suppress from functools import partial import json import logging from aiohttp import web, WSMsgType import async_timeout from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback from homeassistant.components.http import HomeAssistantView from homeassistant.helpers.json import JSONEncoder from .const import MAX_PENDING_MSG, CANCELLATION_ERRORS, URL from .auth import AuthPhase, auth_required_message from .error import Disconnect JSON_DUMP = partial(json.dumps, cls=JSONEncoder) class WebsocketAPIView(HomeAssistantView): """View to serve a websockets endpoint.""" name = "websocketapi" url = URL requires_auth = False async def get(self, request): """Handle an incoming websocket connection.""" return await WebSocketHandler( request.app['hass'], request).async_handle() class WebSocketHandler: """Handle an active websocket client connection.""" def __init__(self, hass, request): """Initialize an active connection.""" self.hass = hass self.request = request self.wsock = None self._to_write = asyncio.Queue(maxsize=MAX_PENDING_MSG, loop=hass.loop) self._handle_task = None self._writer_task = None self._logger = logging.getLogger( "{}.connection.{}".format(__name__, id(self))) async def _writer(self): """Write outgoing messages.""" # Exceptions if Socket disconnected or cancelled by connection handler with suppress(RuntimeError, *CANCELLATION_ERRORS): while not self.wsock.closed: message = await self._to_write.get() if message is None: break self._logger.debug("Sending %s", message) try: await self.wsock.send_json(message, dumps=JSON_DUMP) except TypeError as err: self._logger.error('Unable to serialize to JSON: %s\n%s', err, message) @callback def _send_message(self, message): """Send a message to the client. Closes connection if the client is not reading the messages. Async friendly. """ try: self._to_write.put_nowait(message) except asyncio.QueueFull: self._logger.error("Client exceeded max pending messages [2]: %s", MAX_PENDING_MSG) self._cancel() @callback def _cancel(self): """Cancel the connection.""" self._handle_task.cancel() self._writer_task.cancel() async def async_handle(self): """Handle a websocket response.""" request = self.request wsock = self.wsock = web.WebSocketResponse(heartbeat=55) await wsock.prepare(request) self._logger.debug("Connected") # Py3.7+ if hasattr(asyncio, 'current_task'): # pylint: disable=no-member self._handle_task = asyncio.current_task() else: self._handle_task = asyncio.Task.current_task(loop=self.hass.loop) @callback def handle_hass_stop(event): """Cancel this connection.""" self._cancel() unsub_stop = self.hass.bus.async_listen( EVENT_HOMEASSISTANT_STOP, handle_hass_stop) self._writer_task = self.hass.async_create_task(self._writer()) auth = AuthPhase(self._logger, self.hass, self._send_message, request) connection = None disconnect_warn = None try: self._send_message(auth_required_message()) # Auth Phase try: with async_timeout.timeout(10): msg = await wsock.receive() except asyncio.TimeoutError: disconnect_warn = \ 'Did not receive auth message within 10 seconds' raise Disconnect if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING): raise Disconnect elif msg.type != WSMsgType.TEXT: disconnect_warn = 'Received non-Text message.' raise Disconnect try: msg = msg.json() except ValueError: disconnect_warn = 'Received invalid JSON.' raise Disconnect self._logger.debug("Received %s", msg) connection = await auth.async_handle(msg) # Command phase while not wsock.closed: msg = await wsock.receive() if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING): break elif msg.type != WSMsgType.TEXT: disconnect_warn = 'Received non-Text message.' break try: msg = msg.json() except ValueError: disconnect_warn = 'Received invalid JSON.' break self._logger.debug("Received %s", msg) connection.async_handle(msg) except asyncio.CancelledError: self._logger.info("Connection closed by client") except Disconnect: pass except Exception: # pylint: disable=broad-except self._logger.exception("Unexpected error inside websocket API") finally: unsub_stop() if connection is not None: connection.async_close() try: self._to_write.put_nowait(None) # Make sure all error messages are written before closing await self._writer_task except asyncio.QueueFull: self._writer_task.cancel() await wsock.close() if disconnect_warn is None: self._logger.debug("Disconnected") else: self._logger.warning("Disconnected: %s", disconnect_warn) return wsock
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/websocket_api/http.py
""" Support for MQTT binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.mqtt/ """ import logging from typing import Optional import voluptuous as vol from homeassistant.core import callback from homeassistant.components import mqtt, binary_sensor from homeassistant.components.binary_sensor import ( BinarySensorDevice, DEVICE_CLASSES_SCHEMA) from homeassistant.const import ( CONF_FORCE_UPDATE, CONF_NAME, CONF_VALUE_TEMPLATE, CONF_PAYLOAD_ON, CONF_PAYLOAD_OFF, CONF_DEVICE_CLASS, CONF_DEVICE) from homeassistant.components.mqtt import ( ATTR_DISCOVERY_HASH, CONF_STATE_TOPIC, CONF_AVAILABILITY_TOPIC, CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE, CONF_QOS, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo) from homeassistant.components.mqtt.discovery import MQTT_DISCOVERY_NEW import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.helpers.event as evt from homeassistant.helpers.typing import HomeAssistantType, ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'MQTT Binary sensor' CONF_OFF_DELAY = 'off_delay' CONF_UNIQUE_ID = 'unique_id' DEFAULT_PAYLOAD_OFF = 'OFF' DEFAULT_PAYLOAD_ON = 'ON' DEFAULT_FORCE_UPDATE = False DEPENDENCIES = ['mqtt'] PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string, vol.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean, vol.Optional(CONF_OFF_DELAY): vol.All(vol.Coerce(int), vol.Range(min=0)), # Integrations shouldn't never expose unique_id through configuration # this here is an exception because MQTT is a msg transport, not a protocol vol.Optional(CONF_UNIQUE_ID): cv.string, vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, }).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema) async def async_setup_platform(hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None): """Set up MQTT binary sensor through configuration.yaml.""" await _async_setup_entity(hass, config, async_add_entities) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up MQTT binary sensor dynamically through MQTT discovery.""" async def async_discover(discovery_payload): """Discover and add a MQTT binary sensor.""" config = PLATFORM_SCHEMA(discovery_payload) await _async_setup_entity(hass, config, async_add_entities, discovery_payload[ATTR_DISCOVERY_HASH]) async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(binary_sensor.DOMAIN, 'mqtt'), async_discover) async def _async_setup_entity(hass, config, async_add_entities, discovery_hash=None): """Set up the MQTT binary sensor.""" value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass async_add_entities([MqttBinarySensor( config.get(CONF_NAME), config.get(CONF_STATE_TOPIC), config.get(CONF_AVAILABILITY_TOPIC), config.get(CONF_DEVICE_CLASS), config.get(CONF_QOS), config.get(CONF_FORCE_UPDATE), config.get(CONF_OFF_DELAY), config.get(CONF_PAYLOAD_ON), config.get(CONF_PAYLOAD_OFF), config.get(CONF_PAYLOAD_AVAILABLE), config.get(CONF_PAYLOAD_NOT_AVAILABLE), value_template, config.get(CONF_UNIQUE_ID), config.get(CONF_DEVICE), discovery_hash, )]) class MqttBinarySensor(MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, BinarySensorDevice): """Representation a binary sensor that is updated by MQTT.""" def __init__(self, name, state_topic, availability_topic, device_class, qos, force_update, off_delay, payload_on, payload_off, payload_available, payload_not_available, value_template, unique_id: Optional[str], device_config: Optional[ConfigType], discovery_hash): """Initialize the MQTT binary sensor.""" MqttAvailability.__init__(self, availability_topic, qos, payload_available, payload_not_available) MqttDiscoveryUpdate.__init__(self, discovery_hash) MqttEntityDeviceInfo.__init__(self, device_config) self._name = name self._state = None self._state_topic = state_topic self._device_class = device_class self._payload_on = payload_on self._payload_off = payload_off self._qos = qos self._force_update = force_update self._off_delay = off_delay self._template = value_template self._unique_id = unique_id self._discovery_hash = discovery_hash self._delay_listener = None async def async_added_to_hass(self): """Subscribe mqtt events.""" await MqttAvailability.async_added_to_hass(self) await MqttDiscoveryUpdate.async_added_to_hass(self) @callback def state_message_received(topic, payload, qos): """Handle a new received MQTT state message.""" if self._template is not None: payload = self._template.async_render_with_possible_json_value( payload) if payload == self._payload_on: self._state = True elif payload == self._payload_off: self._state = False else: # Payload is not for this entity _LOGGER.warning('No matching payload found' ' for entity: %s with state_topic: %s', self._name, self._state_topic) return if (self._state and self._off_delay is not None): @callback def off_delay_listener(now): """Switch device off after a delay.""" self._delay_listener = None self._state = False self.async_schedule_update_ha_state() if self._delay_listener is not None: self._delay_listener() self._delay_listener = evt.async_call_later( self.hass, self._off_delay, off_delay_listener) self.async_schedule_update_ha_state() await mqtt.async_subscribe( self.hass, self._state_topic, state_message_received, self._qos) @property def should_poll(self): """Return the polling state.""" return False @property def name(self): """Return the name of the binary sensor.""" return self._name @property def is_on(self): """Return true if the binary sensor is on.""" return self._state @property def device_class(self): """Return the class of this sensor.""" return self._device_class @property def force_update(self): """Force update.""" return self._force_update @property def unique_id(self): """Return a unique ID.""" return self._unique_id
"""The tests for the Conversation component.""" # pylint: disable=protected-access import pytest from homeassistant.setup import async_setup_component from homeassistant.components import conversation import homeassistant.components as component from homeassistant.components.cover import (SERVICE_OPEN_COVER) from homeassistant.helpers import intent from tests.common import async_mock_intent, async_mock_service async def test_calling_intent(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_register_before_setup(hass): """Test calling an intent from a conversation.""" intents = async_mock_intent(hass, 'OrderBeer') hass.components.conversation.async_register('OrderBeer', [ 'A {type} beer, please' ]) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'A Grolsch beer, please' }) await hass.async_block_till_done() assert len(intents) == 1 intent = intents[0] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'A Grolsch beer, please' await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: 'I would like the Grolsch beer' }) await hass.async_block_till_done() assert len(intents) == 2 intent = intents[1] assert intent.platform == 'conversation' assert intent.intent_type == 'OrderBeer' assert intent.slots == {'type': {'value': 'Grolsch'}} assert intent.text_input == 'I would like the Grolsch beer' async def test_http_processing_intent(hass, aiohttp_client): """Test processing intent via HTTP API.""" class TestIntentHandler(intent.IntentHandler): """Test Intent Handler.""" intent_type = 'OrderBeer' async def async_handle(self, intent): """Handle the intent.""" response = intent.create_response() response.async_set_speech( "I've ordered a {}!".format(intent.slots['type']['value'])) response.async_set_card( "Beer ordered", "You chose a {}.".format(intent.slots['type']['value'])) return response intent.async_register(hass, TestIntentHandler()) result = await async_setup_component(hass, 'conversation', { 'conversation': { 'intents': { 'OrderBeer': [ 'I would like the {type} beer' ] } } }) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 'I would like the Grolsch beer' }) assert resp.status == 200 data = await resp.json() assert data == { 'card': { 'simple': { 'content': 'You chose a Grolsch.', 'title': 'Beer ordered' }}, 'speech': { 'plain': { 'extra_data': None, 'speech': "I've ordered a Grolsch!" } } } @pytest.mark.parametrize('sentence', ('turn on kitchen', 'turn kitchen on')) async def test_turn_on_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_cover_intents_loading(hass): """Test Cover Intents Loading.""" with pytest.raises(intent.UnknownIntent): await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) result = await async_setup_component(hass, 'cover', {}) assert result hass.states.async_set('cover.garage_door', 'closed') calls = async_mock_service(hass, 'cover', SERVICE_OPEN_COVER) response = await intent.async_handle( hass, 'test', 'HassOpenCover', {'name': {'value': 'garage door'}} ) await hass.async_block_till_done() assert response.speech['plain']['speech'] == 'Opened garage door' assert len(calls) == 1 call = calls[0] assert call.domain == 'cover' assert call.service == 'open_cover' assert call.data == {'entity_id': 'cover.garage_door'} @pytest.mark.parametrize('sentence', ('turn off kitchen', 'turn kitchen off')) async def test_turn_off_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'turn_off') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_off' assert call.data == {'entity_id': 'light.kitchen'} @pytest.mark.parametrize('sentence', ('toggle kitchen', 'kitchen toggle')) async def test_toggle_intent(hass, sentence): """Test calling the turn on intent.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result hass.states.async_set('light.kitchen', 'on') calls = async_mock_service(hass, 'homeassistant', 'toggle') await hass.services.async_call( 'conversation', 'process', { conversation.ATTR_TEXT: sentence }) await hass.async_block_till_done() assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'toggle' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) hass.states.async_set('light.kitchen', 'off') calls = async_mock_service(hass, 'homeassistant', 'turn_on') resp = await client.post('/api/conversation/process', json={ 'text': 'Turn the kitchen on' }) assert resp.status == 200 assert len(calls) == 1 call = calls[0] assert call.domain == 'homeassistant' assert call.service == 'turn_on' assert call.data == {'entity_id': 'light.kitchen'} async def test_http_api_wrong_data(hass, aiohttp_client): """Test the HTTP conversation API.""" result = await component.async_setup(hass, {}) assert result result = await async_setup_component(hass, 'conversation', {}) assert result client = await aiohttp_client(hass.http.app) resp = await client.post('/api/conversation/process', json={ 'text': 123 }) assert resp.status == 400 resp = await client.post('/api/conversation/process', json={ }) assert resp.status == 400 def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = conversation.create_matcher('Hello world') assert pattern.match('Hello world') is not None # Match a part pattern = conversation.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 = conversation.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 = conversation.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 = conversation.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 = conversation.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'
Danielhiversen/home-assistant
tests/components/test_conversation.py
homeassistant/components/binary_sensor/mqtt.py
"""JSON utility functions.""" import logging from typing import Union, List, Dict, Optional import json import os import tempfile from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) class SerializationError(HomeAssistantError): """Error serializing the data to JSON.""" class WriteError(HomeAssistantError): """Error writing the data.""" def load_json(filename: str, default: Union[List, Dict, None] = None) \ -> Union[List, Dict]: """Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found. """ try: with open(filename, encoding='utf-8') as fdesc: return json.loads(fdesc.read()) # type: ignore except FileNotFoundError: # This is not a fatal error _LOGGER.debug('JSON file not found: %s', filename) except ValueError as error: _LOGGER.exception('Could not parse JSON content: %s', filename) raise HomeAssistantError(error) except OSError as error: _LOGGER.exception('JSON file reading failed: %s', filename) raise HomeAssistantError(error) return {} if default is None else default def save_json(filename: str, data: Union[List, Dict], private: bool = False, *, encoder: Optional[json.JSONEncoder] = None) -> None: """Save JSON data to a file. Returns True on success. """ tmp_filename = "" tmp_path = os.path.split(filename)[0] try: json_data = json.dumps(data, sort_keys=True, indent=4, cls=encoder) # Modern versions of Python tempfile create this file with mode 0o600 with tempfile.NamedTemporaryFile(mode="w", encoding='utf-8', dir=tmp_path, delete=False) as fdesc: fdesc.write(json_data) tmp_filename = fdesc.name if not private: os.chmod(tmp_filename, 0o644) os.replace(tmp_filename, filename) except TypeError as error: _LOGGER.exception('Failed to serialize to JSON: %s', filename) raise SerializationError(error) except OSError as error: _LOGGER.exception('Saving JSON file failed: %s', filename) raise WriteError(error) finally: if os.path.exists(tmp_filename): try: os.remove(tmp_filename) except OSError as err: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("JSON replacement cleanup failed: %s", err)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/util/json.py
"""Support for retrieving meteorological data from Dark Sky.""" from datetime import datetime, timedelta import logging from requests.exceptions import ( ConnectionError as ConnectError, HTTPError, Timeout) import voluptuous as vol from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, PLATFORM_SCHEMA, WeatherEntity) from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME, PRESSURE_HPA, PRESSURE_INHG, TEMP_CELSIUS, TEMP_FAHRENHEIT) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from homeassistant.util.pressure import convert as convert_pressure _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Powered by Dark Sky" FORECAST_MODE = ['hourly', 'daily'] MAP_CONDITION = { 'clear-day': 'sunny', 'clear-night': 'clear-night', 'rain': 'rainy', 'snow': 'snowy', 'sleet': 'snowy-rainy', 'wind': 'windy', 'fog': 'fog', 'cloudy': 'cloudy', 'partly-cloudy-day': 'partlycloudy', 'partly-cloudy-night': 'partlycloudy', 'hail': 'hail', 'thunderstorm': 'lightning', 'tornado': None, } CONF_UNITS = 'units' DEFAULT_NAME = 'Dark Sky' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LATITUDE): cv.latitude, vol.Optional(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_MODE, default='hourly'): vol.In(FORECAST_MODE), vol.Optional(CONF_UNITS): vol.In(['auto', 'si', 'us', 'ca', 'uk', 'uk2']), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=3) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Dark Sky weather.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) mode = config.get(CONF_MODE) units = config.get(CONF_UNITS) if not units: units = 'ca' if hass.config.units.is_metric else 'us' dark_sky = DarkSkyData( config.get(CONF_API_KEY), latitude, longitude, units) add_entities([DarkSkyWeather(name, dark_sky, mode)], True) class DarkSkyWeather(WeatherEntity): """Representation of a weather condition.""" def __init__(self, name, dark_sky, mode): """Initialize Dark Sky weather.""" self._name = name self._dark_sky = dark_sky self._mode = mode self._ds_data = None self._ds_currently = None self._ds_hourly = None self._ds_daily = None @property def attribution(self): """Return the attribution.""" return ATTRIBUTION @property def name(self): """Return the name of the sensor.""" return self._name @property def temperature(self): """Return the temperature.""" return self._ds_currently.get('temperature') @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_FAHRENHEIT if 'us' in self._dark_sky.units \ else TEMP_CELSIUS @property def humidity(self): """Return the humidity.""" return round(self._ds_currently.get('humidity') * 100.0, 2) @property def wind_speed(self): """Return the wind speed.""" return self._ds_currently.get('windSpeed') @property def wind_bearing(self): """Return the wind bearing.""" return self._ds_currently.get('windBearing') @property def ozone(self): """Return the ozone level.""" return self._ds_currently.get('ozone') @property def pressure(self): """Return the pressure.""" pressure = self._ds_currently.get('pressure') if 'us' in self._dark_sky.units: return round( convert_pressure(pressure, PRESSURE_HPA, PRESSURE_INHG), 2) return pressure @property def visibility(self): """Return the visibility.""" return self._ds_currently.get('visibility') @property def condition(self): """Return the weather condition.""" return MAP_CONDITION.get(self._ds_currently.get('icon')) @property def forecast(self): """Return the forecast array.""" # Per conversation with Joshua Reyes of Dark Sky, to get the total # forecasted precipitation, you have to multiple the intensity by # the hours for the forecast interval def calc_precipitation(intensity, hours): amount = None if intensity is not None: amount = round((intensity * hours), 1) return amount if amount > 0 else None data = None if self._mode == 'daily': data = [{ ATTR_FORECAST_TIME: datetime.fromtimestamp(entry.d.get('time')).isoformat(), ATTR_FORECAST_TEMP: entry.d.get('temperatureHigh'), ATTR_FORECAST_TEMP_LOW: entry.d.get('temperatureLow'), ATTR_FORECAST_PRECIPITATION: calc_precipitation(entry.d.get('precipIntensity'), 24), ATTR_FORECAST_WIND_SPEED: entry.d.get('windSpeed'), ATTR_FORECAST_WIND_BEARING: entry.d.get('windBearing'), ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get('icon')) } for entry in self._ds_daily.data] else: data = [{ ATTR_FORECAST_TIME: datetime.fromtimestamp(entry.d.get('time')).isoformat(), ATTR_FORECAST_TEMP: entry.d.get('temperature'), ATTR_FORECAST_PRECIPITATION: calc_precipitation(entry.d.get('precipIntensity'), 1), ATTR_FORECAST_CONDITION: MAP_CONDITION.get(entry.d.get('icon')) } for entry in self._ds_hourly.data] return data def update(self): """Get the latest data from Dark Sky.""" self._dark_sky.update() self._ds_data = self._dark_sky.data self._ds_currently = self._dark_sky.currently.d self._ds_hourly = self._dark_sky.hourly self._ds_daily = self._dark_sky.daily class DarkSkyData: """Get the latest data from Dark Sky.""" def __init__(self, api_key, latitude, longitude, units): """Initialize the data object.""" self._api_key = api_key self.latitude = latitude self.longitude = longitude self.requested_units = units self.data = None self.currently = None self.hourly = None self.daily = None @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Get the latest data from Dark Sky.""" import forecastio try: self.data = forecastio.load_forecast( self._api_key, self.latitude, self.longitude, units=self.requested_units) self.currently = self.data.currently() self.hourly = self.data.hourly() self.daily = self.data.daily() except (ConnectError, HTTPError, Timeout, ValueError) as error: _LOGGER.error("Unable to connect to Dark Sky. %s", error) self.data = None @property def units(self): """Get the unit system of returned data.""" if self.data is None: return None return self.data.json.get('flags').get('units')
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/darksky/weather.py
"""Support for monitoring pyLoad.""" from datetime import timedelta import logging from aiohttp.hdrs import CONTENT_TYPE import requests import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_SSL, CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, CONTENT_TYPE_JSON, CONF_MONITORED_VARIABLES) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) DEFAULT_HOST = 'localhost' DEFAULT_NAME = 'pyLoad' DEFAULT_PORT = 8000 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=15) SENSOR_TYPES = { 'speed': ['speed', 'Speed', 'MB/s'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_MONITORED_VARIABLES, default=['speed']): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SSL, default=False): cv.boolean, vol.Optional(CONF_USERNAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the pyLoad sensors.""" host = config.get(CONF_HOST) port = config.get(CONF_PORT) ssl = 's' if config.get(CONF_SSL) else '' name = config.get(CONF_NAME) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) monitored_types = config.get(CONF_MONITORED_VARIABLES) url = "http{}://{}:{}/api/".format(ssl, host, port) try: pyloadapi = PyLoadAPI( api_url=url, username=username, password=password) pyloadapi.update() except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as conn_err: _LOGGER.error("Error setting up pyLoad API: %s", conn_err) return False devices = [] for ng_type in monitored_types: new_sensor = PyLoadSensor( api=pyloadapi, sensor_type=SENSOR_TYPES.get(ng_type), client_name=name) devices.append(new_sensor) add_entities(devices, True) class PyLoadSensor(Entity): """Representation of a pyLoad sensor.""" def __init__(self, api, sensor_type, client_name): """Initialize a new pyLoad sensor.""" self._name = '{} {}'.format(client_name, sensor_type[1]) self.type = sensor_type[0] self.api = api self._state = None self._unit_of_measurement = sensor_type[2] @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Update state of sensor.""" try: self.api.update() except requests.exceptions.ConnectionError: # Error calling the API, already logged in api.update() return if self.api.status is None: _LOGGER.debug("Update of %s requested, but no status is available", self._name) return value = self.api.status.get(self.type) if value is None: _LOGGER.warning("Unable to locate value for %s", self.type) return if "speed" in self.type and value > 0: # Convert download rate from Bytes/s to MBytes/s self._state = round(value / 2**20, 2) else: self._state = value class PyLoadAPI: """Simple wrapper for pyLoad's API.""" def __init__(self, api_url, username=None, password=None): """Initialize pyLoad API and set headers needed later.""" self.api_url = api_url self.status = None self.headers = {CONTENT_TYPE: CONTENT_TYPE_JSON} if username is not None and password is not None: self.payload = {'username': username, 'password': password} self.login = requests.post( '{}{}'.format(api_url, 'login'), data=self.payload, timeout=5) self.update() def post(self, method, params=None): """Send a POST request and return the response as a dict.""" payload = {'method': method} if params: payload['params'] = params try: response = requests.post( '{}{}'.format(self.api_url, 'statusServer'), json=payload, cookies=self.login.cookies, headers=self.headers, timeout=5) response.raise_for_status() _LOGGER.debug("JSON Response: %s", response.json()) return response.json() except requests.exceptions.ConnectionError as conn_exc: _LOGGER.error("Failed to update pyLoad status. Error: %s", conn_exc) raise @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update cached response.""" self.status = self.post('speed')
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/pyload/sensor.py
"""Connect to a MySensors gateway via pymysensors API.""" import logging import voluptuous as vol from homeassistant.components.mqtt import ( valid_publish_topic, valid_subscribe_topic) from homeassistant.const import CONF_OPTIMISTIC from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import ( ATTR_DEVICES, CONF_BAUD_RATE, CONF_DEVICE, CONF_GATEWAYS, CONF_NODES, CONF_PERSISTENCE, CONF_PERSISTENCE_FILE, CONF_RETAIN, CONF_TCP_PORT, CONF_TOPIC_IN_PREFIX, CONF_TOPIC_OUT_PREFIX, CONF_VERSION, DOMAIN, MYSENSORS_GATEWAYS) from .device import get_mysensors_devices from .gateway import get_mysensors_gateway, setup_gateways, finish_setup _LOGGER = logging.getLogger(__name__) CONF_DEBUG = 'debug' CONF_NODE_NAME = 'name' DEFAULT_BAUD_RATE = 115200 DEFAULT_TCP_PORT = 5003 DEFAULT_VERSION = '1.4' def has_all_unique_files(value): """Validate that all persistence files are unique and set if any is set.""" persistence_files = [ gateway.get(CONF_PERSISTENCE_FILE) for gateway in value] if None in persistence_files and any( name is not None for name in persistence_files): raise vol.Invalid( 'persistence file name of all devices must be set if any is set') if not all(name is None for name in persistence_files): schema = vol.Schema(vol.Unique()) schema(persistence_files) return value def is_persistence_file(value): """Validate that persistence file path ends in either .pickle or .json.""" if value.endswith(('.json', '.pickle')): return value raise vol.Invalid( '{} does not end in either `.json` or `.pickle`'.format(value)) def deprecated(key): """Mark key as deprecated in configuration.""" def validator(config): """Check if key is in config, log warning and remove key.""" if key not in config: return config _LOGGER.warning( '%s option for %s is deprecated. Please remove %s from your ' 'configuration file', key, DOMAIN, key) config.pop(key) return config return validator NODE_SCHEMA = vol.Schema({ cv.positive_int: { vol.Required(CONF_NODE_NAME): cv.string } }) GATEWAY_SCHEMA = { vol.Required(CONF_DEVICE): cv.string, vol.Optional(CONF_PERSISTENCE_FILE): vol.All(cv.string, is_persistence_file), vol.Optional(CONF_BAUD_RATE, default=DEFAULT_BAUD_RATE): cv.positive_int, vol.Optional(CONF_TCP_PORT, default=DEFAULT_TCP_PORT): cv.port, vol.Optional(CONF_TOPIC_IN_PREFIX): valid_subscribe_topic, vol.Optional(CONF_TOPIC_OUT_PREFIX): valid_publish_topic, vol.Optional(CONF_NODES, default={}): NODE_SCHEMA, } CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema(vol.All(deprecated(CONF_DEBUG), { vol.Required(CONF_GATEWAYS): vol.All( cv.ensure_list, has_all_unique_files, [GATEWAY_SCHEMA]), vol.Optional(CONF_OPTIMISTIC, default=False): cv.boolean, vol.Optional(CONF_PERSISTENCE, default=True): cv.boolean, vol.Optional(CONF_RETAIN, default=True): cv.boolean, vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): cv.string, })) }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the MySensors component.""" gateways = await setup_gateways(hass, config) if not gateways: _LOGGER.error( "No devices could be setup as gateways, check your configuration") return False hass.data[MYSENSORS_GATEWAYS] = gateways hass.async_create_task(finish_setup(hass, config, gateways)) return True def _get_mysensors_name(gateway, node_id, child_id): """Return a name for a node child.""" node_name = '{} {}'.format( gateway.sensors[node_id].sketch_name, node_id) node_name = next( (node[CONF_NODE_NAME] for conf_id, node in gateway.nodes_config.items() if node.get(CONF_NODE_NAME) is not None and conf_id == node_id), node_name) return '{} {}'.format(node_name, child_id) @callback def setup_mysensors_platform( hass, domain, discovery_info, device_class, device_args=None, async_add_entities=None): """Set up a MySensors platform.""" # Only act if called via MySensors by discovery event. # Otherwise gateway is not set up. if not discovery_info: return None if device_args is None: device_args = () new_devices = [] new_dev_ids = discovery_info[ATTR_DEVICES] for dev_id in new_dev_ids: devices = get_mysensors_devices(hass, domain) if dev_id in devices: continue gateway_id, node_id, child_id, value_type = dev_id gateway = get_mysensors_gateway(hass, gateway_id) if not gateway: continue device_class_copy = device_class if isinstance(device_class, dict): child = gateway.sensors[node_id].children[child_id] s_type = gateway.const.Presentation(child.type).name device_class_copy = device_class[s_type] name = _get_mysensors_name(gateway, node_id, child_id) args_copy = (*device_args, gateway, node_id, child_id, name, value_type) devices[dev_id] = device_class_copy(*args_copy) new_devices.append(devices[dev_id]) if new_devices: _LOGGER.info("Adding new devices: %s", new_devices) if async_add_entities is not None: async_add_entities(new_devices, True) return new_devices
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/mysensors/__init__.py
"""Config flow to configure the RainMachine component.""" from collections import OrderedDict import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback from homeassistant.const import ( CONF_IP_ADDRESS, CONF_PASSWORD, CONF_PORT, CONF_SCAN_INTERVAL, CONF_SSL) from homeassistant.helpers import aiohttp_client from .const import DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DEFAULT_SSL, DOMAIN @callback def configured_instances(hass): """Return a set of configured RainMachine instances.""" return set( entry.data[CONF_IP_ADDRESS] for entry in hass.config_entries.async_entries(DOMAIN)) @config_entries.HANDLERS.register(DOMAIN) class RainMachineFlowHandler(config_entries.ConfigFlow): """Handle a RainMachine config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize the config flow.""" self.data_schema = OrderedDict() self.data_schema[vol.Required(CONF_IP_ADDRESS)] = str self.data_schema[vol.Required(CONF_PASSWORD)] = str self.data_schema[vol.Optional(CONF_PORT, default=DEFAULT_PORT)] = int async def _show_form(self, errors=None): """Show the form to the user.""" return self.async_show_form( step_id='user', data_schema=vol.Schema(self.data_schema), errors=errors if errors else {}, ) async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" from regenmaschine import login from regenmaschine.errors import RainMachineError if not user_input: return await self._show_form() if user_input[CONF_IP_ADDRESS] in configured_instances(self.hass): return await self._show_form({ CONF_IP_ADDRESS: 'identifier_exists' }) websession = aiohttp_client.async_get_clientsession(self.hass) try: await login( user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD], websession, port=user_input.get(CONF_PORT, DEFAULT_PORT), ssl=True) except RainMachineError: return await self._show_form({ CONF_PASSWORD: 'invalid_credentials' }) # Since the config entry doesn't allow for configuration of SSL, make # sure it's set: if user_input.get(CONF_SSL) is None: user_input[CONF_SSL] = DEFAULT_SSL # Timedeltas are easily serializable, so store the seconds instead: scan_interval = user_input.get( CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) user_input[CONF_SCAN_INTERVAL] = scan_interval.seconds # Unfortunately, RainMachine doesn't provide a way to refresh the # access token without using the IP address and password, so we have to # store it: return self.async_create_entry( title=user_input[CONF_IP_ADDRESS], data=user_input)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/rainmachine/config_flow.py
"""Support for Fibaro thermostats.""" import logging from homeassistant.components.climate.const import ( STATE_AUTO, STATE_COOL, STATE_DRY, STATE_ECO, STATE_FAN_ONLY, STATE_HEAT, STATE_MANUAL, SUPPORT_TARGET_TEMPERATURE, SUPPORT_OPERATION_MODE, SUPPORT_FAN_MODE) from homeassistant.components.climate import ( ClimateDevice) from homeassistant.const import ( ATTR_TEMPERATURE, STATE_OFF, TEMP_CELSIUS, TEMP_FAHRENHEIT) from . import ( FIBARO_DEVICES, FibaroDevice) SPEED_LOW = 'low' SPEED_MEDIUM = 'medium' SPEED_HIGH = 'high' # State definitions missing from HA, but defined by Z-Wave standard. # We map them to states known supported by HA here: STATE_AUXILIARY = STATE_HEAT STATE_RESUME = STATE_HEAT STATE_MOIST = STATE_DRY STATE_AUTO_CHANGEOVER = STATE_AUTO STATE_ENERGY_HEAT = STATE_ECO STATE_ENERGY_COOL = STATE_COOL STATE_FULL_POWER = STATE_AUTO STATE_FORCE_OPEN = STATE_MANUAL STATE_AWAY = STATE_AUTO STATE_FURNACE = STATE_HEAT FAN_AUTO_HIGH = 'auto_high' FAN_AUTO_MEDIUM = 'auto_medium' FAN_CIRCULATION = 'circulation' FAN_HUMIDITY_CIRCULATION = 'humidity_circulation' FAN_LEFT_RIGHT = 'left_right' FAN_UP_DOWN = 'up_down' FAN_QUIET = 'quiet' _LOGGER = logging.getLogger(__name__) # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 128, Thermostat Fan Mode Set version 4::Fan Mode encoding FANMODES = { 0: STATE_OFF, 1: SPEED_LOW, 2: FAN_AUTO_HIGH, 3: SPEED_HIGH, 4: FAN_AUTO_MEDIUM, 5: SPEED_MEDIUM, 6: FAN_CIRCULATION, 7: FAN_HUMIDITY_CIRCULATION, 8: FAN_LEFT_RIGHT, 9: FAN_UP_DOWN, 10: FAN_QUIET, 128: STATE_AUTO } # SDS13781-10 Z-Wave Application Command Class Specification 2019-01-04 # Table 130, Thermostat Mode Set version 3::Mode encoding. OPMODES = { 0: STATE_OFF, 1: STATE_HEAT, 2: STATE_COOL, 3: STATE_AUTO, 4: STATE_AUXILIARY, 5: STATE_RESUME, 6: STATE_FAN_ONLY, 7: STATE_FURNACE, 8: STATE_DRY, 9: STATE_MOIST, 10: STATE_AUTO_CHANGEOVER, 11: STATE_ENERGY_HEAT, 12: STATE_ENERGY_COOL, 13: STATE_AWAY, 15: STATE_FULL_POWER, 31: STATE_FORCE_OPEN } SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE) def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroThermostat(device) for device in hass.data[FIBARO_DEVICES]['climate']], True) class FibaroThermostat(FibaroDevice, ClimateDevice): """Representation of a Fibaro Thermostat.""" def __init__(self, fibaro_device): """Initialize the Fibaro device.""" super().__init__(fibaro_device) self._temp_sensor_device = None self._target_temp_device = None self._op_mode_device = None self._fan_mode_device = None self._support_flags = 0 self.entity_id = 'climate.{}'.format(self.ha_id) self._fan_mode_to_state = {} self._fan_state_to_mode = {} self._op_mode_to_state = {} self._op_state_to_mode = {} siblings = fibaro_device.fibaro_controller.get_siblings( fibaro_device.id) tempunit = 'C' for device in siblings: if device.type == 'com.fibaro.temperatureSensor': self._temp_sensor_device = FibaroDevice(device) tempunit = device.properties.unit if 'setTargetLevel' in device.actions or \ 'setThermostatSetpoint' in device.actions: self._target_temp_device = FibaroDevice(device) self._support_flags |= SUPPORT_TARGET_TEMPERATURE tempunit = device.properties.unit if 'setMode' in device.actions or \ 'setOperatingMode' in device.actions: self._op_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_OPERATION_MODE if 'setFanMode' in device.actions: self._fan_mode_device = FibaroDevice(device) self._support_flags |= SUPPORT_FAN_MODE if tempunit == 'F': self._unit_of_temp = TEMP_FAHRENHEIT else: self._unit_of_temp = TEMP_CELSIUS if self._fan_mode_device: fan_modes = self._fan_mode_device.fibaro_device.\ properties.supportedModes.split(",") for mode in fan_modes: try: self._fan_mode_to_state[int(mode)] = FANMODES[int(mode)] self._fan_state_to_mode[FANMODES[int(mode)]] = int(mode) except KeyError: self._fan_mode_to_state[int(mode)] = 'unknown' if self._op_mode_device: prop = self._op_mode_device.fibaro_device.properties if "supportedOperatingModes" in prop: op_modes = prop.supportedOperatingModes.split(",") elif "supportedModes" in prop: op_modes = prop.supportedModes.split(",") for mode in op_modes: try: self._op_mode_to_state[int(mode)] = OPMODES[int(mode)] self._op_state_to_mode[OPMODES[int(mode)]] = int(mode) except KeyError: self._op_mode_to_state[int(mode)] = 'unknown' async def async_added_to_hass(self): """Call when entity is added to hass.""" _LOGGER.debug("Climate %s\n" "- _temp_sensor_device %s\n" "- _target_temp_device %s\n" "- _op_mode_device %s\n" "- _fan_mode_device %s", self.ha_id, self._temp_sensor_device.ha_id if self._temp_sensor_device else "None", self._target_temp_device.ha_id if self._target_temp_device else "None", self._op_mode_device.ha_id if self._op_mode_device else "None", self._fan_mode_device.ha_id if self._fan_mode_device else "None") await super().async_added_to_hass() # Register update callback for child devices siblings = self.fibaro_device.fibaro_controller.get_siblings( self.fibaro_device.id) for device in siblings: if device != self.fibaro_device: self.controller.register(device.id, self._update_callback) @property def supported_features(self): """Return the list of supported features.""" return self._support_flags @property def fan_list(self): """Return the list of available fan modes.""" if self._fan_mode_device is None: return None return list(self._fan_state_to_mode) @property def current_fan_mode(self): """Return the fan setting.""" if self._fan_mode_device is None: return None mode = int(self._fan_mode_device.fibaro_device.properties.mode) return self._fan_mode_to_state[mode] def set_fan_mode(self, fan_mode): """Set new target fan mode.""" if self._fan_mode_device is None: return self._fan_mode_device.action( "setFanMode", self._fan_state_to_mode[fan_mode]) @property def current_operation(self): """Return current operation ie. heat, cool, idle.""" if self._op_mode_device is None: return None if "operatingMode" in self._op_mode_device.fibaro_device.properties: mode = int(self._op_mode_device.fibaro_device. properties.operatingMode) else: mode = int(self._op_mode_device.fibaro_device.properties.mode) return self._op_mode_to_state.get(mode) @property def operation_list(self): """Return the list of available operation modes.""" if self._op_mode_device is None: return None return list(self._op_state_to_mode) def set_operation_mode(self, operation_mode): """Set new target operation mode.""" if self._op_mode_device is None: return if "setOperatingMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action( "setOperatingMode", self._op_state_to_mode[operation_mode]) elif "setMode" in self._op_mode_device.fibaro_device.actions: self._op_mode_device.action( "setMode", self._op_state_to_mode[operation_mode]) @property def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_temp @property def current_temperature(self): """Return the current temperature.""" if self._temp_sensor_device: device = self._temp_sensor_device.fibaro_device return float(device.properties.value) return None @property def target_temperature(self): """Return the temperature we try to reach.""" if self._target_temp_device: device = self._target_temp_device.fibaro_device return float(device.properties.targetLevel) return None def set_temperature(self, **kwargs): """Set new target temperatures.""" temperature = kwargs.get(ATTR_TEMPERATURE) target = self._target_temp_device if temperature is not None: if "setThermostatSetpoint" in target.fibaro_device.actions: target.action("setThermostatSetpoint", self._op_state_to_mode[self.current_operation], temperature) else: target.action("setTargetLevel", temperature) @property def is_on(self): """Return true if on.""" if self.current_operation == STATE_OFF: return False return True
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/fibaro/climate.py
"""Clickatell platform for notify component.""" import logging import requests import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_RECIPIENT import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import (PLATFORM_SCHEMA, BaseNotificationService) _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'clickatell' BASE_API_URL = 'https://platform.clickatell.com/messages/http/send' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_RECIPIENT): cv.string, }) def get_service(hass, config, discovery_info=None): """Get the Clickatell notification service.""" return ClickatellNotificationService(config) class ClickatellNotificationService(BaseNotificationService): """Implementation of a notification service for the Clickatell service.""" def __init__(self, config): """Initialize the service.""" self.api_key = config.get(CONF_API_KEY) self.recipient = config.get(CONF_RECIPIENT) def send_message(self, message="", **kwargs): """Send a message to a user.""" data = { 'apiKey': self.api_key, 'to': self.recipient, 'content': message, } resp = requests.get(BASE_API_URL, params=data, timeout=5) if (resp.status_code != 200) or (resp.status_code != 201): _LOGGER.error("Error %s : %s", resp.status_code, resp.text)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/clickatell/notify.py
"""Support for WeMo humidifier.""" import asyncio import logging from datetime import timedelta import requests import async_timeout import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.fan import ( DOMAIN, SUPPORT_SET_SPEED, FanEntity, SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH) from homeassistant.exceptions import PlatformNotReady from homeassistant.const import ATTR_ENTITY_ID from . import SUBSCRIPTION_REGISTRY SCAN_INTERVAL = timedelta(seconds=10) DATA_KEY = 'fan.wemo' _LOGGER = logging.getLogger(__name__) ATTR_CURRENT_HUMIDITY = 'current_humidity' ATTR_TARGET_HUMIDITY = 'target_humidity' ATTR_FAN_MODE = 'fan_mode' ATTR_FILTER_LIFE = 'filter_life' ATTR_FILTER_EXPIRED = 'filter_expired' ATTR_WATER_LEVEL = 'water_level' # The WEMO_ constants below come from pywemo itself WEMO_ON = 1 WEMO_OFF = 0 WEMO_HUMIDITY_45 = 0 WEMO_HUMIDITY_50 = 1 WEMO_HUMIDITY_55 = 2 WEMO_HUMIDITY_60 = 3 WEMO_HUMIDITY_100 = 4 WEMO_FAN_OFF = 0 WEMO_FAN_MINIMUM = 1 WEMO_FAN_LOW = 2 # Not used due to limitations of the base fan implementation WEMO_FAN_MEDIUM = 3 WEMO_FAN_HIGH = 4 # Not used due to limitations of the base fan implementation WEMO_FAN_MAXIMUM = 5 WEMO_WATER_EMPTY = 0 WEMO_WATER_LOW = 1 WEMO_WATER_GOOD = 2 SUPPORTED_SPEEDS = [ SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH] SUPPORTED_FEATURES = SUPPORT_SET_SPEED # Since the base fan object supports a set list of fan speeds, # we have to reuse some of them when mapping to the 5 WeMo speeds WEMO_FAN_SPEED_TO_HASS = { WEMO_FAN_OFF: SPEED_OFF, WEMO_FAN_MINIMUM: SPEED_LOW, WEMO_FAN_LOW: SPEED_LOW, # Reusing SPEED_LOW WEMO_FAN_MEDIUM: SPEED_MEDIUM, WEMO_FAN_HIGH: SPEED_HIGH, # Reusing SPEED_HIGH WEMO_FAN_MAXIMUM: SPEED_HIGH } # Because we reused mappings in the previous dict, we have to filter them # back out in this dict, or else we would have duplicate keys HASS_FAN_SPEED_TO_WEMO = {v: k for (k, v) in WEMO_FAN_SPEED_TO_HASS.items() if k not in [WEMO_FAN_LOW, WEMO_FAN_HIGH]} SERVICE_SET_HUMIDITY = 'wemo_set_humidity' SET_HUMIDITY_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_TARGET_HUMIDITY): vol.All(vol.Coerce(float), vol.Range(min=0, max=100)) }) SERVICE_RESET_FILTER_LIFE = 'wemo_reset_filter_life' RESET_FILTER_LIFE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.entity_ids }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up discovered WeMo humidifiers.""" from pywemo import discovery if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} if discovery_info is None: return location = discovery_info['ssdp_description'] mac = discovery_info['mac_address'] try: device = WemoHumidifier( discovery.device_from_description(location, mac)) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error('Unable to access %s (%s)', location, err) raise PlatformNotReady hass.data[DATA_KEY][device.entity_id] = device add_entities([device]) def service_handle(service): """Handle the WeMo humidifier services.""" entity_ids = service.data.get(ATTR_ENTITY_ID) humidifiers = [device for device in hass.data[DATA_KEY].values() if device.entity_id in entity_ids] if service.service == SERVICE_SET_HUMIDITY: target_humidity = service.data.get(ATTR_TARGET_HUMIDITY) for humidifier in humidifiers: humidifier.set_humidity(target_humidity) elif service.service == SERVICE_RESET_FILTER_LIFE: for humidifier in humidifiers: humidifier.reset_filter_life() # Register service(s) hass.services.register( DOMAIN, SERVICE_SET_HUMIDITY, service_handle, schema=SET_HUMIDITY_SCHEMA) hass.services.register( DOMAIN, SERVICE_RESET_FILTER_LIFE, service_handle, schema=RESET_FILTER_LIFE_SCHEMA) class WemoHumidifier(FanEntity): """Representation of a WeMo humidifier.""" def __init__(self, device): """Initialize the WeMo switch.""" self.wemo = device self._state = None self._available = True self._update_lock = None self._fan_mode = None self._target_humidity = None self._current_humidity = None self._water_level = None self._filter_life = None self._filter_expired = None self._last_fan_on_mode = WEMO_FAN_MEDIUM 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_schedule_update_ha_state() @property def unique_id(self): """Return the ID of this WeMo humidifier.""" return self._serialnumber @property def name(self): """Return the name of the humidifier if any.""" return self._name @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.""" return 'mdi:water-percent' @property def device_state_attributes(self): """Return device specific state attributes.""" return { ATTR_CURRENT_HUMIDITY: self._current_humidity, ATTR_TARGET_HUMIDITY: self._target_humidity, ATTR_FAN_MODE: self._fan_mode, ATTR_WATER_LEVEL: self._water_level, ATTR_FILTER_LIFE: self._filter_life, ATTR_FILTER_EXPIRED: self._filter_expired } @property def speed(self) -> str: """Return the current speed.""" return WEMO_FAN_SPEED_TO_HASS.get(self._fan_mode) @property def speed_list(self) -> list: """Get the list of available speeds.""" return SUPPORTED_SPEEDS @property def supported_features(self) -> int: """Flag supported features.""" return SUPPORTED_FEATURES async def async_added_to_hass(self): """Wemo humidifier added to HASS.""" # Define inside async context so we know our event loop self._update_lock = asyncio.Lock() registry = SUBSCRIPTION_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 humidifier 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=True): """Update the device state.""" try: self._state = self.wemo.get_state(force_update) self._fan_mode = self.wemo.fan_mode_string self._target_humidity = self.wemo.desired_humidity_percent self._current_humidity = self.wemo.current_humidity_percent self._water_level = self.wemo.water_level_string self._filter_life = self.wemo.filter_life_percent self._filter_expired = self.wemo.filter_expired if self.wemo.fan_mode != WEMO_FAN_OFF: self._last_fan_on_mode = self.wemo.fan_mode if not self._available: _LOGGER.info('Reconnected to %s', self.name) self._available = True except AttributeError as err: _LOGGER.warning("Could not update status for %s (%s)", self.name, err) self._available = False def turn_on(self, speed: str = None, **kwargs) -> None: """Turn the switch on.""" if speed is None: self.wemo.set_state(self._last_fan_on_mode) else: self.set_speed(speed) def turn_off(self, **kwargs) -> None: """Turn the switch off.""" self.wemo.set_state(WEMO_FAN_OFF) def set_speed(self, speed: str) -> None: """Set the fan_mode of the Humidifier.""" self.wemo.set_state(HASS_FAN_SPEED_TO_WEMO.get(speed)) def set_humidity(self, humidity: float) -> None: """Set the target humidity level for the Humidifier.""" if humidity < 50: self.wemo.set_humidity(WEMO_HUMIDITY_45) elif 50 <= humidity < 55: self.wemo.set_humidity(WEMO_HUMIDITY_50) elif 55 <= humidity < 60: self.wemo.set_humidity(WEMO_HUMIDITY_55) elif 60 <= humidity < 100: self.wemo.set_humidity(WEMO_HUMIDITY_60) elif humidity >= 100: self.wemo.set_humidity(WEMO_HUMIDITY_100) def reset_filter_life(self) -> None: """Reset the filter life to 100%.""" self.wemo.reset_filter_life()
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/wemo/fan.py
"""Support for Google Home Bluetooth tacker.""" from datetime import timedelta import logging from homeassistant.components.device_tracker import DeviceScanner from homeassistant.helpers.event import async_track_time_interval from homeassistant.util import slugify from . import CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME _LOGGER = logging.getLogger(__name__) DEFAULT_SCAN_INTERVAL = timedelta(seconds=10) async def async_setup_scanner(hass, config, async_see, discovery_info=None): """Validate the configuration and return a Google Home scanner.""" if discovery_info is None: _LOGGER.warning( "To use this you need to configure the 'googlehome' component") return False scanner = GoogleHomeDeviceScanner(hass, hass.data[CLIENT], discovery_info, async_see) return await scanner.async_init() class GoogleHomeDeviceScanner(DeviceScanner): """This class queries a Google Home unit.""" def __init__(self, hass, client, config, async_see): """Initialize the scanner.""" self.async_see = async_see self.hass = hass self.rssi = config['rssi_threshold'] self.device_types = config['device_types'] self.host = config['host'] self.client = client async def async_init(self): """Further initialize connection to Google Home.""" await self.client.update_info(self.host) data = self.hass.data[GOOGLEHOME_DOMAIN][self.host] info = data.get('info', {}) connected = bool(info) if connected: await self.async_update() async_track_time_interval(self.hass, self.async_update, DEFAULT_SCAN_INTERVAL) return connected async def async_update(self, now=None): """Ensure the information from Google Home is up to date.""" _LOGGER.debug('Checking Devices on %s', self.host) await self.client.update_bluetooth(self.host) data = self.hass.data[GOOGLEHOME_DOMAIN][self.host] info = data.get('info') bluetooth = data.get('bluetooth') if info is None or bluetooth is None: return google_home_name = info.get('name', NAME) for device in bluetooth: if (device['device_type'] not in self.device_types or device['rssi'] < self.rssi): continue name = "{} {}".format(self.host, device['mac_address']) attributes = {} attributes['btle_mac_address'] = device['mac_address'] attributes['ghname'] = google_home_name attributes['rssi'] = device['rssi'] attributes['source_type'] = 'bluetooth' if device['name']: attributes['name'] = device['name'] await self.async_see(dev_id=slugify(name), attributes=attributes)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/googlehome/device_tracker.py
"""Helpers for config validation using voluptuous.""" import inspect import logging import os import re from datetime import (timedelta, datetime as datetime_sys, time as time_sys, date as date_sys) from socket import _GLOBAL_DEFAULT_TIMEOUT from typing import Any, Union, TypeVar, Callable, Sequence, Dict, Optional from urllib.parse import urlparse from uuid import UUID import voluptuous as vol from pkg_resources import parse_version import homeassistant.util.dt as dt_util from homeassistant.const import ( CONF_PLATFORM, CONF_SCAN_INTERVAL, TEMP_CELSIUS, TEMP_FAHRENHEIT, CONF_ALIAS, CONF_ENTITY_ID, CONF_VALUE_TEMPLATE, WEEKDAYS, CONF_CONDITION, CONF_BELOW, CONF_ABOVE, CONF_TIMEOUT, SUN_EVENT_SUNSET, SUN_EVENT_SUNRISE, CONF_UNIT_SYSTEM_IMPERIAL, CONF_UNIT_SYSTEM_METRIC, ENTITY_MATCH_ALL, CONF_ENTITY_NAMESPACE, __version__) from homeassistant.core import valid_entity_id, split_entity_id from homeassistant.exceptions import TemplateError from homeassistant.helpers import template as template_helper from homeassistant.helpers.logging import KeywordStyleAdapter from homeassistant.util import slugify as util_slugify # pylint: disable=invalid-name TIME_PERIOD_ERROR = "offset {} should be format 'HH:MM' or 'HH:MM:SS'" OLD_SLUG_VALIDATION = r'^[a-z0-9_]+$' OLD_ENTITY_ID_VALIDATION = r"^(\w+)\.(\w+)$" # Keep track of invalid slugs and entity ids found so we can create a # persistent notification. Rare temporary exception to use a global. INVALID_SLUGS_FOUND = {} INVALID_ENTITY_IDS_FOUND = {} INVALID_EXTRA_KEYS_FOUND = [] # Home Assistant types byte = vol.All(vol.Coerce(int), vol.Range(min=0, max=255)) small_float = vol.All(vol.Coerce(float), vol.Range(min=0, max=1)) positive_int = vol.All(vol.Coerce(int), vol.Range(min=0)) latitude = vol.All(vol.Coerce(float), vol.Range(min=-90, max=90), msg='invalid latitude') longitude = vol.All(vol.Coerce(float), vol.Range(min=-180, max=180), msg='invalid longitude') gps = vol.ExactSequence([latitude, longitude]) sun_event = vol.All(vol.Lower, vol.Any(SUN_EVENT_SUNSET, SUN_EVENT_SUNRISE)) port = vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)) # typing typevar T = TypeVar('T') # Adapted from: # https://github.com/alecthomas/voluptuous/issues/115#issuecomment-144464666 def has_at_least_one_key(*keys: str) -> Callable: """Validate that at least one key exists.""" def validate(obj: Dict) -> Dict: """Test keys exist in dict.""" if not isinstance(obj, dict): raise vol.Invalid('expected dictionary') for k in obj.keys(): if k in keys: return obj raise vol.Invalid('must contain one of {}.'.format(', '.join(keys))) return validate def has_at_most_one_key(*keys: str) -> Callable: """Validate that zero keys exist or one key exists.""" def validate(obj: Dict) -> Dict: """Test zero keys exist or one key exists in dict.""" if not isinstance(obj, dict): raise vol.Invalid('expected dictionary') if len(set(keys) & set(obj)) > 1: raise vol.Invalid( 'must contain at most one of {}.'.format(', '.join(keys)) ) return obj return validate def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, str): value = value.lower() if value in ('1', 'true', 'yes', 'on', 'enable'): return True if value in ('0', 'false', 'no', 'off', 'disable'): return False raise vol.Invalid('invalid boolean value {}'.format(value)) return bool(value) def isdevice(value): """Validate that value is a real device.""" try: os.stat(value) return str(value) except OSError: raise vol.Invalid('No device at {} found'.format(value)) def matches_regex(regex): """Validate that the value is a string that matches a regex.""" regex = re.compile(regex) def validator(value: Any) -> str: """Validate that value matches the given regex.""" if not isinstance(value, str): raise vol.Invalid('not a string value: {}'.format(value)) if not regex.match(value): raise vol.Invalid('value {} does not match regular expression {}' .format(value, regex.pattern)) return value return validator def is_regex(value): """Validate that a string is a valid regular expression.""" try: r = re.compile(value) return r except TypeError: raise vol.Invalid("value {} is of the wrong type for a regular " "expression".format(value)) except re.error: raise vol.Invalid("value {} is not a valid regular expression".format( value)) def isfile(value: Any) -> str: """Validate that the value is an existing file.""" if value is None: raise vol.Invalid('None is not file') file_in = os.path.expanduser(str(value)) if not os.path.isfile(file_in): raise vol.Invalid('not a file') if not os.access(file_in, os.R_OK): raise vol.Invalid('file not readable') return file_in def isdir(value: Any) -> str: """Validate that the value is an existing dir.""" if value is None: raise vol.Invalid('not a directory') dir_in = os.path.expanduser(str(value)) if not os.path.isdir(dir_in): raise vol.Invalid('not a directory') if not os.access(dir_in, os.R_OK): raise vol.Invalid('directory not readable') return dir_in def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]: """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value] def entity_id(value: Any) -> str: """Validate Entity ID.""" value = string(value).lower() if valid_entity_id(value): return value if re.match(OLD_ENTITY_ID_VALIDATION, value): # To ease the breaking change, we allow old slugs for now # Remove after 0.94 or 1.0 fixed = '.'.join(util_slugify(part) for part in value.split('.', 1)) INVALID_ENTITY_IDS_FOUND[value] = fixed logging.getLogger(__name__).warning( "Found invalid entity_id %s, please update with %s. This " "will become a breaking change.", value, fixed ) return value raise vol.Invalid('Entity ID {} is an invalid entity id'.format(value)) def entity_ids(value: Union[str, Sequence]) -> Sequence[str]: """Validate Entity IDs.""" if value is None: raise vol.Invalid('Entity IDs can not be None') if isinstance(value, str): value = [ent_id.strip() for ent_id in value.split(',')] return [entity_id(ent_id) for ent_id in value] comp_entity_ids = vol.Any( vol.All(vol.Lower, ENTITY_MATCH_ALL), entity_ids ) def entity_domain(domain: str): """Validate that entity belong to domain.""" def validate(value: Any) -> str: """Test if entity domain is domain.""" ent_domain = entities_domain(domain) return ent_domain(value)[0] return validate def entities_domain(domain: str): """Validate that entities belong to domain.""" def validate(values: Union[str, Sequence]) -> Sequence[str]: """Test if entity domain is domain.""" values = entity_ids(values) for ent_id in values: if split_entity_id(ent_id)[0] != domain: raise vol.Invalid( "Entity ID '{}' does not belong to domain '{}'" .format(ent_id, domain)) return values return validate def enum(enumClass): """Create validator for specified enum.""" return vol.All(vol.In(enumClass.__members__), enumClass.__getitem__) def icon(value): """Validate icon.""" value = str(value) if ':' in value: return value raise vol.Invalid('Icons should be specifed on the form "prefix:name"') time_period_dict = vol.All( dict, vol.Schema({ 'days': vol.Coerce(int), 'hours': vol.Coerce(int), 'minutes': vol.Coerce(int), 'seconds': vol.Coerce(int), 'milliseconds': vol.Coerce(int), }), has_at_least_one_key('days', 'hours', 'minutes', 'seconds', 'milliseconds'), lambda value: timedelta(**value)) def time(value) -> time_sys: """Validate and transform a time.""" if isinstance(value, time_sys): return value try: time_val = dt_util.parse_time(value) except TypeError: raise vol.Invalid('Not a parseable type') if time_val is None: raise vol.Invalid('Invalid time specified: {}'.format(value)) return time_val def date(value) -> date_sys: """Validate and transform a date.""" if isinstance(value, date_sys): return value try: date_val = dt_util.parse_date(value) except TypeError: raise vol.Invalid('Not a parseable type') if date_val is None: raise vol.Invalid("Could not parse date") return date_val def time_period_str(value: str) -> timedelta: """Validate and transform time offset.""" if isinstance(value, int): raise vol.Invalid('Make sure you wrap time values in quotes') if not isinstance(value, str): raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) negative_offset = False if value.startswith('-'): negative_offset = True value = value[1:] elif value.startswith('+'): value = value[1:] try: parsed = [int(x) for x in value.split(':')] except ValueError: raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) if len(parsed) == 2: hour, minute = parsed second = 0 elif len(parsed) == 3: hour, minute, second = parsed else: raise vol.Invalid(TIME_PERIOD_ERROR.format(value)) offset = timedelta(hours=hour, minutes=minute, seconds=second) if negative_offset: offset *= -1 return offset def time_period_seconds(value: Union[int, str]) -> timedelta: """Validate and transform seconds to a time offset.""" try: return timedelta(seconds=int(value)) except (ValueError, TypeError): raise vol.Invalid('Expected seconds, got {}'.format(value)) time_period = vol.Any(time_period_str, time_period_seconds, timedelta, time_period_dict) def match_all(value): """Validate that matches all values.""" return value def positive_timedelta(value: timedelta) -> timedelta: """Validate timedelta is positive.""" if value < timedelta(0): raise vol.Invalid('Time period should be positive') return value def remove_falsy(value: Sequence[T]) -> Sequence[T]: """Remove falsy values from a list.""" return [v for v in value if v] def service(value): """Validate service.""" # Services use same format as entities so we can use same helper. if valid_entity_id(value): return value raise vol.Invalid('Service {} does not match format <domain>.<name>' .format(value)) def schema_with_slug_keys(value_schema: Union[T, Callable]) -> Callable: """Ensure dicts have slugs as keys. Replacement of vol.Schema({cv.slug: value_schema}) to prevent misleading "Extra keys" errors from voluptuous. """ schema = vol.Schema({str: value_schema}) def verify(value: Dict) -> Dict: """Validate all keys are slugs and then the value_schema.""" if not isinstance(value, dict): raise vol.Invalid('expected dictionary') for key in value.keys(): try: slug(key) except vol.Invalid: # To ease the breaking change, we allow old slugs for now # Remove after 0.94 or 1.0 if re.match(OLD_SLUG_VALIDATION, key): fixed = util_slugify(key) INVALID_SLUGS_FOUND[key] = fixed logging.getLogger(__name__).warning( "Found invalid slug %s, please update with %s. This " "will be come a breaking change.", key, fixed ) else: raise return schema(value) return verify def slug(value: Any) -> str: """Validate value is a valid slug.""" if value is None: raise vol.Invalid('Slug should not be None') value = str(value) slg = util_slugify(value) if value == slg: return value raise vol.Invalid('invalid slug {} (try {})'.format(value, slg)) def slugify(value: Any) -> str: """Coerce a value to a slug.""" if value is None: raise vol.Invalid('Slug should not be None') slg = util_slugify(str(value)) if slg: return slg raise vol.Invalid('Unable to slugify {}'.format(value)) def string(value: Any) -> str: """Coerce value to string, except for None.""" if value is None: raise vol.Invalid('string value is None') if isinstance(value, (list, dict)): raise vol.Invalid('value should be a string') return str(value) def temperature_unit(value) -> str: """Validate and transform temperature unit.""" value = str(value).upper() if value == 'C': return TEMP_CELSIUS if value == 'F': return TEMP_FAHRENHEIT raise vol.Invalid('invalid temperature unit (expected C or F)') unit_system = vol.All(vol.Lower, vol.Any(CONF_UNIT_SYSTEM_METRIC, CONF_UNIT_SYSTEM_IMPERIAL)) def template(value): """Validate a jinja2 template.""" if value is None: raise vol.Invalid('template value is None') if isinstance(value, (list, dict, template_helper.Template)): raise vol.Invalid('template value should be a string') value = template_helper.Template(str(value)) try: value.ensure_valid() return value except TemplateError as ex: raise vol.Invalid('invalid template ({})'.format(ex)) def template_complex(value): """Validate a complex jinja2 template.""" if isinstance(value, list): return_value = value.copy() for idx, element in enumerate(return_value): return_value[idx] = template_complex(element) return return_value if isinstance(value, dict): return_value = value.copy() for key, element in return_value.items(): return_value[key] = template_complex(element) return return_value return template(value) def datetime(value): """Validate datetime.""" if isinstance(value, datetime_sys): return value try: date_val = dt_util.parse_datetime(value) except TypeError: date_val = None if date_val is None: raise vol.Invalid('Invalid datetime specified: {}'.format(value)) return date_val def time_zone(value): """Validate timezone.""" if dt_util.get_time_zone(value) is not None: return value raise vol.Invalid( 'Invalid time zone passed in. Valid options can be found here: ' 'http://en.wikipedia.org/wiki/List_of_tz_database_time_zones') weekdays = vol.All(ensure_list, [vol.In(WEEKDAYS)]) def socket_timeout(value): """Validate timeout float > 0.0. None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object. """ if value is None: return _GLOBAL_DEFAULT_TIMEOUT try: float_value = float(value) if float_value > 0.0: return float_value raise vol.Invalid('Invalid socket timeout value.' ' float > 0.0 required.') except Exception as _: raise vol.Invalid('Invalid socket timeout: {err}'.format(err=_)) # pylint: disable=no-value-for-parameter def url(value: Any) -> str: """Validate an URL.""" url_in = str(value) if urlparse(url_in).scheme in ['http', 'https']: return vol.Schema(vol.Url())(url_in) raise vol.Invalid('invalid url') def x10_address(value): """Validate an x10 address.""" regex = re.compile(r'([A-Pa-p]{1})(?:[2-9]|1[0-6]?)$') if not regex.match(value): raise vol.Invalid('Invalid X10 Address') return str(value).lower() def uuid4_hex(value): """Validate a v4 UUID in hex format.""" try: result = UUID(value, version=4) except (ValueError, AttributeError, TypeError) as error: raise vol.Invalid('Invalid Version4 UUID', error_message=str(error)) if result.hex != value.lower(): # UUID() will create a uuid4 if input is invalid raise vol.Invalid('Invalid Version4 UUID') return result.hex def ensure_list_csv(value: Any) -> Sequence: """Ensure that input is a list or make one from comma-separated string.""" if isinstance(value, str): return [member.strip() for member in value.split(',')] return ensure_list(value) def deprecated(key: str, replacement_key: Optional[str] = None, invalidation_version: Optional[str] = None, default: Optional[Any] = None): """ Log key as deprecated and provide a replacement (if exists). Expected behavior: - Outputs the appropriate deprecation warning if key is detected - Processes schema moving the value from key to replacement_key - Processes schema changing nothing if only replacement_key provided - No warning if only replacement_key provided - No warning if neither key nor replacement_key are provided - Adds replacement_key with default value in this case - Once the invalidation_version is crossed, raises vol.Invalid if key is detected """ module_name = inspect.getmodule(inspect.stack()[1][0]).__name__ if replacement_key and invalidation_version: warning = ("The '{key}' option (with value '{value}') is" " deprecated, please replace it with '{replacement_key}'." " This option will become invalid in version" " {invalidation_version}") elif replacement_key: warning = ("The '{key}' option (with value '{value}') is" " deprecated, please replace it with '{replacement_key}'") elif invalidation_version: warning = ("The '{key}' option (with value '{value}') is" " deprecated, please remove it from your configuration." " This option will become invalid in version" " {invalidation_version}") else: warning = ("The '{key}' option (with value '{value}') is" " deprecated, please remove it from your configuration") def check_for_invalid_version(value: Optional[Any]): """Raise error if current version has reached invalidation.""" if not invalidation_version: return if parse_version(__version__) >= parse_version(invalidation_version): raise vol.Invalid( warning.format( key=key, value=value, replacement_key=replacement_key, invalidation_version=invalidation_version ) ) def validator(config: Dict): """Check if key is in config and log warning.""" if key in config: value = config[key] check_for_invalid_version(value) KeywordStyleAdapter(logging.getLogger(module_name)).warning( warning, key=key, value=value, replacement_key=replacement_key, invalidation_version=invalidation_version ) if replacement_key: config.pop(key) else: value = default if (replacement_key and (replacement_key not in config or default == config.get(replacement_key)) and value is not None): config[replacement_key] = value return has_at_most_one_key(key, replacement_key)(config) return validator # Validator helpers def key_dependency(key, dependency): """Validate that all dependencies exist for key.""" def validator(value): """Test dependencies.""" if not isinstance(value, dict): raise vol.Invalid('key dependencies require a dict') if key in value and dependency not in value: raise vol.Invalid('dependency violation - key "{}" requires ' 'key "{}" to exist'.format(key, dependency)) return value return validator # Schemas class HASchema(vol.Schema): """Schema class that allows us to mark PREVENT_EXTRA errors as warnings.""" def __call__(self, data): """Override __call__ to mark PREVENT_EXTRA as warning.""" try: return super().__call__(data) except vol.Invalid as orig_err: if self.extra != vol.PREVENT_EXTRA: raise # orig_error is of type vol.MultipleInvalid (see super __call__) assert isinstance(orig_err, vol.MultipleInvalid) # pylint: disable=no-member # If it fails with PREVENT_EXTRA, try with ALLOW_EXTRA self.extra = vol.ALLOW_EXTRA # In case it still fails the following will raise try: validated = super().__call__(data) finally: self.extra = vol.PREVENT_EXTRA # This is a legacy config, print warning extra_key_errs = [err for err in orig_err.errors if err.error_message == 'extra keys not allowed'] if extra_key_errs: msg = "Your configuration contains extra keys " \ "that the platform does not support.\n" \ "Please remove " submsg = ', '.join('[{}]'.format(err.path[-1]) for err in extra_key_errs) submsg += '. ' if hasattr(data, '__config_file__'): submsg += " (See {}, line {}). ".format( data.__config_file__, data.__line__) msg += submsg logging.getLogger(__name__).warning(msg) INVALID_EXTRA_KEYS_FOUND.append(submsg) else: # This should not happen (all errors should be extra key # errors). Let's raise the original error anyway. raise orig_err # Return legacy validated config return validated def extend(self, schema, required=None, extra=None): """Extend this schema and convert it to HASchema if necessary.""" ret = super().extend(schema, required=required, extra=extra) if extra is not None: return ret return HASchema(ret.schema, required=required, extra=self.extra) PLATFORM_SCHEMA = HASchema({ vol.Required(CONF_PLATFORM): string, vol.Optional(CONF_ENTITY_NAMESPACE): string, vol.Optional(CONF_SCAN_INTERVAL): time_period }) PLATFORM_SCHEMA_BASE = PLATFORM_SCHEMA.extend({ }, extra=vol.ALLOW_EXTRA) EVENT_SCHEMA = vol.Schema({ vol.Optional(CONF_ALIAS): string, vol.Required('event'): string, vol.Optional('event_data'): dict, vol.Optional('event_data_template'): {match_all: template_complex} }) SERVICE_SCHEMA = vol.All(vol.Schema({ vol.Optional(CONF_ALIAS): string, vol.Exclusive('service', 'service name'): service, vol.Exclusive('service_template', 'service name'): template, vol.Optional('data'): dict, vol.Optional('data_template'): {match_all: template_complex}, vol.Optional(CONF_ENTITY_ID): comp_entity_ids, }), has_at_least_one_key('service', 'service_template')) NUMERIC_STATE_CONDITION_SCHEMA = vol.All(vol.Schema({ vol.Required(CONF_CONDITION): 'numeric_state', vol.Required(CONF_ENTITY_ID): entity_id, CONF_BELOW: vol.Coerce(float), CONF_ABOVE: vol.Coerce(float), vol.Optional(CONF_VALUE_TEMPLATE): template, }), has_at_least_one_key(CONF_BELOW, CONF_ABOVE)) STATE_CONDITION_SCHEMA = vol.All(vol.Schema({ vol.Required(CONF_CONDITION): 'state', vol.Required(CONF_ENTITY_ID): entity_id, vol.Required('state'): str, vol.Optional('for'): vol.All(time_period, positive_timedelta), # To support use_trigger_value in automation # Deprecated 2016/04/25 vol.Optional('from'): str, }), key_dependency('for', 'state')) SUN_CONDITION_SCHEMA = vol.All(vol.Schema({ vol.Required(CONF_CONDITION): 'sun', vol.Optional('before'): sun_event, vol.Optional('before_offset'): time_period, vol.Optional('after'): vol.All(vol.Lower, vol.Any( SUN_EVENT_SUNSET, SUN_EVENT_SUNRISE)), vol.Optional('after_offset'): time_period, }), has_at_least_one_key('before', 'after')) TEMPLATE_CONDITION_SCHEMA = vol.Schema({ vol.Required(CONF_CONDITION): 'template', vol.Required(CONF_VALUE_TEMPLATE): template, }) TIME_CONDITION_SCHEMA = vol.All(vol.Schema({ vol.Required(CONF_CONDITION): 'time', 'before': time, 'after': time, 'weekday': weekdays, }), has_at_least_one_key('before', 'after', 'weekday')) ZONE_CONDITION_SCHEMA = vol.Schema({ vol.Required(CONF_CONDITION): 'zone', vol.Required(CONF_ENTITY_ID): entity_id, 'zone': entity_id, # To support use_trigger_value in automation # Deprecated 2016/04/25 vol.Optional('event'): vol.Any('enter', 'leave'), }) AND_CONDITION_SCHEMA = vol.Schema({ vol.Required(CONF_CONDITION): 'and', vol.Required('conditions'): vol.All( ensure_list, # pylint: disable=unnecessary-lambda [lambda value: CONDITION_SCHEMA(value)], ) }) OR_CONDITION_SCHEMA = vol.Schema({ vol.Required(CONF_CONDITION): 'or', vol.Required('conditions'): vol.All( ensure_list, # pylint: disable=unnecessary-lambda [lambda value: CONDITION_SCHEMA(value)], ) }) CONDITION_SCHEMA = vol.Any( NUMERIC_STATE_CONDITION_SCHEMA, STATE_CONDITION_SCHEMA, SUN_CONDITION_SCHEMA, TEMPLATE_CONDITION_SCHEMA, TIME_CONDITION_SCHEMA, ZONE_CONDITION_SCHEMA, AND_CONDITION_SCHEMA, OR_CONDITION_SCHEMA, ) _SCRIPT_DELAY_SCHEMA = vol.Schema({ vol.Optional(CONF_ALIAS): string, vol.Required("delay"): vol.Any( vol.All(time_period, positive_timedelta), template, template_complex) }) _SCRIPT_WAIT_TEMPLATE_SCHEMA = vol.Schema({ vol.Optional(CONF_ALIAS): string, vol.Required("wait_template"): template, vol.Optional(CONF_TIMEOUT): vol.All(time_period, positive_timedelta), vol.Optional("continue_on_timeout"): boolean, }) SCRIPT_SCHEMA = vol.All( ensure_list, [vol.Any(SERVICE_SCHEMA, _SCRIPT_DELAY_SCHEMA, _SCRIPT_WAIT_TEMPLATE_SCHEMA, EVENT_SCHEMA, CONDITION_SCHEMA)], )
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/helpers/config_validation.py
"""Support for Tellstick lights using Tellstick Net.""" import logging from homeassistant.components import light, tellduslive from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light) from homeassistant.helpers.dispatcher import async_dispatcher_connect from .entry import TelldusLiveEntity _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Old way of setting up TelldusLive. Can only be called when a user accidentally mentions the platform in their config. But even in that case it would have been ignored. """ pass async def async_setup_entry(hass, config_entry, async_add_entities): """Set up tellduslive sensors dynamically.""" async def async_discover_light(device_id): """Discover and add a discovered sensor.""" client = hass.data[tellduslive.DOMAIN] async_add_entities([TelldusLiveLight(client, device_id)]) async_dispatcher_connect( hass, tellduslive.TELLDUS_DISCOVERY_NEW.format(light.DOMAIN, tellduslive.DOMAIN), async_discover_light, ) class TelldusLiveLight(TelldusLiveEntity, Light): """Representation of a Tellstick Net light.""" def __init__(self, client, device_id): """Initialize the Tellstick Net light.""" super().__init__(client, device_id) self._last_brightness = self.brightness def changed(self): """Define a property of the device that might have changed.""" self._last_brightness = self.brightness self._update_callback() @property def brightness(self): """Return the brightness of this light between 0..255.""" return self.device.dim_level @property def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS @property def is_on(self): """Return true if light is on.""" return self.device.is_on def turn_on(self, **kwargs): """Turn the light on.""" brightness = kwargs.get(ATTR_BRIGHTNESS, self._last_brightness) self.device.dim(level=brightness) self.changed() def turn_off(self, **kwargs): """Turn the light off.""" self.device.turn_off() self.changed()
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/tellduslive/light.py
"""HTTP views to interact with the device registry.""" import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.decorators import ( async_response, require_admin) from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry WS_TYPE_LIST = 'config/device_registry/list' SCHEMA_WS_LIST = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_LIST, }) WS_TYPE_UPDATE = 'config/device_registry/update' SCHEMA_WS_UPDATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_UPDATE, vol.Required('device_id'): str, vol.Optional('area_id'): vol.Any(str, None), vol.Optional('name_by_user'): vol.Any(str, None), }) async def async_setup(hass): """Enable the Device Registry views.""" hass.components.websocket_api.async_register_command( WS_TYPE_LIST, websocket_list_devices, SCHEMA_WS_LIST ) hass.components.websocket_api.async_register_command( WS_TYPE_UPDATE, websocket_update_device, SCHEMA_WS_UPDATE ) return True @async_response async def websocket_list_devices(hass, connection, msg): """Handle list devices command.""" registry = await async_get_registry(hass) connection.send_message(websocket_api.result_message( msg['id'], [_entry_dict(entry) for entry in registry.devices.values()] )) @require_admin @async_response async def websocket_update_device(hass, connection, msg): """Handle update area websocket command.""" registry = await async_get_registry(hass) msg.pop('type') msg_id = msg.pop('id') entry = registry.async_update_device(**msg) connection.send_message(websocket_api.result_message( msg_id, _entry_dict(entry) )) @callback def _entry_dict(entry): """Convert entry to API format.""" return { 'config_entries': list(entry.config_entries), 'connections': list(entry.connections), 'manufacturer': entry.manufacturer, 'model': entry.model, 'name': entry.name, 'sw_version': entry.sw_version, 'id': entry.id, 'hub_device_id': entry.hub_device_id, 'area_id': entry.area_id, 'name_by_user': entry.name_by_user, }
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/config/device_registry.py
"""Support for Verisure cameras.""" import errno import logging import os from homeassistant.components.camera import Camera from homeassistant.const import EVENT_HOMEASSISTANT_STOP from . import CONF_SMARTCAM, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure Camera.""" if not int(hub.config.get(CONF_SMARTCAM, 1)): return False directory_path = hass.config.config_dir if not os.access(directory_path, os.R_OK): _LOGGER.error("file path %s is not readable", directory_path) return False hub.update_overview() smartcams = [] smartcams.extend([ VerisureSmartcam(hass, device_label, directory_path) for device_label in hub.get( "$.customerImageCameras[*].deviceLabel")]) add_entities(smartcams) class VerisureSmartcam(Camera): """Representation of a Verisure camera.""" def __init__(self, hass, device_label, directory_path): """Initialize Verisure File Camera component.""" super().__init__() self._device_label = device_label self._directory_path = directory_path self._image = None self._image_id = None hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.delete_image) def camera_image(self): """Return image response.""" self.check_imagelist() if not self._image: _LOGGER.debug("No image to display") return _LOGGER.debug("Trying to open %s", self._image) with open(self._image, 'rb') as file: return file.read() def check_imagelist(self): """Check the contents of the image list.""" hub.update_smartcam_imageseries() image_ids = hub.get_image_info( "$.imageSeries[?(@.deviceLabel=='%s')].image[0].imageId", self._device_label) if not image_ids: return new_image_id = image_ids[0] if new_image_id in ('-1', self._image_id): _LOGGER.debug("The image is the same, or loading image_id") return _LOGGER.debug("Download new image %s", new_image_id) new_image_path = os.path.join( self._directory_path, '{}{}'.format(new_image_id, '.jpg')) hub.session.download_image( self._device_label, new_image_id, new_image_path) _LOGGER.debug("Old image_id=%s", self._image_id) self.delete_image(self) self._image_id = new_image_id self._image = new_image_path def delete_image(self, event): """Delete an old image.""" remove_image = os.path.join( self._directory_path, '{}{}'.format(self._image_id, '.jpg')) try: os.remove(remove_image) _LOGGER.debug("Deleting old image %s", remove_image) except OSError as error: if error.errno != errno.ENOENT: raise @property def name(self): """Return the name of this camera.""" return hub.get_first( "$.customerImageCameras[?(@.deviceLabel=='%s')].area", self._device_label)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/verisure/camera.py
"""Support for the Hive binary sensors.""" from homeassistant.components.binary_sensor import BinarySensorDevice from . import DATA_HIVE, DOMAIN DEVICETYPE_DEVICE_CLASS = { 'motionsensor': 'motion', 'contactsensor': 'opening', } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Hive sensor devices.""" if discovery_info is None: return session = hass.data.get(DATA_HIVE) add_entities([HiveBinarySensorEntity(session, discovery_info)]) class HiveBinarySensorEntity(BinarySensorDevice): """Representation of a Hive binary sensor.""" def __init__(self, hivesession, hivedevice): """Initialize the hive sensor.""" self.node_id = hivedevice["Hive_NodeID"] self.node_name = hivedevice["Hive_NodeName"] self.device_type = hivedevice["HA_DeviceType"] self.node_device_type = hivedevice["Hive_DeviceType"] self.session = hivesession self.attributes = {} self.data_updatesource = '{}.{}'.format(self.device_type, self.node_id) self._unique_id = '{}-{}'.format(self.node_id, self.device_type) self.session.entities.append(self) @property def unique_id(self): """Return unique ID of entity.""" return self._unique_id @property def device_info(self): """Return device information.""" return { 'identifiers': { (DOMAIN, self.unique_id) }, 'name': self.name } def handle_update(self, updatesource): """Handle the new update request.""" if '{}.{}'.format(self.device_type, self.node_id) not in updatesource: self.schedule_update_ha_state() @property def device_class(self): """Return the class of this sensor.""" return DEVICETYPE_DEVICE_CLASS.get(self.node_device_type) @property def name(self): """Return the name of the binary sensor.""" return self.node_name @property def device_state_attributes(self): """Show Device Attributes.""" return self.attributes @property def is_on(self): """Return true if the binary sensor is on.""" return self.session.sensor.get_state( self.node_id, self.node_device_type) def update(self): """Update all Node data from Hive.""" self.session.core.update_data(self.node_id) self.attributes = self.session.attributes.state_attributes( self.node_id)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/hive/binary_sensor.py
"""Support for package tracking sensors from 17track.net.""" import logging from datetime import timedelta import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LOCATION, CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME) from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle, slugify _LOGGER = logging.getLogger(__name__) ATTR_DESTINATION_COUNTRY = 'destination_country' ATTR_FRIENDLY_NAME = 'friendly_name' ATTR_INFO_TEXT = 'info_text' ATTR_ORIGIN_COUNTRY = 'origin_country' ATTR_PACKAGES = 'packages' ATTR_PACKAGE_TYPE = 'package_type' ATTR_STATUS = 'status' ATTR_TRACKING_INFO_LANGUAGE = 'tracking_info_language' ATTR_TRACKING_NUMBER = 'tracking_number' CONF_SHOW_ARCHIVED = 'show_archived' CONF_SHOW_DELIVERED = 'show_delivered' DATA_PACKAGES = 'package_data' DATA_SUMMARY = 'summary_data' DEFAULT_ATTRIBUTION = 'Data provided by 17track.net' DEFAULT_SCAN_INTERVAL = timedelta(minutes=10) NOTIFICATION_DELIVERED_ID_SCAFFOLD = 'package_delivered_{0}' NOTIFICATION_DELIVERED_TITLE = 'Package Delivered' NOTIFICATION_DELIVERED_URL_SCAFFOLD = 'https://t.17track.net/track#nums={0}' VALUE_DELIVERED = 'Delivered' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_SHOW_ARCHIVED, default=False): cv.boolean, vol.Optional(CONF_SHOW_DELIVERED, default=False): cv.boolean, }) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Configure the platform and add the sensors.""" from py17track import Client from py17track.errors import SeventeenTrackError websession = aiohttp_client.async_get_clientsession(hass) client = Client(websession) try: login_result = await client.profile.login( config[CONF_USERNAME], config[CONF_PASSWORD]) if not login_result: _LOGGER.error('Invalid username and password provided') return except SeventeenTrackError as err: _LOGGER.error('There was an error while logging in: %s', err) return scan_interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) data = SeventeenTrackData( client, async_add_entities, scan_interval, config[CONF_SHOW_ARCHIVED], config[CONF_SHOW_DELIVERED]) await data.async_update() sensors = [] for status, quantity in data.summary.items(): sensors.append(SeventeenTrackSummarySensor(data, status, quantity)) for package in data.packages: sensors.append(SeventeenTrackPackageSensor(data, package)) async_add_entities(sensors, True) class SeventeenTrackSummarySensor(Entity): """Define a summary sensor.""" def __init__(self, data, status, initial_state): """Initialize.""" self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION} self._data = data self._state = initial_state self._status = status @property def available(self): """Return whether the entity is available.""" return self._state is not None @property def device_state_attributes(self): """Return the device state attributes.""" return self._attrs @property def icon(self): """Return the icon.""" return 'mdi:package' @property def name(self): """Return the name.""" return 'Seventeentrack Packages {0}'.format(self._status) @property def state(self): """Return the state.""" return self._state @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return 'summary_{0}_{1}'.format( self._data.account_id, slugify(self._status)) @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return 'packages' async def async_update(self): """Update the sensor.""" await self._data.async_update() package_data = [] for package in self._data.packages: if package.status != self._status: continue package_data.append({ ATTR_FRIENDLY_NAME: package.friendly_name, ATTR_INFO_TEXT: package.info_text, ATTR_STATUS: package.status, ATTR_TRACKING_NUMBER: package.tracking_number, }) if package_data: self._attrs[ATTR_PACKAGES] = package_data self._state = self._data.summary.get(self._status) class SeventeenTrackPackageSensor(Entity): """Define an individual package sensor.""" def __init__(self, data, package): """Initialize.""" self._attrs = { ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION, ATTR_DESTINATION_COUNTRY: package.destination_country, ATTR_INFO_TEXT: package.info_text, ATTR_LOCATION: package.location, ATTR_ORIGIN_COUNTRY: package.origin_country, ATTR_PACKAGE_TYPE: package.package_type, ATTR_TRACKING_INFO_LANGUAGE: package.tracking_info_language, ATTR_TRACKING_NUMBER: package.tracking_number, } self._data = data self._friendly_name = package.friendly_name self._state = package.status self._tracking_number = package.tracking_number @property def available(self): """Return whether the entity is available.""" return bool([ p for p in self._data.packages if p.tracking_number == self._tracking_number ]) @property def device_state_attributes(self): """Return the device state attributes.""" return self._attrs @property def icon(self): """Return the icon.""" return 'mdi:package' @property def name(self): """Return the name.""" name = self._friendly_name if not name: name = self._tracking_number return 'Seventeentrack Package: {0}'.format(name) @property def state(self): """Return the state.""" return self._state @property def unique_id(self): """Return a unique, HASS-friendly identifier for this entity.""" return 'package_{0}_{1}'.format( self._data.account_id, self._tracking_number) async def async_update(self): """Update the sensor.""" await self._data.async_update() if not self._data.packages: return try: package = next(( p for p in self._data.packages if p.tracking_number == self._tracking_number)) except StopIteration: # If the package no longer exists in the data, log a message and # delete this entity: _LOGGER.info( 'Deleting entity for stale package: %s', self._tracking_number) self.hass.async_create_task(self.async_remove()) return # If the user has elected to not see delivered packages and one gets # delivered, post a notification, remove the entity from the UI, and # delete it from the entity registry: if package.status == VALUE_DELIVERED and not self._data.show_delivered: _LOGGER.info('Package delivered: %s', self._tracking_number) self.hass.components.persistent_notification.create( 'Package Delivered: {0}<br />' 'Visit 17.track for more infomation: {1}' ''.format( self._tracking_number, NOTIFICATION_DELIVERED_URL_SCAFFOLD.format( self._tracking_number)), title=NOTIFICATION_DELIVERED_TITLE, notification_id=NOTIFICATION_DELIVERED_ID_SCAFFOLD.format( self._tracking_number)) reg = self.hass.helpers.entity_registry.async_get_registry() self.hass.async_create_task(reg.async_remove(self.entity_id)) self.hass.async_create_task(self.async_remove()) return self._attrs.update({ ATTR_INFO_TEXT: package.info_text, ATTR_LOCATION: package.location, }) self._state = package.status class SeventeenTrackData: """Define a data handler for 17track.net.""" def __init__( self, client, async_add_entities, scan_interval, show_archived, show_delivered): """Initialize.""" self._async_add_entities = async_add_entities self._client = client self._scan_interval = scan_interval self._show_archived = show_archived self.account_id = client.profile.account_id self.packages = [] self.show_delivered = show_delivered self.summary = {} self.async_update = Throttle(self._scan_interval)(self._async_update) async def _async_update(self): """Get updated data from 17track.net.""" from py17track.errors import SeventeenTrackError try: packages = await self._client.profile.packages( show_archived=self._show_archived) _LOGGER.debug('New package data received: %s', packages) if not self.show_delivered: packages = [p for p in packages if p.status != VALUE_DELIVERED] # Add new packages: to_add = set(packages) - set(self.packages) if self.packages and to_add: self._async_add_entities([ SeventeenTrackPackageSensor(self, package) for package in to_add ], True) self.packages = packages except SeventeenTrackError as err: _LOGGER.error('There was an error retrieving packages: %s', err) self.packages = [] try: self.summary = await self._client.profile.summary( show_archived=self._show_archived) _LOGGER.debug('New summary data received: %s', self.summary) except SeventeenTrackError as err: _LOGGER.error('There was an error retrieving the summary: %s', err) self.summary = {}
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/seventeentrack/sensor.py
"""MySensors constants.""" import homeassistant.helpers.config_validation as cv ATTR_DEVICES = 'devices' CONF_BAUD_RATE = 'baud_rate' CONF_DEVICE = 'device' CONF_GATEWAYS = 'gateways' CONF_NODES = 'nodes' CONF_PERSISTENCE = 'persistence' CONF_PERSISTENCE_FILE = 'persistence_file' CONF_RETAIN = 'retain' CONF_TCP_PORT = 'tcp_port' CONF_TOPIC_IN_PREFIX = 'topic_in_prefix' CONF_TOPIC_OUT_PREFIX = 'topic_out_prefix' CONF_VERSION = 'version' DOMAIN = 'mysensors' MYSENSORS_GATEWAY_READY = 'mysensors_gateway_ready_{}' MYSENSORS_GATEWAYS = 'mysensors_gateways' PLATFORM = 'platform' SCHEMA = 'schema' CHILD_CALLBACK = 'mysensors_child_callback_{}_{}_{}_{}' NODE_CALLBACK = 'mysensors_node_callback_{}_{}' TYPE = 'type' UPDATE_DELAY = 0.1 # MySensors const schemas BINARY_SENSOR_SCHEMA = {PLATFORM: 'binary_sensor', TYPE: 'V_TRIPPED'} CLIMATE_SCHEMA = {PLATFORM: 'climate', TYPE: 'V_HVAC_FLOW_STATE'} LIGHT_DIMMER_SCHEMA = { PLATFORM: 'light', TYPE: 'V_DIMMER', SCHEMA: {'V_DIMMER': cv.string, 'V_LIGHT': cv.string}} LIGHT_PERCENTAGE_SCHEMA = { PLATFORM: 'light', TYPE: 'V_PERCENTAGE', SCHEMA: {'V_PERCENTAGE': cv.string, 'V_STATUS': cv.string}} LIGHT_RGB_SCHEMA = { PLATFORM: 'light', TYPE: 'V_RGB', SCHEMA: { 'V_RGB': cv.string, 'V_STATUS': cv.string}} LIGHT_RGBW_SCHEMA = { PLATFORM: 'light', TYPE: 'V_RGBW', SCHEMA: { 'V_RGBW': cv.string, 'V_STATUS': cv.string}} NOTIFY_SCHEMA = {PLATFORM: 'notify', TYPE: 'V_TEXT'} DEVICE_TRACKER_SCHEMA = {PLATFORM: 'device_tracker', TYPE: 'V_POSITION'} DUST_SCHEMA = [ {PLATFORM: 'sensor', TYPE: 'V_DUST_LEVEL'}, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}] SWITCH_LIGHT_SCHEMA = {PLATFORM: 'switch', TYPE: 'V_LIGHT'} SWITCH_STATUS_SCHEMA = {PLATFORM: 'switch', TYPE: 'V_STATUS'} MYSENSORS_CONST_SCHEMA = { 'S_DOOR': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_MOTION': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SMOKE': [BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SPRINKLER': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_STATUS'}], 'S_WATER_LEAK': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_SOUND': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_VIBRATION': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_MOISTURE': [ BINARY_SENSOR_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}, {PLATFORM: 'switch', TYPE: 'V_ARMED'}], 'S_HVAC': [CLIMATE_SCHEMA], 'S_COVER': [ {PLATFORM: 'cover', TYPE: 'V_DIMMER'}, {PLATFORM: 'cover', TYPE: 'V_PERCENTAGE'}, {PLATFORM: 'cover', TYPE: 'V_LIGHT'}, {PLATFORM: 'cover', TYPE: 'V_STATUS'}], 'S_DIMMER': [LIGHT_DIMMER_SCHEMA, LIGHT_PERCENTAGE_SCHEMA], 'S_RGB_LIGHT': [LIGHT_RGB_SCHEMA], 'S_RGBW_LIGHT': [LIGHT_RGBW_SCHEMA], 'S_INFO': [NOTIFY_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_TEXT'}], 'S_GPS': [ DEVICE_TRACKER_SCHEMA, {PLATFORM: 'sensor', TYPE: 'V_POSITION'}], 'S_TEMP': [{PLATFORM: 'sensor', TYPE: 'V_TEMP'}], 'S_HUM': [{PLATFORM: 'sensor', TYPE: 'V_HUM'}], 'S_BARO': [ {PLATFORM: 'sensor', TYPE: 'V_PRESSURE'}, {PLATFORM: 'sensor', TYPE: 'V_FORECAST'}], 'S_WIND': [ {PLATFORM: 'sensor', TYPE: 'V_WIND'}, {PLATFORM: 'sensor', TYPE: 'V_GUST'}, {PLATFORM: 'sensor', TYPE: 'V_DIRECTION'}], 'S_RAIN': [ {PLATFORM: 'sensor', TYPE: 'V_RAIN'}, {PLATFORM: 'sensor', TYPE: 'V_RAINRATE'}], 'S_UV': [{PLATFORM: 'sensor', TYPE: 'V_UV'}], 'S_WEIGHT': [ {PLATFORM: 'sensor', TYPE: 'V_WEIGHT'}, {PLATFORM: 'sensor', TYPE: 'V_IMPEDANCE'}], 'S_POWER': [ {PLATFORM: 'sensor', TYPE: 'V_WATT'}, {PLATFORM: 'sensor', TYPE: 'V_KWH'}, {PLATFORM: 'sensor', TYPE: 'V_VAR'}, {PLATFORM: 'sensor', TYPE: 'V_VA'}, {PLATFORM: 'sensor', TYPE: 'V_POWER_FACTOR'}], 'S_DISTANCE': [{PLATFORM: 'sensor', TYPE: 'V_DISTANCE'}], 'S_LIGHT_LEVEL': [ {PLATFORM: 'sensor', TYPE: 'V_LIGHT_LEVEL'}, {PLATFORM: 'sensor', TYPE: 'V_LEVEL'}], 'S_IR': [ {PLATFORM: 'sensor', TYPE: 'V_IR_RECEIVE'}, {PLATFORM: 'switch', TYPE: 'V_IR_SEND', SCHEMA: {'V_IR_SEND': cv.string, 'V_LIGHT': cv.string}}], 'S_WATER': [ {PLATFORM: 'sensor', TYPE: 'V_FLOW'}, {PLATFORM: 'sensor', TYPE: 'V_VOLUME'}], 'S_CUSTOM': [ {PLATFORM: 'sensor', TYPE: 'V_VAR1'}, {PLATFORM: 'sensor', TYPE: 'V_VAR2'}, {PLATFORM: 'sensor', TYPE: 'V_VAR3'}, {PLATFORM: 'sensor', TYPE: 'V_VAR4'}, {PLATFORM: 'sensor', TYPE: 'V_VAR5'}, {PLATFORM: 'sensor', TYPE: 'V_CUSTOM'}], 'S_SCENE_CONTROLLER': [ {PLATFORM: 'sensor', TYPE: 'V_SCENE_ON'}, {PLATFORM: 'sensor', TYPE: 'V_SCENE_OFF'}], 'S_COLOR_SENSOR': [{PLATFORM: 'sensor', TYPE: 'V_RGB'}], 'S_MULTIMETER': [ {PLATFORM: 'sensor', TYPE: 'V_VOLTAGE'}, {PLATFORM: 'sensor', TYPE: 'V_CURRENT'}, {PLATFORM: 'sensor', TYPE: 'V_IMPEDANCE'}], 'S_GAS': [ {PLATFORM: 'sensor', TYPE: 'V_FLOW'}, {PLATFORM: 'sensor', TYPE: 'V_VOLUME'}], 'S_WATER_QUALITY': [ {PLATFORM: 'sensor', TYPE: 'V_TEMP'}, {PLATFORM: 'sensor', TYPE: 'V_PH'}, {PLATFORM: 'sensor', TYPE: 'V_ORP'}, {PLATFORM: 'sensor', TYPE: 'V_EC'}, {PLATFORM: 'switch', TYPE: 'V_STATUS'}], 'S_AIR_QUALITY': DUST_SCHEMA, 'S_DUST': DUST_SCHEMA, 'S_LIGHT': [SWITCH_LIGHT_SCHEMA], 'S_BINARY': [SWITCH_STATUS_SCHEMA], 'S_LOCK': [{PLATFORM: 'switch', TYPE: 'V_LOCK_STATUS'}], }
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/mysensors/const.py
"""Cover Platform for the Somfy MyLink component.""" import logging from homeassistant.components.cover import ENTITY_ID_FORMAT, CoverDevice from homeassistant.util import slugify from . import CONF_DEFAULT_REVERSE, DATA_SOMFY_MYLINK _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Discover and configure Somfy covers.""" if discovery_info is None: return somfy_mylink = hass.data[DATA_SOMFY_MYLINK] cover_list = [] try: mylink_status = await somfy_mylink.status_info() except TimeoutError: _LOGGER.error("Unable to connect to the Somfy MyLink device, " "please check your settings") return for cover in mylink_status['result']: entity_id = ENTITY_ID_FORMAT.format(slugify(cover['name'])) entity_config = discovery_info.get(entity_id, {}) default_reverse = discovery_info[CONF_DEFAULT_REVERSE] cover_config = {} cover_config['target_id'] = cover['targetID'] cover_config['name'] = cover['name'] cover_config['reverse'] = entity_config.get('reverse', default_reverse) cover_list.append(SomfyShade(somfy_mylink, **cover_config)) _LOGGER.info('Adding Somfy Cover: %s with targetID %s', cover_config['name'], cover_config['target_id']) async_add_entities(cover_list) class SomfyShade(CoverDevice): """Object for controlling a Somfy cover.""" def __init__(self, somfy_mylink, target_id='AABBCC', name='SomfyShade', reverse=False, device_class='window'): """Initialize the cover.""" self.somfy_mylink = somfy_mylink self._target_id = target_id self._name = name self._reverse = reverse self._device_class = device_class @property def name(self): """Return the name of the cover.""" return self._name @property def is_closed(self): """Return if the cover is closed.""" return None @property def assumed_state(self): """Let HA know the integration is assumed state.""" return True @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return self._device_class async def async_open_cover(self, **kwargs): """Wrap Homeassistant calls to open the cover.""" if not self._reverse: await self.somfy_mylink.move_up(self._target_id) else: await self.somfy_mylink.move_down(self._target_id) async def async_close_cover(self, **kwargs): """Wrap Homeassistant calls to close the cover.""" if not self._reverse: await self.somfy_mylink.move_down(self._target_id) else: await self.somfy_mylink.move_up(self._target_id) async def async_stop_cover(self, **kwargs): """Stop the cover.""" await self.somfy_mylink.move_stop(self._target_id)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/somfy_mylink/cover.py
"""Support for Qwikswitch devices.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA from homeassistant.components.light import ATTR_BRIGHTNESS from homeassistant.const import ( CONF_SENSORS, CONF_SWITCHES, CONF_URL, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) DOMAIN = 'qwikswitch' CONF_DIMMER_ADJUST = 'dimmer_adjust' CONF_BUTTON_EVENTS = 'button_events' CV_DIM_VALUE = vol.All(vol.Coerce(float), vol.Range(min=1, max=3)) CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_URL, default='http://127.0.0.1:2020'): vol.Coerce(str), vol.Optional(CONF_DIMMER_ADJUST, default=1): CV_DIM_VALUE, vol.Optional(CONF_BUTTON_EVENTS, default=[]): cv.ensure_list_csv, vol.Optional(CONF_SENSORS, default=[]): vol.All( cv.ensure_list, [vol.Schema({ vol.Required('id'): str, vol.Optional('channel', default=1): int, vol.Required('name'): str, vol.Required('type'): str, vol.Optional('class'): DEVICE_CLASSES_SCHEMA, vol.Optional('invert'): bool })]), vol.Optional(CONF_SWITCHES, default=[]): vol.All( cv.ensure_list, [str]) })}, extra=vol.ALLOW_EXTRA) class QSEntity(Entity): """Qwikswitch Entity base.""" def __init__(self, qsid, name): """Initialize the QSEntity.""" self._name = name self.qsid = qsid @property def name(self): """Return the name of the sensor.""" return self._name @property def poll(self): """QS sensors gets packets in update_packet.""" return False @property def unique_id(self): """Return a unique identifier for this sensor.""" return "qs{}".format(self.qsid) @callback def update_packet(self, packet): """Receive update packet from QSUSB. Match dispather_send signature.""" self.async_schedule_update_ha_state() async def async_added_to_hass(self): """Listen for updates from QSUSb via dispatcher.""" self.hass.helpers.dispatcher.async_dispatcher_connect( self.qsid, self.update_packet) class QSToggleEntity(QSEntity): """Representation of a Qwikswitch Toggle Entity. Implemented: - QSLight extends QSToggleEntity and Light[2] (ToggleEntity[1]) - QSSwitch extends QSToggleEntity and SwitchDevice[3] (ToggleEntity[1]) [1] /helpers/entity.py [2] /components/light/__init__.py [3] /components/switch/__init__.py """ def __init__(self, qsid, qsusb): """Initialize the ToggleEntity.""" self.device = qsusb.devices[qsid] super().__init__(qsid, self.device.name) @property def is_on(self): """Check if device is on (non-zero).""" return self.device.value > 0 async def async_turn_on(self, **kwargs): """Turn the device on.""" new = kwargs.get(ATTR_BRIGHTNESS, 255) self.hass.data[DOMAIN].devices.set_value(self.qsid, new) async def async_turn_off(self, **_): """Turn the device off.""" self.hass.data[DOMAIN].devices.set_value(self.qsid, 0) async def async_setup(hass, config): """Qwiskswitch component setup.""" from pyqwikswitch.async_ import QSUsb from pyqwikswitch.qwikswitch import ( CMD_BUTTONS, QS_CMD, QS_ID, QSType, SENSORS) # Add cmd's to in /&listen packets will fire events # By default only buttons of type [TOGGLE,SCENE EXE,LEVEL] cmd_buttons = set(CMD_BUTTONS) for btn in config[DOMAIN][CONF_BUTTON_EVENTS]: cmd_buttons.add(btn) url = config[DOMAIN][CONF_URL] dimmer_adjust = config[DOMAIN][CONF_DIMMER_ADJUST] sensors = config[DOMAIN][CONF_SENSORS] switches = config[DOMAIN][CONF_SWITCHES] def callback_value_changed(_qsd, qsid, _val): """Update entity values based on device change.""" _LOGGER.debug("Dispatch %s (update from devices)", qsid) hass.helpers.dispatcher.async_dispatcher_send(qsid, None) session = async_get_clientsession(hass) qsusb = QSUsb(url=url, dim_adj=dimmer_adjust, session=session, callback_value_changed=callback_value_changed) # Discover all devices in QSUSB if not await qsusb.update_from_devices(): return False hass.data[DOMAIN] = qsusb comps = {'switch': [], 'light': [], 'sensor': [], 'binary_sensor': []} try: sensor_ids = [] for sens in sensors: _, _type = SENSORS[sens['type']] sensor_ids.append(sens['id']) if _type is bool: comps['binary_sensor'].append(sens) continue comps['sensor'].append(sens) for _key in ('invert', 'class'): if _key in sens: _LOGGER.warning( "%s should only be used for binary_sensors: %s", _key, sens) except KeyError: _LOGGER.warning("Sensor validation failed") for qsid, dev in qsusb.devices.items(): if qsid in switches: if dev.qstype != QSType.relay: _LOGGER.warning( "You specified a switch that is not a relay %s", qsid) continue comps['switch'].append(qsid) elif dev.qstype in (QSType.relay, QSType.dimmer): comps['light'].append(qsid) else: _LOGGER.warning("Ignored unknown QSUSB device: %s", dev) continue # Load platforms for comp_name, comp_conf in comps.items(): if comp_conf: load_platform(hass, comp_name, DOMAIN, {DOMAIN: comp_conf}, config) def callback_qs_listen(qspacket): """Typically a button press or update signal.""" # If button pressed, fire a hass event if QS_ID in qspacket: if qspacket.get(QS_CMD, '') in cmd_buttons: hass.bus.async_fire( 'qwikswitch.button.{}'.format(qspacket[QS_ID]), qspacket) return if qspacket[QS_ID] in sensor_ids: _LOGGER.debug("Dispatch %s ((%s))", qspacket[QS_ID], qspacket) hass.helpers.dispatcher.async_dispatcher_send( qspacket[QS_ID], qspacket) # Update all ha_objects hass.async_add_job(qsusb.update_from_devices) @callback def async_start(_): """Start listening.""" hass.async_add_job(qsusb.listen, callback_qs_listen) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, async_start) @callback def async_stop(_): """Stop the listener.""" hass.data[DOMAIN].stop() hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_stop) return True
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/qwikswitch/__init__.py
"""Support for the yandex speechkit tts service.""" import asyncio import logging import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.const import CONF_API_KEY from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) YANDEX_API_URL = "https://tts.voicetech.yandex.net/generate?" SUPPORT_LANGUAGES = [ 'ru-RU', 'en-US', 'tr-TR', 'uk-UK' ] SUPPORT_CODECS = [ 'mp3', 'wav', 'opus', ] SUPPORT_VOICES = [ 'jane', 'oksana', 'alyss', 'omazh', 'zahar', 'ermil', 'levitan', 'ermilov', 'silaerkan', 'kolya', 'kostya', 'nastya', 'sasha', 'nick', 'erkanyavas', 'zhenya', 'tanya', 'anton_samokhvalov', 'tatyana_abramova', 'voicesearch', 'ermil_with_tuning', 'robot', 'dude', 'zombie', 'smoky' ] SUPPORTED_EMOTION = [ 'good', 'evil', 'neutral' ] MIN_SPEED = 0.1 MAX_SPEED = 3 CONF_CODEC = 'codec' CONF_VOICE = 'voice' CONF_EMOTION = 'emotion' CONF_SPEED = 'speed' DEFAULT_LANG = 'en-US' DEFAULT_CODEC = 'mp3' DEFAULT_VOICE = 'zahar' DEFAULT_EMOTION = 'neutral' DEFAULT_SPEED = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), vol.Optional(CONF_CODEC, default=DEFAULT_CODEC): vol.In(SUPPORT_CODECS), vol.Optional(CONF_VOICE, default=DEFAULT_VOICE): vol.In(SUPPORT_VOICES), vol.Optional(CONF_EMOTION, default=DEFAULT_EMOTION): vol.In(SUPPORTED_EMOTION), vol.Optional(CONF_SPEED, default=DEFAULT_SPEED): vol.Range(min=MIN_SPEED, max=MAX_SPEED) }) SUPPORTED_OPTIONS = [ CONF_CODEC, CONF_VOICE, CONF_EMOTION, CONF_SPEED, ] async def async_get_engine(hass, config): """Set up VoiceRSS speech component.""" return YandexSpeechKitProvider(hass, config) class YandexSpeechKitProvider(Provider): """VoiceRSS speech api provider.""" def __init__(self, hass, conf): """Init VoiceRSS TTS service.""" self.hass = hass self._codec = conf.get(CONF_CODEC) self._key = conf.get(CONF_API_KEY) self._speaker = conf.get(CONF_VOICE) self._language = conf.get(CONF_LANG) self._emotion = conf.get(CONF_EMOTION) self._speed = str(conf.get(CONF_SPEED)) self.name = 'YandexTTS' @property def default_language(self): """Return the default language.""" return self._language @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES @property def supported_options(self): """Return list of supported options.""" return SUPPORTED_OPTIONS async def async_get_tts_audio(self, message, language, options=None): """Load TTS from yandex.""" websession = async_get_clientsession(self.hass) actual_language = language options = options or {} try: with async_timeout.timeout(10, loop=self.hass.loop): url_param = { 'text': message, 'lang': actual_language, 'key': self._key, 'speaker': options.get(CONF_VOICE, self._speaker), 'format': options.get(CONF_CODEC, self._codec), 'emotion': options.get(CONF_EMOTION, self._emotion), 'speed': options.get(CONF_SPEED, self._speed) } request = await websession.get( YANDEX_API_URL, params=url_param) if request.status != 200: _LOGGER.error("Error %d on load URL %s", request.status, request.url) return (None, None) data = await request.read() except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.error("Timeout for yandex speech kit API") return (None, None) return (self._codec, data)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/yandextts/tts.py
"""Support for EDP re:dy.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, EVENT_HOMEASSISTANT_START) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, discovery, dispatcher import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) DOMAIN = 'edp_redy' EDP_REDY = 'edp_redy' DATA_UPDATE_TOPIC = '{0}_data_update'.format(DOMAIN) UPDATE_INTERVAL = 60 CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string }) }, extra=vol.ALLOW_EXTRA) async def async_setup(hass, config): """Set up the EDP re:dy component.""" from edp_redy import EdpRedySession session = EdpRedySession(config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD], aiohttp_client.async_get_clientsession(hass), hass.loop) hass.data[EDP_REDY] = session platform_loaded = False async def async_update_and_sched(time): update_success = await session.async_update() if update_success: nonlocal platform_loaded # pylint: disable=used-before-assignment if not platform_loaded: for component in ['sensor', 'switch']: await discovery.async_load_platform(hass, component, DOMAIN, {}, config) platform_loaded = True dispatcher.async_dispatcher_send(hass, DATA_UPDATE_TOPIC) # schedule next update async_track_point_in_time(hass, async_update_and_sched, time + timedelta(seconds=UPDATE_INTERVAL)) async def start_component(event): _LOGGER.debug("Starting updates") await async_update_and_sched(dt_util.utcnow()) # only start fetching data after HA boots to prevent delaying the boot # process hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_component) return True class EdpRedyDevice(Entity): """Representation a base re:dy device.""" def __init__(self, session, device_id, name): """Initialize the device.""" self._session = session self._state = None self._is_available = True self._device_state_attributes = {} self._id = device_id self._unique_id = device_id self._name = name if name else device_id async def async_added_to_hass(self): """Subscribe to the data updates topic.""" dispatcher.async_dispatcher_connect( self.hass, DATA_UPDATE_TOPIC, self._data_updated) @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def available(self): """Return True if entity is available.""" return self._is_available @property def should_poll(self): """Return the polling state. No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes.""" return self._device_state_attributes @callback def _data_updated(self): """Update state, trigger updates.""" self.async_schedule_update_ha_state(True) def _parse_data(self, data): """Parse data received from the server.""" if "OutOfOrder" in data: try: self._is_available = not data['OutOfOrder'] except ValueError: _LOGGER.error( "Could not parse OutOfOrder for %s", self._id) self._is_available = False
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/edp_redy/__init__.py
"""Support for the Microsoft Cognitive Services text-to-speech service.""" from http.client import HTTPException import logging import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.const import CONF_API_KEY, CONF_TYPE import homeassistant.helpers.config_validation as cv CONF_GENDER = 'gender' CONF_OUTPUT = 'output' CONF_RATE = 'rate' CONF_VOLUME = 'volume' CONF_PITCH = 'pitch' CONF_CONTOUR = 'contour' _LOGGER = logging.getLogger(__name__) SUPPORTED_LANGUAGES = [ 'ar-eg', 'ar-sa', 'ca-es', 'cs-cz', 'da-dk', 'de-at', 'de-ch', 'de-de', 'el-gr', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-in', 'en-us', 'es-es', 'es-mx', 'fi-fi', 'fr-ca', 'fr-ch', 'fr-fr', 'he-il', 'hi-in', 'hu-hu', 'id-id', 'it-it', 'ja-jp', 'ko-kr', 'nb-no', 'nl-nl', 'pl-pl', 'pt-br', 'pt-pt', 'ro-ro', 'ru-ru', 'sk-sk', 'sv-se', 'th-th', 'tr-tr', 'zh-cn', 'zh-hk', 'zh-tw', ] GENDERS = [ 'Female', 'Male', ] DEFAULT_LANG = 'en-us' DEFAULT_GENDER = 'Female' DEFAULT_TYPE = 'ZiraRUS' DEFAULT_OUTPUT = 'audio-16khz-128kbitrate-mono-mp3' DEFAULT_RATE = 0 DEFAULT_VOLUME = 0 DEFAULT_PITCH = "default" DEFAULT_CONTOUR = "" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORTED_LANGUAGES), vol.Optional(CONF_GENDER, default=DEFAULT_GENDER): vol.In(GENDERS), vol.Optional(CONF_TYPE, default=DEFAULT_TYPE): cv.string, vol.Optional(CONF_RATE, default=DEFAULT_RATE): vol.All(vol.Coerce(int), vol.Range(-100, 100)), vol.Optional(CONF_VOLUME, default=DEFAULT_VOLUME): vol.All(vol.Coerce(int), vol.Range(-100, 100)), vol.Optional(CONF_PITCH, default=DEFAULT_PITCH): cv.string, vol.Optional(CONF_CONTOUR, default=DEFAULT_CONTOUR): cv.string, }) def get_engine(hass, config): """Set up Microsoft speech component.""" return MicrosoftProvider(config[CONF_API_KEY], config[CONF_LANG], config[CONF_GENDER], config[CONF_TYPE], config[CONF_RATE], config[CONF_VOLUME], config[CONF_PITCH], config[CONF_CONTOUR]) class MicrosoftProvider(Provider): """The Microsoft speech API provider.""" def __init__(self, apikey, lang, gender, ttype, rate, volume, pitch, contour): """Init Microsoft TTS service.""" self._apikey = apikey self._lang = lang self._gender = gender self._type = ttype self._output = DEFAULT_OUTPUT self._rate = "{}%".format(rate) self._volume = "{}%".format(volume) self._pitch = pitch self._contour = contour self.name = 'Microsoft' @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORTED_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS from Microsoft.""" if language is None: language = self._lang from pycsspeechtts import pycsspeechtts try: trans = pycsspeechtts.TTSTranslator(self._apikey) data = trans.speak(language=language, gender=self._gender, voiceType=self._type, output=self._output, rate=self._rate, volume=self._volume, pitch=self._pitch, contour=self._contour, text=message) except HTTPException as ex: _LOGGER.error("Error occurred for Microsoft TTS: %s", ex) return(None, None) return ("mp3", data)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/microsoft/tts.py
"""Support for information about the German train system.""" from datetime import timedelta import logging 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 _LOGGER = logging.getLogger(__name__) CONF_DESTINATION = 'to' CONF_START = 'from' 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_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.get(CONF_DESTINATION) only_direct = config.get(CONF_ONLY_DIRECT) add_entities([DeutscheBahnSensor(start, destination, only_direct)], True) class DeutscheBahnSensor(Entity): """Implementation of a Deutsche Bahn sensor.""" def __init__(self, start, goal, only_direct): """Initialize the sensor.""" self._name = '{} to {}'.format(start, goal) self.data = SchieneData(start, goal, 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 += " + {}".format(self.data.connections[0]['delay']) class SchieneData: """Pull data from the bahn.de web page.""" def __init__(self, start, goal, only_direct): """Initialize the sensor.""" import schiene self.start = start self.goal = goal 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.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)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/deutsche_bahn/sensor.py
""" Support for getting the state of a Thermoworks Smoke Thermometer. Requires Smoke Gateway Wifi with an internet connection. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.thermoworks_smoke/ """ import logging from requests import RequestException import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import TEMP_FAHRENHEIT, CONF_EMAIL, CONF_PASSWORD,\ CONF_MONITORED_CONDITIONS, CONF_EXCLUDE, ATTR_BATTERY_LEVEL from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) PROBE_1 = 'probe1' PROBE_2 = 'probe2' PROBE_1_MIN = 'probe1_min' PROBE_1_MAX = 'probe1_max' PROBE_2_MIN = 'probe2_min' PROBE_2_MAX = 'probe2_max' BATTERY_LEVEL = 'battery' FIRMWARE = 'firmware' SERIAL_REGEX = '^(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$' # map types to labels SENSOR_TYPES = { PROBE_1: 'Probe 1', PROBE_2: 'Probe 2', PROBE_1_MIN: 'Probe 1 Min', PROBE_1_MAX: 'Probe 1 Max', PROBE_2_MIN: 'Probe 2 Min', PROBE_2_MAX: 'Probe 2 Max', } # exclude these keys from thermoworks data EXCLUDE_KEYS = [ FIRMWARE ] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_EMAIL): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=[PROBE_1, PROBE_2]): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), vol.Optional(CONF_EXCLUDE, default=[]): vol.All(cv.ensure_list, [cv.matches_regex(SERIAL_REGEX)]), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the thermoworks sensor.""" import thermoworks_smoke from requests.exceptions import HTTPError email = config[CONF_EMAIL] password = config[CONF_PASSWORD] monitored_variables = config[CONF_MONITORED_CONDITIONS] excluded = config[CONF_EXCLUDE] try: mgr = thermoworks_smoke.initialize_app(email, password, True, excluded) # list of sensor devices dev = [] # get list of registered devices for serial in mgr.serials(): for variable in monitored_variables: dev.append(ThermoworksSmokeSensor(variable, serial, mgr)) add_entities(dev, True) except HTTPError as error: msg = "{}".format(error.strerror) if 'EMAIL_NOT_FOUND' in msg or \ 'INVALID_PASSWORD' in msg: _LOGGER.error("Invalid email and password combination") else: _LOGGER.error(msg) class ThermoworksSmokeSensor(Entity): """Implementation of a thermoworks smoke sensor.""" def __init__(self, sensor_type, serial, mgr): """Initialize the sensor.""" self._name = "{name} {sensor}".format( name=mgr.name(serial), sensor=SENSOR_TYPES[sensor_type]) self.type = sensor_type self._state = None self._attributes = {} self._unit_of_measurement = TEMP_FAHRENHEIT self._unique_id = "{serial}-{type}".format( serial=serial, type=sensor_type) self.serial = serial self.mgr = mgr self.update_unit() @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return the unique id for the sensor.""" return self._unique_id @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @property def unit_of_measurement(self): """Return the unit of measurement of this sensor.""" return self._unit_of_measurement def update_unit(self): """Set the units from the data.""" if PROBE_2 in self.type: self._unit_of_measurement = self.mgr.units(self.serial, PROBE_2) else: self._unit_of_measurement = self.mgr.units(self.serial, PROBE_1) def update(self): """Get the monitored data from firebase.""" from stringcase import camelcase, snakecase try: values = self.mgr.data(self.serial) # set state from data based on type of sensor self._state = values.get(camelcase(self.type)) # set units self.update_unit() # set basic attributes for all sensors self._attributes = { 'time': values['time'], 'localtime': values['localtime'] } # set extended attributes for main probe sensors if self.type in [PROBE_1, PROBE_2]: for key, val in values.items(): # add all attributes that don't contain any probe name # or contain a matching probe name if ( (self.type == PROBE_1 and key.find(PROBE_2) == -1) or (self.type == PROBE_2 and key.find(PROBE_1) == -1) ): if key == BATTERY_LEVEL: key = ATTR_BATTERY_LEVEL else: # strip probe label and convert to snake_case key = snakecase(key.replace(self.type, '')) # add to attrs if key and key not in EXCLUDE_KEYS: self._attributes[key] = val # store actual unit because attributes are not converted self._attributes['unit_of_min_max'] = self._unit_of_measurement except (RequestException, ValueError, KeyError): _LOGGER.warning("Could not update status for %s", self.name)
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/thermoworks_smoke/sensor.py
"""Component for interacting with the Yale Smart Alarm System API.""" import logging import voluptuous as vol from homeassistant.components.alarm_control_panel import ( AlarmControlPanel, PLATFORM_SCHEMA) from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, CONF_NAME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED) import homeassistant.helpers.config_validation as cv CONF_AREA_ID = 'area_id' DEFAULT_NAME = 'Yale Smart Alarm' DEFAULT_AREA_ID = '1' _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_AREA_ID, default=DEFAULT_AREA_ID): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the alarm platform.""" name = config[CONF_NAME] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] area_id = config[CONF_AREA_ID] from yalesmartalarmclient.client import ( YaleSmartAlarmClient, AuthenticationError) try: client = YaleSmartAlarmClient(username, password, area_id) except AuthenticationError: _LOGGER.error("Authentication failed. Check credentials") return add_entities([YaleAlarmDevice(name, client)], True) class YaleAlarmDevice(AlarmControlPanel): """Represent a Yale Smart Alarm.""" def __init__(self, name, client): """Initialize the Yale Alarm Device.""" self._name = name self._client = client self._state = None from yalesmartalarmclient.client import (YALE_STATE_DISARM, YALE_STATE_ARM_PARTIAL, YALE_STATE_ARM_FULL) self._state_map = { YALE_STATE_DISARM: STATE_ALARM_DISARMED, YALE_STATE_ARM_PARTIAL: STATE_ALARM_ARMED_HOME, YALE_STATE_ARM_FULL: STATE_ALARM_ARMED_AWAY } @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state def update(self): """Return the state of the device.""" armed_status = self._client.get_armed_status() self._state = self._state_map.get(armed_status) def alarm_disarm(self, code=None): """Send disarm command.""" self._client.disarm() def alarm_arm_home(self, code=None): """Send arm home command.""" self._client.arm_partial() def alarm_arm_away(self, code=None): """Send arm away command.""" self._client.arm_full()
"""Test the Home Assistant local auth provider.""" import asyncio from unittest.mock import Mock, patch import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.auth import auth_manager_from_config, auth_store from homeassistant.auth.providers import ( auth_provider_from_config, homeassistant as hass_auth) from tests.common import mock_coro @pytest.fixture def data(hass): """Create a loaded data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) return data @pytest.fixture def legacy_data(hass): """Create a loaded legacy data class.""" data = hass_auth.Data(hass) hass.loop.run_until_complete(data.async_load()) data.is_legacy = True return data async def test_validating_password_invalid_user(data, hass): """Test validating an invalid user.""" with pytest.raises(hass_auth.InvalidAuth): data.validate_login('non-existing', 'pw') async def test_not_allow_set_id(): """Test we are not allowed to set an ID in config.""" hass = Mock() with pytest.raises(vol.Invalid): await auth_provider_from_config(hass, None, { 'type': 'homeassistant', 'id': 'invalid', }) async def test_new_users_populate_values(hass, data): """Test that we populate data for new users.""" data.add_auth('hello', 'test-pass') await data.async_save() manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] credentials = await provider.async_get_or_create_credentials({ 'username': 'hello' }) user = await manager.async_get_or_create_user(credentials) assert user.name == 'hello' assert user.is_active async def test_changing_password_raises_invalid_user(data, hass): """Test that changing password raises invalid user.""" with pytest.raises(hass_auth.InvalidUser): data.change_password('non-existing', 'pw') # Modern mode async def test_adding_user(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.validate_login(' test-user ', 'test-pass') async def test_adding_user_duplicate_username(data, hass): """Test adding a user with duplicate username.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): data.add_auth('TEST-user ', 'other-pass') async def test_validating_password_invalid_password(data, hass): """Test validating an invalid password.""" data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login(' test-user ', 'invalid-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass ') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'Test-pass') async def test_changing_password(data, hass): """Test adding a user.""" data.add_auth('test-user', 'test-pass') data.change_password('TEST-USER ', 'new-pass') with pytest.raises(hass_auth.InvalidAuth): data.validate_login('test-user', 'test-pass') data.validate_login('test-UsEr', 'new-pass') async def test_login_flow_validates(data, hass): """Test login flow.""" data.add_auth('test-user', 'test-pass') await data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'TEST-user ', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-USER', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-USER' async def test_saving_loading(data, hass): """Test saving and loading JSON.""" data.add_auth('test-user', 'test-pass') data.add_auth('second-user', 'second-pass') await data.async_save() data = hass_auth.Data(hass) await data.async_load() data.validate_login('test-user ', 'test-pass') data.validate_login('second-user ', 'second-pass') async def test_get_or_create_credentials(hass, data): """Test that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is credentials2 # Legacy mode async def test_legacy_adding_user(legacy_data, hass): """Test in legacy mode adding a user.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.validate_login('test-user', 'test-pass') async def test_legacy_adding_user_duplicate_username(legacy_data, hass): """Test in legacy mode adding a user with duplicate username.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidUser): legacy_data.add_auth('test-user', 'other-pass') # Not considered duplicate legacy_data.add_auth('test-user ', 'test-pass') legacy_data.add_auth('Test-user', 'test-pass') async def test_legacy_validating_password_invalid_password(legacy_data, hass): """Test in legacy mode validating an invalid password.""" legacy_data.add_auth('test-user', 'test-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user', 'invalid-pass') async def test_legacy_changing_password(legacy_data, hass): """Test in legacy mode adding a user.""" user = 'test-user' legacy_data.add_auth(user, 'test-pass') legacy_data.change_password(user, 'new-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login(user, 'test-pass') legacy_data.validate_login(user, 'new-pass') async def test_legacy_changing_password_raises_invalid_user(legacy_data, hass): """Test in legacy mode that we initialize an empty config.""" with pytest.raises(hass_auth.InvalidUser): legacy_data.change_password('non-existing', 'pw') async def test_legacy_login_flow_validates(legacy_data, hass): """Test in legacy mode login flow.""" legacy_data.add_auth('test-user', 'test-pass') await legacy_data.async_save() provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) flow = await provider.async_login_flow({}) result = await flow.async_step_init() assert result['type'] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({ 'username': 'incorrect-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'incorrect-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['errors']['base'] == 'invalid_auth' result = await flow.async_step_init({ 'username': 'test-user', 'password': 'test-pass', }) assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result['data']['username'] == 'test-user' async def test_legacy_saving_loading(legacy_data, hass): """Test in legacy mode saving and loading JSON.""" legacy_data.add_auth('test-user', 'test-pass') legacy_data.add_auth('second-user', 'second-pass') await legacy_data.async_save() legacy_data = hass_auth.Data(hass) await legacy_data.async_load() legacy_data.is_legacy = True legacy_data.validate_login('test-user', 'test-pass') legacy_data.validate_login('second-user', 'second-pass') with pytest.raises(hass_auth.InvalidAuth): legacy_data.validate_login('test-user ', 'test-pass') async def test_legacy_get_or_create_credentials(hass, legacy_data): """Test in legacy mode that we can get or create credentials.""" manager = await auth_manager_from_config(hass, [{ 'type': 'homeassistant' }], []) provider = manager.auth_providers[0] provider.data = legacy_data credentials1 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials2 = await provider.async_get_or_create_credentials({ 'username': 'hello' }) assert credentials1 is credentials2 with patch.object(provider, 'async_credentials', return_value=mock_coro([credentials1])): credentials3 = await provider.async_get_or_create_credentials({ 'username': 'hello ' }) assert credentials1 is not credentials3 async def test_race_condition_in_data_loading(hass): """Test race condition in the hass_auth.Data loading. Ref issue: https://github.com/home-assistant/home-assistant/issues/21569 """ counter = 0 async def mock_load(_): """Mock of homeassistant.helpers.storage.Store.async_load.""" nonlocal counter counter += 1 await asyncio.sleep(0) provider = hass_auth.HassAuthProvider(hass, auth_store.AuthStore(hass), {'type': 'homeassistant'}) with patch('homeassistant.helpers.storage.Store.async_load', new=mock_load): task1 = provider.async_validate_login('user', 'pass') task2 = provider.async_validate_login('user', 'pass') results = await asyncio.gather(task1, task2, return_exceptions=True) assert counter == 1 assert isinstance(results[0], hass_auth.InvalidAuth) # results[1] will be a TypeError if race condition occurred assert isinstance(results[1], hass_auth.InvalidAuth)
auduny/home-assistant
tests/auth/providers/test_homeassistant.py
homeassistant/components/yale_smart_alarm/alarm_control_panel.py
# -*- coding: utf-8 -*- import functools from django.contrib.postgres.fields import ArrayField from django.db import models from osf.models.base import BaseModel, ObjectIDMixin def _serialize(fields, instance): return { field: getattr(instance, field if field != 'id' else 'license_id') for field in fields } serialize_node_license = functools.partial(_serialize, ('id', 'name', 'text')) def serialize_node_license_record(node_license_record): if node_license_record is None: return {} ret = serialize_node_license(node_license_record.node_license) ret.update(_serialize(('year', 'copyright_holders'), node_license_record)) return ret class NodeLicenseManager(models.Manager): PREPRINT_ONLY_LICENSES = { 'CCBYNCND', 'CCBYSA40', } def preprint_licenses(self): return self.all() def project_licenses(self): return self.exclude(license_id__in=self.PREPRINT_ONLY_LICENSES) class NodeLicense(ObjectIDMixin, BaseModel): license_id = models.CharField(max_length=128, null=False, unique=True) name = models.CharField(max_length=256, null=False, unique=True) text = models.TextField(null=False) url = models.URLField(blank=True) properties = ArrayField(models.CharField(max_length=128), default=list, blank=True) objects = NodeLicenseManager() def __unicode__(self): return '(license_id={}, name={})'.format(self.license_id, self.name) class Meta: unique_together = ['_id', 'license_id'] class NodeLicenseRecord(ObjectIDMixin, BaseModel): node_license = models.ForeignKey('NodeLicense', null=True, blank=True, on_delete=models.SET_NULL) # Deliberately left as a CharField to support year ranges (e.g. 2012-2015) year = models.CharField(max_length=128, null=True, blank=True) copyright_holders = ArrayField( models.CharField(max_length=256, blank=True, null=True), default=list, blank=True) def __unicode__(self): if self.node_license: return self.node_license.__unicode__() return super(NodeLicenseRecord, self).__unicode__() @property def name(self): return self.node_license.name if self.node_license else None @property def text(self): return self.node_license.text if self.node_license else None @property def license_id(self): return self.node_license.license_id if self.node_license else None @property def url(self): return self.node_license.url if self.node_license else None def to_json(self): return serialize_node_license_record(self) def copy(self): copied = NodeLicenseRecord( node_license=self.node_license, year=self.year, copyright_holders=self.copyright_holders ) copied.save() return copied
from osf.models import Institution from .factories import InstitutionFactory import pytest @pytest.mark.django_db def test_factory(): inst = InstitutionFactory() assert isinstance(inst.name, basestring) assert len(inst.domains) > 0 assert len(inst.email_domains) > 0 @pytest.mark.django_db def test_querying_on_domains(): inst = InstitutionFactory(domains=['foo.test']) result = Institution.objects.filter(domains__contains=['foo.test']) assert inst in result @pytest.mark.django_db def test_institution_banner_path_none(): inst = InstitutionFactory(banner_name='kittens.png') assert inst.banner_path is not None inst.banner_name = None assert inst.banner_path is None @pytest.mark.django_db def test_institution_logo_path_none(): inst = InstitutionFactory(logo_name='kittens.png') assert inst.logo_path is not None inst.logo_name = None assert inst.logo_path is None @pytest.mark.django_db def test_institution_logo_path(): inst = InstitutionFactory(logo_name='osf-shield.png') expected_logo_path = '/static/img/institutions/shields/osf-shield.png' assert inst.logo_path == expected_logo_path @pytest.mark.django_db def test_institution_logo_path_rounded_corners(): inst = InstitutionFactory(logo_name='osf-shield.png') expected_logo_path = '/static/img/institutions/shields-rounded-corners/osf-shield-rounded-corners.png' assert inst.logo_path_rounded_corners == expected_logo_path @pytest.mark.django_db def test_institution_banner_path(): inst = InstitutionFactory(banner_name='osf-banner.png') expected_banner_path = '/static/img/institutions/banners/osf-banner.png' assert inst.banner_path == expected_banner_path
mfraezz/osf.io
osf_tests/test_institution.py
osf/models/licenses.py
""" Print task """ import logging log = logging.getLogger(__name__) def task(ctx, config): """ Print out config argument in teuthology log/output """ log.info('{config}'.format(config=config))
import pytest from mock import patch, Mock from teuthology import ls class TestLs(object): """ Tests for teuthology.ls """ @patch('os.path.isdir') @patch('os.listdir') def test_get_jobs(self, m_listdir, m_isdir): m_listdir.return_value = ["1", "a", "3"] m_isdir.return_value = True results = ls.get_jobs("some/archive/dir") assert results == ["1", "3"] @patch("yaml.safe_load_all") @patch("__builtin__.file") @patch("teuthology.ls.get_jobs") def test_ls(self, m_get_jobs, m_file, m_safe_load_all): m_get_jobs.return_value = ["1", "2"] m_safe_load_all.return_value = [{"failure_reason": "reasons"}] ls.ls("some/archive/div", True) @patch("__builtin__.file") @patch("teuthology.ls.get_jobs") def test_ls_ioerror(self, m_get_jobs, m_file): m_get_jobs.return_value = ["1", "2"] m_file.side_effect = IOError() with pytest.raises(IOError): ls.ls("some/archive/dir", True) @patch("__builtin__.open") @patch("os.popen") @patch("os.path.isdir") @patch("os.path.isfile") def test_print_debug_info(self, m_isfile, m_isdir, m_popen, m_open): m_isfile.return_value = True m_isdir.return_value = True m_popen.return_value = Mock() cmdline = Mock() cmdline.find.return_value = True m_open.return_value = cmdline ls.print_debug_info("the_job", "job/dir", "some/archive/dir")
tchaikov/teuthology
teuthology/test/test_ls.py
teuthology/task/print.py
from six.moves import range class NodeVisitor(object): def visit(self, node): # This is ugly as hell, but we don't have multimethods and # they aren't trivial to fake without access to the class # object from the class body func = getattr(self, "visit_%s" % (node.__class__.__name__)) return func(node) class Node(object): def __init__(self, data=None): self.data = data self.parent = None self.children = [] def append(self, other): other.parent = self self.children.append(other) def remove(self): self.parent.children.remove(self) def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.data) def __str__(self): rv = [repr(self)] for item in self.children: rv.extend(" %s" % line for line in str(item).split("\n")) return "\n".join(rv) def __eq__(self, other): if not (self.__class__ == other.__class__ and self.data == other.data and len(self.children) == len(other.children)): return False for child, other_child in zip(self.children, other.children): if not child == other_child: return False return True def copy(self): new = self.__class__(self.data) for item in self.children: new.append(item.copy()) return new class DataNode(Node): def append(self, other): # Append that retains the invariant that child data nodes # come after child nodes of other types other.parent = self if isinstance(other, DataNode): self.children.append(other) else: index = len(self.children) while index > 0 and isinstance(self.children[index - 1], DataNode): index -= 1 for i in range(index): if other.data == self.children[i].data: raise ValueError("Duplicate key %s" % self.children[i].data) self.children.insert(index, other) class KeyValueNode(Node): def append(self, other): # Append that retains the invariant that conditional nodes # come before unconditional nodes other.parent = self if not isinstance(other, (ListNode, ValueNode, ConditionalNode)): raise TypeError if isinstance(other, (ListNode, ValueNode)): if self.children: assert not isinstance(self.children[-1], (ListNode, ValueNode)) self.children.append(other) else: if self.children and isinstance(self.children[-1], ValueNode): self.children.insert(len(self.children) - 1, other) else: self.children.append(other) class ListNode(Node): def append(self, other): other.parent = self self.children.append(other) class ValueNode(Node): def append(self, other): raise TypeError class AtomNode(ValueNode): pass class ConditionalNode(Node): def append(self, other): if not len(self.children): if not isinstance(other, (BinaryExpressionNode, UnaryExpressionNode, VariableNode)): raise TypeError else: if len(self.children) > 1: raise ValueError if not isinstance(other, (ListNode, ValueNode)): raise TypeError other.parent = self self.children.append(other) class UnaryExpressionNode(Node): def __init__(self, operator, operand): Node.__init__(self) self.append(operator) self.append(operand) def append(self, other): Node.append(self, other) assert len(self.children) <= 2 def copy(self): new = self.__class__(self.children[0].copy(), self.children[1].copy()) return new class BinaryExpressionNode(Node): def __init__(self, operator, operand_0, operand_1): Node.__init__(self) self.append(operator) self.append(operand_0) self.append(operand_1) def append(self, other): Node.append(self, other) assert len(self.children) <= 3 def copy(self): new = self.__class__(self.children[0].copy(), self.children[1].copy(), self.children[2].copy()) return new class UnaryOperatorNode(Node): def append(self, other): raise TypeError class BinaryOperatorNode(Node): def append(self, other): raise TypeError class IndexNode(Node): pass class VariableNode(Node): pass class StringNode(Node): pass class NumberNode(ValueNode): pass
from io import BytesIO import pytest from .. import manifestexpected @pytest.mark.parametrize("fuzzy, expected", [ (b"ref.html:1;200", [("ref.html", ((1, 1), (200, 200)))]), (b"ref.html:0-1;100-200", [("ref.html", ((0, 1), (100, 200)))]), (b"0-1;100-200", [(None, ((0, 1), (100, 200)))]), (b"maxDifference=1;totalPixels=200", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;maxDifference=1", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;1", [(None, ((1, 1), (200, 200)))]), (b"maxDifference=1;200", [(None, ((1, 1), (200, 200)))]), (b"test.html==ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "=="), ((1, 1), (200, 200)))]), (b"test.html!=ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200)))]), (b"[test.html!=ref.html:maxDifference=1;totalPixels=200, test.html==ref1.html:maxDifference=5-10;100]", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200))), ((u"test.html", u"ref1.html", "=="), ((5,10), (100, 100)))]), ]) def test_fuzzy(fuzzy, expected): data = b""" [test.html] fuzzy: %s""" % fuzzy f = BytesIO(data) manifest = manifestexpected.static.compile(f, {}, data_cls_getter=manifestexpected.data_cls_getter, test_path="test/test.html", url_base="/") assert manifest.get_test("/test/test.html").fuzzy == expected
UK992/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/test_manifestexpected.py
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptmanifest/node.py
import sys from mozlog.structured import structuredlog, commandline from .. import wptcommandline from .update import WPTUpdate def remove_logging_args(args): """Take logging args out of the dictionary of command line arguments so they are not passed in as kwargs to the update code. This is particularly necessary here because the arguments are often of type file, which cannot be serialized. :param args: Dictionary of command line arguments. """ for name in args.keys(): if name.startswith("log_"): args.pop(name) def setup_logging(args, defaults): """Use the command line arguments to set up the logger. :param args: Dictionary of command line arguments. :param defaults: Dictionary of {formatter_name: stream} to use if no command line logging is specified""" logger = commandline.setup_logging("web-platform-tests-update", args, defaults) remove_logging_args(args) return logger def run_update(logger, **kwargs): updater = WPTUpdate(logger, **kwargs) return updater.run() def main(): args = wptcommandline.parse_args_update() logger = setup_logging(args, {"mach": sys.stdout}) assert structuredlog.get_default_logger() is not None success = run_update(logger, **args) sys.exit(0 if success else 1)
from io import BytesIO import pytest from .. import manifestexpected @pytest.mark.parametrize("fuzzy, expected", [ (b"ref.html:1;200", [("ref.html", ((1, 1), (200, 200)))]), (b"ref.html:0-1;100-200", [("ref.html", ((0, 1), (100, 200)))]), (b"0-1;100-200", [(None, ((0, 1), (100, 200)))]), (b"maxDifference=1;totalPixels=200", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;maxDifference=1", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;1", [(None, ((1, 1), (200, 200)))]), (b"maxDifference=1;200", [(None, ((1, 1), (200, 200)))]), (b"test.html==ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "=="), ((1, 1), (200, 200)))]), (b"test.html!=ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200)))]), (b"[test.html!=ref.html:maxDifference=1;totalPixels=200, test.html==ref1.html:maxDifference=5-10;100]", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200))), ((u"test.html", u"ref1.html", "=="), ((5,10), (100, 100)))]), ]) def test_fuzzy(fuzzy, expected): data = b""" [test.html] fuzzy: %s""" % fuzzy f = BytesIO(data) manifest = manifestexpected.static.compile(f, {}, data_cls_getter=manifestexpected.data_cls_getter, test_path="test/test.html", url_base="/") assert manifest.get_test("/test/test.html").fuzzy == expected
UK992/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/test_manifestexpected.py
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/update/__init__.py
import subprocess from .base import Browser, ExecutorBrowser, require_arg from .base import get_timeout_multiplier # noqa: F401 from .chrome import executor_kwargs as chrome_executor_kwargs from ..webdriver_server import ChromeDriverServer from ..executors.executorwebdriver import (WebDriverTestharnessExecutor, # noqa: F401 WebDriverRefTestExecutor) # noqa: F401 from ..executors.executorchrome import ChromeDriverWdspecExecutor # noqa: F401 __wptrunner__ = {"product": "chrome_android", "check_args": "check_args", "browser": "ChromeAndroidBrowser", "executor": {"testharness": "WebDriverTestharnessExecutor", "reftest": "WebDriverRefTestExecutor", "wdspec": "ChromeDriverWdspecExecutor"}, "browser_kwargs": "browser_kwargs", "executor_kwargs": "executor_kwargs", "env_extras": "env_extras", "env_options": "env_options", "timeout_multiplier": "get_timeout_multiplier"} _wptserve_ports = set() def check_args(**kwargs): require_arg(kwargs, "package_name") require_arg(kwargs, "webdriver_binary") def browser_kwargs(test_type, run_info_data, config, **kwargs): return {"package_name": kwargs["package_name"], "device_serial": kwargs["device_serial"], "webdriver_binary": kwargs["webdriver_binary"], "webdriver_args": kwargs.get("webdriver_args")} def executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs): # Use update() to modify the global list in place. _wptserve_ports.update(set( server_config['ports']['http'] + server_config['ports']['https'] + server_config['ports']['ws'] + server_config['ports']['wss'] )) executor_kwargs = chrome_executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs) # Remove unsupported options on mobile. del executor_kwargs["capabilities"]["goog:chromeOptions"]["prefs"] del executor_kwargs["capabilities"]["goog:chromeOptions"]["useAutomationExtension"] assert kwargs["package_name"], "missing --package-name" executor_kwargs["capabilities"]["goog:chromeOptions"]["androidPackage"] = \ kwargs["package_name"] if kwargs.get("device_serial"): executor_kwargs["capabilities"]["goog:chromeOptions"]["androidDeviceSerial"] = \ kwargs["device_serial"] return executor_kwargs def env_extras(**kwargs): return [] def env_options(): # allow the use of host-resolver-rules in lieu of modifying /etc/hosts file return {"server_host": "127.0.0.1"} class ChromeAndroidBrowser(Browser): """Chrome is backed by chromedriver, which is supplied through ``wptrunner.webdriver.ChromeDriverServer``. """ def __init__(self, logger, package_name, webdriver_binary="chromedriver", device_serial=None, webdriver_args=None): Browser.__init__(self, logger) self.package_name = package_name self.device_serial = device_serial self.server = ChromeDriverServer(self.logger, binary=webdriver_binary, args=webdriver_args) self.setup_adb_reverse() def _adb_run(self, args): cmd = ['adb'] if self.device_serial: cmd.extend(['-s', self.device_serial]) cmd.extend(args) self.logger.info(' '.join(cmd)) subprocess.check_call(cmd) def setup_adb_reverse(self): self._adb_run(['wait-for-device']) self._adb_run(['forward', '--remove-all']) self._adb_run(['reverse', '--remove-all']) # "adb reverse" forwards network connection from device to host. for port in _wptserve_ports: self._adb_run(['reverse', 'tcp:%d' % port, 'tcp:%d' % port]) def start(self, **kwargs): self.server.start(block=False) def stop(self, force=False): self.server.stop(force=force) def pid(self): return self.server.pid def is_alive(self): # TODO(ato): This only indicates the driver is alive, # and doesn't say anything about whether a browser session # is active. return self.server.is_alive() def cleanup(self): self.stop() self._adb_run(['forward', '--remove-all']) self._adb_run(['reverse', '--remove-all']) def executor_browser(self): return ExecutorBrowser, {"webdriver_url": self.server.url}
from io import BytesIO import pytest from .. import manifestexpected @pytest.mark.parametrize("fuzzy, expected", [ (b"ref.html:1;200", [("ref.html", ((1, 1), (200, 200)))]), (b"ref.html:0-1;100-200", [("ref.html", ((0, 1), (100, 200)))]), (b"0-1;100-200", [(None, ((0, 1), (100, 200)))]), (b"maxDifference=1;totalPixels=200", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;maxDifference=1", [(None, ((1, 1), (200, 200)))]), (b"totalPixels=200;1", [(None, ((1, 1), (200, 200)))]), (b"maxDifference=1;200", [(None, ((1, 1), (200, 200)))]), (b"test.html==ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "=="), ((1, 1), (200, 200)))]), (b"test.html!=ref.html:maxDifference=1;totalPixels=200", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200)))]), (b"[test.html!=ref.html:maxDifference=1;totalPixels=200, test.html==ref1.html:maxDifference=5-10;100]", [((u"test.html", u"ref.html", "!="), ((1, 1), (200, 200))), ((u"test.html", u"ref1.html", "=="), ((5,10), (100, 100)))]), ]) def test_fuzzy(fuzzy, expected): data = b""" [test.html] fuzzy: %s""" % fuzzy f = BytesIO(data) manifest = manifestexpected.static.compile(f, {}, data_cls_getter=manifestexpected.data_cls_getter, test_path="test/test.html", url_base="/") assert manifest.get_test("/test/test.html").fuzzy == expected
UK992/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/test_manifestexpected.py
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/chrome_android.py
import attr from navmazing import NavigateToAttribute from cached_property import cached_property from cfme.modeling.base import BaseCollection, BaseEntity, parent_of_type from cfme.utils.appliance.implementations.ui import navigator, CFMENavigateStep, navigate_to from . import AddBoxView, BoxForm from .dialog_element import ElementCollection class EditBoxView(BoxForm): """EditBox View.""" @property def is_displayed(self): return ( self.in_customization and self.service_dialogs.is_opened and self.title.text == "Editing Dialog {} [Box Information]".format(self.box_label) ) @attr.s class Box(BaseEntity): """A class representing one Box of dialog.""" box_label = attr.ib() box_desc = attr.ib(default=None) _collections = {'elements': ElementCollection} @cached_property def elements(self): return self.collections.elements @property def tree_path(self): return self.parent.tree_path + [self.box_label] @property def tab(self): from .dialog_tab import Tab return parent_of_type(self, Tab) @attr.s class BoxCollection(BaseCollection): ENTITY = Box @property def tree_path(self): return self.parent.tree_path def create(self, box_label=None, box_desc=None): """Create box method. Args: box_label and box_description. """ view = navigate_to(self, "Add") view.new_box.click() view.edit_box.click() view.fill({'box_label': box_label, 'box_desc': box_desc}) view.save_button.click() return self.instantiate(box_label=box_label, box_desc=box_desc) @navigator.register(BoxCollection) class Add(CFMENavigateStep): VIEW = AddBoxView prerequisite = NavigateToAttribute('parent.parent', 'Add') def step(self): self.prerequisite_view.add_section.click()
import pytest from cfme import test_requirements from cfme.common.candu_views import UtilizationZoomView from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.tests.candu import compare_data from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.log import logger from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.tier(3), test_requirements.c_and_u, pytest.mark.usefixtures('setup_provider'), pytest.mark.provider([VMwareProvider, RHEVMProvider, EC2Provider, AzureProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) ] VM_GRAPHS = ['vm_cpu', 'vm_cpu_state', 'vm_memory', 'vm_disk', 'vm_network'] INTERVAL = ['Hourly', 'Daily'] # ToDo: Add support for GCE provider once BZ-1511099 fixed # ToDo: Currently disk activity for EC2 not collecting due to infra issue. # collect test as infra issue resolves. @pytest.mark.uncollectif(lambda provider, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"])) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_vm_most_recent_hour_graph_screen(graph_type, provider, enable_candu): """ Test VM graphs for most recent hour displayed or not prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Check legends hide and display properly or not * Check data for legends collected or not """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') graph = getattr(view, graph_type) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) # Check for legend hide property and graph data graph_data = 0 for leg in graph.all_legends: # check legend hide or not graph.hide_legends(leg) assert not graph.legend_is_displayed(leg) # check legend display or not graph.display_legends(leg) assert graph.legend_is_displayed(leg) # check graph display data or not # Note: legend like %Ready have less value some time zero. so sum data for all legend for data in graph.data_for_legends(leg).values(): graph_data += float(data[leg].replace(',', '').replace('%', '').split()[0]) assert graph_data > 0 @pytest.mark.uncollectif(lambda provider, interval, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"]) or ((provider.one_of(CloudProvider) or provider.one_of(RHEVMProvider)) and interval == 'Daily')) @pytest.mark.parametrize('interval', INTERVAL) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_graph_screen(provider, interval, graph_type, enable_candu): """Test VM graphs for hourly and Daily prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Zoom graph * Compare data of Table and Graph """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) if not provider.one_of(CloudProvider): wait_for( vm.capture_historical_data, delay=20, timeout=1000, message="wait for capturing VM historical data" ) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill(interval) try: graph = getattr(view, graph_type) except AttributeError as e: logger.error(e) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill(interval) # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) graph.zoom_in() view = view.browser.create_view(UtilizationZoomView) assert view.chart.is_displayed graph_data = view.chart.all_data # Clear cache of table widget before read else it will mismatch headers. view.table.clear_cache() table_data = view.table.read() legends = view.chart.all_legends compare_data(table_data=table_data, graph_data=graph_data, legends=legends)
anurag03/integration_tests
cfme/tests/candu/test_vm_graph.py
cfme/automate/dialogs/dialog_box.py
# -*- coding: utf-8 -*- """ignore_stream(\*streams): Marker for uncollecting the tests based on appliance stream. Streams are the first two fields from version of the appliance (5.0, 5.1, ...), the nightly upstream is represented as upstream. If you want to ensure, that the test shall not be collected because it is not supposed to run on 5.0 and 5.1 streams, just put those streams in the parameters and that is enough. It also provides a facility to check the appliance's version/stream for smoke testing. """ import pytest def get_streams_id(appliance): if appliance.is_downstream: return {appliance.version.series(2), "downstream"} else: return {"upstream"} def pytest_addoption(parser): group = parser.getgroup('Specific stream smoke testing') group.addoption('--check-stream', action='store', default="", type=str, dest='check_stream', help='You can use our "downstream-53z" and similar ones.') def pytest_configure(config): config.addinivalue_line("markers", __doc__.splitlines()[0]) def pytest_itemcollected(item): holder = item.config.pluginmanager.getplugin('appliance-holder') streams_id = get_streams_id(holder.held_appliance) marker = item.get_marker("ignore_stream") if marker is None: return if hasattr(item, "callspec"): params = item.callspec.params else: params = {} for arg in marker.args: if isinstance(arg, (tuple, list)): stream, conditions = arg else: stream = arg conditions = {} stream = stream.strip().lower() if stream in streams_id: # Candidate for uncollection if not conditions: # Just uncollect it right away add_mark = True else: add_mark = True for condition_key, condition_value in conditions.items(): if condition_key not in params: continue if params[condition_key] == condition_value: pass # No change else: add_mark = False if add_mark: item.add_marker(pytest.mark.uncollect) def pytest_sessionstart(session): config = session.config # Just to print out the appliance's streams from cfme.fixtures.terminalreporter import reporter holder = config.pluginmanager.getplugin('appliance-holder') reporter(config).write( "\nAppliance's streams: [{}]\n".format( ", ".join(get_streams_id(holder.held_appliance)))) # Bail out if the appliance stream or version do not match check_stream = config.getvalue("check_stream").lower().strip() if check_stream: holder = config.pluginmanager.get_plugin("appliance-holder") curr = holder.held_appliance.version.stream() if check_stream != curr: raise Exception( "Stream mismatch - wanted {} but appliance is {}".format( check_stream, curr))
import pytest from cfme import test_requirements from cfme.common.candu_views import UtilizationZoomView from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.tests.candu import compare_data from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.log import logger from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.tier(3), test_requirements.c_and_u, pytest.mark.usefixtures('setup_provider'), pytest.mark.provider([VMwareProvider, RHEVMProvider, EC2Provider, AzureProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) ] VM_GRAPHS = ['vm_cpu', 'vm_cpu_state', 'vm_memory', 'vm_disk', 'vm_network'] INTERVAL = ['Hourly', 'Daily'] # ToDo: Add support for GCE provider once BZ-1511099 fixed # ToDo: Currently disk activity for EC2 not collecting due to infra issue. # collect test as infra issue resolves. @pytest.mark.uncollectif(lambda provider, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"])) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_vm_most_recent_hour_graph_screen(graph_type, provider, enable_candu): """ Test VM graphs for most recent hour displayed or not prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Check legends hide and display properly or not * Check data for legends collected or not """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') graph = getattr(view, graph_type) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) # Check for legend hide property and graph data graph_data = 0 for leg in graph.all_legends: # check legend hide or not graph.hide_legends(leg) assert not graph.legend_is_displayed(leg) # check legend display or not graph.display_legends(leg) assert graph.legend_is_displayed(leg) # check graph display data or not # Note: legend like %Ready have less value some time zero. so sum data for all legend for data in graph.data_for_legends(leg).values(): graph_data += float(data[leg].replace(',', '').replace('%', '').split()[0]) assert graph_data > 0 @pytest.mark.uncollectif(lambda provider, interval, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"]) or ((provider.one_of(CloudProvider) or provider.one_of(RHEVMProvider)) and interval == 'Daily')) @pytest.mark.parametrize('interval', INTERVAL) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_graph_screen(provider, interval, graph_type, enable_candu): """Test VM graphs for hourly and Daily prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Zoom graph * Compare data of Table and Graph """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) if not provider.one_of(CloudProvider): wait_for( vm.capture_historical_data, delay=20, timeout=1000, message="wait for capturing VM historical data" ) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill(interval) try: graph = getattr(view, graph_type) except AttributeError as e: logger.error(e) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill(interval) # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) graph.zoom_in() view = view.browser.create_view(UtilizationZoomView) assert view.chart.is_displayed graph_data = view.chart.all_data # Clear cache of table widget before read else it will mismatch headers. view.table.clear_cache() table_data = view.table.read() legends = view.chart.all_legends compare_data(table_data=table_data, graph_data=graph_data, legends=legends)
anurag03/integration_tests
cfme/tests/candu/test_vm_graph.py
cfme/markers/stream_excluder.py
# -*- coding: utf-8 -*- from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.log import logger from cfme.utils.wait import wait_for def do_vm_provisioning(appliance, template_name, provider, vm_name, provisioning_data, request, smtp_test, num_sec=1500, wait=True): # generate_tests makes sure these have values vm = appliance.collections.infra_vms.instantiate(name=vm_name, provider=provider, template_name=template_name) note = ('template {} to vm {} on provider {}'.format(template_name, vm_name, provider.key)) provisioning_data.update({ 'request': { 'email': 'template_provisioner@example.com', 'first_name': 'Template', 'last_name': 'Provisioner', 'notes': note}}) provisioning_data['template_name'] = template_name provisioning_data['provider_name'] = provider.name view = navigate_to(vm.parent, 'Provision', wait_for_view=0) view.form.fill_with(provisioning_data, on_change=view.form.submit_button) view.flash.assert_no_error() if not wait: return # Provision Re important in this test logger.info('Waiting for cfme provision request for vm %s', vm_name) request_description = 'Provision from [{}] to [{}]'.format(template_name, vm_name) provision_request = appliance.collections.requests.instantiate(request_description) provision_request.wait_for_request(method='ui', num_sec=num_sec) assert provision_request.is_succeeded(method='ui'), "Provisioning failed: {}".format( provision_request.row.last_message.text) # Wait for the VM to appear on the provider backend before proceeding to ensure proper cleanup logger.info('Waiting for vm %s to appear on provider %s', vm_name, provider.key) wait_for(provider.mgmt.does_vm_exist, func_args=[vm_name], handle_exception=True, num_sec=600) if smtp_test: # Wait for e-mails to appear def verify(): approval = dict(subject_like="%%Your Virtual Machine configuration was Approved%%") expected_text = "Your virtual machine request has Completed - VM:%%{}".format(vm_name) return ( len(smtp_test.get_emails(**approval)) > 0 and len(smtp_test.get_emails(subject_like=expected_text)) > 0 ) wait_for(verify, message="email receive check", delay=30)
import pytest from cfme import test_requirements from cfme.common.candu_views import UtilizationZoomView from cfme.cloud.provider import CloudProvider from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider from cfme.infrastructure.provider.rhevm import RHEVMProvider from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.tests.candu import compare_data from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.log import logger from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.tier(3), test_requirements.c_and_u, pytest.mark.usefixtures('setup_provider'), pytest.mark.provider([VMwareProvider, RHEVMProvider, EC2Provider, AzureProvider], required_fields=[(['cap_and_util', 'capandu_vm'], 'cu-24x7')]) ] VM_GRAPHS = ['vm_cpu', 'vm_cpu_state', 'vm_memory', 'vm_disk', 'vm_network'] INTERVAL = ['Hourly', 'Daily'] # ToDo: Add support for GCE provider once BZ-1511099 fixed # ToDo: Currently disk activity for EC2 not collecting due to infra issue. # collect test as infra issue resolves. @pytest.mark.uncollectif(lambda provider, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"])) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_vm_most_recent_hour_graph_screen(graph_type, provider, enable_candu): """ Test VM graphs for most recent hour displayed or not prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Check legends hide and display properly or not * Check data for legends collected or not """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') graph = getattr(view, graph_type) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill('Most Recent Hour') # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) # Check for legend hide property and graph data graph_data = 0 for leg in graph.all_legends: # check legend hide or not graph.hide_legends(leg) assert not graph.legend_is_displayed(leg) # check legend display or not graph.display_legends(leg) assert graph.legend_is_displayed(leg) # check graph display data or not # Note: legend like %Ready have less value some time zero. so sum data for all legend for data in graph.data_for_legends(leg).values(): graph_data += float(data[leg].replace(',', '').replace('%', '').split()[0]) assert graph_data > 0 @pytest.mark.uncollectif(lambda provider, interval, graph_type: ((provider.one_of(RHEVMProvider) or provider.one_of(AzureProvider)) and graph_type == "vm_cpu_state") or (provider.one_of(EC2Provider) and graph_type in ["vm_cpu_state", "vm_memory", "vm_disk"]) or ((provider.one_of(CloudProvider) or provider.one_of(RHEVMProvider)) and interval == 'Daily')) @pytest.mark.parametrize('interval', INTERVAL) @pytest.mark.parametrize('graph_type', VM_GRAPHS) def test_graph_screen(provider, interval, graph_type, enable_candu): """Test VM graphs for hourly and Daily prerequisites: * C&U enabled appliance Steps: * Navigate to VM (cu-24x7) Utilization Page * Check graph displayed or not * Zoom graph * Compare data of Table and Graph """ collection = provider.appliance.provider_based_collection(provider) vm = collection.instantiate('cu-24x7', provider) if not provider.one_of(CloudProvider): wait_for( vm.capture_historical_data, delay=20, timeout=1000, message="wait for capturing VM historical data" ) vm.wait_candu_data_available(timeout=1200) view = navigate_to(vm, 'candu') view.options.interval.fill(interval) try: graph = getattr(view, graph_type) except AttributeError as e: logger.error(e) assert graph.is_displayed def refresh(): provider.browser.refresh() view = navigate_to(vm, 'candu') view.options.interval.fill(interval) # wait, some time graph took time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=600, fail_func=refresh) graph.zoom_in() view = view.browser.create_view(UtilizationZoomView) assert view.chart.is_displayed graph_data = view.chart.all_data # Clear cache of table widget before read else it will mismatch headers. view.table.clear_cache() table_data = view.table.read() legends = view.chart.all_legends compare_data(table_data=table_data, graph_data=graph_data, legends=legends)
anurag03/integration_tests
cfme/tests/candu/test_vm_graph.py
cfme/provisioning.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Facilities for diffing two FITS files. Includes objects for diffing entire FITS files, individual HDUs, FITS headers, or just FITS data. Used to implement the fitsdiff program. """ import fnmatch import glob import io import operator import os.path import textwrap from collections import defaultdict from inspect import signature from itertools import islice import numpy as np from astropy import __version__ from .card import Card, BLANK_CARD from .header import Header from astropy.utils.decorators import deprecated_renamed_argument # HDUList is used in one of the doctests from .hdu.hdulist import fitsopen, HDUList # pylint: disable=W0611 from .hdu.table import _TableLikeHDU from astropy.utils.diff import (report_diff_values, fixed_width_indent, where_not_allclose, diff_values) __all__ = ['FITSDiff', 'HDUDiff', 'HeaderDiff', 'ImageDataDiff', 'RawDataDiff', 'TableDataDiff'] # Column attributes of interest for comparison _COL_ATTRS = [('unit', 'units'), ('null', 'null values'), ('bscale', 'bscales'), ('bzero', 'bzeros'), ('disp', 'display formats'), ('dim', 'dimensions')] class _BaseDiff: """ Base class for all FITS diff objects. When instantiating a FITS diff object, the first two arguments are always the two objects to diff (two FITS files, two FITS headers, etc.). Instantiating a ``_BaseDiff`` also causes the diff itself to be executed. The returned ``_BaseDiff`` instance has a number of attribute that describe the results of the diff operation. The most basic attribute, present on all ``_BaseDiff`` instances, is ``.identical`` which is `True` if the two objects being compared are identical according to the diff method for objects of that type. """ def __init__(self, a, b): """ The ``_BaseDiff`` class does not implement a ``_diff`` method and should not be instantiated directly. Instead instantiate the appropriate subclass of ``_BaseDiff`` for the objects being compared (for example, use `HeaderDiff` to compare two `Header` objects. """ self.a = a self.b = b # For internal use in report output self._fileobj = None self._indent = 0 self._diff() def __bool__(self): """ A ``_BaseDiff`` object acts as `True` in a boolean context if the two objects compared are identical. Otherwise it acts as `False`. """ return not self.identical @classmethod def fromdiff(cls, other, a, b): """ Returns a new Diff object of a specific subclass from an existing diff object, passing on the values for any arguments they share in common (such as ignore_keywords). For example:: >>> from astropy.io import fits >>> hdul1, hdul2 = fits.HDUList(), fits.HDUList() >>> headera, headerb = fits.Header(), fits.Header() >>> fd = fits.FITSDiff(hdul1, hdul2, ignore_keywords=['*']) >>> hd = fits.HeaderDiff.fromdiff(fd, headera, headerb) >>> list(hd.ignore_keywords) ['*'] """ sig = signature(cls.__init__) # The first 3 arguments of any Diff initializer are self, a, and b. kwargs = {} for arg in list(sig.parameters.keys())[3:]: if hasattr(other, arg): kwargs[arg] = getattr(other, arg) return cls(a, b, **kwargs) @property def identical(self): """ `True` if all the ``.diff_*`` attributes on this diff instance are empty, implying that no differences were found. Any subclass of ``_BaseDiff`` must have at least one ``.diff_*`` attribute, which contains a non-empty value if and only if some difference was found between the two objects being compared. """ return not any(getattr(self, attr) for attr in self.__dict__ if attr.startswith('diff_')) @deprecated_renamed_argument('clobber', 'overwrite', '2.0') def report(self, fileobj=None, indent=0, overwrite=False): """ Generates a text report on the differences (if any) between two objects, and either returns it as a string or writes it to a file-like object. Parameters ---------- fileobj : file-like object, string, or None, optional If `None`, this method returns the report as a string. Otherwise it returns `None` and writes the report to the given file-like object (which must have a ``.write()`` method at a minimum), or to a new file at the path specified. indent : int The number of 4 space tabs to indent the report. overwrite : bool, optional If ``True``, overwrite the output file if it exists. Raises an ``OSError`` if ``False`` and the output file exists. Default is ``False``. .. versionchanged:: 1.3 ``overwrite`` replaces the deprecated ``clobber`` argument. Returns ------- report : str or None """ return_string = False filepath = None if isinstance(fileobj, str): if os.path.exists(fileobj) and not overwrite: raise OSError("File {} exists, aborting (pass in " "overwrite=True to overwrite)".format(fileobj)) else: filepath = fileobj fileobj = open(filepath, 'w') elif fileobj is None: fileobj = io.StringIO() return_string = True self._fileobj = fileobj self._indent = indent # This is used internally by _writeln try: self._report() finally: if filepath: fileobj.close() if return_string: return fileobj.getvalue() def _writeln(self, text): self._fileobj.write(fixed_width_indent(text, self._indent) + '\n') def _diff(self): raise NotImplementedError def _report(self): raise NotImplementedError class FITSDiff(_BaseDiff): """Diff two FITS files by filename, or two `HDUList` objects. `FITSDiff` objects have the following diff attributes: - ``diff_hdu_count``: If the FITS files being compared have different numbers of HDUs, this contains a 2-tuple of the number of HDUs in each file. - ``diff_hdus``: If any HDUs with the same index are different, this contains a list of 2-tuples of the HDU index and the `HDUDiff` object representing the differences between the two HDUs. """ def __init__(self, a, b, ignore_hdus=[], ignore_keywords=[], ignore_comments=[], ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True): """ Parameters ---------- a : str or `HDUList` The filename of a FITS file on disk, or an `HDUList` object. b : str or `HDUList` The filename of a FITS file on disk, or an `HDUList` object to compare to the first file. ignore_hdus : sequence, optional HDU names to ignore when comparing two FITS files or HDU lists; the presence of these HDUs and their contents are ignored. Wildcard strings may also be included in the list. ignore_keywords : sequence, optional Header keywords to ignore when comparing two headers; the presence of these keywords and their values are ignored. Wildcard strings may also be included in the list. ignore_comments : sequence, optional A list of header keywords whose comments should be ignored in the comparison. May contain wildcard strings as with ignore_keywords. ignore_fields : sequence, optional The (case-insensitive) names of any table columns to ignore if any table data is to be compared. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 ignore_blanks : bool, optional Ignore extra whitespace at the end of string values either in headers or data. Extra leading whitespace is not ignored (default: True). ignore_blank_cards : bool, optional Ignore all cards that are blank, i.e. they only contain whitespace (default: True). """ if isinstance(a, str): try: a = fitsopen(a) except Exception as exc: raise OSError("error opening file a ({}): {}: {}".format( a, exc.__class__.__name__, exc.args[0])) close_a = True else: close_a = False if isinstance(b, str): try: b = fitsopen(b) except Exception as exc: raise OSError("error opening file b ({}): {}: {}".format( b, exc.__class__.__name__, exc.args[0])) close_b = True else: close_b = False # Normalize keywords/fields to ignore to upper case self.ignore_hdus = set(k.upper() for k in ignore_hdus) self.ignore_keywords = set(k.upper() for k in ignore_keywords) self.ignore_comments = set(k.upper() for k in ignore_comments) self.ignore_fields = set(k.upper() for k in ignore_fields) self.numdiffs = numdiffs self.rtol = rtol self.atol = atol self.ignore_blanks = ignore_blanks self.ignore_blank_cards = ignore_blank_cards # Some hdu names may be pattern wildcards. Find them. self.ignore_hdu_patterns = set() for name in list(self.ignore_hdus): if name != '*' and glob.has_magic(name): self.ignore_hdus.remove(name) self.ignore_hdu_patterns.add(name) self.diff_hdu_count = () self.diff_hdus = [] try: super().__init__(a, b) finally: if close_a: a.close() if close_b: b.close() def _diff(self): if len(self.a) != len(self.b): self.diff_hdu_count = (len(self.a), len(self.b)) # Record filenames for use later in _report self.filenamea = self.a.filename() if not self.filenamea: self.filenamea = '<{} object at {:#x}>'.format( self.a.__class__.__name__, id(self.a)) self.filenameb = self.b.filename() if not self.filenameb: self.filenameb = '<{} object at {:#x}>'.format( self.b.__class__.__name__, id(self.b)) if self.ignore_hdus: self.a = HDUList([h for h in self.a if h.name not in self.ignore_hdus]) self.b = HDUList([h for h in self.b if h.name not in self.ignore_hdus]) if self.ignore_hdu_patterns: a_names = [hdu.name for hdu in self.a] b_names = [hdu.name for hdu in self.b] for pattern in self.ignore_hdu_patterns: self.a = HDUList([h for h in self.a if h.name not in fnmatch.filter( a_names, pattern)]) self.b = HDUList([h for h in self.b if h.name not in fnmatch.filter( b_names, pattern)]) # For now, just compare the extensions one by one in order. # Might allow some more sophisticated types of diffing later. # TODO: Somehow or another simplify the passing around of diff # options--this will become important as the number of options grows for idx in range(min(len(self.a), len(self.b))): hdu_diff = HDUDiff.fromdiff(self, self.a[idx], self.b[idx]) if not hdu_diff.identical: self.diff_hdus.append((idx, hdu_diff)) def _report(self): wrapper = textwrap.TextWrapper(initial_indent=' ', subsequent_indent=' ') self._fileobj.write('\n') self._writeln(f' fitsdiff: {__version__}') self._writeln(f' a: {self.filenamea}\n b: {self.filenameb}') if self.ignore_hdus: ignore_hdus = ' '.join(sorted(self.ignore_hdus)) self._writeln(' HDU(s) not to be compared:\n{}' .format(wrapper.fill(ignore_hdus))) if self.ignore_hdu_patterns: ignore_hdu_patterns = ' '.join(sorted(self.ignore_hdu_patterns)) self._writeln(' HDU(s) not to be compared:\n{}' .format(wrapper.fill(ignore_hdu_patterns))) if self.ignore_keywords: ignore_keywords = ' '.join(sorted(self.ignore_keywords)) self._writeln(' Keyword(s) not to be compared:\n{}' .format(wrapper.fill(ignore_keywords))) if self.ignore_comments: ignore_comments = ' '.join(sorted(self.ignore_comments)) self._writeln(' Keyword(s) whose comments are not to be compared' ':\n{}'.format(wrapper.fill(ignore_comments))) if self.ignore_fields: ignore_fields = ' '.join(sorted(self.ignore_fields)) self._writeln(' Table column(s) not to be compared:\n{}' .format(wrapper.fill(ignore_fields))) self._writeln(' Maximum number of different data values to be ' 'reported: {}'.format(self.numdiffs)) self._writeln(' Relative tolerance: {}, Absolute tolerance: {}' .format(self.rtol, self.atol)) if self.diff_hdu_count: self._fileobj.write('\n') self._writeln('Files contain different numbers of HDUs:') self._writeln(' a: {}'.format(self.diff_hdu_count[0])) self._writeln(' b: {}'.format(self.diff_hdu_count[1])) if not self.diff_hdus: self._writeln('No differences found between common HDUs.') return elif not self.diff_hdus: self._fileobj.write('\n') self._writeln('No differences found.') return for idx, hdu_diff in self.diff_hdus: # print out the extension heading if idx == 0: self._fileobj.write('\n') self._writeln('Primary HDU:') else: self._fileobj.write('\n') self._writeln(f'Extension HDU {idx}:') hdu_diff.report(self._fileobj, indent=self._indent + 1) class HDUDiff(_BaseDiff): """ Diff two HDU objects, including their headers and their data (but only if both HDUs contain the same type of data (image, table, or unknown). `HDUDiff` objects have the following diff attributes: - ``diff_extnames``: If the two HDUs have different EXTNAME values, this contains a 2-tuple of the different extension names. - ``diff_extvers``: If the two HDUS have different EXTVER values, this contains a 2-tuple of the different extension versions. - ``diff_extlevels``: If the two HDUs have different EXTLEVEL values, this contains a 2-tuple of the different extension levels. - ``diff_extension_types``: If the two HDUs have different XTENSION values, this contains a 2-tuple of the different extension types. - ``diff_headers``: Contains a `HeaderDiff` object for the headers of the two HDUs. This will always contain an object--it may be determined whether the headers are different through ``diff_headers.identical``. - ``diff_data``: Contains either a `ImageDataDiff`, `TableDataDiff`, or `RawDataDiff` as appropriate for the data in the HDUs, and only if the two HDUs have non-empty data of the same type (`RawDataDiff` is used for HDUs containing non-empty data of an indeterminate type). """ def __init__(self, a, b, ignore_keywords=[], ignore_comments=[], ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True): """ Parameters ---------- a : `HDUList` An `HDUList` object. b : str or `HDUList` An `HDUList` object to compare to the first `HDUList` object. ignore_keywords : sequence, optional Header keywords to ignore when comparing two headers; the presence of these keywords and their values are ignored. Wildcard strings may also be included in the list. ignore_comments : sequence, optional A list of header keywords whose comments should be ignored in the comparison. May contain wildcard strings as with ignore_keywords. ignore_fields : sequence, optional The (case-insensitive) names of any table columns to ignore if any table data is to be compared. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 ignore_blanks : bool, optional Ignore extra whitespace at the end of string values either in headers or data. Extra leading whitespace is not ignored (default: True). ignore_blank_cards : bool, optional Ignore all cards that are blank, i.e. they only contain whitespace (default: True). """ self.ignore_keywords = {k.upper() for k in ignore_keywords} self.ignore_comments = {k.upper() for k in ignore_comments} self.ignore_fields = {k.upper() for k in ignore_fields} self.rtol = rtol self.atol = atol self.numdiffs = numdiffs self.ignore_blanks = ignore_blanks self.diff_extnames = () self.diff_extvers = () self.diff_extlevels = () self.diff_extension_types = () self.diff_headers = None self.diff_data = None super().__init__(a, b) def _diff(self): if self.a.name != self.b.name: self.diff_extnames = (self.a.name, self.b.name) if self.a.ver != self.b.ver: self.diff_extvers = (self.a.ver, self.b.ver) if self.a.level != self.b.level: self.diff_extlevels = (self.a.level, self.b.level) if self.a.header.get('XTENSION') != self.b.header.get('XTENSION'): self.diff_extension_types = (self.a.header.get('XTENSION'), self.b.header.get('XTENSION')) self.diff_headers = HeaderDiff.fromdiff(self, self.a.header.copy(), self.b.header.copy()) if self.a.data is None or self.b.data is None: # TODO: Perhaps have some means of marking this case pass elif self.a.is_image and self.b.is_image: self.diff_data = ImageDataDiff.fromdiff(self, self.a.data, self.b.data) elif (isinstance(self.a, _TableLikeHDU) and isinstance(self.b, _TableLikeHDU)): # TODO: Replace this if/when _BaseHDU grows a .is_table property self.diff_data = TableDataDiff.fromdiff(self, self.a.data, self.b.data) elif not self.diff_extension_types: # Don't diff the data for unequal extension types that are not # recognized image or table types self.diff_data = RawDataDiff.fromdiff(self, self.a.data, self.b.data) def _report(self): if self.identical: self._writeln(" No differences found.") if self.diff_extension_types: self._writeln(" Extension types differ:\n a: {}\n " "b: {}".format(*self.diff_extension_types)) if self.diff_extnames: self._writeln(" Extension names differ:\n a: {}\n " "b: {}".format(*self.diff_extnames)) if self.diff_extvers: self._writeln(" Extension versions differ:\n a: {}\n " "b: {}".format(*self.diff_extvers)) if self.diff_extlevels: self._writeln(" Extension levels differ:\n a: {}\n " "b: {}".format(*self.diff_extlevels)) if not self.diff_headers.identical: self._fileobj.write('\n') self._writeln(" Headers contain differences:") self.diff_headers.report(self._fileobj, indent=self._indent + 1) if self.diff_data is not None and not self.diff_data.identical: self._fileobj.write('\n') self._writeln(" Data contains differences:") self.diff_data.report(self._fileobj, indent=self._indent + 1) class HeaderDiff(_BaseDiff): """ Diff two `Header` objects. `HeaderDiff` objects have the following diff attributes: - ``diff_keyword_count``: If the two headers contain a different number of keywords, this contains a 2-tuple of the keyword count for each header. - ``diff_keywords``: If either header contains one or more keywords that don't appear at all in the other header, this contains a 2-tuple consisting of a list of the keywords only appearing in header a, and a list of the keywords only appearing in header b. - ``diff_duplicate_keywords``: If a keyword appears in both headers at least once, but contains a different number of duplicates (for example, a different number of HISTORY cards in each header), an item is added to this dict with the keyword as the key, and a 2-tuple of the different counts of that keyword as the value. For example:: {'HISTORY': (20, 19)} means that header a contains 20 HISTORY cards, while header b contains only 19 HISTORY cards. - ``diff_keyword_values``: If any of the common keyword between the two headers have different values, they appear in this dict. It has a structure similar to ``diff_duplicate_keywords``, with the keyword as the key, and a 2-tuple of the different values as the value. For example:: {'NAXIS': (2, 3)} means that the NAXIS keyword has a value of 2 in header a, and a value of 3 in header b. This excludes any keywords matched by the ``ignore_keywords`` list. - ``diff_keyword_comments``: Like ``diff_keyword_values``, but contains differences between keyword comments. `HeaderDiff` objects also have a ``common_keywords`` attribute that lists all keywords that appear in both headers. """ def __init__(self, a, b, ignore_keywords=[], ignore_comments=[], rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True): """ Parameters ---------- a : `HDUList` An `HDUList` object. b : `HDUList` An `HDUList` object to compare to the first `HDUList` object. ignore_keywords : sequence, optional Header keywords to ignore when comparing two headers; the presence of these keywords and their values are ignored. Wildcard strings may also be included in the list. ignore_comments : sequence, optional A list of header keywords whose comments should be ignored in the comparison. May contain wildcard strings as with ignore_keywords. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 ignore_blanks : bool, optional Ignore extra whitespace at the end of string values either in headers or data. Extra leading whitespace is not ignored (default: True). ignore_blank_cards : bool, optional Ignore all cards that are blank, i.e. they only contain whitespace (default: True). """ self.ignore_keywords = {k.upper() for k in ignore_keywords} self.ignore_comments = {k.upper() for k in ignore_comments} self.rtol = rtol self.atol = atol self.ignore_blanks = ignore_blanks self.ignore_blank_cards = ignore_blank_cards self.ignore_keyword_patterns = set() self.ignore_comment_patterns = set() for keyword in list(self.ignore_keywords): keyword = keyword.upper() if keyword != '*' and glob.has_magic(keyword): self.ignore_keywords.remove(keyword) self.ignore_keyword_patterns.add(keyword) for keyword in list(self.ignore_comments): keyword = keyword.upper() if keyword != '*' and glob.has_magic(keyword): self.ignore_comments.remove(keyword) self.ignore_comment_patterns.add(keyword) # Keywords appearing in each header self.common_keywords = [] # Set to the number of keywords in each header if the counts differ self.diff_keyword_count = () # Set if the keywords common to each header (excluding ignore_keywords) # appear in different positions within the header # TODO: Implement this self.diff_keyword_positions = () # Keywords unique to each header (excluding keywords in # ignore_keywords) self.diff_keywords = () # Keywords that have different numbers of duplicates in each header # (excluding keywords in ignore_keywords) self.diff_duplicate_keywords = {} # Keywords common to each header but having different values (excluding # keywords in ignore_keywords) self.diff_keyword_values = defaultdict(list) # Keywords common to each header but having different comments # (excluding keywords in ignore_keywords or in ignore_comments) self.diff_keyword_comments = defaultdict(list) if isinstance(a, str): a = Header.fromstring(a) if isinstance(b, str): b = Header.fromstring(b) if not (isinstance(a, Header) and isinstance(b, Header)): raise TypeError('HeaderDiff can only diff astropy.io.fits.Header ' 'objects or strings containing FITS headers.') super().__init__(a, b) # TODO: This doesn't pay much attention to the *order* of the keywords, # except in the case of duplicate keywords. The order should be checked # too, or at least it should be an option. def _diff(self): if self.ignore_blank_cards: cardsa = [c for c in self.a.cards if str(c) != BLANK_CARD] cardsb = [c for c in self.b.cards if str(c) != BLANK_CARD] else: cardsa = list(self.a.cards) cardsb = list(self.b.cards) # build dictionaries of keyword values and comments def get_header_values_comments(cards): values = {} comments = {} for card in cards: value = card.value if self.ignore_blanks and isinstance(value, str): value = value.rstrip() values.setdefault(card.keyword, []).append(value) comments.setdefault(card.keyword, []).append(card.comment) return values, comments valuesa, commentsa = get_header_values_comments(cardsa) valuesb, commentsb = get_header_values_comments(cardsb) # Normalize all keyword to upper-case for comparison's sake; # TODO: HIERARCH keywords should be handled case-sensitively I think keywordsa = {k.upper() for k in valuesa} keywordsb = {k.upper() for k in valuesb} self.common_keywords = sorted(keywordsa.intersection(keywordsb)) if len(cardsa) != len(cardsb): self.diff_keyword_count = (len(cardsa), len(cardsb)) # Any other diff attributes should exclude ignored keywords keywordsa = keywordsa.difference(self.ignore_keywords) keywordsb = keywordsb.difference(self.ignore_keywords) if self.ignore_keyword_patterns: for pattern in self.ignore_keyword_patterns: keywordsa = keywordsa.difference(fnmatch.filter(keywordsa, pattern)) keywordsb = keywordsb.difference(fnmatch.filter(keywordsb, pattern)) if '*' in self.ignore_keywords: # Any other differences between keywords are to be ignored return left_only_keywords = sorted(keywordsa.difference(keywordsb)) right_only_keywords = sorted(keywordsb.difference(keywordsa)) if left_only_keywords or right_only_keywords: self.diff_keywords = (left_only_keywords, right_only_keywords) # Compare count of each common keyword for keyword in self.common_keywords: if keyword in self.ignore_keywords: continue if self.ignore_keyword_patterns: skip = False for pattern in self.ignore_keyword_patterns: if fnmatch.fnmatch(keyword, pattern): skip = True break if skip: continue counta = len(valuesa[keyword]) countb = len(valuesb[keyword]) if counta != countb: self.diff_duplicate_keywords[keyword] = (counta, countb) # Compare keywords' values and comments for a, b in zip(valuesa[keyword], valuesb[keyword]): if diff_values(a, b, rtol=self.rtol, atol=self.atol): self.diff_keyword_values[keyword].append((a, b)) else: # If there are duplicate keywords we need to be able to # index each duplicate; if the values of a duplicate # are identical use None here self.diff_keyword_values[keyword].append(None) if not any(self.diff_keyword_values[keyword]): # No differences found; delete the array of Nones del self.diff_keyword_values[keyword] if '*' in self.ignore_comments or keyword in self.ignore_comments: continue if self.ignore_comment_patterns: skip = False for pattern in self.ignore_comment_patterns: if fnmatch.fnmatch(keyword, pattern): skip = True break if skip: continue for a, b in zip(commentsa[keyword], commentsb[keyword]): if diff_values(a, b): self.diff_keyword_comments[keyword].append((a, b)) else: self.diff_keyword_comments[keyword].append(None) if not any(self.diff_keyword_comments[keyword]): del self.diff_keyword_comments[keyword] def _report(self): if self.diff_keyword_count: self._writeln(' Headers have different number of cards:') self._writeln(' a: {}'.format(self.diff_keyword_count[0])) self._writeln(' b: {}'.format(self.diff_keyword_count[1])) if self.diff_keywords: for keyword in self.diff_keywords[0]: if keyword in Card._commentary_keywords: val = self.a[keyword][0] else: val = self.a[keyword] self._writeln(' Extra keyword {!r:8} in a: {!r}'.format( keyword, val)) for keyword in self.diff_keywords[1]: if keyword in Card._commentary_keywords: val = self.b[keyword][0] else: val = self.b[keyword] self._writeln(' Extra keyword {!r:8} in b: {!r}'.format( keyword, val)) if self.diff_duplicate_keywords: for keyword, count in sorted(self.diff_duplicate_keywords.items()): self._writeln(' Inconsistent duplicates of keyword {!r:8}:' .format(keyword)) self._writeln(' Occurs {} time(s) in a, {} times in (b)' .format(*count)) if self.diff_keyword_values or self.diff_keyword_comments: for keyword in self.common_keywords: report_diff_keyword_attr(self._fileobj, 'values', self.diff_keyword_values, keyword, ind=self._indent) report_diff_keyword_attr(self._fileobj, 'comments', self.diff_keyword_comments, keyword, ind=self._indent) # TODO: It might be good if there was also a threshold option for percentage of # different pixels: For example ignore if only 1% of the pixels are different # within some threshold. There are lots of possibilities here, but hold off # for now until specific cases come up. class ImageDataDiff(_BaseDiff): """ Diff two image data arrays (really any array from a PRIMARY HDU or an IMAGE extension HDU, though the data unit is assumed to be "pixels"). `ImageDataDiff` objects have the following diff attributes: - ``diff_dimensions``: If the two arrays contain either a different number of dimensions or different sizes in any dimension, this contains a 2-tuple of the shapes of each array. Currently no further comparison is performed on images that don't have the exact same dimensions. - ``diff_pixels``: If the two images contain any different pixels, this contains a list of 2-tuples of the array index where the difference was found, and another 2-tuple containing the different values. For example, if the pixel at (0, 0) contains different values this would look like:: [(0, 0), (1.1, 2.2)] where 1.1 and 2.2 are the values of that pixel in each array. This array only contains up to ``self.numdiffs`` differences, for storage efficiency. - ``diff_total``: The total number of different pixels found between the arrays. Although ``diff_pixels`` does not necessarily contain all the different pixel values, this can be used to get a count of the total number of differences found. - ``diff_ratio``: Contains the ratio of ``diff_total`` to the total number of pixels in the arrays. """ def __init__(self, a, b, numdiffs=10, rtol=0.0, atol=0.0): """ Parameters ---------- a : `HDUList` An `HDUList` object. b : `HDUList` An `HDUList` object to compare to the first `HDUList` object. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 """ self.numdiffs = numdiffs self.rtol = rtol self.atol = atol self.diff_dimensions = () self.diff_pixels = [] self.diff_ratio = 0 # self.diff_pixels only holds up to numdiffs differing pixels, but this # self.diff_total stores the total count of differences between # the images, but not the different values self.diff_total = 0 super().__init__(a, b) def _diff(self): if self.a.shape != self.b.shape: self.diff_dimensions = (self.a.shape, self.b.shape) # Don't do any further comparison if the dimensions differ # TODO: Perhaps we could, however, diff just the intersection # between the two images return # Find the indices where the values are not equal # If neither a nor b are floating point (or complex), ignore rtol and # atol if not (np.issubdtype(self.a.dtype, np.inexact) or np.issubdtype(self.b.dtype, np.inexact)): rtol = 0 atol = 0 else: rtol = self.rtol atol = self.atol diffs = where_not_allclose(self.a, self.b, atol=atol, rtol=rtol) self.diff_total = len(diffs[0]) if self.diff_total == 0: # Then we're done return if self.numdiffs < 0: numdiffs = self.diff_total else: numdiffs = self.numdiffs self.diff_pixels = [(idx, (self.a[idx], self.b[idx])) for idx in islice(zip(*diffs), 0, numdiffs)] self.diff_ratio = float(self.diff_total) / float(len(self.a.flat)) def _report(self): if self.diff_dimensions: dimsa = ' x '.join(str(d) for d in reversed(self.diff_dimensions[0])) dimsb = ' x '.join(str(d) for d in reversed(self.diff_dimensions[1])) self._writeln(' Data dimensions differ:') self._writeln(f' a: {dimsa}') self._writeln(f' b: {dimsb}') # For now we don't do any further comparison if the dimensions # differ; though in the future it might be nice to be able to # compare at least where the images intersect self._writeln(' No further data comparison performed.') return if not self.diff_pixels: return for index, values in self.diff_pixels: index = [x + 1 for x in reversed(index)] self._writeln(f' Data differs at {index}:') report_diff_values(values[0], values[1], fileobj=self._fileobj, indent_width=self._indent + 1) if self.diff_total > self.numdiffs: self._writeln(' ...') self._writeln(' {} different pixels found ({:.2%} different).' .format(self.diff_total, self.diff_ratio)) class RawDataDiff(ImageDataDiff): """ `RawDataDiff` is just a special case of `ImageDataDiff` where the images are one-dimensional, and the data is treated as a 1-dimensional array of bytes instead of pixel values. This is used to compare the data of two non-standard extension HDUs that were not recognized as containing image or table data. `ImageDataDiff` objects have the following diff attributes: - ``diff_dimensions``: Same as the ``diff_dimensions`` attribute of `ImageDataDiff` objects. Though the "dimension" of each array is just an integer representing the number of bytes in the data. - ``diff_bytes``: Like the ``diff_pixels`` attribute of `ImageDataDiff` objects, but renamed to reflect the minor semantic difference that these are raw bytes and not pixel values. Also the indices are integers instead of tuples. - ``diff_total`` and ``diff_ratio``: Same as `ImageDataDiff`. """ def __init__(self, a, b, numdiffs=10): """ Parameters ---------- a : `HDUList` An `HDUList` object. b : `HDUList` An `HDUList` object to compare to the first `HDUList` object. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). """ self.diff_dimensions = () self.diff_bytes = [] super().__init__(a, b, numdiffs=numdiffs) def _diff(self): super()._diff() if self.diff_dimensions: self.diff_dimensions = (self.diff_dimensions[0][0], self.diff_dimensions[1][0]) self.diff_bytes = [(x[0], y) for x, y in self.diff_pixels] del self.diff_pixels def _report(self): if self.diff_dimensions: self._writeln(' Data sizes differ:') self._writeln(' a: {} bytes'.format(self.diff_dimensions[0])) self._writeln(' b: {} bytes'.format(self.diff_dimensions[1])) # For now we don't do any further comparison if the dimensions # differ; though in the future it might be nice to be able to # compare at least where the images intersect self._writeln(' No further data comparison performed.') return if not self.diff_bytes: return for index, values in self.diff_bytes: self._writeln(f' Data differs at byte {index}:') report_diff_values(values[0], values[1], fileobj=self._fileobj, indent_width=self._indent + 1) self._writeln(' ...') self._writeln(' {} different bytes found ({:.2%} different).' .format(self.diff_total, self.diff_ratio)) class TableDataDiff(_BaseDiff): """ Diff two table data arrays. It doesn't matter whether the data originally came from a binary or ASCII table--the data should be passed in as a recarray. `TableDataDiff` objects have the following diff attributes: - ``diff_column_count``: If the tables being compared have different numbers of columns, this contains a 2-tuple of the column count in each table. Even if the tables have different column counts, an attempt is still made to compare any columns they have in common. - ``diff_columns``: If either table contains columns unique to that table, either in name or format, this contains a 2-tuple of lists. The first element is a list of columns (these are full `Column` objects) that appear only in table a. The second element is a list of tables that appear only in table b. This only lists columns with different column definitions, and has nothing to do with the data in those columns. - ``diff_column_names``: This is like ``diff_columns``, but lists only the names of columns unique to either table, rather than the full `Column` objects. - ``diff_column_attributes``: Lists columns that are in both tables but have different secondary attributes, such as TUNIT or TDISP. The format is a list of 2-tuples: The first a tuple of the column name and the attribute, the second a tuple of the different values. - ``diff_values``: `TableDataDiff` compares the data in each table on a column-by-column basis. If any different data is found, it is added to this list. The format of this list is similar to the ``diff_pixels`` attribute on `ImageDataDiff` objects, though the "index" consists of a (column_name, row) tuple. For example:: [('TARGET', 0), ('NGC1001', 'NGC1002')] shows that the tables contain different values in the 0-th row of the 'TARGET' column. - ``diff_total`` and ``diff_ratio``: Same as `ImageDataDiff`. `TableDataDiff` objects also have a ``common_columns`` attribute that lists the `Column` objects for columns that are identical in both tables, and a ``common_column_names`` attribute which contains a set of the names of those columns. """ def __init__(self, a, b, ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0): """ Parameters ---------- a : `HDUList` An `HDUList` object. b : `HDUList` An `HDUList` object to compare to the first `HDUList` object. ignore_fields : sequence, optional The (case-insensitive) names of any table columns to ignore if any table data is to be compared. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 """ self.ignore_fields = set(ignore_fields) self.numdiffs = numdiffs self.rtol = rtol self.atol = atol self.common_columns = [] self.common_column_names = set() # self.diff_columns contains columns with different column definitions, # but not different column data. Column data is only compared in # columns that have the same definitions self.diff_rows = () self.diff_column_count = () self.diff_columns = () # If two columns have the same name+format, but other attributes are # different (such as TUNIT or such) they are listed here self.diff_column_attributes = [] # Like self.diff_columns, but just contains a list of the column names # unique to each table, and in the order they appear in the tables self.diff_column_names = () self.diff_values = [] self.diff_ratio = 0 self.diff_total = 0 super().__init__(a, b) def _diff(self): # Much of the code for comparing columns is similar to the code for # comparing headers--consider refactoring colsa = self.a.columns colsb = self.b.columns if len(colsa) != len(colsb): self.diff_column_count = (len(colsa), len(colsb)) # Even if the number of columns are unequal, we still do comparison of # any common columns colsa = {c.name.lower(): c for c in colsa} colsb = {c.name.lower(): c for c in colsb} if '*' in self.ignore_fields: # If all columns are to be ignored, ignore any further differences # between the columns return # Keep the user's original ignore_fields list for reporting purposes, # but internally use a case-insensitive version ignore_fields = {f.lower() for f in self.ignore_fields} # It might be nice if there were a cleaner way to do this, but for now # it'll do for fieldname in ignore_fields: fieldname = fieldname.lower() if fieldname in colsa: del colsa[fieldname] if fieldname in colsb: del colsb[fieldname] colsa_set = set(colsa.values()) colsb_set = set(colsb.values()) self.common_columns = sorted(colsa_set.intersection(colsb_set), key=operator.attrgetter('name')) self.common_column_names = {col.name.lower() for col in self.common_columns} left_only_columns = {col.name.lower(): col for col in colsa_set.difference(colsb_set)} right_only_columns = {col.name.lower(): col for col in colsb_set.difference(colsa_set)} if left_only_columns or right_only_columns: self.diff_columns = (left_only_columns, right_only_columns) self.diff_column_names = ([], []) if left_only_columns: for col in self.a.columns: if col.name.lower() in left_only_columns: self.diff_column_names[0].append(col.name) if right_only_columns: for col in self.b.columns: if col.name.lower() in right_only_columns: self.diff_column_names[1].append(col.name) # If the tables have a different number of rows, we don't compare the # columns right now. # TODO: It might be nice to optionally compare the first n rows where n # is the minimum of the row counts between the two tables. if len(self.a) != len(self.b): self.diff_rows = (len(self.a), len(self.b)) return # If the tables contain no rows there's no data to compare, so we're # done at this point. (See ticket #178) if len(self.a) == len(self.b) == 0: return # Like in the old fitsdiff, compare tables on a column by column basis # The difficulty here is that, while FITS column names are meant to be # case-insensitive, Astropy still allows, for the sake of flexibility, # two columns with the same name but different case. When columns are # accessed in FITS tables, a case-sensitive is tried first, and failing # that a case-insensitive match is made. # It's conceivable that the same column could appear in both tables # being compared, but with different case. # Though it *may* lead to inconsistencies in these rare cases, this # just assumes that there are no duplicated column names in either # table, and that the column names can be treated case-insensitively. for col in self.common_columns: name_lower = col.name.lower() if name_lower in ignore_fields: continue cola = colsa[name_lower] colb = colsb[name_lower] for attr, _ in _COL_ATTRS: vala = getattr(cola, attr, None) valb = getattr(colb, attr, None) if diff_values(vala, valb): self.diff_column_attributes.append( ((col.name.upper(), attr), (vala, valb))) arra = self.a[col.name] arrb = self.b[col.name] if (np.issubdtype(arra.dtype, np.floating) and np.issubdtype(arrb.dtype, np.floating)): diffs = where_not_allclose(arra, arrb, rtol=self.rtol, atol=self.atol) elif 'P' in col.format: diffs = ([idx for idx in range(len(arra)) if not np.allclose(arra[idx], arrb[idx], rtol=self.rtol, atol=self.atol)],) else: diffs = np.where(arra != arrb) self.diff_total += len(set(diffs[0])) if self.numdiffs >= 0: if len(self.diff_values) >= self.numdiffs: # Don't save any more diff values continue # Add no more diff'd values than this max_diffs = self.numdiffs - len(self.diff_values) else: max_diffs = len(diffs[0]) last_seen_idx = None for idx in islice(diffs[0], 0, max_diffs): if idx == last_seen_idx: # Skip duplicate indices, which my occur when the column # data contains multi-dimensional values; we're only # interested in storing row-by-row differences continue last_seen_idx = idx self.diff_values.append(((col.name, idx), (arra[idx], arrb[idx]))) total_values = len(self.a) * len(self.a.dtype.fields) self.diff_ratio = float(self.diff_total) / float(total_values) def _report(self): if self.diff_column_count: self._writeln(' Tables have different number of columns:') self._writeln(' a: {}'.format(self.diff_column_count[0])) self._writeln(' b: {}'.format(self.diff_column_count[1])) if self.diff_column_names: # Show columns with names unique to either table for name in self.diff_column_names[0]: format = self.diff_columns[0][name.lower()].format self._writeln(' Extra column {} of format {} in a'.format( name, format)) for name in self.diff_column_names[1]: format = self.diff_columns[1][name.lower()].format self._writeln(' Extra column {} of format {} in b'.format( name, format)) col_attrs = dict(_COL_ATTRS) # Now go through each table again and show columns with common # names but other property differences... for col_attr, vals in self.diff_column_attributes: name, attr = col_attr self._writeln(' Column {} has different {}:'.format( name, col_attrs[attr])) report_diff_values(vals[0], vals[1], fileobj=self._fileobj, indent_width=self._indent + 1) if self.diff_rows: self._writeln(' Table rows differ:') self._writeln(' a: {}'.format(self.diff_rows[0])) self._writeln(' b: {}'.format(self.diff_rows[1])) self._writeln(' No further data comparison performed.') return if not self.diff_values: return # Finally, let's go through and report column data differences: for indx, values in self.diff_values: self._writeln(' Column {} data differs in row {}:'.format(*indx)) report_diff_values(values[0], values[1], fileobj=self._fileobj, indent_width=self._indent + 1) if self.diff_values and self.numdiffs < self.diff_total: self._writeln(' ...{} additional difference(s) found.'.format( self.diff_total - self.numdiffs)) if self.diff_total > self.numdiffs: self._writeln(' ...') self._writeln(' {} different table data element(s) found ' '({:.2%} different).' .format(self.diff_total, self.diff_ratio)) def report_diff_keyword_attr(fileobj, attr, diffs, keyword, ind=0): """ Write a diff between two header keyword values or comments to the specified file-like object. """ if keyword in diffs: vals = diffs[keyword] for idx, val in enumerate(vals): if val is None: continue if idx == 0: dup = '' else: dup = '[{}]'.format(idx + 1) fileobj.write( fixed_width_indent(' Keyword {:8}{} has different {}:\n' .format(keyword, dup, attr), ind)) report_diff_values(val[0], val[1], fileobj=fileobj, indent_width=ind + 1)
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Accuracy tests for AltAz to ICRS coordinate transformations. We use "known good" examples computed with other coordinate libraries. Note that we use very low precision asserts because some people run tests on 32-bit machines and we want the tests to pass there. TODO: check if these tests pass on 32-bit machines and implement higher-precision checks on 64-bit machines. """ import pytest from astropy import units as u from astropy.time import Time from astropy.coordinates.builtin_frames import AltAz from astropy.coordinates import EarthLocation from astropy.coordinates import Angle, SkyCoord @pytest.mark.remote_data def test_against_hor2eq(): """Check that Astropy gives consistent results with an IDL hor2eq example. See : http://idlastro.gsfc.nasa.gov/ftp/pro/astro/hor2eq.pro Test is against these run outputs, run at 2000-01-01T12:00:00: # NORMAL ATMOSPHERE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=781.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 53 40 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 30.1 (hh:mm:ss) Ra, Dec: 07 36 55.6 +15 25 02 (Apparent Coords) Ra, Dec: 07 36 55.2 +15 25 08 (J2000.0000) Ra, Dec: 07 36 55.2 +15 25 08 (J2000) IDL> print, ra, dec 114.23004 15.418818 # NO PRESSURE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=0.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 54 41 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 26.4 (hh:mm:ss) Ra, Dec: 07 36 59.3 +15 25 31 (Apparent Coords) Ra, Dec: 07 36 58.9 +15 25 37 (J2000.0000) Ra, Dec: 07 36 58.9 +15 25 37 (J2000) IDL> print, ra, dec 114.24554 15.427022 """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111d36.0m'), lat=Angle('31d57.8m'), height=2120. * u.m) obstime = Time(2451545.0, format='jd', scale='ut1') altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) altaz_frame_noatm = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.0 * u.bar) altaz = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame) altaz_noatm = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame_noatm) radec_frame = 'icrs' radec_actual = altaz.transform_to(radec_frame) radec_actual_noatm = altaz_noatm.transform_to(radec_frame) radec_expected = SkyCoord('07h36m55.2s +15d25m08s', frame=radec_frame) distance = radec_actual.separation(radec_expected).to('arcsec') # this comes from running the example hor2eq but with the pressure set to 0 radec_expected_noatm = SkyCoord('07h36m58.9s +15d25m37s', frame=radec_frame) distance_noatm = radec_actual_noatm.separation(radec_expected_noatm).to('arcsec') # The baseline difference is ~2.3 arcsec with one atm of pressure. The # difference is mainly due to the somewhat different atmospheric model that # hor2eq assumes. This is confirmed by the second test which has the # atmosphere "off" - the residual difference is small enough to be embedded # in the assumptions about "J2000" or rounding errors. assert distance < 5 * u.arcsec assert distance_noatm < 0.4 * u.arcsec @pytest.mark.remote_data def test_against_pyephem(): """Check that Astropy gives consistent results with one PyEphem example. PyEphem: http://rhodesmill.org/pyephem/ See example input and output here: https://gist.github.com/zonca/1672906 https://github.com/phn/pytpm/issues/2#issuecomment-3698679 """ obstime = Time('2011-09-18 08:50:00') location = EarthLocation(lon=Angle('-109d24m53.1s'), lat=Angle('33d41m46.0s'), height=30000. * u.m) # We are using the default pressure and temperature in PyEphem # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=15 * u.deg_C, pressure=1.010 * u.bar) altaz = SkyCoord('6.8927d -60.7665d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('196.497518d -4.569323d', frame='icrs') # EPHEM # radec_expected = SkyCoord('196.496220d -4.569390d', frame='icrs') # HORIZON distance = radec_actual.separation(radec_expected).to('arcsec') # TODO: why is this difference so large? # It currently is: 31.45187984720655 arcsec assert distance < 1e3 * u.arcsec # Add assert on current Astropy result so that we notice if something changes radec_expected = SkyCoord('196.495372d -4.560694d', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.0031402822944751997 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data def test_against_jpl_horizons(): """Check that Astropy gives consistent results with the JPL Horizons example. The input parameters and reference results are taken from this page: (from the first row of the Results table at the bottom of that page) http://ssd.jpl.nasa.gov/?horizons_tutorial """ obstime = Time('1998-07-28 03:00') location = EarthLocation(lon=Angle('248.405300d'), lat=Angle('31.9585d'), height=2.06 * u.km) # No atmosphere altaz_frame = AltAz(obstime=obstime, location=location) altaz = SkyCoord('143.2970d 2.6223d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('19h24m55.01s -40d56m28.9s', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.238111 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data @pytest.mark.xfail(reason="Current output is completely incorrect") def test_fk5_equinox_and_epoch_j2000_0_to_topocentric_observed(): """ http://phn.github.io/pytpm/conversions.html#fk5-equinox-and-epoch-j2000-0-to-topocentric-observed """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111.598333d'), lat=Angle('31.956389d'), height=2093.093 * u.m) # TODO: height correct? obstime = Time('2010-01-01 12:00:00') # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) radec = SkyCoord('12h22m54.899s 15d49m20.57s', frame='fk5') altaz_actual = radec.transform_to(altaz_frame) altaz_expected = SkyCoord('264d55m06s 37d54m41s', frame='altaz') # altaz_expected = SkyCoord('343.586827647d 15.7683070508d', frame='altaz') # altaz_expected = SkyCoord('133.498195532d 22.0162383595d', frame='altaz') distance = altaz_actual.separation(altaz_expected) # print(altaz_actual) # print(altaz_expected) # print(distance) """TODO: Current output is completely incorrect ... xfailing this test for now. <SkyCoord (AltAz: obstime=2010-01-01 12:00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron):00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=133.4869896371561 deg, alt=67.97857990957701 deg> <SkyCoord (AltAz: obstime=None, location=None, pressure=0.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=264.91833333333335 deg, alt=37.91138888888889 deg> 68d02m45.732s """ assert distance < 1 * u.arcsec
stargaser/astropy
astropy/coordinates/tests/accuracy/test_altaz_icrs.py
astropy/io/fits/diff.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains utililies used for constructing rotation matrices. """ from functools import reduce import numpy as np from astropy import units as u from .angles import Angle def matrix_product(*matrices): """Matrix multiply all arguments together. Arguments should have dimension 2 or larger. Larger dimensional objects are interpreted as stacks of matrices residing in the last two dimensions. This function mostly exists for readability: using `~numpy.matmul` directly, one would have ``matmul(matmul(m1, m2), m3)``, etc. For even better readability, one might consider using `~numpy.matrix` for the arguments (so that one could write ``m1 * m2 * m3``), but then it is not possible to handle stacks of matrices. Once only python >=3.5 is supported, this function can be replaced by ``m1 @ m2 @ m3``. """ return reduce(np.matmul, matrices) def matrix_transpose(matrix): """Transpose a matrix or stack of matrices by swapping the last two axes. This function mostly exists for readability; seeing ``.swapaxes(-2, -1)`` it is not that obvious that one does a transpose. Note that one cannot use `~numpy.ndarray.T`, as this transposes all axes and thus does not work for stacks of matrices. """ return matrix.swapaxes(-2, -1) def rotation_matrix(angle, axis='z', unit=None): """ Generate matrices for rotation by some angle around some axis. Parameters ---------- angle : convertible to `~astropy.coordinates.Angle` The amount of rotation the matrices should represent. Can be an array. axis : str or array_like Either ``'x'``, ``'y'``, ``'z'``, or a (x,y,z) specifying the axis to rotate about. If ``'x'``, ``'y'``, or ``'z'``, the rotation sense is counterclockwise looking down the + axis (e.g. positive rotations obey left-hand-rule). If given as an array, the last dimension should be 3; it will be broadcast against ``angle``. unit : UnitBase, optional If ``angle`` does not have associated units, they are in this unit. If neither are provided, it is assumed to be degrees. Returns ------- rmat : `numpy.matrix` A unitary rotation matrix. """ if isinstance(angle, u.Quantity): angle = angle.to_value(u.radian) else: if unit is None: angle = np.deg2rad(angle) else: angle = u.Unit(unit).to(u.rad, angle) s = np.sin(angle) c = np.cos(angle) # use optimized implementations for x/y/z try: i = 'xyz'.index(axis) except TypeError: axis = np.asarray(axis) axis = axis / np.sqrt((axis * axis).sum(axis=-1, keepdims=True)) R = (axis[..., np.newaxis] * axis[..., np.newaxis, :] * (1. - c)[..., np.newaxis, np.newaxis]) for i in range(0, 3): R[..., i, i] += c a1 = (i + 1) % 3 a2 = (i + 2) % 3 R[..., a1, a2] += axis[..., i] * s R[..., a2, a1] -= axis[..., i] * s else: a1 = (i + 1) % 3 a2 = (i + 2) % 3 R = np.zeros(getattr(angle, 'shape', ()) + (3, 3)) R[..., i, i] = 1. R[..., a1, a1] = c R[..., a1, a2] = s R[..., a2, a1] = -s R[..., a2, a2] = c return R def angle_axis(matrix): """ Angle of rotation and rotation axis for a given rotation matrix. Parameters ---------- matrix : array_like A 3 x 3 unitary rotation matrix (or stack of matrices). Returns ------- angle : `~astropy.coordinates.Angle` The angle of rotation. axis : array The (normalized) axis of rotation (with last dimension 3). """ m = np.asanyarray(matrix) if m.shape[-2:] != (3, 3): raise ValueError('matrix is not 3x3') axis = np.zeros(m.shape[:-1]) axis[..., 0] = m[..., 2, 1] - m[..., 1, 2] axis[..., 1] = m[..., 0, 2] - m[..., 2, 0] axis[..., 2] = m[..., 1, 0] - m[..., 0, 1] r = np.sqrt((axis * axis).sum(-1, keepdims=True)) angle = np.arctan2(r[..., 0], m[..., 0, 0] + m[..., 1, 1] + m[..., 2, 2] - 1.) return Angle(angle, u.radian), -axis / r
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Accuracy tests for AltAz to ICRS coordinate transformations. We use "known good" examples computed with other coordinate libraries. Note that we use very low precision asserts because some people run tests on 32-bit machines and we want the tests to pass there. TODO: check if these tests pass on 32-bit machines and implement higher-precision checks on 64-bit machines. """ import pytest from astropy import units as u from astropy.time import Time from astropy.coordinates.builtin_frames import AltAz from astropy.coordinates import EarthLocation from astropy.coordinates import Angle, SkyCoord @pytest.mark.remote_data def test_against_hor2eq(): """Check that Astropy gives consistent results with an IDL hor2eq example. See : http://idlastro.gsfc.nasa.gov/ftp/pro/astro/hor2eq.pro Test is against these run outputs, run at 2000-01-01T12:00:00: # NORMAL ATMOSPHERE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=781.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 53 40 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 30.1 (hh:mm:ss) Ra, Dec: 07 36 55.6 +15 25 02 (Apparent Coords) Ra, Dec: 07 36 55.2 +15 25 08 (J2000.0000) Ra, Dec: 07 36 55.2 +15 25 08 (J2000) IDL> print, ra, dec 114.23004 15.418818 # NO PRESSURE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=0.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 54 41 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 26.4 (hh:mm:ss) Ra, Dec: 07 36 59.3 +15 25 31 (Apparent Coords) Ra, Dec: 07 36 58.9 +15 25 37 (J2000.0000) Ra, Dec: 07 36 58.9 +15 25 37 (J2000) IDL> print, ra, dec 114.24554 15.427022 """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111d36.0m'), lat=Angle('31d57.8m'), height=2120. * u.m) obstime = Time(2451545.0, format='jd', scale='ut1') altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) altaz_frame_noatm = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.0 * u.bar) altaz = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame) altaz_noatm = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame_noatm) radec_frame = 'icrs' radec_actual = altaz.transform_to(radec_frame) radec_actual_noatm = altaz_noatm.transform_to(radec_frame) radec_expected = SkyCoord('07h36m55.2s +15d25m08s', frame=radec_frame) distance = radec_actual.separation(radec_expected).to('arcsec') # this comes from running the example hor2eq but with the pressure set to 0 radec_expected_noatm = SkyCoord('07h36m58.9s +15d25m37s', frame=radec_frame) distance_noatm = radec_actual_noatm.separation(radec_expected_noatm).to('arcsec') # The baseline difference is ~2.3 arcsec with one atm of pressure. The # difference is mainly due to the somewhat different atmospheric model that # hor2eq assumes. This is confirmed by the second test which has the # atmosphere "off" - the residual difference is small enough to be embedded # in the assumptions about "J2000" or rounding errors. assert distance < 5 * u.arcsec assert distance_noatm < 0.4 * u.arcsec @pytest.mark.remote_data def test_against_pyephem(): """Check that Astropy gives consistent results with one PyEphem example. PyEphem: http://rhodesmill.org/pyephem/ See example input and output here: https://gist.github.com/zonca/1672906 https://github.com/phn/pytpm/issues/2#issuecomment-3698679 """ obstime = Time('2011-09-18 08:50:00') location = EarthLocation(lon=Angle('-109d24m53.1s'), lat=Angle('33d41m46.0s'), height=30000. * u.m) # We are using the default pressure and temperature in PyEphem # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=15 * u.deg_C, pressure=1.010 * u.bar) altaz = SkyCoord('6.8927d -60.7665d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('196.497518d -4.569323d', frame='icrs') # EPHEM # radec_expected = SkyCoord('196.496220d -4.569390d', frame='icrs') # HORIZON distance = radec_actual.separation(radec_expected).to('arcsec') # TODO: why is this difference so large? # It currently is: 31.45187984720655 arcsec assert distance < 1e3 * u.arcsec # Add assert on current Astropy result so that we notice if something changes radec_expected = SkyCoord('196.495372d -4.560694d', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.0031402822944751997 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data def test_against_jpl_horizons(): """Check that Astropy gives consistent results with the JPL Horizons example. The input parameters and reference results are taken from this page: (from the first row of the Results table at the bottom of that page) http://ssd.jpl.nasa.gov/?horizons_tutorial """ obstime = Time('1998-07-28 03:00') location = EarthLocation(lon=Angle('248.405300d'), lat=Angle('31.9585d'), height=2.06 * u.km) # No atmosphere altaz_frame = AltAz(obstime=obstime, location=location) altaz = SkyCoord('143.2970d 2.6223d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('19h24m55.01s -40d56m28.9s', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.238111 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data @pytest.mark.xfail(reason="Current output is completely incorrect") def test_fk5_equinox_and_epoch_j2000_0_to_topocentric_observed(): """ http://phn.github.io/pytpm/conversions.html#fk5-equinox-and-epoch-j2000-0-to-topocentric-observed """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111.598333d'), lat=Angle('31.956389d'), height=2093.093 * u.m) # TODO: height correct? obstime = Time('2010-01-01 12:00:00') # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) radec = SkyCoord('12h22m54.899s 15d49m20.57s', frame='fk5') altaz_actual = radec.transform_to(altaz_frame) altaz_expected = SkyCoord('264d55m06s 37d54m41s', frame='altaz') # altaz_expected = SkyCoord('343.586827647d 15.7683070508d', frame='altaz') # altaz_expected = SkyCoord('133.498195532d 22.0162383595d', frame='altaz') distance = altaz_actual.separation(altaz_expected) # print(altaz_actual) # print(altaz_expected) # print(distance) """TODO: Current output is completely incorrect ... xfailing this test for now. <SkyCoord (AltAz: obstime=2010-01-01 12:00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron):00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=133.4869896371561 deg, alt=67.97857990957701 deg> <SkyCoord (AltAz: obstime=None, location=None, pressure=0.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=264.91833333333335 deg, alt=37.91138888888889 deg> 68d02m45.732s """ assert distance < 1 * u.arcsec
stargaser/astropy
astropy/coordinates/tests/accuracy/test_altaz_icrs.py
astropy/coordinates/matrix_utilities.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains simple input/output related functionality that is not part of a larger framework or standard. """ import pickle __all__ = ['fnpickle', 'fnunpickle'] def fnunpickle(fileorname, number=0): """ Unpickle pickled objects from a specified file and return the contents. Parameters ---------- fileorname : str or file-like The file name or file from which to unpickle objects. If a file object, it should have been opened in binary mode. number : int If 0, a single object will be returned (the first in the file). If >0, this specifies the number of objects to be unpickled, and a list will be returned with exactly that many objects. If <0, all objects in the file will be unpickled and returned as a list. Raises ------ EOFError If ``number`` is >0 and there are fewer than ``number`` objects in the pickled file. Returns ------- contents : obj or list If ``number`` is 0, this is a individual object - the first one unpickled from the file. Otherwise, it is a list of objects unpickled from the file. """ if isinstance(fileorname, str): f = open(fileorname, 'rb') close = True else: f = fileorname close = False try: if number > 0: # get that number res = [] for i in range(number): res.append(pickle.load(f)) elif number < 0: # get all objects res = [] eof = False while not eof: try: res.append(pickle.load(f)) except EOFError: eof = True else: # number==0 res = pickle.load(f) finally: if close: f.close() return res def fnpickle(object, fileorname, protocol=None, append=False): """Pickle an object to a specified file. Parameters ---------- object The python object to pickle. fileorname : str or file-like The filename or file into which the `object` should be pickled. If a file object, it should have been opened in binary mode. protocol : int or None Pickle protocol to use - see the :mod:`pickle` module for details on these options. If None, the most recent protocol will be used. append : bool If True, the object is appended to the end of the file, otherwise the file will be overwritten (if a file object is given instead of a file name, this has no effect). """ if protocol is None: protocol = pickle.HIGHEST_PROTOCOL if isinstance(fileorname, str): f = open(fileorname, 'ab' if append else 'wb') close = True else: f = fileorname close = False try: pickle.dump(object, f, protocol=protocol) finally: if close: f.close()
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Accuracy tests for AltAz to ICRS coordinate transformations. We use "known good" examples computed with other coordinate libraries. Note that we use very low precision asserts because some people run tests on 32-bit machines and we want the tests to pass there. TODO: check if these tests pass on 32-bit machines and implement higher-precision checks on 64-bit machines. """ import pytest from astropy import units as u from astropy.time import Time from astropy.coordinates.builtin_frames import AltAz from astropy.coordinates import EarthLocation from astropy.coordinates import Angle, SkyCoord @pytest.mark.remote_data def test_against_hor2eq(): """Check that Astropy gives consistent results with an IDL hor2eq example. See : http://idlastro.gsfc.nasa.gov/ftp/pro/astro/hor2eq.pro Test is against these run outputs, run at 2000-01-01T12:00:00: # NORMAL ATMOSPHERE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=781.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 53 40 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 30.1 (hh:mm:ss) Ra, Dec: 07 36 55.6 +15 25 02 (Apparent Coords) Ra, Dec: 07 36 55.2 +15 25 08 (J2000.0000) Ra, Dec: 07 36 55.2 +15 25 08 (J2000) IDL> print, ra, dec 114.23004 15.418818 # NO PRESSURE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=0.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 54 41 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 26.4 (hh:mm:ss) Ra, Dec: 07 36 59.3 +15 25 31 (Apparent Coords) Ra, Dec: 07 36 58.9 +15 25 37 (J2000.0000) Ra, Dec: 07 36 58.9 +15 25 37 (J2000) IDL> print, ra, dec 114.24554 15.427022 """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111d36.0m'), lat=Angle('31d57.8m'), height=2120. * u.m) obstime = Time(2451545.0, format='jd', scale='ut1') altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) altaz_frame_noatm = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.0 * u.bar) altaz = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame) altaz_noatm = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame_noatm) radec_frame = 'icrs' radec_actual = altaz.transform_to(radec_frame) radec_actual_noatm = altaz_noatm.transform_to(radec_frame) radec_expected = SkyCoord('07h36m55.2s +15d25m08s', frame=radec_frame) distance = radec_actual.separation(radec_expected).to('arcsec') # this comes from running the example hor2eq but with the pressure set to 0 radec_expected_noatm = SkyCoord('07h36m58.9s +15d25m37s', frame=radec_frame) distance_noatm = radec_actual_noatm.separation(radec_expected_noatm).to('arcsec') # The baseline difference is ~2.3 arcsec with one atm of pressure. The # difference is mainly due to the somewhat different atmospheric model that # hor2eq assumes. This is confirmed by the second test which has the # atmosphere "off" - the residual difference is small enough to be embedded # in the assumptions about "J2000" or rounding errors. assert distance < 5 * u.arcsec assert distance_noatm < 0.4 * u.arcsec @pytest.mark.remote_data def test_against_pyephem(): """Check that Astropy gives consistent results with one PyEphem example. PyEphem: http://rhodesmill.org/pyephem/ See example input and output here: https://gist.github.com/zonca/1672906 https://github.com/phn/pytpm/issues/2#issuecomment-3698679 """ obstime = Time('2011-09-18 08:50:00') location = EarthLocation(lon=Angle('-109d24m53.1s'), lat=Angle('33d41m46.0s'), height=30000. * u.m) # We are using the default pressure and temperature in PyEphem # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=15 * u.deg_C, pressure=1.010 * u.bar) altaz = SkyCoord('6.8927d -60.7665d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('196.497518d -4.569323d', frame='icrs') # EPHEM # radec_expected = SkyCoord('196.496220d -4.569390d', frame='icrs') # HORIZON distance = radec_actual.separation(radec_expected).to('arcsec') # TODO: why is this difference so large? # It currently is: 31.45187984720655 arcsec assert distance < 1e3 * u.arcsec # Add assert on current Astropy result so that we notice if something changes radec_expected = SkyCoord('196.495372d -4.560694d', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.0031402822944751997 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data def test_against_jpl_horizons(): """Check that Astropy gives consistent results with the JPL Horizons example. The input parameters and reference results are taken from this page: (from the first row of the Results table at the bottom of that page) http://ssd.jpl.nasa.gov/?horizons_tutorial """ obstime = Time('1998-07-28 03:00') location = EarthLocation(lon=Angle('248.405300d'), lat=Angle('31.9585d'), height=2.06 * u.km) # No atmosphere altaz_frame = AltAz(obstime=obstime, location=location) altaz = SkyCoord('143.2970d 2.6223d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('19h24m55.01s -40d56m28.9s', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.238111 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data @pytest.mark.xfail(reason="Current output is completely incorrect") def test_fk5_equinox_and_epoch_j2000_0_to_topocentric_observed(): """ http://phn.github.io/pytpm/conversions.html#fk5-equinox-and-epoch-j2000-0-to-topocentric-observed """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111.598333d'), lat=Angle('31.956389d'), height=2093.093 * u.m) # TODO: height correct? obstime = Time('2010-01-01 12:00:00') # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) radec = SkyCoord('12h22m54.899s 15d49m20.57s', frame='fk5') altaz_actual = radec.transform_to(altaz_frame) altaz_expected = SkyCoord('264d55m06s 37d54m41s', frame='altaz') # altaz_expected = SkyCoord('343.586827647d 15.7683070508d', frame='altaz') # altaz_expected = SkyCoord('133.498195532d 22.0162383595d', frame='altaz') distance = altaz_actual.separation(altaz_expected) # print(altaz_actual) # print(altaz_expected) # print(distance) """TODO: Current output is completely incorrect ... xfailing this test for now. <SkyCoord (AltAz: obstime=2010-01-01 12:00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron):00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=133.4869896371561 deg, alt=67.97857990957701 deg> <SkyCoord (AltAz: obstime=None, location=None, pressure=0.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=264.91833333333335 deg, alt=37.91138888888889 deg> 68d02m45.732s """ assert distance < 1 * u.arcsec
stargaser/astropy
astropy/coordinates/tests/accuracy/test_altaz_icrs.py
astropy/io/misc/pickle_helpers.py
# Functions/classes for WCSAxes related to APE14 WCSes import numpy as np from astropy.coordinates import SkyCoord, ICRS, BaseCoordinateFrame from astropy import units as u from astropy.wcs import WCS from astropy.wcs.utils import local_partial_pixel_derivatives from astropy.wcs.wcsapi import SlicedLowLevelWCS from .frame import RectangularFrame, EllipticalFrame, RectangularFrame1D from .transforms import CurvedTransform __all__ = ['transform_coord_meta_from_wcs', 'WCSWorld2PixelTransform', 'WCSPixel2WorldTransform'] IDENTITY = WCS(naxis=2) IDENTITY.wcs.ctype = ["X", "Y"] IDENTITY.wcs.crval = [0., 0.] IDENTITY.wcs.crpix = [1., 1.] IDENTITY.wcs.cdelt = [1., 1.] def transform_coord_meta_from_wcs(wcs, frame_class, slices=None): if slices is not None: slices = tuple(slices) if wcs.pixel_n_dim > 2: if slices is None: raise ValueError("WCS has more than 2 pixel dimensions, so " "'slices' should be set") elif len(slices) != wcs.pixel_n_dim: raise ValueError("'slices' should have as many elements as WCS " "has pixel dimensions (should be {})" .format(wcs.pixel_n_dim)) is_fits_wcs = isinstance(wcs, WCS) coord_meta = {} coord_meta['name'] = [] coord_meta['type'] = [] coord_meta['wrap'] = [] coord_meta['unit'] = [] coord_meta['visible'] = [] coord_meta['format_unit'] = [] for idx in range(wcs.world_n_dim): axis_type = wcs.world_axis_physical_types[idx] axis_unit = u.Unit(wcs.world_axis_units[idx]) coord_wrap = None format_unit = axis_unit coord_type = 'scalar' if axis_type is not None: axis_type_split = axis_type.split('.') if "pos.helioprojective.lon" in axis_type: coord_wrap = 180. format_unit = u.arcsec coord_type = "longitude" elif "pos.helioprojective.lat" in axis_type: format_unit = u.arcsec coord_type = "latitude" elif "pos.heliographic.stonyhurst.lon" in axis_type: coord_wrap = 180. format_unit = u.deg coord_type = "longitude" elif "pos.heliographic.stonyhurst.lat" in axis_type: format_unit = u.deg coord_type = "latitude" elif "pos.heliographic.carrington.lon" in axis_type: coord_wrap = 360. format_unit = u.deg coord_type = "longitude" elif "pos.heliographic.carrington.lat" in axis_type: format_unit = u.deg coord_type = "latitude" elif "pos" in axis_type_split: if "lon" in axis_type_split: coord_type = "longitude" elif "lat" in axis_type_split: coord_type = "latitude" elif "ra" in axis_type_split: coord_type = "longitude" format_unit = u.hourangle elif "dec" in axis_type_split: coord_type = "latitude" elif "alt" in axis_type_split: coord_type = "longitude" elif "az" in axis_type_split: coord_type = "latitude" elif "long" in axis_type_split: coord_type = "longitude" coord_meta['type'].append(coord_type) coord_meta['wrap'].append(coord_wrap) coord_meta['format_unit'].append(format_unit) coord_meta['unit'].append(axis_unit) # For FITS-WCS, for backward-compatibility, we need to make sure that we # provide aliases based on CTYPE for the name. if is_fits_wcs: name = [] if isinstance(wcs, WCS): name.append(wcs.wcs.ctype[idx].lower()) name.append(wcs.wcs.ctype[idx][:4].replace('-', '').lower()) elif isinstance(wcs, SlicedLowLevelWCS): name.append(wcs._wcs.wcs.ctype[wcs._world_keep[idx]].lower()) name.append(wcs._wcs.wcs.ctype[wcs._world_keep[idx]][:4].replace('-', '').lower()) if name[0] == name[1]: name = name[0:1] if axis_type: name.insert(0, axis_type) name = tuple(name) if len(name) > 1 else name[0] else: name = axis_type or '' coord_meta['name'].append(name) coord_meta['default_axislabel_position'] = [''] * wcs.world_n_dim coord_meta['default_ticklabel_position'] = [''] * wcs.world_n_dim coord_meta['default_ticks_position'] = [''] * wcs.world_n_dim # If the world axis has a name use it, else display the world axis physical type. fallback_labels = [name[0] if isinstance(name, (list, tuple)) else name for name in coord_meta['name']] coord_meta['default_axis_label'] = [wcs.world_axis_names[i] or fallback_label for i, fallback_label in enumerate(fallback_labels)] transform_wcs, invert_xy, world_map = apply_slices(wcs, slices) transform = WCSPixel2WorldTransform(transform_wcs, invert_xy=invert_xy) for i in range(len(coord_meta['type'])): coord_meta['visible'].append(i in world_map) inv_all_corr = [False] * wcs.world_n_dim m = transform_wcs.axis_correlation_matrix.copy() if invert_xy: inv_all_corr = np.all(m, axis=1) m = m[:, ::-1] if frame_class is RectangularFrame: for i, spine_name in enumerate('bltr'): pos = np.nonzero(m[:, i % 2])[0] # If all the axes we have are correlated with each other and we # have inverted the axes, then we need to reverse the index so we # put the 'y' on the left. if inv_all_corr[i % 2]: pos = pos[::-1] if len(pos) > 0: index = world_map[pos[0]] coord_meta['default_axislabel_position'][index] = spine_name coord_meta['default_ticklabel_position'][index] = spine_name coord_meta['default_ticks_position'][index] = spine_name m[pos[0], :] = 0 # In the special and common case where the frame is rectangular and # we are dealing with 2-d WCS (after slicing), we show all ticks on # all axes for backward-compatibility. if len(world_map) == 2: for index in world_map: coord_meta['default_ticks_position'][index] = 'bltr' elif frame_class is RectangularFrame1D: derivs = np.abs(local_partial_pixel_derivatives(transform_wcs, *[0]*transform_wcs.pixel_n_dim, normalize_by_world=False))[:, 0] for i, spine_name in enumerate('bt'): # Here we are iterating over the correlated axes in world axis order. # We want to sort the correlated axes by their partial derivatives, # so we put the most rapidly changing world axis on the bottom. pos = np.nonzero(m[:, 0])[0] order = np.argsort(derivs[pos])[::-1] # Sort largest to smallest pos = pos[order] if len(pos) > 0: index = world_map[pos[0]] coord_meta['default_axislabel_position'][index] = spine_name coord_meta['default_ticklabel_position'][index] = spine_name coord_meta['default_ticks_position'][index] = spine_name m[pos[0], :] = 0 # In the special and common case where the frame is rectangular and # we are dealing with 2-d WCS (after slicing), we show all ticks on # all axes for backward-compatibility. if len(world_map) == 1: for index in world_map: coord_meta['default_ticks_position'][index] = 'bt' elif frame_class is EllipticalFrame: if 'longitude' in coord_meta['type']: lon_idx = coord_meta['type'].index('longitude') coord_meta['default_axislabel_position'][lon_idx] = 'h' coord_meta['default_ticklabel_position'][lon_idx] = 'h' coord_meta['default_ticks_position'][lon_idx] = 'h' if 'latitude' in coord_meta['type']: lat_idx = coord_meta['type'].index('latitude') coord_meta['default_axislabel_position'][lat_idx] = 'c' coord_meta['default_ticklabel_position'][lat_idx] = 'c' coord_meta['default_ticks_position'][lat_idx] = 'c' else: for index in range(len(coord_meta['type'])): if index in world_map: coord_meta['default_axislabel_position'][index] = frame_class.spine_names coord_meta['default_ticklabel_position'][index] = frame_class.spine_names coord_meta['default_ticks_position'][index] = frame_class.spine_names return transform, coord_meta def apply_slices(wcs, slices): """ Take the input WCS and slices and return a sliced WCS for the transform and a mapping of world axes in the sliced WCS to the input WCS. """ if isinstance(wcs, SlicedLowLevelWCS): world_keep = list(wcs._world_keep) else: world_keep = list(range(wcs.world_n_dim)) # world_map is the index of the world axis in the input WCS for a given # axis in the transform_wcs world_map = list(range(wcs.world_n_dim)) transform_wcs = wcs invert_xy = False if slices is not None: wcs_slice = list(slices) wcs_slice[wcs_slice.index("x")] = slice(None) if 'y' in slices: wcs_slice[wcs_slice.index("y")] = slice(None) invert_xy = slices.index('x') > slices.index('y') transform_wcs = SlicedLowLevelWCS(wcs, wcs_slice[::-1]) world_map = tuple(world_keep.index(i) for i in transform_wcs._world_keep) return transform_wcs, invert_xy, world_map def wcsapi_to_celestial_frame(wcs): for cls, _, kwargs, *_ in wcs.world_axis_object_classes.values(): if issubclass(cls, SkyCoord): return kwargs.get('frame', ICRS()) elif issubclass(cls, BaseCoordinateFrame): return cls(**kwargs) class WCSWorld2PixelTransform(CurvedTransform): """ WCS transformation from world to pixel coordinates """ has_inverse = True frame_in = None def __init__(self, wcs, invert_xy=False): super().__init__() if wcs.pixel_n_dim > 2: raise ValueError('Only pixel_n_dim =< 2 is supported') self.wcs = wcs self.invert_xy = invert_xy self.frame_in = wcsapi_to_celestial_frame(wcs) def __eq__(self, other): return (isinstance(other, type(self)) and self.wcs is other.wcs and self.invert_xy == other.invert_xy) @property def input_dims(self): return self.wcs.world_n_dim def transform(self, world): # Convert to a list of arrays world = list(world.T) if len(world) != self.wcs.world_n_dim: raise ValueError(f"Expected {self.wcs.world_n_dim} world coordinates, got {len(world)} ") if len(world[0]) == 0: pixel = np.zeros((0, 2)) else: pixel = self.wcs.world_to_pixel_values(*world) if self.invert_xy: pixel = pixel[::-1] pixel = np.array(pixel).T return pixel transform_non_affine = transform def inverted(self): """ Return the inverse of the transform """ return WCSPixel2WorldTransform(self.wcs, invert_xy=self.invert_xy) class WCSPixel2WorldTransform(CurvedTransform): """ WCS transformation from pixel to world coordinates """ has_inverse = True def __init__(self, wcs, invert_xy=False): super().__init__() if wcs.pixel_n_dim > 2: raise ValueError('Only pixel_n_dim =< 2 is supported') self.wcs = wcs self.invert_xy = invert_xy self.frame_out = wcsapi_to_celestial_frame(wcs) def __eq__(self, other): return (isinstance(other, type(self)) and self.wcs is other.wcs and self.invert_xy == other.invert_xy) @property def output_dims(self): return self.wcs.world_n_dim def transform(self, pixel): # Convert to a list of arrays pixel = list(pixel.T) if len(pixel) != self.wcs.pixel_n_dim: raise ValueError(f"Expected {self.wcs.pixel_n_dim} world coordinates, got {len(pixel)} ") if self.invert_xy: pixel = pixel[::-1] if len(pixel[0]) == 0: world = np.zeros((0, self.wcs.world_n_dim)) else: world = self.wcs.pixel_to_world_values(*pixel) if self.wcs.world_n_dim == 1: world = [world] # At the moment, one has to manually check that the transformation # round-trips, otherwise it should be considered invalid. pixel_check = self.wcs.world_to_pixel_values(*world) if self.wcs.pixel_n_dim == 1: pixel_check = [pixel_check] with np.errstate(invalid='ignore'): invalid = np.zeros(len(pixel[0]), dtype=bool) for ipix in range(len(pixel)): invalid |= np.abs(pixel_check[ipix] - pixel[ipix]) > 1. for iwrl in range(len(world)): world[iwrl][invalid] = np.nan world = np.array(world).T return world transform_non_affine = transform def inverted(self): """ Return the inverse of the transform """ return WCSWorld2PixelTransform(self.wcs, invert_xy=self.invert_xy)
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Accuracy tests for AltAz to ICRS coordinate transformations. We use "known good" examples computed with other coordinate libraries. Note that we use very low precision asserts because some people run tests on 32-bit machines and we want the tests to pass there. TODO: check if these tests pass on 32-bit machines and implement higher-precision checks on 64-bit machines. """ import pytest from astropy import units as u from astropy.time import Time from astropy.coordinates.builtin_frames import AltAz from astropy.coordinates import EarthLocation from astropy.coordinates import Angle, SkyCoord @pytest.mark.remote_data def test_against_hor2eq(): """Check that Astropy gives consistent results with an IDL hor2eq example. See : http://idlastro.gsfc.nasa.gov/ftp/pro/astro/hor2eq.pro Test is against these run outputs, run at 2000-01-01T12:00:00: # NORMAL ATMOSPHERE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=781.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 53 40 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 30.1 (hh:mm:ss) Ra, Dec: 07 36 55.6 +15 25 02 (Apparent Coords) Ra, Dec: 07 36 55.2 +15 25 08 (J2000.0000) Ra, Dec: 07 36 55.2 +15 25 08 (J2000) IDL> print, ra, dec 114.23004 15.418818 # NO PRESSURE CASE IDL> hor2eq, ten(37,54,41), ten(264,55,06), 2451545.0d, ra, dec, /verb, obs='kpno', pres=0.0, temp=273.0 Latitude = +31 57 48.0 Longitude = *** 36 00.0 Julian Date = 2451545.000000 Az, El = 17 39 40.4 +37 54 41 (Observer Coords) Az, El = 17 39 40.4 +37 54 41 (Apparent Coords) LMST = +11 15 26.5 LAST = +11 15 25.7 Hour Angle = +03 38 26.4 (hh:mm:ss) Ra, Dec: 07 36 59.3 +15 25 31 (Apparent Coords) Ra, Dec: 07 36 58.9 +15 25 37 (J2000.0000) Ra, Dec: 07 36 58.9 +15 25 37 (J2000) IDL> print, ra, dec 114.24554 15.427022 """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111d36.0m'), lat=Angle('31d57.8m'), height=2120. * u.m) obstime = Time(2451545.0, format='jd', scale='ut1') altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) altaz_frame_noatm = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.0 * u.bar) altaz = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame) altaz_noatm = SkyCoord('264d55m06s 37d54m41s', frame=altaz_frame_noatm) radec_frame = 'icrs' radec_actual = altaz.transform_to(radec_frame) radec_actual_noatm = altaz_noatm.transform_to(radec_frame) radec_expected = SkyCoord('07h36m55.2s +15d25m08s', frame=radec_frame) distance = radec_actual.separation(radec_expected).to('arcsec') # this comes from running the example hor2eq but with the pressure set to 0 radec_expected_noatm = SkyCoord('07h36m58.9s +15d25m37s', frame=radec_frame) distance_noatm = radec_actual_noatm.separation(radec_expected_noatm).to('arcsec') # The baseline difference is ~2.3 arcsec with one atm of pressure. The # difference is mainly due to the somewhat different atmospheric model that # hor2eq assumes. This is confirmed by the second test which has the # atmosphere "off" - the residual difference is small enough to be embedded # in the assumptions about "J2000" or rounding errors. assert distance < 5 * u.arcsec assert distance_noatm < 0.4 * u.arcsec @pytest.mark.remote_data def test_against_pyephem(): """Check that Astropy gives consistent results with one PyEphem example. PyEphem: http://rhodesmill.org/pyephem/ See example input and output here: https://gist.github.com/zonca/1672906 https://github.com/phn/pytpm/issues/2#issuecomment-3698679 """ obstime = Time('2011-09-18 08:50:00') location = EarthLocation(lon=Angle('-109d24m53.1s'), lat=Angle('33d41m46.0s'), height=30000. * u.m) # We are using the default pressure and temperature in PyEphem # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=15 * u.deg_C, pressure=1.010 * u.bar) altaz = SkyCoord('6.8927d -60.7665d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('196.497518d -4.569323d', frame='icrs') # EPHEM # radec_expected = SkyCoord('196.496220d -4.569390d', frame='icrs') # HORIZON distance = radec_actual.separation(radec_expected).to('arcsec') # TODO: why is this difference so large? # It currently is: 31.45187984720655 arcsec assert distance < 1e3 * u.arcsec # Add assert on current Astropy result so that we notice if something changes radec_expected = SkyCoord('196.495372d -4.560694d', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.0031402822944751997 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data def test_against_jpl_horizons(): """Check that Astropy gives consistent results with the JPL Horizons example. The input parameters and reference results are taken from this page: (from the first row of the Results table at the bottom of that page) http://ssd.jpl.nasa.gov/?horizons_tutorial """ obstime = Time('1998-07-28 03:00') location = EarthLocation(lon=Angle('248.405300d'), lat=Angle('31.9585d'), height=2.06 * u.km) # No atmosphere altaz_frame = AltAz(obstime=obstime, location=location) altaz = SkyCoord('143.2970d 2.6223d', frame=altaz_frame) radec_actual = altaz.transform_to('icrs') radec_expected = SkyCoord('19h24m55.01s -40d56m28.9s', frame='icrs') distance = radec_actual.separation(radec_expected).to('arcsec') # Current value: 0.238111 arcsec assert distance < 1 * u.arcsec @pytest.mark.remote_data @pytest.mark.xfail(reason="Current output is completely incorrect") def test_fk5_equinox_and_epoch_j2000_0_to_topocentric_observed(): """ http://phn.github.io/pytpm/conversions.html#fk5-equinox-and-epoch-j2000-0-to-topocentric-observed """ # Observatory position for `kpno` from here: # http://idlastro.gsfc.nasa.gov/ftp/pro/astro/observatory.pro location = EarthLocation(lon=Angle('-111.598333d'), lat=Angle('31.956389d'), height=2093.093 * u.m) # TODO: height correct? obstime = Time('2010-01-01 12:00:00') # relative_humidity = ? # obswl = ? altaz_frame = AltAz(obstime=obstime, location=location, temperature=0 * u.deg_C, pressure=0.781 * u.bar) radec = SkyCoord('12h22m54.899s 15d49m20.57s', frame='fk5') altaz_actual = radec.transform_to(altaz_frame) altaz_expected = SkyCoord('264d55m06s 37d54m41s', frame='altaz') # altaz_expected = SkyCoord('343.586827647d 15.7683070508d', frame='altaz') # altaz_expected = SkyCoord('133.498195532d 22.0162383595d', frame='altaz') distance = altaz_actual.separation(altaz_expected) # print(altaz_actual) # print(altaz_expected) # print(distance) """TODO: Current output is completely incorrect ... xfailing this test for now. <SkyCoord (AltAz: obstime=2010-01-01 12:00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron):00:00.000, location=(-1994497.7199061865, -5037954.447348028, 3357437.2294832403) m, pressure=781.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=133.4869896371561 deg, alt=67.97857990957701 deg> <SkyCoord (AltAz: obstime=None, location=None, pressure=0.0 hPa, temperature=0.0 deg_C, relative_humidity=0, obswl=1.0 micron): az=264.91833333333335 deg, alt=37.91138888888889 deg> 68d02m45.732s """ assert distance < 1 * u.arcsec
stargaser/astropy
astropy/coordinates/tests/accuracy/test_altaz_icrs.py
astropy/visualization/wcsaxes/wcsapi.py
from cupy import _core def _negative_gcd_error(): raise TypeError("gcd cannot be computed with boolean arrays") def _negative_lcm_error(): raise TypeError("lcm cannot be computed with boolean arrays") _gcd_preamble = ''' template <typename T> inline __device__ T gcd(T in0, T in1) { T r; while (in1 != 0) { r = in0 % in1; in0 = in1; in1 = r; } if (in0 < 0) return -in0; return in0; } ''' gcd = _core.create_ufunc( 'cupy_gcd', (('??->?', _negative_gcd_error), 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q'), 'out0 = gcd(in0, in1)', preamble=_gcd_preamble, doc='''Computes gcd of ``x1`` and ``x2`` elementwise. .. seealso:: :data:`numpy.gcd` ''') _lcm_preamble = _gcd_preamble + ''' template <typename T> inline __device__ T lcm(T in0, T in1) { T r = gcd(in0, in1); if (r == 0) return 0; r = in0 / r * in1; if (r < 0) return -r; return r; } ''' lcm = _core.create_ufunc( 'cupy_lcm', (('??->?', _negative_lcm_error), 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q'), 'out0 = lcm(in0, in1)', preamble=_lcm_preamble, doc='''Computes lcm of ``x1`` and ``x2`` elementwise. .. seealso:: :data:`numpy.lcm` ''')
import unittest import numpy import pytest import cupy import cupyx from cupyx import jit from cupy import testing from cupy.cuda import runtime class TestRaw(unittest.TestCase): def test_raw_grid_1D(self): @jit.rawkernel() def f(arr1, arr2): x = jit.grid(1) if x < arr1.size: arr2[x] = arr1[x] x = cupy.arange(10) y = cupy.empty_like(x) f((1,), (10,), (x, y)) assert (x == y).all() def test_raw_grid_2D(self): @jit.rawkernel() def f(arr1, arr2, n, m): x, y = jit.grid(2) # TODO(leofang): make it possible to write this: # if x < arr1.shape[0] and y < arr1.shape[1]: if x < n and y < m: arr2[x, y] = arr1[x, y] x = cupy.arange(20).reshape(4, 5) y = cupy.empty_like(x) f((1,), (4, 5), (x, y, x.shape[0], x.shape[1])) assert (x == y).all() def test_raw_grid_3D(self): @jit.rawkernel() def f(arr1, arr2, k, m, n): x, y, z = jit.grid(3) if x < k and y < m and z < n: arr2[x, y, z] = arr1[x, y, z] l, m, n = (2, 3, 4) x = cupy.arange(24).reshape(l, m, n) y = cupy.empty_like(x) f(((l+1)//2, (m+1)//2, (n+1)//2), (2, 2, 2), (x, y, l, m, n)) assert (x == y).all() def test_raw_grid_invalid1(self): @jit.rawkernel() def f(): x, = jit.grid(1) # cannot unpack an int with pytest.raises(ValueError): f((1,), (1,), ()) def test_raw_grid_invalid2(self): @jit.rawkernel() def f(): x = jit.grid(2) y = cupy.int64(x) # <- x is a tuple # NOQA # we don't care the exception type as long as something is raised with pytest.raises(Exception): f((1,), (1,), ()) def test_raw_grid_invalid3(self): for n in (0, 4, 'abc', [0], (1,)): @jit.rawkernel() def f(): x = jit.grid(n) # n can only be 1, 2, 3 (as int) # NOQA err = ValueError if isinstance(n, int) else TypeError with pytest.raises(err): f((1,), (1,), ()) def test_raw_one_thread(self): @jit.rawkernel() def f(x, y): y[0] = x[0] x = cupy.array([10], dtype=numpy.int32) y = cupy.array([20], dtype=numpy.int32) f((1,), (1,), (x, y)) assert int(y[0]) == 10 def test_raw_elementwise_single_op(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x y[tid] = x[tid] x = testing.shaped_random((30,), dtype=numpy.int32, seed=0) y = testing.shaped_random((30,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_elementwise_loop(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, numpy.uint32(1024))) assert bool((x == y).all()) def test_raw_multidimensional_array(self): @jit.rawkernel() def f(x, y, n_row, n_col): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x size = n_row * n_col for i in range(tid, size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, n, m)) assert bool((x == y).all()) def test_raw_multidimensional_array_with_attr(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x n_col = x.size // len(x) for i in range(tid, x.size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_ndim(self): @jit.rawkernel() def f(x, y): y[0] = x.ndim x = cupy.empty((1, 1, 1, 1, 1, 1, 1), dtype=numpy.int32) y = cupy.zeros((1,), dtype=numpy.int64) f((1,), (1,), (x, y)) assert y.item() == 7 def test_raw_0dim_array(self): @jit.rawkernel() def f(x, y): y[()] = x[()] x = testing.shaped_random((), dtype=numpy.int32, seed=0) y = testing.shaped_random((), dtype=numpy.int32, seed=1) f((1,), (1,), (x, y)) assert bool((x == y).all()) def test_min(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = min(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.minimum(x, cupy.minimum(y, z)) assert bool((r == expected).all()) def test_max(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = max(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.maximum(x, cupy.maximum(y, z)) assert bool((r == expected).all()) def test_syncthreads(self): @jit.rawkernel() def f(x, y, buf): tid = jit.threadIdx.x + jit.threadIdx.y * jit.blockDim.x ntid = jit.blockDim.x * jit.blockDim.y buf[tid] = x[ntid - tid - 1] jit.syncthreads() y[tid] = buf[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) buf = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) f((1,), (32, 32), (x, y, buf)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp(self): @jit.rawkernel() def f(x): laneId = jit.threadIdx.x & 0x1f if laneId < 16: x[laneId] = 1 else: x[laneId] = 2 jit.syncwarp() x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.ones_like(x) f((1,), (32,), (x,)) y[16:] += 1 assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp_mask(self): @jit.rawkernel() def f(x, m): laneId = jit.threadIdx.x & 0x1f if laneId < m: x[laneId] = 1 jit.syncwarp(mask=m) for mask in (2, 4, 8, 16, 32): x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.zeros_like(x) f((1,), (32,), (x, mask)) y[:mask] += 1 assert bool((x == y).all()) def test_shared_memory_static(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, 32) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y)) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) def test_shared_memory_dynamic(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, None) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y), shared_mem=128) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) @staticmethod def _check(a, e): if a.dtype == numpy.float16: testing.assert_allclose(a, e, rtol=3e-2, atol=3e-2) else: testing.assert_allclose(a, e, rtol=1e-5, atol=1e-5) @testing.for_dtypes('iILQfd' if runtime.is_hip else 'iILQefd') def test_atomic_add(self, dtype): @jit.rawkernel() def f(x, index, out): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x jit.atomic_add(out, index[tid], x[tid]) x = testing.shaped_random((1024,), dtype=dtype, seed=0) index = testing.shaped_random( (1024,), dtype=numpy.bool_, seed=1).astype(numpy.int32) out = cupy.zeros((2,), dtype=dtype) f((32,), (32,), (x, index, out)) expected = cupy.zeros((2,), dtype=dtype) cupyx.scatter_add(expected, index, x) self._check(out, expected) def test_raw_grid_block_interface(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f[5, 6](x, y, numpy.uint32(1024)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl(self, dtype): # strictly speaking this function is invalid in Python (see the # discussion in cupy/cupy#5340), but it serves for our purpose @jit.rawkernel() def f(a, b): laneId = jit.threadIdx.x & 0x1f if laneId == 0: value = a value = jit.shfl_sync(0xffffffff, value, 0) b[laneId] = value a = dtype(100) b = cupy.empty((32,), dtype=dtype) f[1, 32](a, b) assert (b == a * cupy.ones((32,), dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_shfl_width(self): @jit.rawkernel() def f(a, b, w): laneId = jit.threadIdx.x & 0x1f value = jit.shfl_sync(0xffffffff, b[jit.threadIdx.x], 0, width=w) b[laneId] = value c = cupy.arange(32, dtype=cupy.int32) for w in (2, 4, 8, 16, 32): a = cupy.int32(100) b = cupy.arange(32, dtype=cupy.int32) f[1, 32](a, b, w) c[c % w != 0] = c[c % w == 0] assert (b == c).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_up(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_up_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N)] + [i for i in range(32-N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_down(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_down_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N, 32)] + [(32-N+i) for i in range(N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_xor(self, dtype): @jit.rawkernel() def f_shfl_xor(a): laneId = jit.threadIdx.x & 0x1f value = 31 - laneId i = 16 while i >= 1: value += jit.shfl_xor_sync(0xffffffff, value, i) i //= 2 a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) b = a.copy() f_shfl_xor[1, 32](a) assert (a == b.sum() * cupy.ones(32, dtype=dtype)).all() def test_error_msg(self): @jit.rawkernel() def f(x): return unknown_var # NOQA import re mes = re.escape('''Unbound name: unknown_var @jit.rawkernel() def f(x): > return unknown_var # NOQA ''') x = cupy.zeros((10,), dtype=numpy.float32) with pytest.raises(NameError, match=mes): f((1,), (1,), (x,))
cupy/cupy
tests/cupyx_tests/jit_tests/test_raw.py
cupy/_math/rational.py
import numpy as _numpy from cupy_backends.cuda.api import runtime def bytes(length): """Returns random bytes. .. note:: This function is just a wrapper for :obj:`numpy.random.bytes`. The resulting bytes are generated on the host (NumPy), not GPU. .. seealso:: :meth:`numpy.random.bytes <numpy.random.mtrand.RandomState.bytes>` """ # TODO(kmaehashi): should it be provided in CuPy? return _numpy.random.bytes(length) def default_rng(seed=None): # NOQA avoid redefinition of seed """Construct a new Generator with the default BitGenerator (XORWOW). Args: seed (None, int, array_like[ints], numpy.random.SeedSequence, cupy.random.BitGenerator, cupy.random.Generator, optional): A seed to initialize the :class:`cupy.random.BitGenerator`. If an ``int`` or ``array_like[ints]`` or None is passed, then it will be passed to :class:`numpy.random.SeedSequence` to detive the initial :class:`BitGenerator` state. One may also pass in a `SeedSequence instance. Adiditionally, when passed :class:`BitGenerator`, it will be wrapped by :class:`Generator`. If passed a :class:`Generator`, it will be returned unaltered. Returns: Generator: The initialized generator object. """ # NOQA, list of types need to be in one line for sphinx if runtime.is_hip: raise RuntimeError('Generator API not supported in HIP,' ' please use the legacy one.') if isinstance(seed, BitGenerator): return Generator(seed) elif isinstance(seed, Generator): return seed return Generator(XORWOW(seed)) # import class and function from cupy.random._distributions import beta # NOQA from cupy.random._distributions import binomial # NOQA from cupy.random._distributions import chisquare # NOQA from cupy.random._distributions import dirichlet # NOQA from cupy.random._distributions import exponential # NOQA from cupy.random._distributions import f # NOQA from cupy.random._distributions import gamma # NOQA from cupy.random._distributions import geometric # NOQA from cupy.random._distributions import gumbel # NOQA from cupy.random._distributions import hypergeometric # NOQA from cupy.random._distributions import laplace # NOQA from cupy.random._distributions import logistic # NOQA from cupy.random._distributions import lognormal # NOQA from cupy.random._distributions import logseries # NOQA from cupy.random._distributions import multivariate_normal # NOQA from cupy.random._distributions import negative_binomial # NOQA from cupy.random._distributions import noncentral_chisquare # NOQA from cupy.random._distributions import noncentral_f # NOQA from cupy.random._distributions import normal # NOQA from cupy.random._distributions import pareto # NOQA from cupy.random._distributions import poisson # NOQA from cupy.random._distributions import power # NOQA from cupy.random._distributions import rayleigh # NOQA from cupy.random._distributions import standard_cauchy # NOQA from cupy.random._distributions import standard_exponential # NOQA from cupy.random._distributions import standard_gamma # NOQA from cupy.random._distributions import standard_normal # NOQA from cupy.random._distributions import standard_t # NOQA from cupy.random._distributions import triangular # NOQA from cupy.random._distributions import uniform # NOQA from cupy.random._distributions import vonmises # NOQA from cupy.random._distributions import wald # NOQA from cupy.random._distributions import weibull # NOQA from cupy.random._distributions import zipf # NOQA from cupy.random._generator import get_random_state # NOQA from cupy.random._generator import RandomState # NOQA from cupy.random._generator import reset_states # NOQA from cupy.random._generator import seed # NOQA from cupy.random._generator import set_random_state # NOQA from cupy.random._permutations import permutation # NOQA from cupy.random._permutations import shuffle # NOQA from cupy.random._sample import choice # NOQA from cupy.random._sample import multinomial # NOQA from cupy.random._sample import rand # NOQA from cupy.random._sample import randint # NOQA from cupy.random._sample import randn # NOQA from cupy.random._sample import random_integers # NOQA from cupy.random._sample import random_sample # NOQA from cupy.random._sample import random_sample as random # NOQA from cupy.random._sample import random_sample as ranf # NOQA from cupy.random._sample import random_sample as sample # NOQA if not runtime.is_hip: # This is disabled for HIP due to a problem when using # dynamic dispatching of kernels # see https://github.com/ROCm-Developer-Tools/HIP/issues/2186 from cupy.random._bit_generator import BitGenerator # NOQA from cupy.random._bit_generator import XORWOW # NOQA from cupy.random._bit_generator import MRG32k3a # NOQA from cupy.random._bit_generator import Philox4x3210 # NOQA from cupy.random._generator_api import Generator # NOQA
import unittest import numpy import pytest import cupy import cupyx from cupyx import jit from cupy import testing from cupy.cuda import runtime class TestRaw(unittest.TestCase): def test_raw_grid_1D(self): @jit.rawkernel() def f(arr1, arr2): x = jit.grid(1) if x < arr1.size: arr2[x] = arr1[x] x = cupy.arange(10) y = cupy.empty_like(x) f((1,), (10,), (x, y)) assert (x == y).all() def test_raw_grid_2D(self): @jit.rawkernel() def f(arr1, arr2, n, m): x, y = jit.grid(2) # TODO(leofang): make it possible to write this: # if x < arr1.shape[0] and y < arr1.shape[1]: if x < n and y < m: arr2[x, y] = arr1[x, y] x = cupy.arange(20).reshape(4, 5) y = cupy.empty_like(x) f((1,), (4, 5), (x, y, x.shape[0], x.shape[1])) assert (x == y).all() def test_raw_grid_3D(self): @jit.rawkernel() def f(arr1, arr2, k, m, n): x, y, z = jit.grid(3) if x < k and y < m and z < n: arr2[x, y, z] = arr1[x, y, z] l, m, n = (2, 3, 4) x = cupy.arange(24).reshape(l, m, n) y = cupy.empty_like(x) f(((l+1)//2, (m+1)//2, (n+1)//2), (2, 2, 2), (x, y, l, m, n)) assert (x == y).all() def test_raw_grid_invalid1(self): @jit.rawkernel() def f(): x, = jit.grid(1) # cannot unpack an int with pytest.raises(ValueError): f((1,), (1,), ()) def test_raw_grid_invalid2(self): @jit.rawkernel() def f(): x = jit.grid(2) y = cupy.int64(x) # <- x is a tuple # NOQA # we don't care the exception type as long as something is raised with pytest.raises(Exception): f((1,), (1,), ()) def test_raw_grid_invalid3(self): for n in (0, 4, 'abc', [0], (1,)): @jit.rawkernel() def f(): x = jit.grid(n) # n can only be 1, 2, 3 (as int) # NOQA err = ValueError if isinstance(n, int) else TypeError with pytest.raises(err): f((1,), (1,), ()) def test_raw_one_thread(self): @jit.rawkernel() def f(x, y): y[0] = x[0] x = cupy.array([10], dtype=numpy.int32) y = cupy.array([20], dtype=numpy.int32) f((1,), (1,), (x, y)) assert int(y[0]) == 10 def test_raw_elementwise_single_op(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x y[tid] = x[tid] x = testing.shaped_random((30,), dtype=numpy.int32, seed=0) y = testing.shaped_random((30,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_elementwise_loop(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, numpy.uint32(1024))) assert bool((x == y).all()) def test_raw_multidimensional_array(self): @jit.rawkernel() def f(x, y, n_row, n_col): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x size = n_row * n_col for i in range(tid, size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, n, m)) assert bool((x == y).all()) def test_raw_multidimensional_array_with_attr(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x n_col = x.size // len(x) for i in range(tid, x.size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_ndim(self): @jit.rawkernel() def f(x, y): y[0] = x.ndim x = cupy.empty((1, 1, 1, 1, 1, 1, 1), dtype=numpy.int32) y = cupy.zeros((1,), dtype=numpy.int64) f((1,), (1,), (x, y)) assert y.item() == 7 def test_raw_0dim_array(self): @jit.rawkernel() def f(x, y): y[()] = x[()] x = testing.shaped_random((), dtype=numpy.int32, seed=0) y = testing.shaped_random((), dtype=numpy.int32, seed=1) f((1,), (1,), (x, y)) assert bool((x == y).all()) def test_min(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = min(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.minimum(x, cupy.minimum(y, z)) assert bool((r == expected).all()) def test_max(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = max(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.maximum(x, cupy.maximum(y, z)) assert bool((r == expected).all()) def test_syncthreads(self): @jit.rawkernel() def f(x, y, buf): tid = jit.threadIdx.x + jit.threadIdx.y * jit.blockDim.x ntid = jit.blockDim.x * jit.blockDim.y buf[tid] = x[ntid - tid - 1] jit.syncthreads() y[tid] = buf[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) buf = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) f((1,), (32, 32), (x, y, buf)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp(self): @jit.rawkernel() def f(x): laneId = jit.threadIdx.x & 0x1f if laneId < 16: x[laneId] = 1 else: x[laneId] = 2 jit.syncwarp() x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.ones_like(x) f((1,), (32,), (x,)) y[16:] += 1 assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp_mask(self): @jit.rawkernel() def f(x, m): laneId = jit.threadIdx.x & 0x1f if laneId < m: x[laneId] = 1 jit.syncwarp(mask=m) for mask in (2, 4, 8, 16, 32): x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.zeros_like(x) f((1,), (32,), (x, mask)) y[:mask] += 1 assert bool((x == y).all()) def test_shared_memory_static(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, 32) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y)) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) def test_shared_memory_dynamic(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, None) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y), shared_mem=128) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) @staticmethod def _check(a, e): if a.dtype == numpy.float16: testing.assert_allclose(a, e, rtol=3e-2, atol=3e-2) else: testing.assert_allclose(a, e, rtol=1e-5, atol=1e-5) @testing.for_dtypes('iILQfd' if runtime.is_hip else 'iILQefd') def test_atomic_add(self, dtype): @jit.rawkernel() def f(x, index, out): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x jit.atomic_add(out, index[tid], x[tid]) x = testing.shaped_random((1024,), dtype=dtype, seed=0) index = testing.shaped_random( (1024,), dtype=numpy.bool_, seed=1).astype(numpy.int32) out = cupy.zeros((2,), dtype=dtype) f((32,), (32,), (x, index, out)) expected = cupy.zeros((2,), dtype=dtype) cupyx.scatter_add(expected, index, x) self._check(out, expected) def test_raw_grid_block_interface(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f[5, 6](x, y, numpy.uint32(1024)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl(self, dtype): # strictly speaking this function is invalid in Python (see the # discussion in cupy/cupy#5340), but it serves for our purpose @jit.rawkernel() def f(a, b): laneId = jit.threadIdx.x & 0x1f if laneId == 0: value = a value = jit.shfl_sync(0xffffffff, value, 0) b[laneId] = value a = dtype(100) b = cupy.empty((32,), dtype=dtype) f[1, 32](a, b) assert (b == a * cupy.ones((32,), dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_shfl_width(self): @jit.rawkernel() def f(a, b, w): laneId = jit.threadIdx.x & 0x1f value = jit.shfl_sync(0xffffffff, b[jit.threadIdx.x], 0, width=w) b[laneId] = value c = cupy.arange(32, dtype=cupy.int32) for w in (2, 4, 8, 16, 32): a = cupy.int32(100) b = cupy.arange(32, dtype=cupy.int32) f[1, 32](a, b, w) c[c % w != 0] = c[c % w == 0] assert (b == c).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_up(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_up_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N)] + [i for i in range(32-N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_down(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_down_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N, 32)] + [(32-N+i) for i in range(N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_xor(self, dtype): @jit.rawkernel() def f_shfl_xor(a): laneId = jit.threadIdx.x & 0x1f value = 31 - laneId i = 16 while i >= 1: value += jit.shfl_xor_sync(0xffffffff, value, i) i //= 2 a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) b = a.copy() f_shfl_xor[1, 32](a) assert (a == b.sum() * cupy.ones(32, dtype=dtype)).all() def test_error_msg(self): @jit.rawkernel() def f(x): return unknown_var # NOQA import re mes = re.escape('''Unbound name: unknown_var @jit.rawkernel() def f(x): > return unknown_var # NOQA ''') x = cupy.zeros((10,), dtype=numpy.float32) with pytest.raises(NameError, match=mes): f((1,), (1,), (x,))
cupy/cupy
tests/cupyx_tests/jit_tests/test_raw.py
cupy/random/__init__.py
import numpy try: import scipy.sparse _scipy_available = True except ImportError: _scipy_available = False import cupy from cupy import _core from cupy import cusparse from cupyx.scipy.sparse import base from cupyx.scipy.sparse import csc from cupyx.scipy.sparse import csr from cupyx.scipy.sparse import data as sparse_data from cupyx.scipy.sparse import _util from cupyx.scipy.sparse import sputils class coo_matrix(sparse_data._data_matrix): """COOrdinate format sparse matrix. This can be instantiated in several ways. ``coo_matrix(D)`` ``D`` is a rank-2 :class:`cupy.ndarray`. ``coo_matrix(S)`` ``S`` is another sparse matrix. It is equivalent to ``S.tocoo()``. ``coo_matrix((M, N), [dtype])`` It constructs an empty matrix whose shape is ``(M, N)``. Default dtype is float64. ``coo_matrix((data, (row, col)))`` All ``data``, ``row`` and ``col`` are one-dimenaional :class:`cupy.ndarray`. Args: arg1: Arguments for the initializer. shape (tuple): Shape of a matrix. Its length must be two. dtype: Data type. It must be an argument of :class:`numpy.dtype`. copy (bool): If ``True``, copies of given data are always used. .. seealso:: :class:`scipy.sparse.coo_matrix` """ format = 'coo' _sum_duplicates_diff = _core.ElementwiseKernel( 'raw T row, raw T col', 'T diff', ''' T diff_out = 1; if (i == 0 || row[i - 1] == row[i] && col[i - 1] == col[i]) { diff_out = 0; } diff = diff_out; ''', 'sum_duplicates_diff') def __init__(self, arg1, shape=None, dtype=None, copy=False): if shape is not None and len(shape) != 2: raise ValueError( 'Only two-dimensional sparse arrays are supported.') if base.issparse(arg1): x = arg1.asformat(self.format) data = x.data row = x.row col = x.col if arg1.format != self.format: # When formats are differnent, all arrays are already copied copy = False if shape is None: shape = arg1.shape self.has_canonical_format = x.has_canonical_format elif _util.isshape(arg1): m, n = arg1 m, n = int(m), int(n) data = cupy.zeros(0, dtype if dtype else 'd') row = cupy.zeros(0, dtype='i') col = cupy.zeros(0, dtype='i') # shape and copy argument is ignored shape = (m, n) copy = False self.has_canonical_format = True elif _scipy_available and scipy.sparse.issparse(arg1): # Convert scipy.sparse to cupyx.scipy.sparse x = arg1.tocoo() data = cupy.array(x.data) row = cupy.array(x.row, dtype='i') col = cupy.array(x.col, dtype='i') copy = False if shape is None: shape = arg1.shape self.has_canonical_format = x.has_canonical_format elif isinstance(arg1, tuple) and len(arg1) == 2: try: data, (row, col) = arg1 except (TypeError, ValueError): raise TypeError('invalid input format') if not (base.isdense(data) and data.ndim == 1 and base.isdense(row) and row.ndim == 1 and base.isdense(col) and col.ndim == 1): raise ValueError('row, column, and data arrays must be 1-D') if not (len(data) == len(row) == len(col)): raise ValueError( 'row, column, and data array must all be the same length') self.has_canonical_format = False elif base.isdense(arg1): if arg1.ndim > 2: raise TypeError('expected dimension <= 2 array or matrix') dense = cupy.atleast_2d(arg1) row, col = dense.nonzero() data = dense[row, col] shape = dense.shape self.has_canonical_format = True else: raise TypeError('invalid input format') if dtype is None: dtype = data.dtype else: dtype = numpy.dtype(dtype) if dtype != 'f' and dtype != 'd' and dtype != 'F' and dtype != 'D': raise ValueError( 'Only float32, float64, complex64 and complex128' ' are supported') data = data.astype(dtype, copy=copy) row = row.astype('i', copy=copy) col = col.astype('i', copy=copy) if shape is None: if len(row) == 0 or len(col) == 0: raise ValueError( 'cannot infer dimensions from zero sized index arrays') shape = (int(row.max()) + 1, int(col.max()) + 1) if len(data) > 0: if row.max() >= shape[0]: raise ValueError('row index exceeds matrix dimensions') if col.max() >= shape[1]: raise ValueError('column index exceeds matrix dimensions') if row.min() < 0: raise ValueError('negative row index found') if col.min() < 0: raise ValueError('negative column index found') sparse_data._data_matrix.__init__(self, data) self.row = row self.col = col if not _util.isshape(shape): raise ValueError('invalid shape (must be a 2-tuple of int)') self._shape = int(shape[0]), int(shape[1]) def _with_data(self, data, copy=True): """Returns a matrix with the same sparsity structure as self, but with different data. By default the index arrays (i.e. .row and .col) are copied. """ if copy: return coo_matrix( (data, (self.row.copy(), self.col.copy())), shape=self.shape, dtype=data.dtype) else: return coo_matrix( (data, (self.row, self.col)), shape=self.shape, dtype=data.dtype) def diagonal(self, k=0): """Returns the k-th diagonal of the matrix. Args: k (int, optional): Which diagonal to get, corresponding to elements a[i, i+k]. Default: 0 (the main diagonal). Returns: cupy.ndarray : The k-th diagonal. """ rows, cols = self.shape if k <= -rows or k >= cols: return cupy.empty(0, dtype=self.data.dtype) diag = cupy.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=self.dtype) diag_mask = (self.row + k) == self.col if self.has_canonical_format: row = self.row[diag_mask] data = self.data[diag_mask] else: row, _, data = self._sum_duplicates(self.row[diag_mask], self.col[diag_mask], self.data[diag_mask]) diag[row + min(k, 0)] = data return diag def setdiag(self, values, k=0): """Set diagonal or off-diagonal elements of the array. Args: values (ndarray): New values of the diagonal elements. Values may have any length. If the diagonal is longer than values, then the remaining diagonal entries will not be set. If values are longer than the diagonal, then the remaining values are ignored. If a scalar value is given, all of the diagonal is set to it. k (int, optional): Which off-diagonal to set, corresponding to elements a[i,i+k]. Default: 0 (the main diagonal). """ M, N = self.shape if (k > 0 and k >= N) or (k < 0 and -k >= M): raise ValueError("k exceeds matrix dimensions") if values.ndim and not len(values): return idx_dtype = self.row.dtype # Determine which triples to keep and where to put the new ones. full_keep = self.col - self.row != k if k < 0: max_index = min(M + k, N) if values.ndim: max_index = min(max_index, len(values)) keep = cupy.logical_or(full_keep, self.col >= max_index) new_row = cupy.arange(-k, -k + max_index, dtype=idx_dtype) new_col = cupy.arange(max_index, dtype=idx_dtype) else: max_index = min(M, N - k) if values.ndim: max_index = min(max_index, len(values)) keep = cupy.logical_or(full_keep, self.row >= max_index) new_row = cupy.arange(max_index, dtype=idx_dtype) new_col = cupy.arange(k, k + max_index, dtype=idx_dtype) # Define the array of data consisting of the entries to be added. if values.ndim: new_data = values[:max_index] else: new_data = cupy.empty(max_index, dtype=self.dtype) new_data[:] = values # Update the internal structure. self.row = cupy.concatenate((self.row[keep], new_row)) self.col = cupy.concatenate((self.col[keep], new_col)) self.data = cupy.concatenate((self.data[keep], new_data)) self.has_canonical_format = False def eliminate_zeros(self): """Removes zero entories in place.""" ind = self.data != 0 self.data = self.data[ind] self.row = self.row[ind] self.col = self.col[ind] def get_shape(self): """Returns the shape of the matrix. Returns: tuple: Shape of the matrix. """ return self._shape def getnnz(self, axis=None): """Returns the number of stored values, including explicit zeros.""" if axis is None: return self.data.size else: raise ValueError def get(self, stream=None): """Returns a copy of the array on host memory. Args: stream (cupy.cuda.Stream): CUDA stream object. If it is given, the copy runs asynchronously. Otherwise, the copy is synchronous. Returns: scipy.sparse.coo_matrix: Copy of the array on host memory. """ if not _scipy_available: raise RuntimeError('scipy is not available') data = self.data.get(stream) row = self.row.get(stream) col = self.col.get(stream) return scipy.sparse.coo_matrix( (data, (row, col)), shape=self.shape) def reshape(self, *shape, order='C'): """Gives a new shape to a sparse matrix without changing its data. Args: shape (tuple): The new shape should be compatible with the original shape. order: {'C', 'F'} (optional) Read the elements using this index order. 'C' means to read and write the elements using C-like index order. 'F' means to read and write the elements using Fortran-like index order. Default: C. Returns: cupyx.scipy.sparse.coo_matrix: sparse matrix """ shape = sputils.check_shape(shape, self.shape) if shape == self.shape: return self nrows, ncols = self.shape if order == 'C': # C to represent matrix in row major format dtype = sputils.get_index_dtype(maxval=(ncols * max(0, nrows - 1) + max(0, ncols - 1))) flat_indices = cupy.multiply(ncols, self.row, dtype=dtype) + self.col new_row, new_col = divmod(flat_indices, shape[1]) elif order == 'F': dtype = sputils.get_index_dtype(maxval=(ncols * max(0, nrows - 1) + max(0, ncols - 1))) flat_indices = cupy.multiply(ncols, self.row, dtype=dtype) + self.row new_col, new_row = divmod(flat_indices, shape[0]) else: raise ValueError("'order' must be 'C' or 'F'") new_data = self.data return coo_matrix((new_data, (new_row, new_col)), shape=shape, copy=False) def sum_duplicates(self): """Eliminate duplicate matrix entries by adding them together. .. warning:: When sorting the indices, CuPy follows the convention of cuSPARSE, which is different from that of SciPy. Therefore, the order of the output indices may differ: .. code-block:: python >>> # 1 0 0 >>> # A = 1 1 0 >>> # 1 1 1 >>> data = cupy.array([1, 1, 1, 1, 1, 1], 'f') >>> row = cupy.array([0, 1, 1, 2, 2, 2], 'i') >>> col = cupy.array([0, 0, 1, 0, 1, 2], 'i') >>> A = cupyx.scipy.sparse.coo_matrix((data, (row, col)), ... shape=(3, 3)) >>> a = A.get() >>> A.sum_duplicates() >>> a.sum_duplicates() # a is scipy.sparse.coo_matrix >>> A.row array([0, 1, 1, 2, 2, 2], dtype=int32) >>> a.row array([0, 1, 2, 1, 2, 2], dtype=int32) >>> A.col array([0, 0, 1, 0, 1, 2], dtype=int32) >>> a.col array([0, 0, 0, 1, 1, 2], dtype=int32) .. warning:: Calling this function might synchronize the device. .. seealso:: :meth:`scipy.sparse.coo_matrix.sum_duplicates` """ if self.has_canonical_format: return # Note: The sorting order below follows the cuSPARSE convention (first # row then col, so-called row-major) and differs from that of SciPy, as # the cuSPARSE functions such as cusparseSpMV() assume this sorting # order. # See https://docs.nvidia.com/cuda/cusparse/index.html#coo-format keys = cupy.stack([self.col, self.row]) order = cupy.lexsort(keys) src_data = self.data[order] src_row = self.row[order] src_col = self.col[order] diff = self._sum_duplicates_diff(src_row, src_col, size=self.row.size) if diff[1:].all(): # All elements have different indices. data = src_data row = src_row col = src_col else: # TODO(leofang): move the kernels outside this method index = cupy.cumsum(diff, dtype='i') size = int(index[-1]) + 1 data = cupy.zeros(size, dtype=self.data.dtype) row = cupy.empty(size, dtype='i') col = cupy.empty(size, dtype='i') if self.data.dtype.kind == 'f': cupy.ElementwiseKernel( 'T src_data, int32 src_row, int32 src_col, int32 index', 'raw T data, raw int32 row, raw int32 col', ''' atomicAdd(&data[index], src_data); row[index] = src_row; col[index] = src_col; ''', 'sum_duplicates_assign' )(src_data, src_row, src_col, index, data, row, col) elif self.data.dtype.kind == 'c': cupy.ElementwiseKernel( 'T src_real, T src_imag, int32 src_row, int32 src_col, ' 'int32 index', 'raw T real, raw T imag, raw int32 row, raw int32 col', ''' atomicAdd(&real[index], src_real); atomicAdd(&imag[index], src_imag); row[index] = src_row; col[index] = src_col; ''', 'sum_duplicates_assign_complex' )(src_data.real, src_data.imag, src_row, src_col, index, data.real, data.imag, row, col) self.data = data self.row = row self.col = col self.has_canonical_format = True def toarray(self, order=None, out=None): """Returns a dense matrix representing the same value. Args: order (str): Not supported. out: Not supported. Returns: cupy.ndarray: Dense array representing the same value. .. seealso:: :meth:`scipy.sparse.coo_matrix.toarray` """ return self.tocsr().toarray(order=order, out=out) def tocoo(self, copy=False): """Converts the matrix to COOdinate format. Args: copy (bool): If ``False``, it shares data arrays as much as possible. Returns: cupyx.scipy.sparse.coo_matrix: Converted matrix. """ if copy: return self.copy() else: return self def tocsc(self, copy=False): """Converts the matrix to Compressed Sparse Column format. Args: copy (bool): If ``False``, it shares data arrays as much as possible. Actually this option is ignored because all arrays in a matrix cannot be shared in coo to csc conversion. Returns: cupyx.scipy.sparse.csc_matrix: Converted matrix. """ if self.nnz == 0: return csc.csc_matrix(self.shape, dtype=self.dtype) # copy is silently ignored (in line with SciPy) because both # sum_duplicates and coosort change the underlying data x = self.copy() x.sum_duplicates() cusparse.coosort(x, 'c') x = cusparse.coo2csc(x) x.has_canonical_format = True return x def tocsr(self, copy=False): """Converts the matrix to Compressed Sparse Row format. Args: copy (bool): If ``False``, it shares data arrays as much as possible. Actually this option is ignored because all arrays in a matrix cannot be shared in coo to csr conversion. Returns: cupyx.scipy.sparse.csr_matrix: Converted matrix. """ if self.nnz == 0: return csr.csr_matrix(self.shape, dtype=self.dtype) # copy is silently ignored (in line with SciPy) because both # sum_duplicates and coosort change the underlying data x = self.copy() x.sum_duplicates() cusparse.coosort(x, 'r') x = cusparse.coo2csr(x) x.has_canonical_format = True return x def transpose(self, axes=None, copy=False): """Returns a transpose matrix. Args: axes: This option is not supported. copy (bool): If ``True``, a returned matrix shares no data. Otherwise, it shared data arrays as much as possible. Returns: cupyx.scipy.sparse.spmatrix: Transpose matrix. """ if axes is not None: raise ValueError( 'Sparse matrices do not support an \'axes\' parameter because ' 'swapping dimensions is the only logical permutation.') shape = self.shape[1], self.shape[0] return coo_matrix( (self.data, (self.col, self.row)), shape=shape, copy=copy) def isspmatrix_coo(x): """Checks if a given matrix is of COO format. Returns: bool: Returns if ``x`` is :class:`cupyx.scipy.sparse.coo_matrix`. """ return isinstance(x, coo_matrix)
import unittest import numpy import pytest import cupy import cupyx from cupyx import jit from cupy import testing from cupy.cuda import runtime class TestRaw(unittest.TestCase): def test_raw_grid_1D(self): @jit.rawkernel() def f(arr1, arr2): x = jit.grid(1) if x < arr1.size: arr2[x] = arr1[x] x = cupy.arange(10) y = cupy.empty_like(x) f((1,), (10,), (x, y)) assert (x == y).all() def test_raw_grid_2D(self): @jit.rawkernel() def f(arr1, arr2, n, m): x, y = jit.grid(2) # TODO(leofang): make it possible to write this: # if x < arr1.shape[0] and y < arr1.shape[1]: if x < n and y < m: arr2[x, y] = arr1[x, y] x = cupy.arange(20).reshape(4, 5) y = cupy.empty_like(x) f((1,), (4, 5), (x, y, x.shape[0], x.shape[1])) assert (x == y).all() def test_raw_grid_3D(self): @jit.rawkernel() def f(arr1, arr2, k, m, n): x, y, z = jit.grid(3) if x < k and y < m and z < n: arr2[x, y, z] = arr1[x, y, z] l, m, n = (2, 3, 4) x = cupy.arange(24).reshape(l, m, n) y = cupy.empty_like(x) f(((l+1)//2, (m+1)//2, (n+1)//2), (2, 2, 2), (x, y, l, m, n)) assert (x == y).all() def test_raw_grid_invalid1(self): @jit.rawkernel() def f(): x, = jit.grid(1) # cannot unpack an int with pytest.raises(ValueError): f((1,), (1,), ()) def test_raw_grid_invalid2(self): @jit.rawkernel() def f(): x = jit.grid(2) y = cupy.int64(x) # <- x is a tuple # NOQA # we don't care the exception type as long as something is raised with pytest.raises(Exception): f((1,), (1,), ()) def test_raw_grid_invalid3(self): for n in (0, 4, 'abc', [0], (1,)): @jit.rawkernel() def f(): x = jit.grid(n) # n can only be 1, 2, 3 (as int) # NOQA err = ValueError if isinstance(n, int) else TypeError with pytest.raises(err): f((1,), (1,), ()) def test_raw_one_thread(self): @jit.rawkernel() def f(x, y): y[0] = x[0] x = cupy.array([10], dtype=numpy.int32) y = cupy.array([20], dtype=numpy.int32) f((1,), (1,), (x, y)) assert int(y[0]) == 10 def test_raw_elementwise_single_op(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x y[tid] = x[tid] x = testing.shaped_random((30,), dtype=numpy.int32, seed=0) y = testing.shaped_random((30,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_elementwise_loop(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, numpy.uint32(1024))) assert bool((x == y).all()) def test_raw_multidimensional_array(self): @jit.rawkernel() def f(x, y, n_row, n_col): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x size = n_row * n_col for i in range(tid, size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y, n, m)) assert bool((x == y).all()) def test_raw_multidimensional_array_with_attr(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x n_col = x.size // len(x) for i in range(tid, x.size, ntid): i_row = i // n_col i_col = i % n_col y[i_row, i_col] = x[i_row, i_col] n, m = numpy.uint32(12), numpy.uint32(13) x = testing.shaped_random((n, m), dtype=numpy.int32, seed=0) y = testing.shaped_random((n, m), dtype=numpy.int32, seed=1) f((5,), (6,), (x, y)) assert bool((x == y).all()) def test_raw_ndim(self): @jit.rawkernel() def f(x, y): y[0] = x.ndim x = cupy.empty((1, 1, 1, 1, 1, 1, 1), dtype=numpy.int32) y = cupy.zeros((1,), dtype=numpy.int64) f((1,), (1,), (x, y)) assert y.item() == 7 def test_raw_0dim_array(self): @jit.rawkernel() def f(x, y): y[()] = x[()] x = testing.shaped_random((), dtype=numpy.int32, seed=0) y = testing.shaped_random((), dtype=numpy.int32, seed=1) f((1,), (1,), (x, y)) assert bool((x == y).all()) def test_min(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = min(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.minimum(x, cupy.minimum(y, z)) assert bool((r == expected).all()) def test_max(self): @jit.rawkernel() def f(x, y, z, r): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x r[tid] = max(x[tid], y[tid], z[tid]) x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3) f((8,), (128,), (x, y, z, r)) expected = cupy.maximum(x, cupy.maximum(y, z)) assert bool((r == expected).all()) def test_syncthreads(self): @jit.rawkernel() def f(x, y, buf): tid = jit.threadIdx.x + jit.threadIdx.y * jit.blockDim.x ntid = jit.blockDim.x * jit.blockDim.y buf[tid] = x[ntid - tid - 1] jit.syncthreads() y[tid] = buf[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) buf = testing.shaped_random((1024,), dtype=numpy.int32, seed=2) f((1,), (32, 32), (x, y, buf)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp(self): @jit.rawkernel() def f(x): laneId = jit.threadIdx.x & 0x1f if laneId < 16: x[laneId] = 1 else: x[laneId] = 2 jit.syncwarp() x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.ones_like(x) f((1,), (32,), (x,)) y[16:] += 1 assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_syncwarp_mask(self): @jit.rawkernel() def f(x, m): laneId = jit.threadIdx.x & 0x1f if laneId < m: x[laneId] = 1 jit.syncwarp(mask=m) for mask in (2, 4, 8, 16, 32): x = cupy.zeros((32,), dtype=numpy.int32) y = cupy.zeros_like(x) f((1,), (32,), (x, mask)) y[:mask] += 1 assert bool((x == y).all()) def test_shared_memory_static(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, 32) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y)) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) def test_shared_memory_dynamic(self): @jit.rawkernel() def f(x, y): tid = jit.threadIdx.x ntid = jit.blockDim.x bid = jit.blockIdx.x i = tid + bid * ntid smem = jit.shared_memory(numpy.int32, None) smem[tid] = x[i] jit.syncthreads() y[i] = smem[ntid - tid - 1] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f((32,), (32,), (x, y), shared_mem=128) expected = x.reshape(32, 32)[:, ::-1].ravel() assert bool((y == expected).all()) @staticmethod def _check(a, e): if a.dtype == numpy.float16: testing.assert_allclose(a, e, rtol=3e-2, atol=3e-2) else: testing.assert_allclose(a, e, rtol=1e-5, atol=1e-5) @testing.for_dtypes('iILQfd' if runtime.is_hip else 'iILQefd') def test_atomic_add(self, dtype): @jit.rawkernel() def f(x, index, out): tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x jit.atomic_add(out, index[tid], x[tid]) x = testing.shaped_random((1024,), dtype=dtype, seed=0) index = testing.shaped_random( (1024,), dtype=numpy.bool_, seed=1).astype(numpy.int32) out = cupy.zeros((2,), dtype=dtype) f((32,), (32,), (x, index, out)) expected = cupy.zeros((2,), dtype=dtype) cupyx.scatter_add(expected, index, x) self._check(out, expected) def test_raw_grid_block_interface(self): @jit.rawkernel() def f(x, y, size): tid = jit.threadIdx.x + jit.blockDim.x * jit.blockIdx.x ntid = jit.blockDim.x * jit.gridDim.x for i in range(tid, size, ntid): y[i] = x[i] x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0) y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1) f[5, 6](x, y, numpy.uint32(1024)) assert bool((x == y).all()) # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl(self, dtype): # strictly speaking this function is invalid in Python (see the # discussion in cupy/cupy#5340), but it serves for our purpose @jit.rawkernel() def f(a, b): laneId = jit.threadIdx.x & 0x1f if laneId == 0: value = a value = jit.shfl_sync(0xffffffff, value, 0) b[laneId] = value a = dtype(100) b = cupy.empty((32,), dtype=dtype) f[1, 32](a, b) assert (b == a * cupy.ones((32,), dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') def test_shfl_width(self): @jit.rawkernel() def f(a, b, w): laneId = jit.threadIdx.x & 0x1f value = jit.shfl_sync(0xffffffff, b[jit.threadIdx.x], 0, width=w) b[laneId] = value c = cupy.arange(32, dtype=cupy.int32) for w in (2, 4, 8, 16, 32): a = cupy.int32(100) b = cupy.arange(32, dtype=cupy.int32) f[1, 32](a, b, w) c[c % w != 0] = c[c % w == 0] assert (b == c).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_up(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_up_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N)] + [i for i in range(32-N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_down(self, dtype): N = 5 @jit.rawkernel() def f(a): value = jit.shfl_down_sync(0xffffffff, a[jit.threadIdx.x], N) a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) f[1, 32](a) expected = [i for i in range(N, 32)] + [(32-N+i) for i in range(N)] assert(a == cupy.asarray(expected, dtype=dtype)).all() # TODO(leofang): enable HIP when cupy/cupy#5348 is resolved @unittest.skipIf(runtime.is_hip, 'HIP is not yet supported') # TODO(leofang): test float16 ('e') once cupy/cupy#5346 is resolved @testing.for_dtypes('iIlqfd' if runtime.is_hip else 'iIlLqQfd') def test_shfl_xor(self, dtype): @jit.rawkernel() def f_shfl_xor(a): laneId = jit.threadIdx.x & 0x1f value = 31 - laneId i = 16 while i >= 1: value += jit.shfl_xor_sync(0xffffffff, value, i) i //= 2 a[jit.threadIdx.x] = value a = cupy.arange(32, dtype=dtype) b = a.copy() f_shfl_xor[1, 32](a) assert (a == b.sum() * cupy.ones(32, dtype=dtype)).all() def test_error_msg(self): @jit.rawkernel() def f(x): return unknown_var # NOQA import re mes = re.escape('''Unbound name: unknown_var @jit.rawkernel() def f(x): > return unknown_var # NOQA ''') x = cupy.zeros((10,), dtype=numpy.float32) with pytest.raises(NameError, match=mes): f((1,), (1,), (x,))
cupy/cupy
tests/cupyx_tests/jit_tests/test_raw.py
cupyx/scipy/sparse/coo.py
from typing import List, cast import numpy as np from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions from pandas.compat._optional import import_optional_dependency import pandas as pd from pandas.io.excel._base import BaseExcelReader class ODFReader(BaseExcelReader): """ Read tables out of OpenDocument formatted files. Parameters ---------- filepath_or_buffer : string, path to be parsed or an open readable stream. storage_options : dict, optional passed to fsspec for appropriate URLs (see ``_get_filepath_or_buffer``) """ def __init__( self, filepath_or_buffer: FilePathOrBuffer, storage_options: StorageOptions = None, ): import_optional_dependency("odf") super().__init__(filepath_or_buffer, storage_options=storage_options) @property def _workbook_class(self): from odf.opendocument import OpenDocument return OpenDocument def load_workbook(self, filepath_or_buffer: FilePathOrBuffer): from odf.opendocument import load return load(filepath_or_buffer) @property def empty_value(self) -> str: """Property for compat with other readers.""" return "" @property def sheet_names(self) -> List[str]: """Return a list of sheet names present in the document""" from odf.table import Table tables = self.book.getElementsByType(Table) return [t.getAttribute("name") for t in tables] def get_sheet_by_index(self, index: int): from odf.table import Table tables = self.book.getElementsByType(Table) return tables[index] def get_sheet_by_name(self, name: str): from odf.table import Table tables = self.book.getElementsByType(Table) for table in tables: if table.getAttribute("name") == name: return table self.close() raise ValueError(f"sheet {name} not found") def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: """ Parse an ODF Table into a list of lists """ from odf.table import CoveredTableCell, TableCell, TableRow covered_cell_name = CoveredTableCell().qname table_cell_name = TableCell().qname cell_names = {covered_cell_name, table_cell_name} sheet_rows = sheet.getElementsByType(TableRow) empty_rows = 0 max_row_len = 0 table: List[List[Scalar]] = [] for i, sheet_row in enumerate(sheet_rows): sheet_cells = [x for x in sheet_row.childNodes if x.qname in cell_names] empty_cells = 0 table_row: List[Scalar] = [] for j, sheet_cell in enumerate(sheet_cells): if sheet_cell.qname == table_cell_name: value = self._get_cell_value(sheet_cell, convert_float) else: value = self.empty_value column_repeat = self._get_column_repeat(sheet_cell) # Queue up empty values, writing only if content succeeds them if value == self.empty_value: empty_cells += column_repeat else: table_row.extend([self.empty_value] * empty_cells) empty_cells = 0 table_row.extend([value] * column_repeat) if max_row_len < len(table_row): max_row_len = len(table_row) row_repeat = self._get_row_repeat(sheet_row) if self._is_empty_row(sheet_row): empty_rows += row_repeat else: # add blank rows to our table table.extend([[self.empty_value]] * empty_rows) empty_rows = 0 for _ in range(row_repeat): table.append(table_row) # Make our table square for row in table: if len(row) < max_row_len: row.extend([self.empty_value] * (max_row_len - len(row))) return table def _get_row_repeat(self, row) -> int: """ Return number of times this row was repeated Repeating an empty row appeared to be a common way of representing sparse rows in the table. """ from odf.namespaces import TABLENS return int(row.attributes.get((TABLENS, "number-rows-repeated"), 1)) def _get_column_repeat(self, cell) -> int: from odf.namespaces import TABLENS return int(cell.attributes.get((TABLENS, "number-columns-repeated"), 1)) def _is_empty_row(self, row) -> bool: """ Helper function to find empty rows """ for column in row.childNodes: if len(column.childNodes) > 0: return False return True def _get_cell_value(self, cell, convert_float: bool) -> Scalar: from odf.namespaces import OFFICENS if str(cell) == "#N/A": return np.nan cell_type = cell.attributes.get((OFFICENS, "value-type")) if cell_type == "boolean": if str(cell) == "TRUE": return True return False if cell_type is None: return self.empty_value elif cell_type == "float": # GH5394 cell_value = float(cell.attributes.get((OFFICENS, "value"))) if convert_float: val = int(cell_value) if val == cell_value: return val return cell_value elif cell_type == "percentage": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "string": return self._get_cell_string_value(cell) elif cell_type == "currency": cell_value = cell.attributes.get((OFFICENS, "value")) return float(cell_value) elif cell_type == "date": cell_value = cell.attributes.get((OFFICENS, "date-value")) return pd.to_datetime(cell_value) elif cell_type == "time": result = pd.to_datetime(str(cell)) result = cast(pd.Timestamp, result) return result.time() else: self.close() raise ValueError(f"Unrecognized type {cell_type}") def _get_cell_string_value(self, cell) -> str: """ Find and decode OpenDocument text:s tags that represent a run length encoded sequence of space characters. """ from odf.element import Element from odf.namespaces import TEXTNS from odf.text import S text_s = S().qname value = [] for fragment in cell.childNodes: if isinstance(fragment, Element): if fragment.qname == text_s: spaces = int(fragment.attributes.get((TEXTNS, "c"), 1)) value.append(" " * spaces) else: # recursive impl needed in case of nested fragments # with multiple spaces # https://github.com/pandas-dev/pandas/pull/36175#discussion_r484639704 value.append(self._get_cell_string_value(fragment)) else: value.append(str(fragment)) return "".join(value)
import numpy as np import pytest import pandas as pd from pandas import ( CategoricalDtype, CategoricalIndex, DataFrame, Index, IntervalIndex, MultiIndex, Series, Timestamp, ) import pandas._testing as tm class TestDataFrameSortIndex: def test_sort_index_and_reconstruction_doc_example(self): # doc example df = DataFrame( {"value": [1, 2, 3, 4]}, index=MultiIndex( levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) assert df.index.is_lexsorted() assert not df.index.is_monotonic # sort it expected = DataFrame( {"value": [2, 1, 4, 3]}, index=MultiIndex( levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = df.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # reconstruct result = df.sort_index().copy() result.index = result.index._sort_levels_monotonic() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) def test_sort_index_non_existent_label_multiindex(self): # GH#12261 df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []])) df.loc["b", "2"] = 1 df.loc["a", "3"] = 1 result = df.sort_index().index.is_monotonic assert result is True def test_sort_index_reorder_on_ops(self): # GH#15687 df = DataFrame( np.random.randn(8, 2), index=MultiIndex.from_product( [["a", "b"], ["big", "small"], ["red", "blu"]], names=["letter", "size", "color"], ), columns=["near", "far"], ) df = df.sort_index() def my_func(group): group.index = ["newz", "newa"] return group result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() expected = MultiIndex.from_product( [["a", "b"], ["big", "small"], ["newa", "newz"]], names=["letter", "size", None], ) tm.assert_index_equal(result.index, expected) def test_sort_index_nan_multiindex(self): # GH#14784 # incorrect sorting w.r.t. nans tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] mi = MultiIndex.from_tuples(tuples) df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) s = Series(np.arange(4), index=mi) df2 = DataFrame( { "date": pd.DatetimeIndex( [ "20121002", "20121007", "20130130", "20130202", "20130305", "20121002", "20121207", "20130130", "20130202", "20130305", "20130202", "20130305", ] ), "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], "whole_cost": [ 1790, np.nan, 280, 259, np.nan, 623, 90, 312, np.nan, 301, 359, 801, ], "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], } ).set_index(["date", "user_id"]) # sorting frame, default nan position is last result = df.sort_index() expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position last result = df.sort_index(na_position="last") expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position first result = df.sort_index(na_position="first") expected = df.iloc[[1, 2, 3, 0], :] tm.assert_frame_equal(result, expected) # sorting frame with removed rows result = df2.dropna().sort_index() expected = df2.sort_index().dropna() tm.assert_frame_equal(result, expected) # sorting series, default nan position is last result = s.sort_index() expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position last result = s.sort_index(na_position="last") expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position first result = s.sort_index(na_position="first") expected = s.iloc[[1, 2, 3, 0]] tm.assert_series_equal(result, expected) def test_sort_index_nan(self): # GH#3917 # Test DataFrame with nan label df = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) # NaN label, ascending=True, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=True, na_position="last") expected = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=True, na_position='first' sorted_df = df.sort_index(na_position="first") expected = DataFrame( {"A": [4, 1, 2, np.nan, 1, 6, 8], "B": [5, 9, np.nan, 5, 2, 5, 4]}, index=[np.nan, 1, 2, 3, 4, 5, 6], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=False) expected = DataFrame( {"A": [8, 6, 1, np.nan, 2, 1, 4], "B": [4, 5, 2, 5, np.nan, 9, 5]}, index=[6, 5, 4, 3, 2, 1, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='first' sorted_df = df.sort_index( kind="quicksort", ascending=False, na_position="first" ) expected = DataFrame( {"A": [4, 8, 6, 1, np.nan, 2, 1], "B": [5, 4, 5, 2, 5, np.nan, 9]}, index=[np.nan, 6, 5, 4, 3, 2, 1], ) tm.assert_frame_equal(sorted_df, expected) def test_sort_index_multi_index(self): # GH#25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ) result = df.set_index(list("abc")).sort_index(level=list("ba")) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ) expected = expected.set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_inplace(self): frame = DataFrame( np.random.randn(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"] ) # axis=0 unordered = frame.loc[[3, 2, 4, 1]] a_id = id(unordered["A"]) df = unordered.copy() return_value = df.sort_index(inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) assert a_id != id(df["A"]) df = unordered.copy() return_value = df.sort_index(ascending=False, inplace=True) assert return_value is None expected = frame[::-1] tm.assert_frame_equal(df, expected) # axis=1 unordered = frame.loc[:, ["D", "B", "C", "A"]] df = unordered.copy() return_value = df.sort_index(axis=1, inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) df = unordered.copy() return_value = df.sort_index(axis=1, ascending=False, inplace=True) assert return_value is None expected = frame.iloc[:, ::-1] tm.assert_frame_equal(df, expected) def test_sort_index_different_sortorder(self): A = np.arange(20).repeat(5) B = np.tile(np.arange(5), 20) indexer = np.random.permutation(100) A = A.take(indexer) B = B.take(indexer) df = DataFrame({"A": A, "B": B, "C": np.random.randn(100)}) ex_indexer = np.lexsort((df.B.max() - df.B, df.A)) expected = df.take(ex_indexer) # test with multiindex, too idf = df.set_index(["A", "B"]) result = idf.sort_index(ascending=[1, 0]) expected = idf.take(ex_indexer) tm.assert_frame_equal(result, expected) # also, Series! result = idf["C"].sort_index(ascending=[1, 0]) tm.assert_series_equal(result, expected["C"]) def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) df = DataFrame([[1, 2], [3, 4]], mi) result = df.sort_index(level="A", sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) result = df.sort_index(level=["A", "B"], sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) # Error thrown by sort_index when # first index is sorted last (GH#26053) result = df.sort_index(level=["C", "B", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["B", "C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) def test_sort_index_categorical_index(self): df = DataFrame( { "A": np.arange(6, dtype="int64"), "B": Series(list("aabbca")).astype(CategoricalDtype(list("cab"))), } ).set_index("B") result = df.sort_index() expected = df.iloc[[4, 0, 1, 5, 2, 3]] tm.assert_frame_equal(result, expected) result = df.sort_index(ascending=False) expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) def test_sort_index(self): # GH#13496 frame = DataFrame( np.arange(16).reshape(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"], ) # axis=0 : sort rows by index labels unordered = frame.loc[[3, 2, 4, 1]] result = unordered.sort_index(axis=0) expected = frame tm.assert_frame_equal(result, expected) result = unordered.sort_index(ascending=False) expected = frame[::-1] tm.assert_frame_equal(result, expected) # axis=1 : sort columns by column names unordered = frame.iloc[:, [2, 1, 3, 0]] result = unordered.sort_index(axis=1) tm.assert_frame_equal(result, frame) result = unordered.sort_index(axis=1, ascending=False) expected = frame.iloc[:, ::-1] tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("level", ["A", 0]) # GH#21052 def test_sort_index_multiindex(self, level): # GH#13496 # sort rows by specified level of multi-index mi = MultiIndex.from_tuples( [[2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list("ABC") ) df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 2], [2, 1, 3]], names=list("ABC") ) expected = DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi) result = df.sort_index(level=level) tm.assert_frame_equal(result, expected) # sort_remaining=False expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 3], [2, 1, 2]], names=list("ABC") ) expected = DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi) result = df.sort_index(level=level, sort_remaining=False) tm.assert_frame_equal(result, expected) def test_sort_index_intervalindex(self): # this is a de-facto sort via unstack # confirming that we sort in the order of the bins y = Series(np.random.randn(100)) x1 = Series(np.sign(np.random.randn(100))) x2 = pd.cut(Series(np.random.randn(100)), bins=[-3, -0.5, 0, 0.5, 3]) model = pd.concat([y, x1, x2], axis=1, keys=["Y", "X1", "X2"]) result = model.groupby(["X1", "X2"], observed=True).mean().unstack() expected = IntervalIndex.from_tuples( [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right" ) result = result.columns.levels[1].categories tm.assert_index_equal(result, expected) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, False, [5, 3, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, False, [2, 3, 5]), ], ) def test_sort_index_ignore_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114 original_index = [2, 5, 3] df = DataFrame(original_dict, index=original_index) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index)) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, False, MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")), ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, False, MultiIndex.from_tuples([[3, 4], [2, 1]], names=list("AB")), ), ], ) def test_sort_index_ignore_index_multi_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114, this is to test ignore_index on MulitIndex of index mi = MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")) df = DataFrame(original_dict, index=mi) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=mi)) def test_sort_index_categorical_multiindex(self): # GH#15058 df = DataFrame( { "a": range(6), "l1": pd.Categorical( ["a", "a", "b", "b", "c", "c"], categories=["c", "a", "b"], ordered=True, ), "l2": [0, 1, 0, 1, 0, 1], } ) result = df.set_index(["l1", "l2"]).sort_index() expected = DataFrame( [4, 5, 0, 1, 2, 3], columns=["a"], index=MultiIndex( levels=[ CategoricalIndex( ["c", "a", "b"], categories=["c", "a", "b"], ordered=True, name="l1", dtype="category", ), [0, 1], ], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], names=["l1", "l2"], ), ) tm.assert_frame_equal(result, expected) def test_sort_index_and_reconstruction(self): # GH#15622 # lexsortedness should be identical # across MultiIndex construction methods df = DataFrame([[1, 1], [2, 2]], index=list("ab")) expected = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_tuples( [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] ), ) assert expected.index.is_lexsorted() result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_product([[0.5, 0.8], list("ab")]), ) result = result.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex( levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = result.sort_index() assert result.index.is_lexsorted() tm.assert_frame_equal(result, expected) concatted = pd.concat([df, df], keys=[0.8, 0.5]) result = concatted.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # GH#14015 df = DataFrame( [[1, 2], [6, 7]], columns=MultiIndex.from_tuples( [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], names=["l1", "Date"], ), ) df.columns = df.columns.set_levels( pd.to_datetime(df.columns.levels[1]), level=1 ) assert not df.columns.is_lexsorted() assert not df.columns.is_monotonic result = df.sort_index(axis=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic result = df.sort_index(axis=1, level=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic # TODO: better name, de-duplicate with test_sort_index_level above def test_sort_index_level2(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) df = frame.copy() df.index = np.arange(len(df)) # axis=1 # series a_sorted = frame["A"].sort_index(level=0) # preserve names assert a_sorted.index.names == frame.index.names # inplace rs = frame.copy() return_value = rs.sort_index(level=0, inplace=True) assert return_value is None tm.assert_frame_equal(rs, frame.sort_index(level=0)) def test_sort_index_level_large_cardinality(self): # GH#2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) # it works! result = df.sort_index(level=0) assert result.index.lexsort_depth == 3 # GH#2684 (int32) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) # it works! result = df.sort_index(level=0) assert (result.dtypes.values == df.dtypes.values).all() assert result.index.lexsort_depth == 3 def test_sort_index_level_by_name(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) frame.index.names = ["first", "second"] result = frame.sort_index(level="second") expected = frame.sort_index(level=1) tm.assert_frame_equal(result, expected) def test_sort_index_level_mixed(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) sorted_before = frame.sort_index(level=1) df = frame.copy() df["foo"] = "bar" sorted_after = df.sort_index(level=1) tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) dft = frame.T sorted_before = dft.sort_index(level=1, axis=1) dft["foo", "three"] = "bar" sorted_after = dft.sort_index(level=1, axis=1) tm.assert_frame_equal( sorted_before.drop([("foo", "three")], axis=1), sorted_after.drop([("foo", "three")], axis=1), ) def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data result = frame.sort_index() assert result.index.names == frame.index.names @pytest.mark.parametrize( "gen,extra", [ ([1.0, 3.0, 2.0, 5.0], 4.0), ([1, 3, 2, 5], 4), ( [ Timestamp("20130101"), Timestamp("20130103"), Timestamp("20130102"), Timestamp("20130105"), ], Timestamp("20130104"), ), (["1one", "3one", "2one", "5one"], "4one"), ], ) def test_sort_index_multilevel_repr_8017(self, gen, extra): np.random.seed(0) data = np.random.randn(3, 4) columns = MultiIndex.from_tuples([("red", i) for i in gen]) df = DataFrame(data, index=list("def"), columns=columns) df2 = pd.concat( [ df, DataFrame( "world", index=list("def"), columns=MultiIndex.from_tuples([("red", extra)]), ), ], axis=1, ) # check that the repr is good # make sure that we have a correct sparsified repr # e.g. only 1 header of read assert str(df2).splitlines()[0].split() == ["red"] # GH 8017 # sorting fails after columns added # construct single-dtype then sort result = df.copy().sort_index(axis=1) expected = df.iloc[:, [0, 2, 1, 3]] tm.assert_frame_equal(result, expected) result = df2.sort_index(axis=1) expected = df2.iloc[:, [0, 2, 1, 4, 3]] tm.assert_frame_equal(result, expected) # setitem then sort result = df.copy() result[("red", extra)] = "world" result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "categories", [ pytest.param(["a", "b", "c"], id="str"), pytest.param( [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], id="pd.Interval", ), ], ) def test_sort_index_with_categories(self, categories): # GH#23452 df = DataFrame( {"foo": range(len(categories))}, index=CategoricalIndex( data=categories, categories=categories, ordered=True ), ) df.index = df.index.reorder_categories(df.index.categories[::-1]) result = df.sort_index() expected = DataFrame( {"foo": reversed(range(len(categories)))}, index=CategoricalIndex( data=categories[::-1], categories=categories[::-1], ordered=True ), ) tm.assert_frame_equal(result, expected) class TestDataFrameSortIndexKey: def test_sort_multi_index_key(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ).set_index(list("abc")) result = df.sort_index(level=list("ac"), key=lambda x: x) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index(level=list("ac"), key=lambda x: -x) expected = DataFrame( {"a": [3, 2, 1], "b": [0, 0, 0], "c": [0, 2, 1], "d": list("acb")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_key(self): # issue 27237 df = DataFrame(np.arange(6, dtype="int64"), index=list("aaBBca")) result = df.sort_index() expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower()) expected = df.iloc[[0, 1, 5, 2, 3, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower(), ascending=False) expected = df.iloc[[4, 2, 3, 0, 1, 5]] tm.assert_frame_equal(result, expected) def test_sort_index_key_int(self): df = DataFrame(np.arange(6, dtype="int64"), index=np.arange(6, dtype="int64")) result = df.sort_index() tm.assert_frame_equal(result, df) result = df.sort_index(key=lambda x: -x) expected = df.sort_index(ascending=False) tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: 2 * x) tm.assert_frame_equal(result, df) def test_sort_multi_index_key_str(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": ["B", "a", "C"], "b": [0, 1, 0], "c": list("abc"), "d": [0, 1, 2]} ).set_index(list("abc")) result = df.sort_index(level="a", key=lambda x: x.str.lower()) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index( level=list("abc"), # can refer to names key=lambda x: x.str.lower() if x.name in ["a", "c"] else -x, ) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_changes_length_raises(self): df = DataFrame({"A": [1, 2, 3]}) with pytest.raises(ValueError, match="change the shape"): df.sort_index(key=lambda x: x[:1]) def test_sort_index_multiindex_sparse_column(self): # GH 29735, testing that sort_index on a multiindexed frame with sparse # columns fills with 0. expected = DataFrame( { i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) for i in range(0, 4) }, index=MultiIndex.from_product([[1, 2], [1, 2]]), ) result = expected.sort_index(level=0) tm.assert_frame_equal(result, expected)
jreback/pandas
pandas/tests/frame/methods/test_sort_index.py
pandas/io/excel/_odfreader.py
""" Helpers for configuring locale settings. Name `localization` is chosen to avoid overlap with builtin `locale` module. """ from contextlib import contextmanager import locale import re import subprocess from pandas._config.config import options @contextmanager def set_locale(new_locale, lc_var: int = locale.LC_ALL): """ Context manager for temporarily setting a locale. Parameters ---------- new_locale : str or tuple A string of the form <language_country>.<encoding>. For example to set the current locale to US English with a UTF8 encoding, you would pass "en_US.UTF-8". lc_var : int, default `locale.LC_ALL` The category of the locale being set. Notes ----- This is useful when you want to run a particular block of code under a particular locale, without globally setting the locale. This probably isn't thread-safe. """ current_locale = locale.getlocale() try: locale.setlocale(lc_var, new_locale) normalized_locale = locale.getlocale() if all(x is not None for x in normalized_locale): yield ".".join(normalized_locale) else: yield new_locale finally: locale.setlocale(lc_var, current_locale) def can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool: """ Check to see if we can set a locale, and subsequently get the locale, without raising an Exception. Parameters ---------- lc : str The locale to attempt to set. lc_var : int, default `locale.LC_ALL` The category of the locale being set. Returns ------- bool Whether the passed locale can be set """ try: with set_locale(lc, lc_var=lc_var): pass except (ValueError, locale.Error): # horrible name for a Exception subclass return False else: return True def _valid_locales(locales, normalize): """ Return a list of normalized locales that do not throw an ``Exception`` when set. Parameters ---------- locales : str A string where each locale is separated by a newline. normalize : bool Whether to call ``locale.normalize`` on each locale. Returns ------- valid_locales : list A list of valid locales. """ return [ loc for loc in ( locale.normalize(loc.strip()) if normalize else loc.strip() for loc in locales ) if can_set_locale(loc) ] def _default_locale_getter(): return subprocess.check_output(["locale -a"], shell=True) def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter): """ Get all the locales that are available on the system. Parameters ---------- prefix : str If not ``None`` then return only those locales with the prefix provided. For example to get all English language locales (those that start with ``"en"``), pass ``prefix="en"``. normalize : bool Call ``locale.normalize`` on the resulting list of available locales. If ``True``, only locales that can be set without throwing an ``Exception`` are returned. locale_getter : callable The function to use to retrieve the current locales. This should return a string with each locale separated by a newline character. Returns ------- locales : list of strings A list of locale strings that can be set with ``locale.setlocale()``. For example:: locale.setlocale(locale.LC_ALL, locale_string) On error will return None (no locale available, e.g. Windows) """ try: raw_locales = locale_getter() except subprocess.CalledProcessError: # Raised on (some? all?) Windows platforms because Note: "locale -a" # is not defined return None try: # raw_locales is "\n" separated list of locales # it may contain non-decodable parts, so split # extract what we can and then rejoin. raw_locales = raw_locales.split(b"\n") out_locales = [] for x in raw_locales: try: out_locales.append(str(x, encoding=options.display.encoding)) except UnicodeError: # 'locale -a' is used to populated 'raw_locales' and on # Redhat 7 Linux (and maybe others) prints locale names # using windows-1252 encoding. Bug only triggered by # a few special characters and when there is an # extensive list of installed locales. out_locales.append(str(x, encoding="windows-1252")) except TypeError: pass if prefix is None: return _valid_locales(out_locales, normalize) pattern = re.compile(f"{prefix}.*") found = pattern.findall("\n".join(out_locales)) return _valid_locales(found, normalize)
import numpy as np import pytest import pandas as pd from pandas import ( CategoricalDtype, CategoricalIndex, DataFrame, Index, IntervalIndex, MultiIndex, Series, Timestamp, ) import pandas._testing as tm class TestDataFrameSortIndex: def test_sort_index_and_reconstruction_doc_example(self): # doc example df = DataFrame( {"value": [1, 2, 3, 4]}, index=MultiIndex( levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) assert df.index.is_lexsorted() assert not df.index.is_monotonic # sort it expected = DataFrame( {"value": [2, 1, 4, 3]}, index=MultiIndex( levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = df.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # reconstruct result = df.sort_index().copy() result.index = result.index._sort_levels_monotonic() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) def test_sort_index_non_existent_label_multiindex(self): # GH#12261 df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []])) df.loc["b", "2"] = 1 df.loc["a", "3"] = 1 result = df.sort_index().index.is_monotonic assert result is True def test_sort_index_reorder_on_ops(self): # GH#15687 df = DataFrame( np.random.randn(8, 2), index=MultiIndex.from_product( [["a", "b"], ["big", "small"], ["red", "blu"]], names=["letter", "size", "color"], ), columns=["near", "far"], ) df = df.sort_index() def my_func(group): group.index = ["newz", "newa"] return group result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() expected = MultiIndex.from_product( [["a", "b"], ["big", "small"], ["newa", "newz"]], names=["letter", "size", None], ) tm.assert_index_equal(result.index, expected) def test_sort_index_nan_multiindex(self): # GH#14784 # incorrect sorting w.r.t. nans tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] mi = MultiIndex.from_tuples(tuples) df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) s = Series(np.arange(4), index=mi) df2 = DataFrame( { "date": pd.DatetimeIndex( [ "20121002", "20121007", "20130130", "20130202", "20130305", "20121002", "20121207", "20130130", "20130202", "20130305", "20130202", "20130305", ] ), "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], "whole_cost": [ 1790, np.nan, 280, 259, np.nan, 623, 90, 312, np.nan, 301, 359, 801, ], "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], } ).set_index(["date", "user_id"]) # sorting frame, default nan position is last result = df.sort_index() expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position last result = df.sort_index(na_position="last") expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position first result = df.sort_index(na_position="first") expected = df.iloc[[1, 2, 3, 0], :] tm.assert_frame_equal(result, expected) # sorting frame with removed rows result = df2.dropna().sort_index() expected = df2.sort_index().dropna() tm.assert_frame_equal(result, expected) # sorting series, default nan position is last result = s.sort_index() expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position last result = s.sort_index(na_position="last") expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position first result = s.sort_index(na_position="first") expected = s.iloc[[1, 2, 3, 0]] tm.assert_series_equal(result, expected) def test_sort_index_nan(self): # GH#3917 # Test DataFrame with nan label df = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) # NaN label, ascending=True, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=True, na_position="last") expected = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=True, na_position='first' sorted_df = df.sort_index(na_position="first") expected = DataFrame( {"A": [4, 1, 2, np.nan, 1, 6, 8], "B": [5, 9, np.nan, 5, 2, 5, 4]}, index=[np.nan, 1, 2, 3, 4, 5, 6], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=False) expected = DataFrame( {"A": [8, 6, 1, np.nan, 2, 1, 4], "B": [4, 5, 2, 5, np.nan, 9, 5]}, index=[6, 5, 4, 3, 2, 1, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='first' sorted_df = df.sort_index( kind="quicksort", ascending=False, na_position="first" ) expected = DataFrame( {"A": [4, 8, 6, 1, np.nan, 2, 1], "B": [5, 4, 5, 2, 5, np.nan, 9]}, index=[np.nan, 6, 5, 4, 3, 2, 1], ) tm.assert_frame_equal(sorted_df, expected) def test_sort_index_multi_index(self): # GH#25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ) result = df.set_index(list("abc")).sort_index(level=list("ba")) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ) expected = expected.set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_inplace(self): frame = DataFrame( np.random.randn(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"] ) # axis=0 unordered = frame.loc[[3, 2, 4, 1]] a_id = id(unordered["A"]) df = unordered.copy() return_value = df.sort_index(inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) assert a_id != id(df["A"]) df = unordered.copy() return_value = df.sort_index(ascending=False, inplace=True) assert return_value is None expected = frame[::-1] tm.assert_frame_equal(df, expected) # axis=1 unordered = frame.loc[:, ["D", "B", "C", "A"]] df = unordered.copy() return_value = df.sort_index(axis=1, inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) df = unordered.copy() return_value = df.sort_index(axis=1, ascending=False, inplace=True) assert return_value is None expected = frame.iloc[:, ::-1] tm.assert_frame_equal(df, expected) def test_sort_index_different_sortorder(self): A = np.arange(20).repeat(5) B = np.tile(np.arange(5), 20) indexer = np.random.permutation(100) A = A.take(indexer) B = B.take(indexer) df = DataFrame({"A": A, "B": B, "C": np.random.randn(100)}) ex_indexer = np.lexsort((df.B.max() - df.B, df.A)) expected = df.take(ex_indexer) # test with multiindex, too idf = df.set_index(["A", "B"]) result = idf.sort_index(ascending=[1, 0]) expected = idf.take(ex_indexer) tm.assert_frame_equal(result, expected) # also, Series! result = idf["C"].sort_index(ascending=[1, 0]) tm.assert_series_equal(result, expected["C"]) def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) df = DataFrame([[1, 2], [3, 4]], mi) result = df.sort_index(level="A", sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) result = df.sort_index(level=["A", "B"], sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) # Error thrown by sort_index when # first index is sorted last (GH#26053) result = df.sort_index(level=["C", "B", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["B", "C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) def test_sort_index_categorical_index(self): df = DataFrame( { "A": np.arange(6, dtype="int64"), "B": Series(list("aabbca")).astype(CategoricalDtype(list("cab"))), } ).set_index("B") result = df.sort_index() expected = df.iloc[[4, 0, 1, 5, 2, 3]] tm.assert_frame_equal(result, expected) result = df.sort_index(ascending=False) expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) def test_sort_index(self): # GH#13496 frame = DataFrame( np.arange(16).reshape(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"], ) # axis=0 : sort rows by index labels unordered = frame.loc[[3, 2, 4, 1]] result = unordered.sort_index(axis=0) expected = frame tm.assert_frame_equal(result, expected) result = unordered.sort_index(ascending=False) expected = frame[::-1] tm.assert_frame_equal(result, expected) # axis=1 : sort columns by column names unordered = frame.iloc[:, [2, 1, 3, 0]] result = unordered.sort_index(axis=1) tm.assert_frame_equal(result, frame) result = unordered.sort_index(axis=1, ascending=False) expected = frame.iloc[:, ::-1] tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("level", ["A", 0]) # GH#21052 def test_sort_index_multiindex(self, level): # GH#13496 # sort rows by specified level of multi-index mi = MultiIndex.from_tuples( [[2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list("ABC") ) df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 2], [2, 1, 3]], names=list("ABC") ) expected = DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi) result = df.sort_index(level=level) tm.assert_frame_equal(result, expected) # sort_remaining=False expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 3], [2, 1, 2]], names=list("ABC") ) expected = DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi) result = df.sort_index(level=level, sort_remaining=False) tm.assert_frame_equal(result, expected) def test_sort_index_intervalindex(self): # this is a de-facto sort via unstack # confirming that we sort in the order of the bins y = Series(np.random.randn(100)) x1 = Series(np.sign(np.random.randn(100))) x2 = pd.cut(Series(np.random.randn(100)), bins=[-3, -0.5, 0, 0.5, 3]) model = pd.concat([y, x1, x2], axis=1, keys=["Y", "X1", "X2"]) result = model.groupby(["X1", "X2"], observed=True).mean().unstack() expected = IntervalIndex.from_tuples( [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right" ) result = result.columns.levels[1].categories tm.assert_index_equal(result, expected) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, False, [5, 3, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, False, [2, 3, 5]), ], ) def test_sort_index_ignore_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114 original_index = [2, 5, 3] df = DataFrame(original_dict, index=original_index) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index)) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, False, MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")), ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, False, MultiIndex.from_tuples([[3, 4], [2, 1]], names=list("AB")), ), ], ) def test_sort_index_ignore_index_multi_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114, this is to test ignore_index on MulitIndex of index mi = MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")) df = DataFrame(original_dict, index=mi) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=mi)) def test_sort_index_categorical_multiindex(self): # GH#15058 df = DataFrame( { "a": range(6), "l1": pd.Categorical( ["a", "a", "b", "b", "c", "c"], categories=["c", "a", "b"], ordered=True, ), "l2": [0, 1, 0, 1, 0, 1], } ) result = df.set_index(["l1", "l2"]).sort_index() expected = DataFrame( [4, 5, 0, 1, 2, 3], columns=["a"], index=MultiIndex( levels=[ CategoricalIndex( ["c", "a", "b"], categories=["c", "a", "b"], ordered=True, name="l1", dtype="category", ), [0, 1], ], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], names=["l1", "l2"], ), ) tm.assert_frame_equal(result, expected) def test_sort_index_and_reconstruction(self): # GH#15622 # lexsortedness should be identical # across MultiIndex construction methods df = DataFrame([[1, 1], [2, 2]], index=list("ab")) expected = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_tuples( [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] ), ) assert expected.index.is_lexsorted() result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_product([[0.5, 0.8], list("ab")]), ) result = result.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex( levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = result.sort_index() assert result.index.is_lexsorted() tm.assert_frame_equal(result, expected) concatted = pd.concat([df, df], keys=[0.8, 0.5]) result = concatted.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # GH#14015 df = DataFrame( [[1, 2], [6, 7]], columns=MultiIndex.from_tuples( [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], names=["l1", "Date"], ), ) df.columns = df.columns.set_levels( pd.to_datetime(df.columns.levels[1]), level=1 ) assert not df.columns.is_lexsorted() assert not df.columns.is_monotonic result = df.sort_index(axis=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic result = df.sort_index(axis=1, level=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic # TODO: better name, de-duplicate with test_sort_index_level above def test_sort_index_level2(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) df = frame.copy() df.index = np.arange(len(df)) # axis=1 # series a_sorted = frame["A"].sort_index(level=0) # preserve names assert a_sorted.index.names == frame.index.names # inplace rs = frame.copy() return_value = rs.sort_index(level=0, inplace=True) assert return_value is None tm.assert_frame_equal(rs, frame.sort_index(level=0)) def test_sort_index_level_large_cardinality(self): # GH#2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) # it works! result = df.sort_index(level=0) assert result.index.lexsort_depth == 3 # GH#2684 (int32) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) # it works! result = df.sort_index(level=0) assert (result.dtypes.values == df.dtypes.values).all() assert result.index.lexsort_depth == 3 def test_sort_index_level_by_name(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) frame.index.names = ["first", "second"] result = frame.sort_index(level="second") expected = frame.sort_index(level=1) tm.assert_frame_equal(result, expected) def test_sort_index_level_mixed(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) sorted_before = frame.sort_index(level=1) df = frame.copy() df["foo"] = "bar" sorted_after = df.sort_index(level=1) tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) dft = frame.T sorted_before = dft.sort_index(level=1, axis=1) dft["foo", "three"] = "bar" sorted_after = dft.sort_index(level=1, axis=1) tm.assert_frame_equal( sorted_before.drop([("foo", "three")], axis=1), sorted_after.drop([("foo", "three")], axis=1), ) def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data result = frame.sort_index() assert result.index.names == frame.index.names @pytest.mark.parametrize( "gen,extra", [ ([1.0, 3.0, 2.0, 5.0], 4.0), ([1, 3, 2, 5], 4), ( [ Timestamp("20130101"), Timestamp("20130103"), Timestamp("20130102"), Timestamp("20130105"), ], Timestamp("20130104"), ), (["1one", "3one", "2one", "5one"], "4one"), ], ) def test_sort_index_multilevel_repr_8017(self, gen, extra): np.random.seed(0) data = np.random.randn(3, 4) columns = MultiIndex.from_tuples([("red", i) for i in gen]) df = DataFrame(data, index=list("def"), columns=columns) df2 = pd.concat( [ df, DataFrame( "world", index=list("def"), columns=MultiIndex.from_tuples([("red", extra)]), ), ], axis=1, ) # check that the repr is good # make sure that we have a correct sparsified repr # e.g. only 1 header of read assert str(df2).splitlines()[0].split() == ["red"] # GH 8017 # sorting fails after columns added # construct single-dtype then sort result = df.copy().sort_index(axis=1) expected = df.iloc[:, [0, 2, 1, 3]] tm.assert_frame_equal(result, expected) result = df2.sort_index(axis=1) expected = df2.iloc[:, [0, 2, 1, 4, 3]] tm.assert_frame_equal(result, expected) # setitem then sort result = df.copy() result[("red", extra)] = "world" result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "categories", [ pytest.param(["a", "b", "c"], id="str"), pytest.param( [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], id="pd.Interval", ), ], ) def test_sort_index_with_categories(self, categories): # GH#23452 df = DataFrame( {"foo": range(len(categories))}, index=CategoricalIndex( data=categories, categories=categories, ordered=True ), ) df.index = df.index.reorder_categories(df.index.categories[::-1]) result = df.sort_index() expected = DataFrame( {"foo": reversed(range(len(categories)))}, index=CategoricalIndex( data=categories[::-1], categories=categories[::-1], ordered=True ), ) tm.assert_frame_equal(result, expected) class TestDataFrameSortIndexKey: def test_sort_multi_index_key(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ).set_index(list("abc")) result = df.sort_index(level=list("ac"), key=lambda x: x) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index(level=list("ac"), key=lambda x: -x) expected = DataFrame( {"a": [3, 2, 1], "b": [0, 0, 0], "c": [0, 2, 1], "d": list("acb")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_key(self): # issue 27237 df = DataFrame(np.arange(6, dtype="int64"), index=list("aaBBca")) result = df.sort_index() expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower()) expected = df.iloc[[0, 1, 5, 2, 3, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower(), ascending=False) expected = df.iloc[[4, 2, 3, 0, 1, 5]] tm.assert_frame_equal(result, expected) def test_sort_index_key_int(self): df = DataFrame(np.arange(6, dtype="int64"), index=np.arange(6, dtype="int64")) result = df.sort_index() tm.assert_frame_equal(result, df) result = df.sort_index(key=lambda x: -x) expected = df.sort_index(ascending=False) tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: 2 * x) tm.assert_frame_equal(result, df) def test_sort_multi_index_key_str(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": ["B", "a", "C"], "b": [0, 1, 0], "c": list("abc"), "d": [0, 1, 2]} ).set_index(list("abc")) result = df.sort_index(level="a", key=lambda x: x.str.lower()) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index( level=list("abc"), # can refer to names key=lambda x: x.str.lower() if x.name in ["a", "c"] else -x, ) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_changes_length_raises(self): df = DataFrame({"A": [1, 2, 3]}) with pytest.raises(ValueError, match="change the shape"): df.sort_index(key=lambda x: x[:1]) def test_sort_index_multiindex_sparse_column(self): # GH 29735, testing that sort_index on a multiindexed frame with sparse # columns fills with 0. expected = DataFrame( { i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) for i in range(0, 4) }, index=MultiIndex.from_product([[1, 2], [1, 2]]), ) result = expected.sort_index(level=0) tm.assert_frame_equal(result, expected)
jreback/pandas
pandas/tests/frame/methods/test_sort_index.py
pandas/_config/localization.py
from typing import Optional, Type import pytest import pandas as pd import pandas._testing as tm from pandas.core import ops from .base import BaseExtensionTests class BaseOpsUtil(BaseExtensionTests): def get_op_from_name(self, op_name): return tm.get_op_from_name(op_name) def check_opname(self, s, op_name, other, exc=Exception): op = self.get_op_from_name(op_name) self._check_op(s, op, other, op_name, exc) def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: result = op(s, other) if isinstance(s, pd.DataFrame): if len(s.columns) != 1: raise NotImplementedError expected = s.iloc[:, 0].combine(other, op).to_frame() self.assert_frame_equal(result, expected) else: expected = s.combine(other, op) self.assert_series_equal(result, expected) else: with pytest.raises(exc): op(s, other) def _check_divmod_op(self, s, op, other, exc=Exception): # divmod has multiple return values, so check separately if exc is None: result_div, result_mod = op(s, other) if op is divmod: expected_div, expected_mod = s // other, s % other else: expected_div, expected_mod = other // s, other % s self.assert_series_equal(result_div, expected_div) self.assert_series_equal(result_mod, expected_mod) else: with pytest.raises(exc): divmod(s, other) class BaseArithmeticOpsTests(BaseOpsUtil): """ Various Series and DataFrame arithmetic ops methods. Subclasses supporting various ops should set the class variables to indicate that they support ops of that kind * series_scalar_exc = TypeError * frame_scalar_exc = TypeError * series_array_exc = TypeError * divmod_exc = TypeError """ series_scalar_exc: Optional[Type[TypeError]] = TypeError frame_scalar_exc: Optional[Type[TypeError]] = TypeError series_array_exc: Optional[Type[TypeError]] = TypeError divmod_exc: Optional[Type[TypeError]] = TypeError def test_arith_series_with_scalar(self, data, all_arithmetic_operators): # series & scalar op_name = all_arithmetic_operators s = pd.Series(data) self.check_opname(s, op_name, s.iloc[0], exc=self.series_scalar_exc) @pytest.mark.xfail(run=False, reason="_reduce needs implementation") def test_arith_frame_with_scalar(self, data, all_arithmetic_operators): # frame & scalar op_name = all_arithmetic_operators df = pd.DataFrame({"A": data}) self.check_opname(df, op_name, data[0], exc=self.frame_scalar_exc) def test_arith_series_with_array(self, data, all_arithmetic_operators): # ndarray & other series op_name = all_arithmetic_operators s = pd.Series(data) self.check_opname( s, op_name, pd.Series([s.iloc[0]] * len(s)), exc=self.series_array_exc ) def test_divmod(self, data): s = pd.Series(data) self._check_divmod_op(s, divmod, 1, exc=self.divmod_exc) self._check_divmod_op(1, ops.rdivmod, s, exc=self.divmod_exc) def test_divmod_series_array(self, data, data_for_twos): s = pd.Series(data) self._check_divmod_op(s, divmod, data) other = data_for_twos self._check_divmod_op(other, ops.rdivmod, s) other = pd.Series(other) self._check_divmod_op(other, ops.rdivmod, s) def test_add_series_with_extension_array(self, data): s = pd.Series(data) result = s + data expected = pd.Series(data + data) self.assert_series_equal(result, expected) def test_error(self, data, all_arithmetic_operators): # invalid ops op_name = all_arithmetic_operators with pytest.raises(AttributeError): getattr(data, op_name) @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) if box is pd.DataFrame: other = other.to_frame() if hasattr(data, "__add__"): result = data.__add__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement add") class BaseComparisonOpsTests(BaseOpsUtil): """Various Series and DataFrame comparison ops methods.""" def _compare_other(self, s, data, op_name, other): op = self.get_op_from_name(op_name) if op_name == "__eq__": assert not op(s, other).all() elif op_name == "__ne__": assert op(s, other).all() else: # array assert getattr(data, op_name)(other) is NotImplemented # series s = pd.Series(data) with pytest.raises(TypeError): op(s, other) def test_compare_scalar(self, data, all_compare_operators): op_name = all_compare_operators s = pd.Series(data) self._compare_other(s, data, op_name, 0) def test_compare_array(self, data, all_compare_operators): op_name = all_compare_operators s = pd.Series(data) other = pd.Series([data[0]] * len(data)) self._compare_other(s, data, op_name, other) @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) if box is pd.DataFrame: other = other.to_frame() if hasattr(data, "__eq__"): result = data.__eq__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement __eq__") if hasattr(data, "__ne__"): result = data.__ne__(other) assert result is NotImplemented else: raise pytest.skip(f"{type(data).__name__} does not implement __ne__") class BaseUnaryOpsTests(BaseOpsUtil): def test_invert(self, data): s = pd.Series(data, name="name") result = ~s expected = pd.Series(~data, name="name") self.assert_series_equal(result, expected)
import numpy as np import pytest import pandas as pd from pandas import ( CategoricalDtype, CategoricalIndex, DataFrame, Index, IntervalIndex, MultiIndex, Series, Timestamp, ) import pandas._testing as tm class TestDataFrameSortIndex: def test_sort_index_and_reconstruction_doc_example(self): # doc example df = DataFrame( {"value": [1, 2, 3, 4]}, index=MultiIndex( levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) assert df.index.is_lexsorted() assert not df.index.is_monotonic # sort it expected = DataFrame( {"value": [2, 1, 4, 3]}, index=MultiIndex( levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = df.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # reconstruct result = df.sort_index().copy() result.index = result.index._sort_levels_monotonic() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) def test_sort_index_non_existent_label_multiindex(self): # GH#12261 df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []])) df.loc["b", "2"] = 1 df.loc["a", "3"] = 1 result = df.sort_index().index.is_monotonic assert result is True def test_sort_index_reorder_on_ops(self): # GH#15687 df = DataFrame( np.random.randn(8, 2), index=MultiIndex.from_product( [["a", "b"], ["big", "small"], ["red", "blu"]], names=["letter", "size", "color"], ), columns=["near", "far"], ) df = df.sort_index() def my_func(group): group.index = ["newz", "newa"] return group result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index() expected = MultiIndex.from_product( [["a", "b"], ["big", "small"], ["newa", "newz"]], names=["letter", "size", None], ) tm.assert_index_equal(result.index, expected) def test_sort_index_nan_multiindex(self): # GH#14784 # incorrect sorting w.r.t. nans tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]] mi = MultiIndex.from_tuples(tuples) df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD")) s = Series(np.arange(4), index=mi) df2 = DataFrame( { "date": pd.DatetimeIndex( [ "20121002", "20121007", "20130130", "20130202", "20130305", "20121002", "20121207", "20130130", "20130202", "20130305", "20130202", "20130305", ] ), "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], "whole_cost": [ 1790, np.nan, 280, 259, np.nan, 623, 90, 312, np.nan, 301, 359, 801, ], "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12], } ).set_index(["date", "user_id"]) # sorting frame, default nan position is last result = df.sort_index() expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position last result = df.sort_index(na_position="last") expected = df.iloc[[3, 0, 2, 1], :] tm.assert_frame_equal(result, expected) # sorting frame, nan position first result = df.sort_index(na_position="first") expected = df.iloc[[1, 2, 3, 0], :] tm.assert_frame_equal(result, expected) # sorting frame with removed rows result = df2.dropna().sort_index() expected = df2.sort_index().dropna() tm.assert_frame_equal(result, expected) # sorting series, default nan position is last result = s.sort_index() expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position last result = s.sort_index(na_position="last") expected = s.iloc[[3, 0, 2, 1]] tm.assert_series_equal(result, expected) # sorting series, nan position first result = s.sort_index(na_position="first") expected = s.iloc[[1, 2, 3, 0]] tm.assert_series_equal(result, expected) def test_sort_index_nan(self): # GH#3917 # Test DataFrame with nan label df = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) # NaN label, ascending=True, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=True, na_position="last") expected = DataFrame( {"A": [1, 2, np.nan, 1, 6, 8, 4], "B": [9, np.nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=True, na_position='first' sorted_df = df.sort_index(na_position="first") expected = DataFrame( {"A": [4, 1, 2, np.nan, 1, 6, 8], "B": [5, 9, np.nan, 5, 2, 5, 4]}, index=[np.nan, 1, 2, 3, 4, 5, 6], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=False) expected = DataFrame( {"A": [8, 6, 1, np.nan, 2, 1, 4], "B": [4, 5, 2, 5, np.nan, 9, 5]}, index=[6, 5, 4, 3, 2, 1, np.nan], ) tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='first' sorted_df = df.sort_index( kind="quicksort", ascending=False, na_position="first" ) expected = DataFrame( {"A": [4, 8, 6, 1, np.nan, 2, 1], "B": [5, 4, 5, 2, 5, np.nan, 9]}, index=[np.nan, 6, 5, 4, 3, 2, 1], ) tm.assert_frame_equal(sorted_df, expected) def test_sort_index_multi_index(self): # GH#25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ) result = df.set_index(list("abc")).sort_index(level=list("ba")) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ) expected = expected.set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_inplace(self): frame = DataFrame( np.random.randn(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"] ) # axis=0 unordered = frame.loc[[3, 2, 4, 1]] a_id = id(unordered["A"]) df = unordered.copy() return_value = df.sort_index(inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) assert a_id != id(df["A"]) df = unordered.copy() return_value = df.sort_index(ascending=False, inplace=True) assert return_value is None expected = frame[::-1] tm.assert_frame_equal(df, expected) # axis=1 unordered = frame.loc[:, ["D", "B", "C", "A"]] df = unordered.copy() return_value = df.sort_index(axis=1, inplace=True) assert return_value is None expected = frame tm.assert_frame_equal(df, expected) df = unordered.copy() return_value = df.sort_index(axis=1, ascending=False, inplace=True) assert return_value is None expected = frame.iloc[:, ::-1] tm.assert_frame_equal(df, expected) def test_sort_index_different_sortorder(self): A = np.arange(20).repeat(5) B = np.tile(np.arange(5), 20) indexer = np.random.permutation(100) A = A.take(indexer) B = B.take(indexer) df = DataFrame({"A": A, "B": B, "C": np.random.randn(100)}) ex_indexer = np.lexsort((df.B.max() - df.B, df.A)) expected = df.take(ex_indexer) # test with multiindex, too idf = df.set_index(["A", "B"]) result = idf.sort_index(ascending=[1, 0]) expected = idf.take(ex_indexer) tm.assert_frame_equal(result, expected) # also, Series! result = idf["C"].sort_index(ascending=[1, 0]) tm.assert_series_equal(result, expected["C"]) def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) df = DataFrame([[1, 2], [3, 4]], mi) result = df.sort_index(level="A", sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) result = df.sort_index(level=["A", "B"], sort_remaining=False) expected = df tm.assert_frame_equal(result, expected) # Error thrown by sort_index when # first index is sorted last (GH#26053) result = df.sort_index(level=["C", "B", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["B", "C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) result = df.sort_index(level=["C", "A"]) expected = df.iloc[[1, 0]] tm.assert_frame_equal(result, expected) def test_sort_index_categorical_index(self): df = DataFrame( { "A": np.arange(6, dtype="int64"), "B": Series(list("aabbca")).astype(CategoricalDtype(list("cab"))), } ).set_index("B") result = df.sort_index() expected = df.iloc[[4, 0, 1, 5, 2, 3]] tm.assert_frame_equal(result, expected) result = df.sort_index(ascending=False) expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) def test_sort_index(self): # GH#13496 frame = DataFrame( np.arange(16).reshape(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"], ) # axis=0 : sort rows by index labels unordered = frame.loc[[3, 2, 4, 1]] result = unordered.sort_index(axis=0) expected = frame tm.assert_frame_equal(result, expected) result = unordered.sort_index(ascending=False) expected = frame[::-1] tm.assert_frame_equal(result, expected) # axis=1 : sort columns by column names unordered = frame.iloc[:, [2, 1, 3, 0]] result = unordered.sort_index(axis=1) tm.assert_frame_equal(result, frame) result = unordered.sort_index(axis=1, ascending=False) expected = frame.iloc[:, ::-1] tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("level", ["A", 0]) # GH#21052 def test_sort_index_multiindex(self, level): # GH#13496 # sort rows by specified level of multi-index mi = MultiIndex.from_tuples( [[2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list("ABC") ) df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 2], [2, 1, 3]], names=list("ABC") ) expected = DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi) result = df.sort_index(level=level) tm.assert_frame_equal(result, expected) # sort_remaining=False expected_mi = MultiIndex.from_tuples( [[1, 1, 1], [2, 1, 3], [2, 1, 2]], names=list("ABC") ) expected = DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi) result = df.sort_index(level=level, sort_remaining=False) tm.assert_frame_equal(result, expected) def test_sort_index_intervalindex(self): # this is a de-facto sort via unstack # confirming that we sort in the order of the bins y = Series(np.random.randn(100)) x1 = Series(np.sign(np.random.randn(100))) x2 = pd.cut(Series(np.random.randn(100)), bins=[-3, -0.5, 0, 0.5, 3]) model = pd.concat([y, x1, x2], axis=1, keys=["Y", "X1", "X2"]) result = model.groupby(["X1", "X2"], observed=True).mean().unstack() expected = IntervalIndex.from_tuples( [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], closed="right" ) result = result.columns.levels[1].categories tm.assert_index_equal(result, expected) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, True, [0, 1, 2]), ({"A": [1, 2, 3]}, {"A": [2, 3, 1]}, False, False, [5, 3, 2]), ({"A": [1, 2, 3]}, {"A": [1, 3, 2]}, True, False, [2, 3, 5]), ], ) def test_sort_index_ignore_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114 original_index = [2, 5, 3] df = DataFrame(original_dict, index=original_index) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index)) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize( "original_dict, sorted_dict, ascending, ignore_index, output_index", [ ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, True, [0, 1], ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [1, 2], "M2": [3, 4]}, True, False, MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")), ), ( {"M1": [1, 2], "M2": [3, 4]}, {"M1": [2, 1], "M2": [4, 3]}, False, False, MultiIndex.from_tuples([[3, 4], [2, 1]], names=list("AB")), ), ], ) def test_sort_index_ignore_index_multi_index( self, inplace, original_dict, sorted_dict, ascending, ignore_index, output_index ): # GH 30114, this is to test ignore_index on MulitIndex of index mi = MultiIndex.from_tuples([[2, 1], [3, 4]], names=list("AB")) df = DataFrame(original_dict, index=mi) expected_df = DataFrame(sorted_dict, index=output_index) kwargs = { "ascending": ascending, "ignore_index": ignore_index, "inplace": inplace, } if inplace: result_df = df.copy() result_df.sort_index(**kwargs) else: result_df = df.sort_index(**kwargs) tm.assert_frame_equal(result_df, expected_df) tm.assert_frame_equal(df, DataFrame(original_dict, index=mi)) def test_sort_index_categorical_multiindex(self): # GH#15058 df = DataFrame( { "a": range(6), "l1": pd.Categorical( ["a", "a", "b", "b", "c", "c"], categories=["c", "a", "b"], ordered=True, ), "l2": [0, 1, 0, 1, 0, 1], } ) result = df.set_index(["l1", "l2"]).sort_index() expected = DataFrame( [4, 5, 0, 1, 2, 3], columns=["a"], index=MultiIndex( levels=[ CategoricalIndex( ["c", "a", "b"], categories=["c", "a", "b"], ordered=True, name="l1", dtype="category", ), [0, 1], ], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], names=["l1", "l2"], ), ) tm.assert_frame_equal(result, expected) def test_sort_index_and_reconstruction(self): # GH#15622 # lexsortedness should be identical # across MultiIndex construction methods df = DataFrame([[1, 1], [2, 2]], index=list("ab")) expected = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_tuples( [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")] ), ) assert expected.index.is_lexsorted() result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex.from_product([[0.5, 0.8], list("ab")]), ) result = result.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) result = DataFrame( [[1, 1], [2, 2], [1, 1], [2, 2]], index=MultiIndex( levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]] ), ) result = result.sort_index() assert result.index.is_lexsorted() tm.assert_frame_equal(result, expected) concatted = pd.concat([df, df], keys=[0.8, 0.5]) result = concatted.sort_index() assert result.index.is_lexsorted() assert result.index.is_monotonic tm.assert_frame_equal(result, expected) # GH#14015 df = DataFrame( [[1, 2], [6, 7]], columns=MultiIndex.from_tuples( [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")], names=["l1", "Date"], ), ) df.columns = df.columns.set_levels( pd.to_datetime(df.columns.levels[1]), level=1 ) assert not df.columns.is_lexsorted() assert not df.columns.is_monotonic result = df.sort_index(axis=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic result = df.sort_index(axis=1, level=1) assert result.columns.is_lexsorted() assert result.columns.is_monotonic # TODO: better name, de-duplicate with test_sort_index_level above def test_sort_index_level2(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) df = frame.copy() df.index = np.arange(len(df)) # axis=1 # series a_sorted = frame["A"].sort_index(level=0) # preserve names assert a_sorted.index.names == frame.index.names # inplace rs = frame.copy() return_value = rs.sort_index(level=0, inplace=True) assert return_value is None tm.assert_frame_equal(rs, frame.sort_index(level=0)) def test_sort_index_level_large_cardinality(self): # GH#2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64) # it works! result = df.sort_index(level=0) assert result.index.lexsort_depth == 3 # GH#2684 (int32) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32) # it works! result = df.sort_index(level=0) assert (result.dtypes.values == df.dtypes.values).all() assert result.index.lexsort_depth == 3 def test_sort_index_level_by_name(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) frame.index.names = ["first", "second"] result = frame.sort_index(level="second") expected = frame.sort_index(level=1) tm.assert_frame_equal(result, expected) def test_sort_index_level_mixed(self): mi = MultiIndex( levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=["first", "second"], ) frame = DataFrame( np.random.randn(10, 3), index=mi, columns=Index(["A", "B", "C"], name="exp"), ) sorted_before = frame.sort_index(level=1) df = frame.copy() df["foo"] = "bar" sorted_after = df.sort_index(level=1) tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1)) dft = frame.T sorted_before = dft.sort_index(level=1, axis=1) dft["foo", "three"] = "bar" sorted_after = dft.sort_index(level=1, axis=1) tm.assert_frame_equal( sorted_before.drop([("foo", "three")], axis=1), sorted_after.drop([("foo", "three")], axis=1), ) def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data result = frame.sort_index() assert result.index.names == frame.index.names @pytest.mark.parametrize( "gen,extra", [ ([1.0, 3.0, 2.0, 5.0], 4.0), ([1, 3, 2, 5], 4), ( [ Timestamp("20130101"), Timestamp("20130103"), Timestamp("20130102"), Timestamp("20130105"), ], Timestamp("20130104"), ), (["1one", "3one", "2one", "5one"], "4one"), ], ) def test_sort_index_multilevel_repr_8017(self, gen, extra): np.random.seed(0) data = np.random.randn(3, 4) columns = MultiIndex.from_tuples([("red", i) for i in gen]) df = DataFrame(data, index=list("def"), columns=columns) df2 = pd.concat( [ df, DataFrame( "world", index=list("def"), columns=MultiIndex.from_tuples([("red", extra)]), ), ], axis=1, ) # check that the repr is good # make sure that we have a correct sparsified repr # e.g. only 1 header of read assert str(df2).splitlines()[0].split() == ["red"] # GH 8017 # sorting fails after columns added # construct single-dtype then sort result = df.copy().sort_index(axis=1) expected = df.iloc[:, [0, 2, 1, 3]] tm.assert_frame_equal(result, expected) result = df2.sort_index(axis=1) expected = df2.iloc[:, [0, 2, 1, 4, 3]] tm.assert_frame_equal(result, expected) # setitem then sort result = df.copy() result[("red", extra)] = "world" result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "categories", [ pytest.param(["a", "b", "c"], id="str"), pytest.param( [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], id="pd.Interval", ), ], ) def test_sort_index_with_categories(self, categories): # GH#23452 df = DataFrame( {"foo": range(len(categories))}, index=CategoricalIndex( data=categories, categories=categories, ordered=True ), ) df.index = df.index.reorder_categories(df.index.categories[::-1]) result = df.sort_index() expected = DataFrame( {"foo": reversed(range(len(categories)))}, index=CategoricalIndex( data=categories[::-1], categories=categories[::-1], ordered=True ), ) tm.assert_frame_equal(result, expected) class TestDataFrameSortIndexKey: def test_sort_multi_index_key(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": [3, 1, 2], "b": [0, 0, 0], "c": [0, 1, 2], "d": list("abc")} ).set_index(list("abc")) result = df.sort_index(level=list("ac"), key=lambda x: x) expected = DataFrame( {"a": [1, 2, 3], "b": [0, 0, 0], "c": [1, 2, 0], "d": list("bca")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index(level=list("ac"), key=lambda x: -x) expected = DataFrame( {"a": [3, 2, 1], "b": [0, 0, 0], "c": [0, 2, 1], "d": list("acb")} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_sort_index_key(self): # issue 27237 df = DataFrame(np.arange(6, dtype="int64"), index=list("aaBBca")) result = df.sort_index() expected = df.iloc[[2, 3, 0, 1, 5, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower()) expected = df.iloc[[0, 1, 5, 2, 3, 4]] tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: x.str.lower(), ascending=False) expected = df.iloc[[4, 2, 3, 0, 1, 5]] tm.assert_frame_equal(result, expected) def test_sort_index_key_int(self): df = DataFrame(np.arange(6, dtype="int64"), index=np.arange(6, dtype="int64")) result = df.sort_index() tm.assert_frame_equal(result, df) result = df.sort_index(key=lambda x: -x) expected = df.sort_index(ascending=False) tm.assert_frame_equal(result, expected) result = df.sort_index(key=lambda x: 2 * x) tm.assert_frame_equal(result, df) def test_sort_multi_index_key_str(self): # GH 25775, testing that sorting by index works with a multi-index. df = DataFrame( {"a": ["B", "a", "C"], "b": [0, 1, 0], "c": list("abc"), "d": [0, 1, 2]} ).set_index(list("abc")) result = df.sort_index(level="a", key=lambda x: x.str.lower()) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) result = df.sort_index( level=list("abc"), # can refer to names key=lambda x: x.str.lower() if x.name in ["a", "c"] else -x, ) expected = DataFrame( {"a": ["a", "B", "C"], "b": [1, 0, 0], "c": list("bac"), "d": [1, 0, 2]} ).set_index(list("abc")) tm.assert_frame_equal(result, expected) def test_changes_length_raises(self): df = DataFrame({"A": [1, 2, 3]}) with pytest.raises(ValueError, match="change the shape"): df.sort_index(key=lambda x: x[:1]) def test_sort_index_multiindex_sparse_column(self): # GH 29735, testing that sort_index on a multiindexed frame with sparse # columns fills with 0. expected = DataFrame( { i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) for i in range(0, 4) }, index=MultiIndex.from_product([[1, 2], [1, 2]]), ) result = expected.sort_index(level=0) tm.assert_frame_equal(result, expected)
jreback/pandas
pandas/tests/frame/methods/test_sort_index.py
pandas/tests/extension/base/ops.py
""" Decorators for labeling and modifying behavior of test objects. Decorators that merely return a modified version of the original function object are straightforward. Decorators that return a new function object need to use :: nose.tools.make_decorator(original_function)(decorator) in returning the decorator, in order to preserve meta-data such as function name, setup and teardown functions and so on - see ``nose.tools`` for more information. """ import collections.abc from .utils import SkipTest, assert_warns, HAS_REFCOUNT __all__ = ['slow', 'setastest', 'skipif', 'knownfailureif', 'deprecated', 'parametrize', '_needs_refcount',] def slow(t): """ Label a test as 'slow'. The exact definition of a slow test is obviously both subjective and hardware-dependent, but in general any individual test that requires more than a second or two should be labeled as slow (the whole suite consists of thousands of tests, so even a second is significant). Parameters ---------- t : callable The test to label as slow. Returns ------- t : callable The decorated test `t`. Examples -------- The `numpy.testing` module includes ``import decorators as dec``. A test can be decorated as slow like this:: from numpy.testing import * @dec.slow def test_big(self): print('Big, slow test') """ t.slow = True return t def setastest(tf=True): """ Signals to nose that this function is or is not a test. Parameters ---------- tf : bool If True, specifies that the decorated callable is a test. If False, specifies that the decorated callable is not a test. Default is True. Notes ----- This decorator can't use the nose namespace, because it can be called from a non-test module. See also ``istest`` and ``nottest`` in ``nose.tools``. Examples -------- `setastest` can be used in the following way:: from numpy.testing import dec @dec.setastest(False) def func_with_test_in_name(arg1, arg2): pass """ def set_test(t): t.__test__ = tf return t return set_test def skipif(skip_condition, msg=None): """ Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ def skip_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose # Allow for both boolean or callable skip conditions. if isinstance(skip_condition, collections.abc.Callable): skip_val = lambda: skip_condition() else: skip_val = lambda: skip_condition def get_msg(func,msg=None): """Skip message with information about function being skipped.""" if msg is None: out = 'Test skipped due to test condition' else: out = msg return "Skipping test: %s: %s" % (func.__name__, out) # We need to define *two* skippers because Python doesn't allow both # return with value and yield inside the same function. def skipper_func(*args, **kwargs): """Skipper for normal test functions.""" if skip_val(): raise SkipTest(get_msg(f, msg)) else: return f(*args, **kwargs) def skipper_gen(*args, **kwargs): """Skipper for test generators.""" if skip_val(): raise SkipTest(get_msg(f, msg)) else: yield from f(*args, **kwargs) # Choose the right skipper to use when building the actual decorator. if nose.util.isgenerator(f): skipper = skipper_gen else: skipper = skipper_func return nose.tools.make_decorator(f)(skipper) return skip_decorator def knownfailureif(fail_condition, msg=None): """ Make function raise KnownFailureException exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- fail_condition : bool or callable Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False). msg : str, optional Message to give on raising a KnownFailureException exception. Default is None. Returns ------- decorator : function Decorator, which, when applied to a function, causes KnownFailureException to be raised when `fail_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ if msg is None: msg = 'Test skipped due to known failure' # Allow for both boolean or callable known failure conditions. if isinstance(fail_condition, collections.abc.Callable): fail_val = lambda: fail_condition() else: fail_val = lambda: fail_condition def knownfail_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose from .noseclasses import KnownFailureException def knownfailer(*args, **kwargs): if fail_val(): raise KnownFailureException(msg) else: return f(*args, **kwargs) return nose.tools.make_decorator(f)(knownfailer) return knownfail_decorator def deprecated(conditional=True): """ Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, optional Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True. Returns ------- decorator : function The `deprecated` decorator itself. Notes ----- .. versionadded:: 1.4.0 """ def deprecate_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose def _deprecated_imp(*args, **kwargs): # Poor man's replacement for the with statement with assert_warns(DeprecationWarning): f(*args, **kwargs) if isinstance(conditional, collections.abc.Callable): cond = conditional() else: cond = conditional if cond: return nose.tools.make_decorator(f)(_deprecated_imp) else: return f return deprecate_decorator def parametrize(vars, input): """ Pytest compatibility class. This implements the simplest level of pytest.mark.parametrize for use in nose as an aid in making the transition to pytest. It achieves that by adding a dummy var parameter and ignoring the doc_func parameter of the base class. It does not support variable substitution by name, nor does it support nesting or classes. See the pytest documentation for usage. .. versionadded:: 1.14.0 """ from .parameterized import parameterized return parameterized(input) _needs_refcount = skipif(not HAS_REFCOUNT, "python has no sys.getrefcount")
import sys import warnings import itertools import platform import pytest from decimal import Decimal import numpy as np from numpy.core import umath from numpy.random import rand, randint, randn from numpy.testing import ( assert_, assert_equal, assert_raises, assert_raises_regex, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_warns, HAS_REFCOUNT ) from hypothesis import assume, given, strategies as st from hypothesis.extra import numpy as hynp class TestResize: def test_copies(self): A = np.array([[1, 2], [3, 4]]) Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) assert_equal(np.resize(A, (2, 4)), Ar1) Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(np.resize(A, (4, 2)), Ar2) Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]) assert_equal(np.resize(A, (4, 3)), Ar3) def test_zeroresize(self): A = np.array([[1, 2], [3, 4]]) Ar = np.resize(A, (0,)) assert_array_equal(Ar, np.array([])) assert_equal(A.dtype, Ar.dtype) Ar = np.resize(A, (0, 2)) assert_equal(Ar.shape, (0, 2)) Ar = np.resize(A, (2, 0)) assert_equal(Ar.shape, (2, 0)) def test_reshape_from_zero(self): # See also gh-6740 A = np.zeros(0, dtype=[('a', np.float32)]) Ar = np.resize(A, (2, 1)) assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype)) assert_equal(A.dtype, Ar.dtype) class TestNonarrayArgs: # check that non-array arguments to functions wrap them in arrays def test_choose(self): choices = [[0, 1, 2], [3, 4, 5], [5, 6, 7]] tgt = [5, 1, 5] a = [2, 0, 1] out = np.choose(a, choices) assert_equal(out, tgt) def test_clip(self): arr = [-1, 5, 2, 3, 10, -4, -9] out = np.clip(arr, 2, 7) tgt = [2, 5, 2, 3, 7, 2, 2] assert_equal(out, tgt) def test_compress(self): arr = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] tgt = [[5, 6, 7, 8, 9]] out = np.compress([0, 1], arr, axis=0) assert_equal(out, tgt) def test_count_nonzero(self): arr = [[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]] tgt = np.array([2, 3]) out = np.count_nonzero(arr, axis=1) assert_equal(out, tgt) def test_cumproduct(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.all(np.cumproduct(A) == np.array([1, 2, 6, 24, 120, 720]))) def test_diagonal(self): a = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] out = np.diagonal(a) tgt = [0, 5, 10] assert_equal(out, tgt) def test_mean(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.mean(A) == 3.5) assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5]))) assert_(np.all(np.mean(A, 1) == np.array([2., 5.]))) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.mean([]))) assert_(w[0].category is RuntimeWarning) def test_ptp(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.ptp(a, axis=0), 15.0) def test_prod(self): arr = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] tgt = [24, 1890, 600] assert_equal(np.prod(arr, axis=-1), tgt) def test_ravel(self): a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] assert_equal(np.ravel(a), tgt) def test_repeat(self): a = [1, 2, 3] tgt = [1, 1, 2, 2, 3, 3] out = np.repeat(a, 2) assert_equal(out, tgt) def test_reshape(self): arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] assert_equal(np.reshape(arr, (2, 6)), tgt) def test_round(self): arr = [1.56, 72.54, 6.35, 3.25] tgt = [1.6, 72.5, 6.4, 3.2] assert_equal(np.around(arr, decimals=1), tgt) def test_searchsorted(self): arr = [-8, -5, -1, 3, 6, 10] out = np.searchsorted(arr, 0) assert_equal(out, 3) def test_size(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.size(A) == 6) assert_(np.size(A, 0) == 2) assert_(np.size(A, 1) == 3) def test_squeeze(self): A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]] assert_equal(np.squeeze(A).shape, (3, 3)) assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3)) assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3)) def test_std(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(np.std(A), 1.707825127659933) assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5])) assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.std([]))) assert_(w[0].category is RuntimeWarning) def test_swapaxes(self): tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]] a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]] out = np.swapaxes(a, 0, 2) assert_equal(out, tgt) def test_sum(self): m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] tgt = [[6], [15], [24]] out = np.sum(m, axis=1, keepdims=True) assert_equal(tgt, out) def test_take(self): tgt = [2, 3, 5] indices = [1, 2, 4] a = [1, 2, 3, 4, 5] out = np.take(a, indices) assert_equal(out, tgt) def test_trace(self): c = [[1, 2], [3, 4], [5, 6]] assert_equal(np.trace(c), 5) def test_transpose(self): arr = [[1, 2], [3, 4], [5, 6]] tgt = [[1, 3, 5], [2, 4, 6]] assert_equal(np.transpose(arr, (1, 0)), tgt) def test_var(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(np.var(A), 2.9166666666666665) assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25])) assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.var([]))) assert_(w[0].category is RuntimeWarning) B = np.array([None, 0]) B[0] = 1j assert_almost_equal(np.var(B), 0.25) class TestIsscalar: def test_isscalar(self): assert_(np.isscalar(3.1)) assert_(np.isscalar(np.int16(12345))) assert_(np.isscalar(False)) assert_(np.isscalar('numpy')) assert_(not np.isscalar([3.1])) assert_(not np.isscalar(None)) # PEP 3141 from fractions import Fraction assert_(np.isscalar(Fraction(5, 17))) from numbers import Number assert_(np.isscalar(Number())) class TestBoolScalar: def test_logical(self): f = np.False_ t = np.True_ s = "xyz" assert_((t and s) is s) assert_((f and s) is f) def test_bitwise_or(self): f = np.False_ t = np.True_ assert_((t | t) is t) assert_((f | t) is t) assert_((t | f) is t) assert_((f | f) is f) def test_bitwise_and(self): f = np.False_ t = np.True_ assert_((t & t) is t) assert_((f & t) is f) assert_((t & f) is f) assert_((f & f) is f) def test_bitwise_xor(self): f = np.False_ t = np.True_ assert_((t ^ t) is f) assert_((f ^ t) is t) assert_((t ^ f) is t) assert_((f ^ f) is f) class TestBoolArray: def setup(self): # offset for simd tests self.t = np.array([True] * 41, dtype=bool)[1::] self.f = np.array([False] * 41, dtype=bool)[1::] self.o = np.array([False] * 42, dtype=bool)[2::] self.nm = self.f.copy() self.im = self.t.copy() self.nm[3] = True self.nm[-2] = True self.im[3] = False self.im[-2] = False def test_all_any(self): assert_(self.t.all()) assert_(self.t.any()) assert_(not self.f.all()) assert_(not self.f.any()) assert_(self.nm.any()) assert_(self.im.any()) assert_(not self.nm.all()) assert_(not self.im.all()) # check bad element in all positions for i in range(256 - 7): d = np.array([False] * 256, dtype=bool)[7::] d[i] = True assert_(np.any(d)) e = np.array([True] * 256, dtype=bool)[7::] e[i] = False assert_(not np.all(e)) assert_array_equal(e, ~d) # big array test for blocked libc loops for i in list(range(9, 6000, 507)) + [7764, 90021, -10]: d = np.array([False] * 100043, dtype=bool) d[i] = True assert_(np.any(d), msg="%r" % i) e = np.array([True] * 100043, dtype=bool) e[i] = False assert_(not np.all(e), msg="%r" % i) def test_logical_not_abs(self): assert_array_equal(~self.t, self.f) assert_array_equal(np.abs(~self.t), self.f) assert_array_equal(np.abs(~self.f), self.t) assert_array_equal(np.abs(self.f), self.f) assert_array_equal(~np.abs(self.f), self.t) assert_array_equal(~np.abs(self.t), self.f) assert_array_equal(np.abs(~self.nm), self.im) np.logical_not(self.t, out=self.o) assert_array_equal(self.o, self.f) np.abs(self.t, out=self.o) assert_array_equal(self.o, self.t) def test_logical_and_or_xor(self): assert_array_equal(self.t | self.t, self.t) assert_array_equal(self.f | self.f, self.f) assert_array_equal(self.t | self.f, self.t) assert_array_equal(self.f | self.t, self.t) np.logical_or(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t & self.t, self.t) assert_array_equal(self.f & self.f, self.f) assert_array_equal(self.t & self.f, self.f) assert_array_equal(self.f & self.t, self.f) np.logical_and(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t ^ self.t, self.f) assert_array_equal(self.f ^ self.f, self.f) assert_array_equal(self.t ^ self.f, self.t) assert_array_equal(self.f ^ self.t, self.t) np.logical_xor(self.t, self.t, out=self.o) assert_array_equal(self.o, self.f) assert_array_equal(self.nm & self.t, self.nm) assert_array_equal(self.im & self.f, False) assert_array_equal(self.nm & True, self.nm) assert_array_equal(self.im & False, self.f) assert_array_equal(self.nm | self.t, self.t) assert_array_equal(self.im | self.f, self.im) assert_array_equal(self.nm | True, self.t) assert_array_equal(self.im | False, self.im) assert_array_equal(self.nm ^ self.t, self.im) assert_array_equal(self.im ^ self.f, self.im) assert_array_equal(self.nm ^ True, self.im) assert_array_equal(self.im ^ False, self.im) class TestBoolCmp: def setup(self): self.f = np.ones(256, dtype=np.float32) self.ef = np.ones(self.f.size, dtype=bool) self.d = np.ones(128, dtype=np.float64) self.ed = np.ones(self.d.size, dtype=bool) # generate values for all permutation of 256bit simd vectors s = 0 for i in range(32): self.f[s:s+8] = [i & 2**x for x in range(8)] self.ef[s:s+8] = [(i & 2**x) != 0 for x in range(8)] s += 8 s = 0 for i in range(16): self.d[s:s+4] = [i & 2**x for x in range(4)] self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)] s += 4 self.nf = self.f.copy() self.nd = self.d.copy() self.nf[self.ef] = np.nan self.nd[self.ed] = np.nan self.inff = self.f.copy() self.infd = self.d.copy() self.inff[::3][self.ef[::3]] = np.inf self.infd[::3][self.ed[::3]] = np.inf self.inff[1::3][self.ef[1::3]] = -np.inf self.infd[1::3][self.ed[1::3]] = -np.inf self.inff[2::3][self.ef[2::3]] = np.nan self.infd[2::3][self.ed[2::3]] = np.nan self.efnonan = self.ef.copy() self.efnonan[2::3] = False self.ednonan = self.ed.copy() self.ednonan[2::3] = False self.signf = self.f.copy() self.signd = self.d.copy() self.signf[self.ef] *= -1. self.signd[self.ed] *= -1. self.signf[1::6][self.ef[1::6]] = -np.inf self.signd[1::6][self.ed[1::6]] = -np.inf self.signf[3::6][self.ef[3::6]] = -np.nan self.signd[3::6][self.ed[3::6]] = -np.nan self.signf[4::6][self.ef[4::6]] = -0. self.signd[4::6][self.ed[4::6]] = -0. def test_float(self): # offset for alignment test for i in range(4): assert_array_equal(self.f[i:] > 0, self.ef[i:]) assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:]) assert_array_equal(self.f[i:] == 0, ~self.ef[i:]) assert_array_equal(-self.f[i:] < 0, self.ef[i:]) assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:]) r = self.f[i:] != 0 assert_array_equal(r, self.ef[i:]) r2 = self.f[i:] != np.zeros_like(self.f[i:]) r3 = 0 != self.f[i:] assert_array_equal(r, r2) assert_array_equal(r, r3) # check bool == 0x1 assert_array_equal(r.view(np.int8), r.astype(np.int8)) assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) # isnan on amd64 takes the same code path assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:]) assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:]) assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:]) assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:]) assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:]) def test_double(self): # offset for alignment test for i in range(2): assert_array_equal(self.d[i:] > 0, self.ed[i:]) assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:]) assert_array_equal(self.d[i:] == 0, ~self.ed[i:]) assert_array_equal(-self.d[i:] < 0, self.ed[i:]) assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:]) r = self.d[i:] != 0 assert_array_equal(r, self.ed[i:]) r2 = self.d[i:] != np.zeros_like(self.d[i:]) r3 = 0 != self.d[i:] assert_array_equal(r, r2) assert_array_equal(r, r3) # check bool == 0x1 assert_array_equal(r.view(np.int8), r.astype(np.int8)) assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) # isnan on amd64 takes the same code path assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:]) assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:]) assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:]) assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:]) assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:]) class TestSeterr: def test_default(self): err = np.geterr() assert_equal(err, dict(divide='warn', invalid='warn', over='warn', under='ignore') ) def test_set(self): with np.errstate(): err = np.seterr() old = np.seterr(divide='print') assert_(err == old) new = np.seterr() assert_(new['divide'] == 'print') np.seterr(over='raise') assert_(np.geterr()['over'] == 'raise') assert_(new['divide'] == 'print') np.seterr(**old) assert_(np.geterr() == old) @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.") def test_divide_err(self): with np.errstate(divide='raise'): with assert_raises(FloatingPointError): np.array([1.]) / np.array([0.]) np.seterr(divide='ignore') np.array([1.]) / np.array([0.]) def test_errobj(self): olderrobj = np.geterrobj() self.called = 0 try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with np.errstate(divide='warn'): np.seterrobj([20000, 1, None]) np.array([1.]) / np.array([0.]) assert_equal(len(w), 1) def log_err(*args): self.called += 1 extobj_err = args assert_(len(extobj_err) == 2) assert_("divide" in extobj_err[0]) with np.errstate(divide='ignore'): np.seterrobj([20000, 3, log_err]) np.array([1.]) / np.array([0.]) assert_equal(self.called, 1) np.seterrobj(olderrobj) with np.errstate(divide='ignore'): np.divide(1., 0., extobj=[20000, 3, log_err]) assert_equal(self.called, 2) finally: np.seterrobj(olderrobj) del self.called def test_errobj_noerrmask(self): # errmask = 0 has a special code path for the default olderrobj = np.geterrobj() try: # set errobj to something non default np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT + 1, None]) # call a ufunc np.isnan(np.array([6])) # same with the default, lots of times to get rid of possible # pre-existing stack in the code for i in range(10000): np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT, None]) np.isnan(np.array([6])) finally: np.seterrobj(olderrobj) class TestFloatExceptions: def assert_raises_fpe(self, fpeerr, flop, x, y): ftype = type(x) try: flop(x, y) assert_(False, "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) except FloatingPointError as exc: assert_(str(exc).find(fpeerr) >= 0, "Type %s raised wrong fpe error '%s'." % (ftype, exc)) def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2): # Check that fpe exception is raised. # # Given a floating operation `flop` and two scalar values, check that # the operation raises the floating point exception specified by # `fpeerr`. Tests all variants with 0-d array scalars as well. self.assert_raises_fpe(fpeerr, flop, sc1, sc2) self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2) self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()]) self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()]) def test_floating_exceptions(self): # Test basic arithmetic function errors with np.errstate(all='raise'): # Test for all real and complex float types for typecode in np.typecodes['AllFloat']: ftype = np.obj2sctype(typecode) if np.dtype(ftype).kind == 'f': # Get some extreme values for the type fi = np.finfo(ftype) ft_tiny = fi.tiny ft_max = fi.max ft_eps = fi.eps underflow = 'underflow' divbyzero = 'divide by zero' else: # 'c', complex, corresponding real dtype rtype = type(ftype(0).real) fi = np.finfo(rtype) ft_tiny = ftype(fi.tiny) ft_max = ftype(fi.max) ft_eps = ftype(fi.eps) # The complex types raise different exceptions underflow = '' divbyzero = '' overflow = 'overflow' invalid = 'invalid' self.assert_raises_fpe(underflow, lambda a, b: a/b, ft_tiny, ft_max) self.assert_raises_fpe(underflow, lambda a, b: a*b, ft_tiny, ft_tiny) self.assert_raises_fpe(overflow, lambda a, b: a*b, ft_max, ftype(2)) self.assert_raises_fpe(overflow, lambda a, b: a/b, ft_max, ftype(0.5)) self.assert_raises_fpe(overflow, lambda a, b: a+b, ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, lambda a, b: a-b, -ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, np.power, ftype(2), ftype(2**fi.nexp)) self.assert_raises_fpe(divbyzero, lambda a, b: a/b, ftype(1), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b: a/b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a/b, ftype(0), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b: a-b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a+b, ftype(np.inf), ftype(-np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a*b, ftype(0), ftype(np.inf)) def test_warnings(self): # test warning code path with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with np.errstate(all="warn"): np.divide(1, 0.) assert_equal(len(w), 1) assert_("divide by zero" in str(w[0].message)) np.array(1e300) * np.array(1e300) assert_equal(len(w), 2) assert_("overflow" in str(w[-1].message)) np.array(np.inf) - np.array(np.inf) assert_equal(len(w), 3) assert_("invalid value" in str(w[-1].message)) np.array(1e-300) * np.array(1e-300) assert_equal(len(w), 4) assert_("underflow" in str(w[-1].message)) class TestTypes: def check_promotion_cases(self, promote_func): # tests that the scalars get coerced correctly. b = np.bool_(0) i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0) u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0) f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0) c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0) # coercion within the same kind assert_equal(promote_func(i8, i16), np.dtype(np.int16)) assert_equal(promote_func(i32, i8), np.dtype(np.int32)) assert_equal(promote_func(i16, i64), np.dtype(np.int64)) assert_equal(promote_func(u8, u32), np.dtype(np.uint32)) assert_equal(promote_func(f32, f64), np.dtype(np.float64)) assert_equal(promote_func(fld, f32), np.dtype(np.longdouble)) assert_equal(promote_func(f64, fld), np.dtype(np.longdouble)) assert_equal(promote_func(c128, c64), np.dtype(np.complex128)) assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble)) assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble)) # coercion between kinds assert_equal(promote_func(b, i32), np.dtype(np.int32)) assert_equal(promote_func(b, u8), np.dtype(np.uint8)) assert_equal(promote_func(i8, u8), np.dtype(np.int16)) assert_equal(promote_func(u8, i32), np.dtype(np.int32)) assert_equal(promote_func(i64, u32), np.dtype(np.int64)) assert_equal(promote_func(u64, i32), np.dtype(np.float64)) assert_equal(promote_func(i32, f32), np.dtype(np.float64)) assert_equal(promote_func(i64, f32), np.dtype(np.float64)) assert_equal(promote_func(f32, i16), np.dtype(np.float32)) assert_equal(promote_func(f32, u32), np.dtype(np.float64)) assert_equal(promote_func(f32, c64), np.dtype(np.complex64)) assert_equal(promote_func(c128, f32), np.dtype(np.complex128)) assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble)) # coercion between scalars and 1-D arrays assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8)) assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8)) assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32)) assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32)) assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int8)) assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.int32)) assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.uint32)) assert_equal(promote_func(np.int32(-1), np.array([u64])), np.dtype(np.float64)) assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float32)) assert_equal(promote_func(fld, np.array([f32])), np.dtype(np.float32)) assert_equal(promote_func(np.array([f64]), fld), np.dtype(np.float64)) assert_equal(promote_func(fld, np.array([c64])), np.dtype(np.complex64)) assert_equal(promote_func(c64, np.array([f64])), np.dtype(np.complex128)) assert_equal(promote_func(np.complex64(3j), np.array([f64])), np.dtype(np.complex128)) # coercion between scalars and 1-D arrays, where # the scalar has greater kind than the array assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64)) assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64)) assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64)) assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64)) assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64)) # uint and int are treated as the same "kind" for # the purposes of array-scalar promotion. assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.uint16)) # float and complex are treated as the same "kind" for # the purposes of array-scalar promotion, so that you can do # (0j + float32array) to get a complex64 array instead of # a complex128 array. assert_equal(promote_func(np.array([f32]), c128), np.dtype(np.complex64)) def test_coercion(self): def res_type(a, b): return np.add(a, b).dtype self.check_promotion_cases(res_type) # Use-case: float/complex scalar * bool/int8 array # shouldn't narrow the float/complex type for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]: b = 1.234 * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.longdouble(1.234) * a assert_equal(b.dtype, np.dtype(np.longdouble), "array type %s" % a.dtype) b = np.float64(1.234) * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.float32(1.234) * a assert_equal(b.dtype, np.dtype('f4'), "array type %s" % a.dtype) b = np.float16(1.234) * a assert_equal(b.dtype, np.dtype('f2'), "array type %s" % a.dtype) b = 1.234j * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.clongdouble(1.234j) * a assert_equal(b.dtype, np.dtype(np.clongdouble), "array type %s" % a.dtype) b = np.complex128(1.234j) * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.complex64(1.234j) * a assert_equal(b.dtype, np.dtype('c8'), "array type %s" % a.dtype) # The following use-case is problematic, and to resolve its # tricky side-effects requires more changes. # # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is # a float32, shouldn't promote to float64 # # a = np.array([1.0, 1.5], dtype=np.float32) # t = np.array([True, False]) # b = t*a # assert_equal(b, [1.0, 0.0]) # assert_equal(b.dtype, np.dtype('f4')) # b = (1-t)*a # assert_equal(b, [0.0, 1.5]) # assert_equal(b.dtype, np.dtype('f4')) # # Probably ~t (bitwise negation) is more proper to use here, # but this is arguably less intuitive to understand at a glance, and # would fail if 't' is actually an integer array instead of boolean: # # b = (~t)*a # assert_equal(b, [0.0, 1.5]) # assert_equal(b.dtype, np.dtype('f4')) def test_result_type(self): self.check_promotion_cases(np.result_type) assert_(np.result_type(None) == np.dtype(None)) def test_promote_types_endian(self): # promote_types should always return native-endian types assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8')) assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8')) assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21')) assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21')) assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21')) assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21')) assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8')) assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8')) assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8')) assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8')) assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8')) assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8')) assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8')) assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8')) assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8')) assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8')) def test_promote_types_strings(self): assert_equal(np.promote_types('bool', 'S'), np.dtype('S5')) assert_equal(np.promote_types('b', 'S'), np.dtype('S4')) assert_equal(np.promote_types('u1', 'S'), np.dtype('S3')) assert_equal(np.promote_types('u2', 'S'), np.dtype('S5')) assert_equal(np.promote_types('u4', 'S'), np.dtype('S10')) assert_equal(np.promote_types('u8', 'S'), np.dtype('S20')) assert_equal(np.promote_types('i1', 'S'), np.dtype('S4')) assert_equal(np.promote_types('i2', 'S'), np.dtype('S6')) assert_equal(np.promote_types('i4', 'S'), np.dtype('S11')) assert_equal(np.promote_types('i8', 'S'), np.dtype('S21')) assert_equal(np.promote_types('bool', 'U'), np.dtype('U5')) assert_equal(np.promote_types('b', 'U'), np.dtype('U4')) assert_equal(np.promote_types('u1', 'U'), np.dtype('U3')) assert_equal(np.promote_types('u2', 'U'), np.dtype('U5')) assert_equal(np.promote_types('u4', 'U'), np.dtype('U10')) assert_equal(np.promote_types('u8', 'U'), np.dtype('U20')) assert_equal(np.promote_types('i1', 'U'), np.dtype('U4')) assert_equal(np.promote_types('i2', 'U'), np.dtype('U6')) assert_equal(np.promote_types('i4', 'U'), np.dtype('U11')) assert_equal(np.promote_types('i8', 'U'), np.dtype('U21')) assert_equal(np.promote_types('bool', 'S1'), np.dtype('S5')) assert_equal(np.promote_types('bool', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('b', 'S1'), np.dtype('S4')) assert_equal(np.promote_types('b', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u1', 'S1'), np.dtype('S3')) assert_equal(np.promote_types('u1', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u2', 'S1'), np.dtype('S5')) assert_equal(np.promote_types('u2', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u4', 'S1'), np.dtype('S10')) assert_equal(np.promote_types('u4', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u8', 'S1'), np.dtype('S20')) assert_equal(np.promote_types('u8', 'S30'), np.dtype('S30')) def test_can_cast(self): assert_(np.can_cast(np.int32, np.int64)) assert_(np.can_cast(np.float64, complex)) assert_(not np.can_cast(complex, float)) assert_(np.can_cast('i8', 'f8')) assert_(not np.can_cast('i8', 'f4')) assert_(np.can_cast('i4', 'S11')) assert_(np.can_cast('i8', 'i8', 'no')) assert_(not np.can_cast('<i8', '>i8', 'no')) assert_(np.can_cast('<i8', '>i8', 'equiv')) assert_(not np.can_cast('<i4', '>i8', 'equiv')) assert_(np.can_cast('<i4', '>i8', 'safe')) assert_(not np.can_cast('<i8', '>i4', 'safe')) assert_(np.can_cast('<i8', '>i4', 'same_kind')) assert_(not np.can_cast('<i8', '>u4', 'same_kind')) assert_(np.can_cast('<i8', '>u4', 'unsafe')) assert_(np.can_cast('bool', 'S5')) assert_(not np.can_cast('bool', 'S4')) assert_(np.can_cast('b', 'S4')) assert_(not np.can_cast('b', 'S3')) assert_(np.can_cast('u1', 'S3')) assert_(not np.can_cast('u1', 'S2')) assert_(np.can_cast('u2', 'S5')) assert_(not np.can_cast('u2', 'S4')) assert_(np.can_cast('u4', 'S10')) assert_(not np.can_cast('u4', 'S9')) assert_(np.can_cast('u8', 'S20')) assert_(not np.can_cast('u8', 'S19')) assert_(np.can_cast('i1', 'S4')) assert_(not np.can_cast('i1', 'S3')) assert_(np.can_cast('i2', 'S6')) assert_(not np.can_cast('i2', 'S5')) assert_(np.can_cast('i4', 'S11')) assert_(not np.can_cast('i4', 'S10')) assert_(np.can_cast('i8', 'S21')) assert_(not np.can_cast('i8', 'S20')) assert_(np.can_cast('bool', 'S5')) assert_(not np.can_cast('bool', 'S4')) assert_(np.can_cast('b', 'U4')) assert_(not np.can_cast('b', 'U3')) assert_(np.can_cast('u1', 'U3')) assert_(not np.can_cast('u1', 'U2')) assert_(np.can_cast('u2', 'U5')) assert_(not np.can_cast('u2', 'U4')) assert_(np.can_cast('u4', 'U10')) assert_(not np.can_cast('u4', 'U9')) assert_(np.can_cast('u8', 'U20')) assert_(not np.can_cast('u8', 'U19')) assert_(np.can_cast('i1', 'U4')) assert_(not np.can_cast('i1', 'U3')) assert_(np.can_cast('i2', 'U6')) assert_(not np.can_cast('i2', 'U5')) assert_(np.can_cast('i4', 'U11')) assert_(not np.can_cast('i4', 'U10')) assert_(np.can_cast('i8', 'U21')) assert_(not np.can_cast('i8', 'U20')) assert_raises(TypeError, np.can_cast, 'i4', None) assert_raises(TypeError, np.can_cast, None, 'i4') # Also test keyword arguments assert_(np.can_cast(from_=np.int32, to=np.int64)) def test_can_cast_simple_to_structured(self): # Non-structured can only be cast to structured in 'unsafe' mode. assert_(not np.can_cast('i4', 'i4,i4')) assert_(not np.can_cast('i4', 'i4,i2')) assert_(np.can_cast('i4', 'i4,i4', casting='unsafe')) assert_(np.can_cast('i4', 'i4,i2', casting='unsafe')) # Even if there is just a single field which is OK. assert_(not np.can_cast('i2', [('f1', 'i4')])) assert_(not np.can_cast('i2', [('f1', 'i4')], casting='same_kind')) assert_(np.can_cast('i2', [('f1', 'i4')], casting='unsafe')) # It should be the same for recursive structured or subarrays. assert_(not np.can_cast('i2', [('f1', 'i4,i4')])) assert_(np.can_cast('i2', [('f1', 'i4,i4')], casting='unsafe')) assert_(not np.can_cast('i2', [('f1', '(2,3)i4')])) assert_(np.can_cast('i2', [('f1', '(2,3)i4')], casting='unsafe')) def test_can_cast_structured_to_simple(self): # Need unsafe casting for structured to simple. assert_(not np.can_cast([('f1', 'i4')], 'i4')) assert_(np.can_cast([('f1', 'i4')], 'i4', casting='unsafe')) assert_(np.can_cast([('f1', 'i4')], 'i2', casting='unsafe')) # Since it is unclear what is being cast, multiple fields to # single should not work even for unsafe casting. assert_(not np.can_cast('i4,i4', 'i4', casting='unsafe')) # But a single field inside a single field is OK. assert_(not np.can_cast([('f1', [('x', 'i4')])], 'i4')) assert_(np.can_cast([('f1', [('x', 'i4')])], 'i4', casting='unsafe')) # And a subarray is fine too - it will just take the first element # (arguably not very consistently; might also take the first field). assert_(not np.can_cast([('f0', '(3,)i4')], 'i4')) assert_(np.can_cast([('f0', '(3,)i4')], 'i4', casting='unsafe')) # But a structured subarray with multiple fields should fail. assert_(not np.can_cast([('f0', ('i4,i4'), (2,))], 'i4', casting='unsafe')) def test_can_cast_values(self): # gh-5917 for dt in np.sctypes['int'] + np.sctypes['uint']: ii = np.iinfo(dt) assert_(np.can_cast(ii.min, dt)) assert_(np.can_cast(ii.max, dt)) assert_(not np.can_cast(ii.min - 1, dt)) assert_(not np.can_cast(ii.max + 1, dt)) for dt in np.sctypes['float']: fi = np.finfo(dt) assert_(np.can_cast(fi.min, dt)) assert_(np.can_cast(fi.max, dt)) # Custom exception class to test exception propagation in fromiter class NIterError(Exception): pass class TestFromiter: def makegen(self): return (x**2 for x in range(24)) def test_types(self): ai32 = np.fromiter(self.makegen(), np.int32) ai64 = np.fromiter(self.makegen(), np.int64) af = np.fromiter(self.makegen(), float) assert_(ai32.dtype == np.dtype(np.int32)) assert_(ai64.dtype == np.dtype(np.int64)) assert_(af.dtype == np.dtype(float)) def test_lengths(self): expected = np.array(list(self.makegen())) a = np.fromiter(self.makegen(), int) a20 = np.fromiter(self.makegen(), int, 20) assert_(len(a) == len(expected)) assert_(len(a20) == 20) assert_raises(ValueError, np.fromiter, self.makegen(), int, len(expected) + 10) def test_values(self): expected = np.array(list(self.makegen())) a = np.fromiter(self.makegen(), int) a20 = np.fromiter(self.makegen(), int, 20) assert_(np.alltrue(a == expected, axis=0)) assert_(np.alltrue(a20 == expected[:20], axis=0)) def load_data(self, n, eindex): # Utility method for the issue 2592 tests. # Raise an exception at the desired index in the iterator. for e in range(n): if e == eindex: raise NIterError('error at index %s' % eindex) yield e def test_2592(self): # Test iteration exceptions are correctly raised. count, eindex = 10, 5 assert_raises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) def test_2592_edge(self): # Test iter. exceptions, edge case (exception at end of iterator). count = 10 eindex = count-1 assert_raises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) class TestNonzero: def test_nonzero_trivial(self): assert_equal(np.count_nonzero(np.array([])), 0) assert_equal(np.count_nonzero(np.array([], dtype='?')), 0) assert_equal(np.nonzero(np.array([])), ([],)) assert_equal(np.count_nonzero(np.array([0])), 0) assert_equal(np.count_nonzero(np.array([0], dtype='?')), 0) assert_equal(np.nonzero(np.array([0])), ([],)) assert_equal(np.count_nonzero(np.array([1])), 1) assert_equal(np.count_nonzero(np.array([1], dtype='?')), 1) assert_equal(np.nonzero(np.array([1])), ([0],)) def test_nonzero_zerod(self): assert_equal(np.count_nonzero(np.array(0)), 0) assert_equal(np.count_nonzero(np.array(0, dtype='?')), 0) with assert_warns(DeprecationWarning): assert_equal(np.nonzero(np.array(0)), ([],)) assert_equal(np.count_nonzero(np.array(1)), 1) assert_equal(np.count_nonzero(np.array(1, dtype='?')), 1) with assert_warns(DeprecationWarning): assert_equal(np.nonzero(np.array(1)), ([0],)) def test_nonzero_onedim(self): x = np.array([1, 0, 2, -1, 0, 0, 8]) assert_equal(np.count_nonzero(x), 4) assert_equal(np.count_nonzero(x), 4) assert_equal(np.nonzero(x), ([0, 2, 3, 6],)) x = np.array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)], dtype=[('a', 'i4'), ('b', 'i2')]) assert_equal(np.count_nonzero(x['a']), 3) assert_equal(np.count_nonzero(x['b']), 4) assert_equal(np.nonzero(x['a']), ([0, 2, 3],)) assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],)) def test_nonzero_twodim(self): x = np.array([[0, 1, 0], [2, 0, 3]]) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2])) x = np.eye(3) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2])) x = np.array([[(0, 1), (0, 0), (1, 11)], [(1, 1), (1, 0), (0, 0)], [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')]) assert_equal(np.count_nonzero(x['a']), 4) assert_equal(np.count_nonzero(x['b']), 5) assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1])) assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2])) assert_(not x['a'].T.flags.aligned) assert_equal(np.count_nonzero(x['a'].T), 4) assert_equal(np.count_nonzero(x['b'].T), 5) assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0])) assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2])) def test_sparse(self): # test special sparse condition boolean code path for i in range(20): c = np.zeros(200, dtype=bool) c[i::20] = True assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20)) c = np.zeros(400, dtype=bool) c[10 + i:20 + i] = True c[20 + i*2] = True assert_equal(np.nonzero(c)[0], np.concatenate((np.arange(10 + i, 20 + i), [20 + i*2]))) def test_return_type(self): class C(np.ndarray): pass for view in (C, np.ndarray): for nd in range(1, 4): shape = tuple(range(2, 2+nd)) x = np.arange(np.prod(shape)).reshape(shape).view(view) for nzx in (np.nonzero(x), x.nonzero()): for nzx_i in nzx: assert_(type(nzx_i) is np.ndarray) assert_(nzx_i.flags.writeable) def test_count_nonzero_axis(self): # Basic check of functionality m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]]) expected = np.array([1, 1, 1, 1, 1]) assert_equal(np.count_nonzero(m, axis=0), expected) expected = np.array([2, 3]) assert_equal(np.count_nonzero(m, axis=1), expected) assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1)) assert_raises(TypeError, np.count_nonzero, m, axis='foo') assert_raises(np.AxisError, np.count_nonzero, m, axis=3) assert_raises(TypeError, np.count_nonzero, m, axis=np.array([[1], [2]])) def test_count_nonzero_axis_all_dtypes(self): # More thorough test that the axis argument is respected # for all dtypes and responds correctly when presented with # either integer or tuple arguments for axis msg = "Mismatch for dtype: %s" def assert_equal_w_dt(a, b, err_msg): assert_equal(a.dtype, b.dtype, err_msg=err_msg) assert_equal(a, b, err_msg=err_msg) for dt in np.typecodes['All']: err_msg = msg % (np.dtype(dt).name,) if dt != 'V': if dt != 'M': m = np.zeros((3, 3), dtype=dt) n = np.ones(1, dtype=dt) m[0, 0] = n[0] m[1, 0] = n[0] else: # np.zeros doesn't work for np.datetime64 m = np.array(['1970-01-01'] * 9) m = m.reshape((3, 3)) m[0, 0] = '1970-01-12' m[1, 0] = '1970-01-12' m = m.astype(dt) expected = np.array([2, 0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=0), expected, err_msg=err_msg) expected = np.array([1, 1, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=1), expected, err_msg=err_msg) expected = np.array(2) assert_equal(np.count_nonzero(m, axis=(0, 1)), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m, axis=None), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m), expected, err_msg=err_msg) if dt == 'V': # There are no 'nonzero' objects for np.void, so the testing # setup is slightly different for this dtype m = np.array([np.void(1)] * 6).reshape((2, 3)) expected = np.array([0, 0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=0), expected, err_msg=err_msg) expected = np.array([0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=1), expected, err_msg=err_msg) expected = np.array(0) assert_equal(np.count_nonzero(m, axis=(0, 1)), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m, axis=None), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m), expected, err_msg=err_msg) def test_count_nonzero_axis_consistent(self): # Check that the axis behaviour for valid axes in # non-special cases is consistent (and therefore # correct) by checking it against an integer array # that is then casted to the generic object dtype from itertools import combinations, permutations axis = (0, 1, 2, 3) size = (5, 5, 5, 5) msg = "Mismatch for axis: %s" rng = np.random.RandomState(1234) m = rng.randint(-100, 100, size=size) n = m.astype(object) for length in range(len(axis)): for combo in combinations(axis, length): for perm in permutations(combo): assert_equal( np.count_nonzero(m, axis=perm), np.count_nonzero(n, axis=perm), err_msg=msg % (perm,)) def test_countnonzero_axis_empty(self): a = np.array([[0, 0, 1], [1, 0, 1]]) assert_equal(np.count_nonzero(a, axis=()), a.astype(bool)) def test_array_method(self): # Tests that the array method # call to nonzero works m = np.array([[1, 0, 0], [4, 0, 6]]) tgt = [[0, 1, 1], [0, 0, 2]] assert_equal(m.nonzero(), tgt) def test_nonzero_invalid_object(self): # gh-9295 a = np.array([np.array([1, 2]), 3], dtype=object) assert_raises(ValueError, np.nonzero, a) class BoolErrors: def __bool__(self): raise ValueError("Not allowed") assert_raises(ValueError, np.nonzero, np.array([BoolErrors()])) def test_nonzero_sideeffect_safety(self): # gh-13631 class FalseThenTrue: _val = False def __bool__(self): try: return self._val finally: self._val = True class TrueThenFalse: _val = True def __bool__(self): try: return self._val finally: self._val = False # result grows on the second pass a = np.array([True, FalseThenTrue()]) assert_raises(RuntimeError, np.nonzero, a) a = np.array([[True], [FalseThenTrue()]]) assert_raises(RuntimeError, np.nonzero, a) # result shrinks on the second pass a = np.array([False, TrueThenFalse()]) assert_raises(RuntimeError, np.nonzero, a) a = np.array([[False], [TrueThenFalse()]]) assert_raises(RuntimeError, np.nonzero, a) def test_nonzero_exception_safe(self): # gh-13930 class ThrowsAfter: def __init__(self, iters): self.iters_left = iters def __bool__(self): if self.iters_left == 0: raise ValueError("called `iters` times") self.iters_left -= 1 return True """ Test that a ValueError is raised instead of a SystemError If the __bool__ function is called after the error state is set, Python (cpython) will raise a SystemError. """ # assert that an exception in first pass is handled correctly a = np.array([ThrowsAfter(5)]*10) assert_raises(ValueError, np.nonzero, a) # raise exception in second pass for 1-dimensional loop a = np.array([ThrowsAfter(15)]*10) assert_raises(ValueError, np.nonzero, a) # raise exception in second pass for n-dimensional loop a = np.array([[ThrowsAfter(15)]]*10) assert_raises(ValueError, np.nonzero, a) class TestIndex: def test_boolean(self): a = rand(3, 5, 8) V = rand(5, 8) g1 = randint(0, 5, size=15) g2 = randint(0, 8, size=15) V[g1, g2] = -V[g1, g2] assert_((np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all()) def test_boolean_edgecase(self): a = np.array([], dtype='int32') b = np.array([], dtype='bool') c = a[b] assert_equal(c, []) assert_equal(c.dtype, np.dtype('int32')) class TestBinaryRepr: def test_zero(self): assert_equal(np.binary_repr(0), '0') def test_positive(self): assert_equal(np.binary_repr(10), '1010') assert_equal(np.binary_repr(12522), '11000011101010') assert_equal(np.binary_repr(10736848), '101000111101010011010000') def test_negative(self): assert_equal(np.binary_repr(-1), '-1') assert_equal(np.binary_repr(-10), '-1010') assert_equal(np.binary_repr(-12522), '-11000011101010') assert_equal(np.binary_repr(-10736848), '-101000111101010011010000') def test_sufficient_width(self): assert_equal(np.binary_repr(0, width=5), '00000') assert_equal(np.binary_repr(10, width=7), '0001010') assert_equal(np.binary_repr(-5, width=7), '1111011') def test_neg_width_boundaries(self): # see gh-8670 # Ensure that the example in the issue does not # break before proceeding to a more thorough test. assert_equal(np.binary_repr(-128, width=8), '10000000') for width in range(1, 11): num = -2**(width - 1) exp = '1' + (width - 1) * '0' assert_equal(np.binary_repr(num, width=width), exp) def test_large_neg_int64(self): # See gh-14289. assert_equal(np.binary_repr(np.int64(-2**62), width=64), '11' + '0'*62) class TestBaseRepr: def test_base3(self): assert_equal(np.base_repr(3**5, 3), '100000') def test_positive(self): assert_equal(np.base_repr(12, 10), '12') assert_equal(np.base_repr(12, 10, 4), '000012') assert_equal(np.base_repr(12, 4), '30') assert_equal(np.base_repr(3731624803700888, 36), '10QR0ROFCEW') def test_negative(self): assert_equal(np.base_repr(-12, 10), '-12') assert_equal(np.base_repr(-12, 10, 4), '-000012') assert_equal(np.base_repr(-12, 4), '-30') def test_base_range(self): with assert_raises(ValueError): np.base_repr(1, 1) with assert_raises(ValueError): np.base_repr(1, 37) class TestArrayComparisons: def test_array_equal(self): res = np.array_equal(np.array([1, 2]), np.array([1, 2])) assert_(res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([3, 4])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([1, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array(['a'], dtype='S1'), np.array(['a'], dtype='S1')) assert_(res) assert_(type(res) is bool) res = np.array_equal(np.array([('a', 1)], dtype='S1,u4'), np.array([('a', 1)], dtype='S1,u4')) assert_(res) assert_(type(res) is bool) def test_none_compares_elementwise(self): a = np.array([None, 1, None], dtype=object) assert_equal(a == None, [True, False, True]) assert_equal(a != None, [False, True, False]) a = np.ones(3) assert_equal(a == None, [False, False, False]) assert_equal(a != None, [True, True, True]) def test_array_equiv(self): res = np.array_equiv(np.array([1, 2]), np.array([1, 2])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([3, 4])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([1, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 1]), np.array([1])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([2])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) assert_(not res) assert_(type(res) is bool) def assert_array_strict_equal(x, y): assert_array_equal(x, y) # Check flags, 32 bit arches typically don't provide 16 byte alignment if ((x.dtype.alignment <= 8 or np.intp().dtype.itemsize != 4) and sys.platform != 'win32'): assert_(x.flags == y.flags) else: assert_(x.flags.owndata == y.flags.owndata) assert_(x.flags.writeable == y.flags.writeable) assert_(x.flags.c_contiguous == y.flags.c_contiguous) assert_(x.flags.f_contiguous == y.flags.f_contiguous) assert_(x.flags.writebackifcopy == y.flags.writebackifcopy) # check endianness assert_(x.dtype.isnative == y.dtype.isnative) class TestClip: def setup(self): self.nr = 5 self.nc = 3 def fastclip(self, a, m, M, out=None, casting=None): if out is None: if casting is None: return a.clip(m, M) else: return a.clip(m, M, casting=casting) else: if casting is None: return a.clip(m, M, out) else: return a.clip(m, M, out, casting=casting) def clip(self, a, m, M, out=None): # use slow-clip selector = np.less(a, m) + 2*np.greater(a, M) return selector.choose((a, m, M), out=out) # Handy functions def _generate_data(self, n, m): return randn(n, m) def _generate_data_complex(self, n, m): return randn(n, m) + 1.j * rand(n, m) def _generate_flt_data(self, n, m): return (randn(n, m)).astype(np.float32) def _neg_byteorder(self, a): a = np.asarray(a) if sys.byteorder == 'little': a = a.astype(a.dtype.newbyteorder('>')) else: a = a.astype(a.dtype.newbyteorder('<')) return a def _generate_non_native_data(self, n, m): data = randn(n, m) data = self._neg_byteorder(data) assert_(not data.dtype.isnative) return data def _generate_int_data(self, n, m): return (10 * rand(n, m)).astype(np.int64) def _generate_int32_data(self, n, m): return (10 * rand(n, m)).astype(np.int32) # Now the real test cases @pytest.mark.parametrize("dtype", '?bhilqpBHILQPefdgFDGO') def test_ones_pathological(self, dtype): # for preservation of behavior described in # gh-12519; amin > amax behavior may still change # in the future arr = np.ones(10, dtype=dtype) expected = np.zeros(10, dtype=dtype) actual = np.clip(arr, 1, 0) if dtype == 'O': assert actual.tolist() == expected.tolist() else: assert_equal(actual, expected) def test_simple_double(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.1 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_int(self): # Test native int input with scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(int) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_array_double(self): # Test native double input with array min/max. a = self._generate_data(self.nr, self.nc) m = np.zeros(a.shape) M = m + 0.5 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_nonnative(self): # Test non native double input with scalar min/max. # Test native double input with non native double scalar min/max. a = self._generate_non_native_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) # Test native double input with non native double scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = self._neg_byteorder(0.6) assert_(not M.dtype.isnative) ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) def test_simple_complex(self): # Test native complex input with native double scalar min/max. # Test native input with complex double scalar min/max. a = 3 * self._generate_data_complex(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) # Test native input with complex double scalar min/max. a = 3 * self._generate_data(self.nr, self.nc) m = -0.5 + 1.j M = 1. + 2.j ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_clip_complex(self): # Address Issue gh-5354 for clipping complex arrays # Test native complex input without explicit min/max # ie, either min=None or max=None a = np.ones(10, dtype=complex) m = a.min() M = a.max() am = self.fastclip(a, m, None) aM = self.fastclip(a, None, M) assert_array_strict_equal(am, a) assert_array_strict_equal(aM, a) def test_clip_non_contig(self): # Test clip for non contiguous native input and native scalar min/max. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = self.fastclip(a, -1.6, 1.7) act = self.clip(a, -1.6, 1.7) assert_array_strict_equal(ac, act) def test_simple_out(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = np.zeros(a.shape) act = np.zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) @pytest.mark.parametrize("casting", [None, "unsafe"]) def test_simple_int32_inout(self, casting): # Test native int32 input with double min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = np.float64(0) M = np.float64(2) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() if casting is None: with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac, casting=casting) else: # explicitly passing "unsafe" will silence warning self.fastclip(a, m, M, ac, casting=casting) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_out(self): # Test native int32 input with int32 scalar min/max and int64 out. a = self._generate_int32_data(self.nr, self.nc) m = np.int32(-1) M = np.int32(1) ac = np.zeros(a.shape, dtype=np.int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_inout(self): # Test native int32 input with double array min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = np.zeros(a.shape, np.float64) M = np.float64(1) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int32_out(self): # Test native double input with scalar min/max and int out. a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_inplace_01(self): # Test native double input with array min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = np.zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_simple_inplace_02(self): # Test native double input with scalar min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(ac, m, M, ac) assert_array_strict_equal(a, ac) def test_noncontig_inplace(self): # Test non contiguous double input with double scalar min/max in-place. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(ac, m, M, ac) assert_array_equal(a, ac) def test_type_cast_01(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_02(self): # Test native int32 input with int32 scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(np.int32) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_03(self): # Test native int32 input with float64 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = -2 M = 4 ac = self.fastclip(a, np.float64(m), np.float64(M)) act = self.clip(a, np.float64(m), np.float64(M)) assert_array_strict_equal(ac, act) def test_type_cast_04(self): # Test native int32 input with float32 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = np.float32(-2) M = np.float32(4) act = self.fastclip(a, m, M) ac = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_05(self): # Test native int32 with double arrays min/max. a = self._generate_int_data(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m * np.zeros(a.shape), M) act = self.clip(a, m * np.zeros(a.shape), M) assert_array_strict_equal(ac, act) def test_type_cast_06(self): # Test native with NON native scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.5 m_s = self._neg_byteorder(m) M = 1. act = self.clip(a, m_s, M) ac = self.fastclip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_07(self): # Test NON native with native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * np.ones(a.shape) M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) act = a_s.clip(m, M) ac = self.fastclip(a_s, m, M) assert_array_strict_equal(ac, act) def test_type_cast_08(self): # Test NON native with native scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) ac = self.fastclip(a_s, m, M) act = a_s.clip(m, M) assert_array_strict_equal(ac, act) def test_type_cast_09(self): # Test native with NON native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * np.ones(a.shape) M = 1. m_s = self._neg_byteorder(m) assert_(not m_s.dtype.isnative) ac = self.fastclip(a, m_s, M) act = self.clip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_10(self): # Test native int32 with float min/max and float out for output argument. a = self._generate_int_data(self.nr, self.nc) b = np.zeros(a.shape, dtype=np.float32) m = np.float32(-0.5) M = np.float32(1) act = self.clip(a, m, M, out=b) ac = self.fastclip(a, m, M, out=b) assert_array_strict_equal(ac, act) def test_type_cast_11(self): # Test non native with native scalar, min/max, out non native a = self._generate_non_native_data(self.nr, self.nc) b = a.copy() b = b.astype(b.dtype.newbyteorder('>')) bt = b.copy() m = -0.5 M = 1. self.fastclip(a, m, M, out=b) self.clip(a, m, M, out=bt) assert_array_strict_equal(b, bt) def test_type_cast_12(self): # Test native int32 input and min/max and float out a = self._generate_int_data(self.nr, self.nc) b = np.zeros(a.shape, dtype=np.float32) m = np.int32(0) M = np.int32(1) act = self.clip(a, m, M, out=b) ac = self.fastclip(a, m, M, out=b) assert_array_strict_equal(ac, act) def test_clip_with_out_simple(self): # Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = np.zeros(a.shape) act = np.zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple2(self): # Test native int32 input with double min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = np.float64(0) M = np.float64(2) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple_int32(self): # Test native int32 input with int32 scalar min/max and int64 out a = self._generate_int32_data(self.nr, self.nc) m = np.int32(-1) M = np.int32(1) ac = np.zeros(a.shape, dtype=np.int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_int32(self): # Test native int32 input with double array min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = np.zeros(a.shape, np.float64) M = np.float64(1) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_outint32(self): # Test native double input with scalar min/max and int out a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_transposed(self): # Test that the out argument works when transposed a = np.arange(16).reshape(4, 4) out = np.empty_like(a).T a.clip(4, 10, out=out) expected = self.clip(a, 4, 10) assert_array_equal(out, expected) def test_clip_with_out_memory_overlap(self): # Test that the out argument works when it has memory overlap a = np.arange(16).reshape(4, 4) ac = a.copy() a[:-1].clip(4, 10, out=a[1:]) expected = self.clip(ac[:-1], 4, 10) assert_array_equal(a[1:], expected) def test_clip_inplace_array(self): # Test native double input with array min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = np.zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_inplace_simple(self): # Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_func_takes_out(self): # Ensure that the clip() function takes an out=argument. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 a2 = np.clip(a, m, M, out=a) self.clip(a, m, M, ac) assert_array_strict_equal(a2, ac) assert_(a2 is a) def test_clip_nan(self): d = np.arange(7.) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan, max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=-2, max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan, max=10), d) def test_object_clip(self): a = np.arange(10, dtype=object) actual = np.clip(a, 1, 5) expected = np.array([1, 1, 2, 3, 4, 5, 5, 5, 5, 5]) assert actual.tolist() == expected.tolist() def test_clip_all_none(self): a = np.arange(10, dtype=object) with assert_raises_regex(ValueError, 'max or min'): np.clip(a, None, None) def test_clip_invalid_casting(self): a = np.arange(10, dtype=object) with assert_raises_regex(ValueError, 'casting must be one of'): self.fastclip(a, 1, 8, casting="garbage") @pytest.mark.parametrize("amin, amax", [ # two scalars (1, 0), # mix scalar and array (1, np.zeros(10)), # two arrays (np.ones(10), np.zeros(10)), ]) def test_clip_value_min_max_flip(self, amin, amax): a = np.arange(10, dtype=np.int64) # requirement from ufunc_docstrings.py expected = np.minimum(np.maximum(a, amin), amax) actual = np.clip(a, amin, amax) assert_equal(actual, expected) @pytest.mark.parametrize("arr, amin, amax, exp", [ # for a bug in npy_ObjectClip, based on a # case produced by hypothesis (np.zeros(10, dtype=np.int64), 0, -2**64+1, np.full(10, -2**64+1, dtype=object)), # for bugs in NPY_TIMEDELTA_MAX, based on a case # produced by hypothesis (np.zeros(10, dtype='m8') - 1, 0, 0, np.zeros(10, dtype='m8')), ]) def test_clip_problem_cases(self, arr, amin, amax, exp): actual = np.clip(arr, amin, amax) assert_equal(actual, exp) @pytest.mark.xfail(reason="no scalar nan propagation yet", raises=AssertionError, strict=True) @pytest.mark.parametrize("arr, amin, amax", [ # problematic scalar nan case from hypothesis (np.zeros(10, dtype=np.int64), np.array(np.nan), np.zeros(10, dtype=np.int32)), ]) @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_clip_scalar_nan_propagation(self, arr, amin, amax): # enforcement of scalar nan propagation for comparisons # called through clip() expected = np.minimum(np.maximum(arr, amin), amax) actual = np.clip(arr, amin, amax) assert_equal(actual, expected) @pytest.mark.xfail(reason="propagation doesn't match spec") @pytest.mark.parametrize("arr, amin, amax", [ (np.array([1] * 10, dtype='m8'), np.timedelta64('NaT'), np.zeros(10, dtype=np.int32)), ]) @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_NaT_propagation(self, arr, amin, amax): # NOTE: the expected function spec doesn't # propagate NaT, but clip() now does expected = np.minimum(np.maximum(arr, amin), amax) actual = np.clip(arr, amin, amax) assert_equal(actual, expected) @given(data=st.data(), shape=hynp.array_shapes()) def test_clip_property(self, data, shape): """A property-based test using Hypothesis. This aims for maximum generality: it could in principle generate *any* valid inputs to np.clip, and in practice generates much more varied inputs than human testers come up with. Because many of the inputs have tricky dependencies - compatible dtypes and mutually-broadcastable shapes - we use `st.data()` strategy draw values *inside* the test function, from strategies we construct based on previous values. An alternative would be to define a custom strategy with `@st.composite`, but until we have duplicated code inline is fine. That accounts for most of the function; the actual test is just three lines to calculate and compare actual vs expected results! """ # Our base array and bounds should not need to be of the same type as # long as they are all compatible - so we allow any int or float type. dtype_strategy = hynp.integer_dtypes() | hynp.floating_dtypes() # The following line is a total hack to disable the varied-dtypes # component of this test, because result != expected if dtypes can vary. dtype_strategy = st.just(data.draw(dtype_strategy)) # Generate an arbitrary array of the chosen shape and dtype # This is the value that we clip. arr = data.draw(hynp.arrays(dtype=dtype_strategy, shape=shape)) # Generate shapes for the bounds which can be broadcast with each other # and with the base shape. Below, we might decide to use scalar bounds, # but it's clearer to generate these shapes unconditionally in advance. in_shapes, result_shape = data.draw( hynp.mutually_broadcastable_shapes( num_shapes=2, base_shape=shape, # Commenting out the min_dims line allows zero-dimensional arrays, # and zero-dimensional arrays containing NaN make the test fail. min_dims=1 ) ) amin = data.draw( dtype_strategy.flatmap(hynp.from_dtype) | hynp.arrays(dtype=dtype_strategy, shape=in_shapes[0]) ) amax = data.draw( dtype_strategy.flatmap(hynp.from_dtype) | hynp.arrays(dtype=dtype_strategy, shape=in_shapes[1]) ) # If we allow either bound to be a scalar `nan`, the test will fail - # so we just "assume" that away (if it is, this raises a special # exception and Hypothesis will try again with different inputs) assume(not np.isscalar(amin) or not np.isnan(amin)) assume(not np.isscalar(amax) or not np.isnan(amax)) # Then calculate our result and expected result and check that they're # equal! See gh-12519 for discussion deciding on this property. result = np.clip(arr, amin, amax) expected = np.minimum(amax, np.maximum(arr, amin)) assert_array_equal(result, expected) class TestAllclose: rtol = 1e-5 atol = 1e-8 def setup(self): self.olderr = np.seterr(invalid='ignore') def teardown(self): np.seterr(**self.olderr) def tst_allclose(self, x, y): assert_(np.allclose(x, y), "%s and %s not close" % (x, y)) def tst_not_allclose(self, x, y): assert_(not np.allclose(x, y), "%s and %s shouldn't be close" % (x, y)) def test_ip_allclose(self): # Parametric test factory. arr = np.array([100, 1000]) aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([1, 0], [1, 0]), ([atol], [0]), ([1], [1+rtol+atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol*2), (aran, aran + aran*rtol), (np.inf, np.inf), (np.inf, [np.inf])] for (x, y) in data: self.tst_allclose(x, y) def test_ip_not_allclose(self): # Parametric test factory. aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([np.inf, 0], [1, np.inf]), ([np.inf, 0], [1, 0]), ([np.inf, np.inf], [1, np.inf]), ([np.inf, np.inf], [1, 0]), ([-np.inf, 0], [np.inf, 0]), ([np.nan, 0], [np.nan, 0]), ([atol*2], [0]), ([1], [1+rtol+atol*2]), (aran, aran + aran*atol + atol*2), (np.array([np.inf, 1]), np.array([0, np.inf]))] for (x, y) in data: self.tst_not_allclose(x, y) def test_no_parameter_modification(self): x = np.array([np.inf, 1]) y = np.array([0, np.inf]) np.allclose(x, y) assert_array_equal(x, np.array([np.inf, 1])) assert_array_equal(y, np.array([0, np.inf])) def test_min_int(self): # Could make problems because of abs(min_int) == min_int min_int = np.iinfo(np.int_).min a = np.array([min_int], dtype=np.int_) assert_(np.allclose(a, a)) def test_equalnan(self): x = np.array([1.0, np.nan]) assert_(np.allclose(x, x, equal_nan=True)) def test_return_class_is_ndarray(self): # Issue gh-6475 # Check that allclose does not preserve subtypes class Foo(np.ndarray): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) a = Foo([1]) assert_(type(np.allclose(a, a)) is bool) class TestIsclose: rtol = 1e-5 atol = 1e-8 def setup(self): atol = self.atol rtol = self.rtol arr = np.array([100, 1000]) aran = np.arange(125).reshape((5, 5, 5)) self.all_close_tests = [ ([1, 0], [1, 0]), ([atol], [0]), ([1], [1 + rtol + atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol), (aran, aran + aran*rtol), (np.inf, np.inf), (np.inf, [np.inf]), ([np.inf, -np.inf], [np.inf, -np.inf]), ] self.none_close_tests = [ ([np.inf, 0], [1, np.inf]), ([np.inf, -np.inf], [1, 0]), ([np.inf, np.inf], [1, -np.inf]), ([np.inf, np.inf], [1, 0]), ([np.nan, 0], [np.nan, -np.inf]), ([atol*2], [0]), ([1], [1 + rtol + atol*2]), (aran, aran + rtol*1.1*aran + atol*1.1), (np.array([np.inf, 1]), np.array([0, np.inf])), ] self.some_close_tests = [ ([np.inf, 0], [np.inf, atol*2]), ([atol, 1, 1e6*(1 + 2*rtol) + atol], [0, np.nan, 1e6]), (np.arange(3), [0, 1, 2.1]), (np.nan, [np.nan, np.nan, np.nan]), ([0], [atol, np.inf, -np.inf, np.nan]), (0, [atol, np.inf, -np.inf, np.nan]), ] self.some_close_results = [ [True, False], [True, False, False], [True, True, False], [False, False, False], [True, False, False, False], [True, False, False, False], ] def test_ip_isclose(self): self.setup() tests = self.some_close_tests results = self.some_close_results for (x, y), result in zip(tests, results): assert_array_equal(np.isclose(x, y), result) def tst_all_isclose(self, x, y): assert_(np.all(np.isclose(x, y)), "%s and %s not close" % (x, y)) def tst_none_isclose(self, x, y): msg = "%s and %s shouldn't be close" assert_(not np.any(np.isclose(x, y)), msg % (x, y)) def tst_isclose_allclose(self, x, y): msg = "isclose.all() and allclose aren't same for %s and %s" msg2 = "isclose and allclose aren't same for %s and %s" if np.isscalar(x) and np.isscalar(y): assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y)) else: assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y)) def test_ip_all_isclose(self): self.setup() for (x, y) in self.all_close_tests: self.tst_all_isclose(x, y) def test_ip_none_isclose(self): self.setup() for (x, y) in self.none_close_tests: self.tst_none_isclose(x, y) def test_ip_isclose_allclose(self): self.setup() tests = (self.all_close_tests + self.none_close_tests + self.some_close_tests) for (x, y) in tests: self.tst_isclose_allclose(x, y) def test_equal_nan(self): assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True]) arr = np.array([1.0, np.nan]) assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True]) def test_masked_arrays(self): # Make sure to test the output type when arguments are interchanged. x = np.ma.masked_where([True, True, False], np.arange(3)) assert_(type(x) is type(np.isclose(2, x))) assert_(type(x) is type(np.isclose(x, 2))) x = np.ma.masked_where([True, True, False], [np.nan, np.inf, np.nan]) assert_(type(x) is type(np.isclose(np.inf, x))) assert_(type(x) is type(np.isclose(x, np.inf))) x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan]) y = np.isclose(np.nan, x, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) y = np.isclose(x, np.nan, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan]) y = np.isclose(x, x, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) def test_scalar_return(self): assert_(np.isscalar(np.isclose(1, 1))) def test_no_parameter_modification(self): x = np.array([np.inf, 1]) y = np.array([0, np.inf]) np.isclose(x, y) assert_array_equal(x, np.array([np.inf, 1])) assert_array_equal(y, np.array([0, np.inf])) def test_non_finite_scalar(self): # GH7014, when two scalars are compared the output should also be a # scalar assert_(np.isclose(np.inf, -np.inf) is np.False_) assert_(np.isclose(0, np.inf) is np.False_) assert_(type(np.isclose(0, np.inf)) is np.bool_) class TestStdVar: def setup(self): self.A = np.array([1, -1, 1, -1]) self.real_var = 1 def test_basic(self): assert_almost_equal(np.var(self.A), self.real_var) assert_almost_equal(np.std(self.A)**2, self.real_var) def test_scalars(self): assert_equal(np.var(1), 0) assert_equal(np.std(1), 0) def test_ddof1(self): assert_almost_equal(np.var(self.A, ddof=1), self.real_var*len(self.A)/float(len(self.A)-1)) assert_almost_equal(np.std(self.A, ddof=1)**2, self.real_var*len(self.A)/float(len(self.A)-1)) def test_ddof2(self): assert_almost_equal(np.var(self.A, ddof=2), self.real_var*len(self.A)/float(len(self.A)-2)) assert_almost_equal(np.std(self.A, ddof=2)**2, self.real_var*len(self.A)/float(len(self.A)-2)) def test_out_scalar(self): d = np.arange(10) out = np.array(0.) r = np.std(d, out=out) assert_(r is out) assert_array_equal(r, out) r = np.var(d, out=out) assert_(r is out) assert_array_equal(r, out) r = np.mean(d, out=out) assert_(r is out) assert_array_equal(r, out) class TestStdVarComplex: def test_basic(self): A = np.array([1, 1.j, -1, -1.j]) real_var = 1 assert_almost_equal(np.var(A), real_var) assert_almost_equal(np.std(A)**2, real_var) def test_scalars(self): assert_equal(np.var(1j), 0) assert_equal(np.std(1j), 0) class TestCreationFuncs: # Test ones, zeros, empty and full. def setup(self): dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())} # void, bytes, str variable_sized = {tp for tp in dtypes if tp.str.endswith('0')} self.dtypes = sorted(dtypes - variable_sized | {np.dtype(tp.str.replace("0", str(i))) for tp in variable_sized for i in range(1, 10)}, key=lambda dtype: dtype.str) self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'} self.ndims = 10 def check_function(self, func, fill_value=None): par = ((0, 1, 2), range(self.ndims), self.orders, self.dtypes) fill_kwarg = {} if fill_value is not None: fill_kwarg = {'fill_value': fill_value} for size, ndims, order, dtype in itertools.product(*par): shape = ndims * [size] # do not fill void type if fill_kwarg and dtype.str.startswith('|V'): continue arr = func(shape, order=order, dtype=dtype, **fill_kwarg) assert_equal(arr.dtype, dtype) assert_(getattr(arr.flags, self.orders[order])) if fill_value is not None: if dtype.str.startswith('|S'): val = str(fill_value) else: val = fill_value assert_equal(arr, dtype.type(val)) def test_zeros(self): self.check_function(np.zeros) def test_ones(self): self.check_function(np.zeros) def test_empty(self): self.check_function(np.empty) def test_full(self): self.check_function(np.full, 0) self.check_function(np.full, 1) @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") def test_for_reference_leak(self): # Make sure we have an object for reference dim = 1 beg = sys.getrefcount(dim) np.zeros([dim]*10) assert_(sys.getrefcount(dim) == beg) np.ones([dim]*10) assert_(sys.getrefcount(dim) == beg) np.empty([dim]*10) assert_(sys.getrefcount(dim) == beg) np.full([dim]*10, 0) assert_(sys.getrefcount(dim) == beg) class TestLikeFuncs: '''Test ones_like, zeros_like, empty_like and full_like''' def setup(self): self.data = [ # Array scalars (np.array(3.), None), (np.array(3), 'f8'), # 1D arrays (np.arange(6, dtype='f4'), None), (np.arange(6), 'c16'), # 2D C-layout arrays (np.arange(6).reshape(2, 3), None), (np.arange(6).reshape(3, 2), 'i1'), # 2D F-layout arrays (np.arange(6).reshape((2, 3), order='F'), None), (np.arange(6).reshape((3, 2), order='F'), 'i1'), # 3D C-layout arrays (np.arange(24).reshape(2, 3, 4), None), (np.arange(24).reshape(4, 3, 2), 'f4'), # 3D F-layout arrays (np.arange(24).reshape((2, 3, 4), order='F'), None), (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'), # 3D non-C/F-layout arrays (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None), (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'), ] self.shapes = [(5,), (5,6,), (5,6,7,)] def compare_array_value(self, dz, value, fill_value): if value is not None: if fill_value: try: z = dz.dtype.type(value) except OverflowError: pass else: assert_(np.all(dz == z)) else: assert_(np.all(dz == value)) def check_like_function(self, like_function, value, fill_value=False): if fill_value: fill_kwarg = {'fill_value': value} else: fill_kwarg = {} for d, dtype in self.data: # default (K) order, dtype dz = like_function(d, dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_equal(np.array(dz.strides)*d.dtype.itemsize, np.array(d.strides)*dz.dtype.itemsize) assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous) assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # C order, default dtype dz = like_function(d, order='C', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # F order, default dtype dz = like_function(d, order='F', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # A order dz = like_function(d, order='A', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) if d.flags.f_contiguous: assert_(dz.flags.f_contiguous) else: assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # Test the 'shape' parameter for s in self.shapes: for o in 'CFA': sz = like_function(d, dtype=dtype, shape=s, order=o, **fill_kwarg) assert_equal(sz.shape, s) if dtype is None: assert_equal(sz.dtype, d.dtype) else: assert_equal(sz.dtype, np.dtype(dtype)) if o == 'C' or (o == 'A' and d.flags.c_contiguous): assert_(sz.flags.c_contiguous) elif o == 'F' or (o == 'A' and d.flags.f_contiguous): assert_(sz.flags.f_contiguous) self.compare_array_value(sz, value, fill_value) if (d.ndim != len(s)): assert_equal(np.argsort(like_function(d, dtype=dtype, shape=s, order='K', **fill_kwarg).strides), np.argsort(np.empty(s, dtype=dtype, order='C').strides)) else: assert_equal(np.argsort(like_function(d, dtype=dtype, shape=s, order='K', **fill_kwarg).strides), np.argsort(d.strides)) # Test the 'subok' parameter class MyNDArray(np.ndarray): pass a = np.array([[1, 2], [3, 4]]).view(MyNDArray) b = like_function(a, **fill_kwarg) assert_(type(b) is MyNDArray) b = like_function(a, subok=False, **fill_kwarg) assert_(type(b) is not MyNDArray) def test_ones_like(self): self.check_like_function(np.ones_like, 1) def test_zeros_like(self): self.check_like_function(np.zeros_like, 0) def test_empty_like(self): self.check_like_function(np.empty_like, None) def test_filled_like(self): self.check_like_function(np.full_like, 0, True) self.check_like_function(np.full_like, 1, True) self.check_like_function(np.full_like, 1000, True) self.check_like_function(np.full_like, 123.456, True) self.check_like_function(np.full_like, np.inf, True) class TestCorrelate: def _setup(self, dt): self.x = np.array([1, 2, 3, 4, 5], dtype=dt) self.xs = np.arange(1, 20)[::3] self.y = np.array([-1, -2, -3], dtype=dt) self.z1 = np.array([ -3., -8., -14., -20., -26., -14., -5.], dtype=dt) self.z1_4 = np.array([-2., -5., -8., -11., -14., -5.], dtype=dt) self.z1r = np.array([-15., -22., -22., -16., -10., -4., -1.], dtype=dt) self.z2 = np.array([-5., -14., -26., -20., -14., -8., -3.], dtype=dt) self.z2r = np.array([-1., -4., -10., -16., -22., -22., -15.], dtype=dt) self.zs = np.array([-3., -14., -30., -48., -66., -84., -102., -54., -19.], dtype=dt) def test_float(self): self._setup(float) z = np.correlate(self.x, self.y, 'full') assert_array_almost_equal(z, self.z1) z = np.correlate(self.x, self.y[:-1], 'full') assert_array_almost_equal(z, self.z1_4) z = np.correlate(self.y, self.x, 'full') assert_array_almost_equal(z, self.z2) z = np.correlate(self.x[::-1], self.y, 'full') assert_array_almost_equal(z, self.z1r) z = np.correlate(self.y, self.x[::-1], 'full') assert_array_almost_equal(z, self.z2r) z = np.correlate(self.xs, self.y, 'full') assert_array_almost_equal(z, self.zs) def test_object(self): self._setup(Decimal) z = np.correlate(self.x, self.y, 'full') assert_array_almost_equal(z, self.z1) z = np.correlate(self.y, self.x, 'full') assert_array_almost_equal(z, self.z2) def test_no_overwrite(self): d = np.ones(100) k = np.ones(3) np.correlate(d, k) assert_array_equal(d, np.ones(100)) assert_array_equal(k, np.ones(3)) def test_complex(self): x = np.array([1, 2, 3, 4+1j], dtype=complex) y = np.array([-1, -2j, 3+1j], dtype=complex) r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex) r_z = r_z[::-1].conjugate() z = np.correlate(y, x, mode='full') assert_array_almost_equal(z, r_z) def test_zero_size(self): with pytest.raises(ValueError): np.correlate(np.array([]), np.ones(1000), mode='full') with pytest.raises(ValueError): np.correlate(np.ones(1000), np.array([]), mode='full') class TestConvolve: def test_object(self): d = [1.] * 100 k = [1.] * 3 assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3)) def test_no_overwrite(self): d = np.ones(100) k = np.ones(3) np.convolve(d, k) assert_array_equal(d, np.ones(100)) assert_array_equal(k, np.ones(3)) class TestArgwhere: @pytest.mark.parametrize('nd', [0, 1, 2]) def test_nd(self, nd): # get an nd array with multiple elements in every dimension x = np.empty((2,)*nd, bool) # none x[...] = False assert_equal(np.argwhere(x).shape, (0, nd)) # only one x[...] = False x.flat[0] = True assert_equal(np.argwhere(x).shape, (1, nd)) # all but one x[...] = True x.flat[0] = False assert_equal(np.argwhere(x).shape, (x.size - 1, nd)) # all x[...] = True assert_equal(np.argwhere(x).shape, (x.size, nd)) def test_2D(self): x = np.arange(6).reshape((2, 3)) assert_array_equal(np.argwhere(x > 1), [[0, 2], [1, 0], [1, 1], [1, 2]]) def test_list(self): assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]]) class TestStringFunction: def test_set_string_function(self): a = np.array([1]) np.set_string_function(lambda x: "FOO", repr=True) assert_equal(repr(a), "FOO") np.set_string_function(None, repr=True) assert_equal(repr(a), "array([1])") np.set_string_function(lambda x: "FOO", repr=False) assert_equal(str(a), "FOO") np.set_string_function(None, repr=False) assert_equal(str(a), "[1]") class TestRoll: def test_roll1d(self): x = np.arange(10) xr = np.roll(x, 2) assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) def test_roll2d(self): x2 = np.reshape(np.arange(10), (2, 5)) x2r = np.roll(x2, 1) assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]])) x2r = np.roll(x2, 1, axis=0) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, 1, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) # Roll multiple axes at once. x2r = np.roll(x2, 1, axis=(0, 1)) assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]])) x2r = np.roll(x2, (1, 0), axis=(0, 1)) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, (-1, 0), axis=(0, 1)) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, (0, 1), axis=(0, 1)) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) x2r = np.roll(x2, (0, -1), axis=(0, 1)) assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]])) x2r = np.roll(x2, (1, 1), axis=(0, 1)) assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]])) x2r = np.roll(x2, (-1, -1), axis=(0, 1)) assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]])) # Roll the same axis multiple times. x2r = np.roll(x2, 1, axis=(0, 0)) assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])) x2r = np.roll(x2, 1, axis=(1, 1)) assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]])) # Roll more than one turn in either direction. x2r = np.roll(x2, 6, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) x2r = np.roll(x2, -4, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) def test_roll_empty(self): x = np.array([]) assert_equal(np.roll(x, 1), np.array([])) class TestRollaxis: # expected shape indexed by (axis, start) for array of # shape (1, 2, 3, 4) tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4), (0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4), (0, 4): (2, 3, 4, 1), (1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4), (1, 2): (1, 2, 3, 4), (1, 3): (1, 3, 2, 4), (1, 4): (1, 3, 4, 2), (2, 0): (3, 1, 2, 4), (2, 1): (1, 3, 2, 4), (2, 2): (1, 2, 3, 4), (2, 3): (1, 2, 3, 4), (2, 4): (1, 2, 4, 3), (3, 0): (4, 1, 2, 3), (3, 1): (1, 4, 2, 3), (3, 2): (1, 2, 4, 3), (3, 3): (1, 2, 3, 4), (3, 4): (1, 2, 3, 4)} def test_exceptions(self): a = np.arange(1*2*3*4).reshape(1, 2, 3, 4) assert_raises(np.AxisError, np.rollaxis, a, -5, 0) assert_raises(np.AxisError, np.rollaxis, a, 0, -5) assert_raises(np.AxisError, np.rollaxis, a, 4, 0) assert_raises(np.AxisError, np.rollaxis, a, 0, 5) def test_results(self): a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy() aind = np.indices(a.shape) assert_(a.flags['OWNDATA']) for (i, j) in self.tgtshape: # positive axis, positive start res = np.rollaxis(a, axis=i, start=j) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(i, j)], str((i,j))) assert_(not res.flags['OWNDATA']) # negative axis, positive start ip = i + 1 res = np.rollaxis(a, axis=-ip, start=j) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(4 - ip, j)]) assert_(not res.flags['OWNDATA']) # positive axis, negative start jp = j + 1 if j < 4 else j res = np.rollaxis(a, axis=i, start=-jp) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(i, 4 - jp)]) assert_(not res.flags['OWNDATA']) # negative axis, negative start ip = i + 1 jp = j + 1 if j < 4 else j res = np.rollaxis(a, axis=-ip, start=-jp) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)]) assert_(not res.flags['OWNDATA']) class TestMoveaxis: def test_move_to_end(self): x = np.random.randn(5, 6, 7) for source, expected in [(0, (6, 7, 5)), (1, (5, 7, 6)), (2, (5, 6, 7)), (-1, (5, 6, 7))]: actual = np.moveaxis(x, source, -1).shape assert_(actual, expected) def test_move_new_position(self): x = np.random.randn(1, 2, 3, 4) for source, destination, expected in [ (0, 1, (2, 1, 3, 4)), (1, 2, (1, 3, 2, 4)), (1, -1, (1, 3, 4, 2)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, expected) def test_preserve_order(self): x = np.zeros((1, 2, 3, 4)) for source, destination in [ (0, 0), (3, -1), (-1, 3), ([0, -1], [0, -1]), ([2, 0], [2, 0]), (range(4), range(4)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, (1, 2, 3, 4)) def test_move_multiples(self): x = np.zeros((0, 1, 2, 3)) for source, destination, expected in [ ([0, 1], [2, 3], (2, 3, 0, 1)), ([2, 3], [0, 1], (2, 3, 0, 1)), ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)), ([3, 0], [1, 0], (0, 3, 1, 2)), ([0, 3], [0, 1], (0, 3, 1, 2)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, expected) def test_errors(self): x = np.random.randn(1, 2, 3) assert_raises_regex(np.AxisError, 'source.*out of bounds', np.moveaxis, x, 3, 0) assert_raises_regex(np.AxisError, 'source.*out of bounds', np.moveaxis, x, -4, 0) assert_raises_regex(np.AxisError, 'destination.*out of bounds', np.moveaxis, x, 0, 5) assert_raises_regex(ValueError, 'repeated axis in `source`', np.moveaxis, x, [0, 0], [0, 1]) assert_raises_regex(ValueError, 'repeated axis in `destination`', np.moveaxis, x, [0, 1], [1, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, 0, [0, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, [0, 1], [0]) def test_array_likes(self): x = np.ma.zeros((1, 2, 3)) result = np.moveaxis(x, 0, 0) assert_(x.shape, result.shape) assert_(isinstance(result, np.ma.MaskedArray)) x = [1, 2, 3] result = np.moveaxis(x, 0, 0) assert_(x, list(result)) assert_(isinstance(result, np.ndarray)) class TestCross: def test_2x2(self): u = [1, 2] v = [3, 4] z = -2 cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_2x3(self): u = [1, 2] v = [3, 4, 5] z = np.array([10, -5, -2]) cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_3x3(self): u = [1, 2, 3] v = [4, 5, 6] z = np.array([-3, 6, -3]) cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_broadcasting(self): # Ticket #2624 (Trac #2032) u = np.tile([1, 2], (11, 1)) v = np.tile([3, 4], (11, 1)) z = -2 assert_equal(np.cross(u, v), z) assert_equal(np.cross(v, u), -z) assert_equal(np.cross(u, u), 0) u = np.tile([1, 2], (11, 1)).T v = np.tile([3, 4, 5], (11, 1)) z = np.tile([10, -5, -2], (11, 1)) assert_equal(np.cross(u, v, axisa=0), z) assert_equal(np.cross(v, u.T), -z) assert_equal(np.cross(v, v), 0) u = np.tile([1, 2, 3], (11, 1)).T v = np.tile([3, 4], (11, 1)).T z = np.tile([-12, 9, -2], (11, 1)) assert_equal(np.cross(u, v, axisa=0, axisb=0), z) assert_equal(np.cross(v.T, u.T), -z) assert_equal(np.cross(u.T, u.T), 0) u = np.tile([1, 2, 3], (5, 1)) v = np.tile([4, 5, 6], (5, 1)).T z = np.tile([-3, 6, -3], (5, 1)) assert_equal(np.cross(u, v, axisb=0), z) assert_equal(np.cross(v.T, u), -z) assert_equal(np.cross(u, u), 0) def test_broadcasting_shapes(self): u = np.ones((2, 1, 3)) v = np.ones((5, 3)) assert_equal(np.cross(u, v).shape, (2, 5, 3)) u = np.ones((10, 3, 5)) v = np.ones((2, 5)) assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3)) assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=2) assert_raises(np.AxisError, np.cross, u, v, axisa=3, axisb=0) u = np.ones((10, 3, 5, 7)) v = np.ones((5, 7, 2)) assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7)) assert_raises(np.AxisError, np.cross, u, v, axisa=-5, axisb=2) assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=-4) # gh-5885 u = np.ones((3, 4, 2)) for axisc in range(-2, 2): assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4)) def test_outer_out_param(): arr1 = np.ones((5,)) arr2 = np.ones((2,)) arr3 = np.linspace(-2, 2, 5) out1 = np.ndarray(shape=(5,5)) out2 = np.ndarray(shape=(2, 5)) res1 = np.outer(arr1, arr3, out1) assert_equal(res1, out1) assert_equal(np.outer(arr2, arr3, out2), out2) class TestIndices: def test_simple(self): [x, y] = np.indices((4, 3)) assert_array_equal(x, np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])) assert_array_equal(y, np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]])) def test_single_input(self): [x] = np.indices((4,)) assert_array_equal(x, np.array([0, 1, 2, 3])) [x] = np.indices((4,), sparse=True) assert_array_equal(x, np.array([0, 1, 2, 3])) def test_scalar_input(self): assert_array_equal([], np.indices(())) assert_array_equal([], np.indices((), sparse=True)) assert_array_equal([[]], np.indices((0,))) assert_array_equal([[]], np.indices((0,), sparse=True)) def test_sparse(self): [x, y] = np.indices((4,3), sparse=True) assert_array_equal(x, np.array([[0], [1], [2], [3]])) assert_array_equal(y, np.array([[0, 1, 2]])) @pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) @pytest.mark.parametrize("dims", [(), (0,), (4, 3)]) def test_return_type(self, dtype, dims): inds = np.indices(dims, dtype=dtype) assert_(inds.dtype == dtype) for arr in np.indices(dims, dtype=dtype, sparse=True): assert_(arr.dtype == dtype) class TestRequire: flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS', 'F', 'F_CONTIGUOUS', 'FORTRAN', 'A', 'ALIGNED', 'W', 'WRITEABLE', 'O', 'OWNDATA'] def generate_all_false(self, dtype): arr = np.zeros((2, 2), [('junk', 'i1'), ('a', dtype)]) arr.setflags(write=False) a = arr['a'] assert_(not a.flags['C']) assert_(not a.flags['F']) assert_(not a.flags['O']) assert_(not a.flags['W']) assert_(not a.flags['A']) return a def set_and_check_flag(self, flag, dtype, arr): if dtype is None: dtype = arr.dtype b = np.require(arr, dtype, [flag]) assert_(b.flags[flag]) assert_(b.dtype == dtype) # a further call to np.require ought to return the same array # unless OWNDATA is specified. c = np.require(b, None, [flag]) if flag[0] != 'O': assert_(c is b) else: assert_(c.flags[flag]) def test_require_each(self): id = ['f8', 'i4'] fd = [None, 'f8', 'c16'] for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names): a = self.generate_all_false(idtype) self.set_and_check_flag(flag, fdtype, a) def test_unknown_requirement(self): a = self.generate_all_false('f8') assert_raises(KeyError, np.require, a, None, 'Q') def test_non_array_input(self): a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O']) assert_(a.flags['O']) assert_(a.flags['C']) assert_(a.flags['A']) assert_(a.dtype == 'i4') assert_equal(a, [1, 2, 3, 4]) def test_C_and_F_simul(self): a = self.generate_all_false('f8') assert_raises(ValueError, np.require, a, None, ['C', 'F']) def test_ensure_array(self): class ArraySubclass(np.ndarray): pass a = ArraySubclass((2, 2)) b = np.require(a, None, ['E']) assert_(type(b) is np.ndarray) def test_preserve_subtype(self): class ArraySubclass(np.ndarray): pass for flag in self.flag_names: a = ArraySubclass((2, 2)) self.set_and_check_flag(flag, None, a) class TestBroadcast: def test_broadcast_in_args(self): # gh-5881 arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)), np.empty((5, 1, 7))] mits = [np.broadcast(*arrs), np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])), np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])), np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])), np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])] for mit in mits: assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 4) for a, ia in zip(arrs, mit.iters): assert_(a is ia.base) def test_broadcast_single_arg(self): # gh-6899 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 1) assert_(arrs[0] is mit.iters[0].base) def test_number_of_arguments(self): arr = np.empty((5,)) for j in range(35): arrs = [arr] * j if j > 32: assert_raises(ValueError, np.broadcast, *arrs) else: mit = np.broadcast(*arrs) assert_equal(mit.numiter, j) def test_broadcast_error_kwargs(self): #gh-13455 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) mit2 = np.broadcast(*arrs, **{}) assert_equal(mit.shape, mit2.shape) assert_equal(mit.ndim, mit2.ndim) assert_equal(mit.nd, mit2.nd) assert_equal(mit.numiter, mit2.numiter) assert_(mit.iters[0].base is mit2.iters[0].base) assert_raises(ValueError, np.broadcast, 1, **{'x': 1}) class TestKeepdims: class sub_array(np.ndarray): def sum(self, axis=None, dtype=None, out=None): return np.ndarray.sum(self, axis, dtype, out, keepdims=True) def test_raise(self): sub_class = self.sub_array x = np.arange(30).view(sub_class) assert_raises(TypeError, np.sum, x, keepdims=True) class TestTensordot: def test_zero_dimension(self): # Test resolution to issue #5663 a = np.ndarray((3,0)) b = np.ndarray((0,4)) td = np.tensordot(a, b, (1, 0)) assert_array_equal(td, np.dot(a, b)) assert_array_equal(td, np.einsum('ij,jk', a, b)) def test_zero_dimensional(self): # gh-12130 arr_0d = np.array(1) ret = np.tensordot(arr_0d, arr_0d, ([], [])) # contracting no axes is well defined assert_array_equal(ret, arr_0d)
pdebuyl/numpy
numpy/core/tests/test_numeric.py
numpy/testing/_private/decorators.py
#!/usr/bin/env python3 """ cpuinfo Copyright 2002 Pearu Peterson all rights reserved, Pearu Peterson <pearu@cens.ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson """ __all__ = ['cpu'] import os import platform import re import sys import types import warnings from subprocess import getstatusoutput def getoutput(cmd, successful_status=(0,), stacklevel=1): try: status, output = getstatusoutput(cmd) except EnvironmentError as e: warnings.warn(str(e), UserWarning, stacklevel=stacklevel) return False, "" if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status: return True, output return False, output def command_info(successful_status=(0,), stacklevel=1, **kw): info = {} for key in kw: ok, output = getoutput(kw[key], successful_status=successful_status, stacklevel=stacklevel+1) if ok: info[key] = output.strip() return info def command_by_line(cmd, successful_status=(0,), stacklevel=1): ok, output = getoutput(cmd, successful_status=successful_status, stacklevel=stacklevel+1) if not ok: return for line in output.splitlines(): yield line.strip() def key_value_from_command(cmd, sep, successful_status=(0,), stacklevel=1): d = {} for line in command_by_line(cmd, successful_status=successful_status, stacklevel=stacklevel+1): l = [s.strip() for s in line.split(sep, 1)] if len(l) == 2: d[l[0]] = l[1] return d class CPUInfoBase: """Holds CPU information and provides methods for requiring the availability of various CPU features. """ def _try_call(self, func): try: return func() except Exception: pass def __getattr__(self, name): if not name.startswith('_'): if hasattr(self, '_'+name): attr = getattr(self, '_'+name) if isinstance(attr, types.MethodType): return lambda func=self._try_call,attr=attr : func(attr) else: return lambda : None raise AttributeError(name) def _getNCPUs(self): return 1 def __get_nbits(self): abits = platform.architecture()[0] nbits = re.compile(r'(\d+)bit').search(abits).group(1) return nbits def _is_32bit(self): return self.__get_nbits() == '32' def _is_64bit(self): return self.__get_nbits() == '64' class LinuxCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = [ {} ] ok, output = getoutput('uname -m') if ok: info[0]['uname_m'] = output.strip() try: fo = open('/proc/cpuinfo') except EnvironmentError as e: warnings.warn(str(e), UserWarning, stacklevel=2) else: for line in fo: name_value = [s.strip() for s in line.split(':', 1)] if len(name_value) != 2: continue name, value = name_value if not info or name in info[-1]: # next processor info.append({}) info[-1][name] = value fo.close() self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['vendor_id']=='AuthenticAMD' def _is_AthlonK6_2(self): return self._is_AMD() and self.info[0]['model'] == '2' def _is_AthlonK6_3(self): return self._is_AMD() and self.info[0]['model'] == '3' def _is_AthlonK6(self): return re.match(r'.*?AMD-K6', self.info[0]['model name']) is not None def _is_AthlonK7(self): return re.match(r'.*?AMD-K7', self.info[0]['model name']) is not None def _is_AthlonMP(self): return re.match(r'.*?Athlon\(tm\) MP\b', self.info[0]['model name']) is not None def _is_AMD64(self): return self.is_AMD() and self.info[0]['family'] == '15' def _is_Athlon64(self): return re.match(r'.*?Athlon\(tm\) 64\b', self.info[0]['model name']) is not None def _is_AthlonHX(self): return re.match(r'.*?Athlon HX\b', self.info[0]['model name']) is not None def _is_Opteron(self): return re.match(r'.*?Opteron\b', self.info[0]['model name']) is not None def _is_Hammer(self): return re.match(r'.*?Hammer\b', self.info[0]['model name']) is not None # Alpha def _is_Alpha(self): return self.info[0]['cpu']=='Alpha' def _is_EV4(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV4' def _is_EV5(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV5' def _is_EV56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV56' def _is_PCA56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'PCA56' # Intel #XXX _is_i386 = _not_impl def _is_Intel(self): return self.info[0]['vendor_id']=='GenuineIntel' def _is_i486(self): return self.info[0]['cpu']=='i486' def _is_i586(self): return self.is_Intel() and self.info[0]['cpu family'] == '5' def _is_i686(self): return self.is_Intel() and self.info[0]['cpu family'] == '6' def _is_Celeron(self): return re.match(r'.*?Celeron', self.info[0]['model name']) is not None def _is_Pentium(self): return re.match(r'.*?Pentium', self.info[0]['model name']) is not None def _is_PentiumII(self): return re.match(r'.*?Pentium.*?II\b', self.info[0]['model name']) is not None def _is_PentiumPro(self): return re.match(r'.*?PentiumPro\b', self.info[0]['model name']) is not None def _is_PentiumMMX(self): return re.match(r'.*?Pentium.*?MMX\b', self.info[0]['model name']) is not None def _is_PentiumIII(self): return re.match(r'.*?Pentium.*?III\b', self.info[0]['model name']) is not None def _is_PentiumIV(self): return re.match(r'.*?Pentium.*?(IV|4)\b', self.info[0]['model name']) is not None def _is_PentiumM(self): return re.match(r'.*?Pentium.*?M\b', self.info[0]['model name']) is not None def _is_Prescott(self): return self.is_PentiumIV() and self.has_sse3() def _is_Nocona(self): return (self.is_Intel() and (self.info[0]['cpu family'] == '6' or self.info[0]['cpu family'] == '15') and (self.has_sse3() and not self.has_ssse3()) and re.match(r'.*?\blm\b', self.info[0]['flags']) is not None) def _is_Core2(self): return (self.is_64bit() and self.is_Intel() and re.match(r'.*?Core\(TM\)2\b', self.info[0]['model name']) is not None) def _is_Itanium(self): return re.match(r'.*?Itanium\b', self.info[0]['family']) is not None def _is_XEON(self): return re.match(r'.*?XEON\b', self.info[0]['model name'], re.IGNORECASE) is not None _is_Xeon = _is_XEON # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_fdiv_bug(self): return self.info[0]['fdiv_bug']=='yes' def _has_f00f_bug(self): return self.info[0]['f00f_bug']=='yes' def _has_mmx(self): return re.match(r'.*?\bmmx\b', self.info[0]['flags']) is not None def _has_sse(self): return re.match(r'.*?\bsse\b', self.info[0]['flags']) is not None def _has_sse2(self): return re.match(r'.*?\bsse2\b', self.info[0]['flags']) is not None def _has_sse3(self): return re.match(r'.*?\bpni\b', self.info[0]['flags']) is not None def _has_ssse3(self): return re.match(r'.*?\bssse3\b', self.info[0]['flags']) is not None def _has_3dnow(self): return re.match(r'.*?\b3dnow\b', self.info[0]['flags']) is not None def _has_3dnowext(self): return re.match(r'.*?\b3dnowext\b', self.info[0]['flags']) is not None class IRIXCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = key_value_from_command('sysconf', sep=' ', successful_status=(0, 1)) self.__class__.info = info def _not_impl(self): pass def _is_singleCPU(self): return self.info.get('NUM_PROCESSORS') == '1' def _getNCPUs(self): return int(self.info.get('NUM_PROCESSORS', 1)) def __cputype(self, n): return self.info.get('PROCESSORS').split()[0].lower() == 'r%s' % (n) def _is_r2000(self): return self.__cputype(2000) def _is_r3000(self): return self.__cputype(3000) def _is_r3900(self): return self.__cputype(3900) def _is_r4000(self): return self.__cputype(4000) def _is_r4100(self): return self.__cputype(4100) def _is_r4300(self): return self.__cputype(4300) def _is_r4400(self): return self.__cputype(4400) def _is_r4600(self): return self.__cputype(4600) def _is_r4650(self): return self.__cputype(4650) def _is_r5000(self): return self.__cputype(5000) def _is_r6000(self): return self.__cputype(6000) def _is_r8000(self): return self.__cputype(8000) def _is_r10000(self): return self.__cputype(10000) def _is_r12000(self): return self.__cputype(12000) def _is_rorion(self): return self.__cputype('orion') def get_ip(self): try: return self.info.get('MACHINE') except Exception: pass def __machine(self, n): return self.info.get('MACHINE').lower() == 'ip%s' % (n) def _is_IP19(self): return self.__machine(19) def _is_IP20(self): return self.__machine(20) def _is_IP21(self): return self.__machine(21) def _is_IP22(self): return self.__machine(22) def _is_IP22_4k(self): return self.__machine(22) and self._is_r4000() def _is_IP22_5k(self): return self.__machine(22) and self._is_r5000() def _is_IP24(self): return self.__machine(24) def _is_IP25(self): return self.__machine(25) def _is_IP26(self): return self.__machine(26) def _is_IP27(self): return self.__machine(27) def _is_IP28(self): return self.__machine(28) def _is_IP30(self): return self.__machine(30) def _is_IP32(self): return self.__machine(32) def _is_IP32_5k(self): return self.__machine(32) and self._is_r5000() def _is_IP32_10k(self): return self.__machine(32) and self._is_r10000() class DarwinCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', machine='machine') info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=') self.__class__.info = info def _not_impl(self): pass def _getNCPUs(self): return int(self.info['sysctl_hw'].get('hw.ncpu', 1)) def _is_Power_Macintosh(self): return self.info['sysctl_hw']['hw.machine']=='Power Macintosh' def _is_i386(self): return self.info['arch']=='i386' def _is_ppc(self): return self.info['arch']=='ppc' def __machine(self, n): return self.info['machine'] == 'ppc%s'%n def _is_ppc601(self): return self.__machine(601) def _is_ppc602(self): return self.__machine(602) def _is_ppc603(self): return self.__machine(603) def _is_ppc603e(self): return self.__machine('603e') def _is_ppc604(self): return self.__machine(604) def _is_ppc604e(self): return self.__machine('604e') def _is_ppc620(self): return self.__machine(620) def _is_ppc630(self): return self.__machine(630) def _is_ppc740(self): return self.__machine(740) def _is_ppc7400(self): return self.__machine(7400) def _is_ppc7450(self): return self.__machine(7450) def _is_ppc750(self): return self.__machine(750) def _is_ppc403(self): return self.__machine(403) def _is_ppc505(self): return self.__machine(505) def _is_ppc801(self): return self.__machine(801) def _is_ppc821(self): return self.__machine(821) def _is_ppc823(self): return self.__machine(823) def _is_ppc860(self): return self.__machine(860) class SunOSCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', mach='mach', uname_i='uname_i', isainfo_b='isainfo -b', isainfo_n='isainfo -n', ) info['uname_X'] = key_value_from_command('uname -X', sep='=') for line in command_by_line('psrinfo -v 0'): m = re.match(r'\s*The (?P<p>[\w\d]+) processor operates at', line) if m: info['processor'] = m.group('p') break self.__class__.info = info def _not_impl(self): pass def _is_i386(self): return self.info['isainfo_n']=='i386' def _is_sparc(self): return self.info['isainfo_n']=='sparc' def _is_sparcv9(self): return self.info['isainfo_n']=='sparcv9' def _getNCPUs(self): return int(self.info['uname_X'].get('NumCPU', 1)) def _is_sun4(self): return self.info['arch']=='sun4' def _is_SUNW(self): return re.match(r'SUNW', self.info['uname_i']) is not None def _is_sparcstation5(self): return re.match(r'.*SPARCstation-5', self.info['uname_i']) is not None def _is_ultra1(self): return re.match(r'.*Ultra-1', self.info['uname_i']) is not None def _is_ultra250(self): return re.match(r'.*Ultra-250', self.info['uname_i']) is not None def _is_ultra2(self): return re.match(r'.*Ultra-2', self.info['uname_i']) is not None def _is_ultra30(self): return re.match(r'.*Ultra-30', self.info['uname_i']) is not None def _is_ultra4(self): return re.match(r'.*Ultra-4', self.info['uname_i']) is not None def _is_ultra5_10(self): return re.match(r'.*Ultra-5_10', self.info['uname_i']) is not None def _is_ultra5(self): return re.match(r'.*Ultra-5', self.info['uname_i']) is not None def _is_ultra60(self): return re.match(r'.*Ultra-60', self.info['uname_i']) is not None def _is_ultra80(self): return re.match(r'.*Ultra-80', self.info['uname_i']) is not None def _is_ultraenterprice(self): return re.match(r'.*Ultra-Enterprise', self.info['uname_i']) is not None def _is_ultraenterprice10k(self): return re.match(r'.*Ultra-Enterprise-10000', self.info['uname_i']) is not None def _is_sunfire(self): return re.match(r'.*Sun-Fire', self.info['uname_i']) is not None def _is_ultra(self): return re.match(r'.*Ultra', self.info['uname_i']) is not None def _is_cpusparcv7(self): return self.info['processor']=='sparcv7' def _is_cpusparcv8(self): return self.info['processor']=='sparcv8' def _is_cpusparcv9(self): return self.info['processor']=='sparcv9' class Win32CPUInfo(CPUInfoBase): info = None pkey = r"HARDWARE\DESCRIPTION\System\CentralProcessor" # XXX: what does the value of # HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0 # mean? def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! import winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" r"\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except Exception as e: print(e, '(ignoring)') self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['VendorIdentifier']=='AuthenticAMD' def _is_Am486(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_Am5x86(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_AMDK5(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [0, 1, 2, 3] def _is_AMDK6(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [6, 7] def _is_AMDK6_2(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==8 def _is_AMDK6_3(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==9 def _is_AMDK7(self): return self.is_AMD() and self.info[0]['Family'] == 6 # To reliably distinguish between the different types of AMD64 chips # (Athlon64, Operton, Athlon64 X2, Semperon, Turion 64, etc.) would # require looking at the 'brand' from cpuid def _is_AMD64(self): return self.is_AMD() and self.info[0]['Family'] == 15 # Intel def _is_Intel(self): return self.info[0]['VendorIdentifier']=='GenuineIntel' def _is_i386(self): return self.info[0]['Family']==3 def _is_i486(self): return self.info[0]['Family']==4 def _is_i586(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_i686(self): return self.is_Intel() and self.info[0]['Family']==6 def _is_Pentium(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_PentiumMMX(self): return self.is_Intel() and self.info[0]['Family']==5 \ and self.info[0]['Model']==4 def _is_PentiumPro(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model']==1 def _is_PentiumII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [3, 5, 6] def _is_PentiumIII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [7, 8, 9, 10, 11] def _is_PentiumIV(self): return self.is_Intel() and self.info[0]['Family']==15 def _is_PentiumM(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [9, 13, 14] def _is_Core2(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [15, 16, 17] # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_mmx(self): if self.is_Intel(): return (self.info[0]['Family']==5 and self.info[0]['Model']==4) \ or (self.info[0]['Family'] in [6, 15]) elif self.is_AMD(): return self.info[0]['Family'] in [5, 6, 15] else: return False def _has_sse(self): if self.is_Intel(): return ((self.info[0]['Family']==6 and self.info[0]['Model'] in [7, 8, 9, 10, 11]) or self.info[0]['Family']==15) elif self.is_AMD(): return ((self.info[0]['Family']==6 and self.info[0]['Model'] in [6, 7, 8, 10]) or self.info[0]['Family']==15) else: return False def _has_sse2(self): if self.is_Intel(): return self.is_Pentium4() or self.is_PentiumM() \ or self.is_Core2() elif self.is_AMD(): return self.is_AMD64() else: return False def _has_3dnow(self): return self.is_AMD() and self.info[0]['Family'] in [5, 6, 15] def _has_3dnowext(self): return self.is_AMD() and self.info[0]['Family'] in [6, 15] if sys.platform.startswith('linux'): # variations: linux2,linux-i386 (any others?) cpuinfo = LinuxCPUInfo elif sys.platform.startswith('irix'): cpuinfo = IRIXCPUInfo elif sys.platform == 'darwin': cpuinfo = DarwinCPUInfo elif sys.platform.startswith('sunos'): cpuinfo = SunOSCPUInfo elif sys.platform.startswith('win32'): cpuinfo = Win32CPUInfo elif sys.platform.startswith('cygwin'): cpuinfo = LinuxCPUInfo #XXX: other OS's. Eg. use _winreg on Win32. Or os.uname on unices. else: cpuinfo = CPUInfoBase cpu = cpuinfo() #if __name__ == "__main__": # # cpu.is_blaa() # cpu.is_Intel() # cpu.is_Alpha() # # print('CPU information:'), # for name in dir(cpuinfo): # if name[0]=='_' and name[1]!='_': # r = getattr(cpu,name[1:])() # if r: # if r!=1: # print('%s=%s' %(name[1:],r)) # else: # print(name[1:]), # print()
import sys import warnings import itertools import platform import pytest from decimal import Decimal import numpy as np from numpy.core import umath from numpy.random import rand, randint, randn from numpy.testing import ( assert_, assert_equal, assert_raises, assert_raises_regex, assert_array_equal, assert_almost_equal, assert_array_almost_equal, assert_warns, HAS_REFCOUNT ) from hypothesis import assume, given, strategies as st from hypothesis.extra import numpy as hynp class TestResize: def test_copies(self): A = np.array([[1, 2], [3, 4]]) Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) assert_equal(np.resize(A, (2, 4)), Ar1) Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(np.resize(A, (4, 2)), Ar2) Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]) assert_equal(np.resize(A, (4, 3)), Ar3) def test_zeroresize(self): A = np.array([[1, 2], [3, 4]]) Ar = np.resize(A, (0,)) assert_array_equal(Ar, np.array([])) assert_equal(A.dtype, Ar.dtype) Ar = np.resize(A, (0, 2)) assert_equal(Ar.shape, (0, 2)) Ar = np.resize(A, (2, 0)) assert_equal(Ar.shape, (2, 0)) def test_reshape_from_zero(self): # See also gh-6740 A = np.zeros(0, dtype=[('a', np.float32)]) Ar = np.resize(A, (2, 1)) assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype)) assert_equal(A.dtype, Ar.dtype) class TestNonarrayArgs: # check that non-array arguments to functions wrap them in arrays def test_choose(self): choices = [[0, 1, 2], [3, 4, 5], [5, 6, 7]] tgt = [5, 1, 5] a = [2, 0, 1] out = np.choose(a, choices) assert_equal(out, tgt) def test_clip(self): arr = [-1, 5, 2, 3, 10, -4, -9] out = np.clip(arr, 2, 7) tgt = [2, 5, 2, 3, 7, 2, 2] assert_equal(out, tgt) def test_compress(self): arr = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] tgt = [[5, 6, 7, 8, 9]] out = np.compress([0, 1], arr, axis=0) assert_equal(out, tgt) def test_count_nonzero(self): arr = [[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]] tgt = np.array([2, 3]) out = np.count_nonzero(arr, axis=1) assert_equal(out, tgt) def test_cumproduct(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.all(np.cumproduct(A) == np.array([1, 2, 6, 24, 120, 720]))) def test_diagonal(self): a = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] out = np.diagonal(a) tgt = [0, 5, 10] assert_equal(out, tgt) def test_mean(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.mean(A) == 3.5) assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5]))) assert_(np.all(np.mean(A, 1) == np.array([2., 5.]))) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.mean([]))) assert_(w[0].category is RuntimeWarning) def test_ptp(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.ptp(a, axis=0), 15.0) def test_prod(self): arr = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] tgt = [24, 1890, 600] assert_equal(np.prod(arr, axis=-1), tgt) def test_ravel(self): a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] assert_equal(np.ravel(a), tgt) def test_repeat(self): a = [1, 2, 3] tgt = [1, 1, 2, 2, 3, 3] out = np.repeat(a, 2) assert_equal(out, tgt) def test_reshape(self): arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] assert_equal(np.reshape(arr, (2, 6)), tgt) def test_round(self): arr = [1.56, 72.54, 6.35, 3.25] tgt = [1.6, 72.5, 6.4, 3.2] assert_equal(np.around(arr, decimals=1), tgt) def test_searchsorted(self): arr = [-8, -5, -1, 3, 6, 10] out = np.searchsorted(arr, 0) assert_equal(out, 3) def test_size(self): A = [[1, 2, 3], [4, 5, 6]] assert_(np.size(A) == 6) assert_(np.size(A, 0) == 2) assert_(np.size(A, 1) == 3) def test_squeeze(self): A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]] assert_equal(np.squeeze(A).shape, (3, 3)) assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3)) assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3)) assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3)) assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3)) def test_std(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(np.std(A), 1.707825127659933) assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5])) assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.std([]))) assert_(w[0].category is RuntimeWarning) def test_swapaxes(self): tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]] a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]] out = np.swapaxes(a, 0, 2) assert_equal(out, tgt) def test_sum(self): m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] tgt = [[6], [15], [24]] out = np.sum(m, axis=1, keepdims=True) assert_equal(tgt, out) def test_take(self): tgt = [2, 3, 5] indices = [1, 2, 4] a = [1, 2, 3, 4, 5] out = np.take(a, indices) assert_equal(out, tgt) def test_trace(self): c = [[1, 2], [3, 4], [5, 6]] assert_equal(np.trace(c), 5) def test_transpose(self): arr = [[1, 2], [3, 4], [5, 6]] tgt = [[1, 3, 5], [2, 4, 6]] assert_equal(np.transpose(arr, (1, 0)), tgt) def test_var(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(np.var(A), 2.9166666666666665) assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25])) assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(np.isnan(np.var([]))) assert_(w[0].category is RuntimeWarning) B = np.array([None, 0]) B[0] = 1j assert_almost_equal(np.var(B), 0.25) class TestIsscalar: def test_isscalar(self): assert_(np.isscalar(3.1)) assert_(np.isscalar(np.int16(12345))) assert_(np.isscalar(False)) assert_(np.isscalar('numpy')) assert_(not np.isscalar([3.1])) assert_(not np.isscalar(None)) # PEP 3141 from fractions import Fraction assert_(np.isscalar(Fraction(5, 17))) from numbers import Number assert_(np.isscalar(Number())) class TestBoolScalar: def test_logical(self): f = np.False_ t = np.True_ s = "xyz" assert_((t and s) is s) assert_((f and s) is f) def test_bitwise_or(self): f = np.False_ t = np.True_ assert_((t | t) is t) assert_((f | t) is t) assert_((t | f) is t) assert_((f | f) is f) def test_bitwise_and(self): f = np.False_ t = np.True_ assert_((t & t) is t) assert_((f & t) is f) assert_((t & f) is f) assert_((f & f) is f) def test_bitwise_xor(self): f = np.False_ t = np.True_ assert_((t ^ t) is f) assert_((f ^ t) is t) assert_((t ^ f) is t) assert_((f ^ f) is f) class TestBoolArray: def setup(self): # offset for simd tests self.t = np.array([True] * 41, dtype=bool)[1::] self.f = np.array([False] * 41, dtype=bool)[1::] self.o = np.array([False] * 42, dtype=bool)[2::] self.nm = self.f.copy() self.im = self.t.copy() self.nm[3] = True self.nm[-2] = True self.im[3] = False self.im[-2] = False def test_all_any(self): assert_(self.t.all()) assert_(self.t.any()) assert_(not self.f.all()) assert_(not self.f.any()) assert_(self.nm.any()) assert_(self.im.any()) assert_(not self.nm.all()) assert_(not self.im.all()) # check bad element in all positions for i in range(256 - 7): d = np.array([False] * 256, dtype=bool)[7::] d[i] = True assert_(np.any(d)) e = np.array([True] * 256, dtype=bool)[7::] e[i] = False assert_(not np.all(e)) assert_array_equal(e, ~d) # big array test for blocked libc loops for i in list(range(9, 6000, 507)) + [7764, 90021, -10]: d = np.array([False] * 100043, dtype=bool) d[i] = True assert_(np.any(d), msg="%r" % i) e = np.array([True] * 100043, dtype=bool) e[i] = False assert_(not np.all(e), msg="%r" % i) def test_logical_not_abs(self): assert_array_equal(~self.t, self.f) assert_array_equal(np.abs(~self.t), self.f) assert_array_equal(np.abs(~self.f), self.t) assert_array_equal(np.abs(self.f), self.f) assert_array_equal(~np.abs(self.f), self.t) assert_array_equal(~np.abs(self.t), self.f) assert_array_equal(np.abs(~self.nm), self.im) np.logical_not(self.t, out=self.o) assert_array_equal(self.o, self.f) np.abs(self.t, out=self.o) assert_array_equal(self.o, self.t) def test_logical_and_or_xor(self): assert_array_equal(self.t | self.t, self.t) assert_array_equal(self.f | self.f, self.f) assert_array_equal(self.t | self.f, self.t) assert_array_equal(self.f | self.t, self.t) np.logical_or(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t & self.t, self.t) assert_array_equal(self.f & self.f, self.f) assert_array_equal(self.t & self.f, self.f) assert_array_equal(self.f & self.t, self.f) np.logical_and(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t ^ self.t, self.f) assert_array_equal(self.f ^ self.f, self.f) assert_array_equal(self.t ^ self.f, self.t) assert_array_equal(self.f ^ self.t, self.t) np.logical_xor(self.t, self.t, out=self.o) assert_array_equal(self.o, self.f) assert_array_equal(self.nm & self.t, self.nm) assert_array_equal(self.im & self.f, False) assert_array_equal(self.nm & True, self.nm) assert_array_equal(self.im & False, self.f) assert_array_equal(self.nm | self.t, self.t) assert_array_equal(self.im | self.f, self.im) assert_array_equal(self.nm | True, self.t) assert_array_equal(self.im | False, self.im) assert_array_equal(self.nm ^ self.t, self.im) assert_array_equal(self.im ^ self.f, self.im) assert_array_equal(self.nm ^ True, self.im) assert_array_equal(self.im ^ False, self.im) class TestBoolCmp: def setup(self): self.f = np.ones(256, dtype=np.float32) self.ef = np.ones(self.f.size, dtype=bool) self.d = np.ones(128, dtype=np.float64) self.ed = np.ones(self.d.size, dtype=bool) # generate values for all permutation of 256bit simd vectors s = 0 for i in range(32): self.f[s:s+8] = [i & 2**x for x in range(8)] self.ef[s:s+8] = [(i & 2**x) != 0 for x in range(8)] s += 8 s = 0 for i in range(16): self.d[s:s+4] = [i & 2**x for x in range(4)] self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)] s += 4 self.nf = self.f.copy() self.nd = self.d.copy() self.nf[self.ef] = np.nan self.nd[self.ed] = np.nan self.inff = self.f.copy() self.infd = self.d.copy() self.inff[::3][self.ef[::3]] = np.inf self.infd[::3][self.ed[::3]] = np.inf self.inff[1::3][self.ef[1::3]] = -np.inf self.infd[1::3][self.ed[1::3]] = -np.inf self.inff[2::3][self.ef[2::3]] = np.nan self.infd[2::3][self.ed[2::3]] = np.nan self.efnonan = self.ef.copy() self.efnonan[2::3] = False self.ednonan = self.ed.copy() self.ednonan[2::3] = False self.signf = self.f.copy() self.signd = self.d.copy() self.signf[self.ef] *= -1. self.signd[self.ed] *= -1. self.signf[1::6][self.ef[1::6]] = -np.inf self.signd[1::6][self.ed[1::6]] = -np.inf self.signf[3::6][self.ef[3::6]] = -np.nan self.signd[3::6][self.ed[3::6]] = -np.nan self.signf[4::6][self.ef[4::6]] = -0. self.signd[4::6][self.ed[4::6]] = -0. def test_float(self): # offset for alignment test for i in range(4): assert_array_equal(self.f[i:] > 0, self.ef[i:]) assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:]) assert_array_equal(self.f[i:] == 0, ~self.ef[i:]) assert_array_equal(-self.f[i:] < 0, self.ef[i:]) assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:]) r = self.f[i:] != 0 assert_array_equal(r, self.ef[i:]) r2 = self.f[i:] != np.zeros_like(self.f[i:]) r3 = 0 != self.f[i:] assert_array_equal(r, r2) assert_array_equal(r, r3) # check bool == 0x1 assert_array_equal(r.view(np.int8), r.astype(np.int8)) assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) # isnan on amd64 takes the same code path assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:]) assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:]) assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:]) assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:]) assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:]) def test_double(self): # offset for alignment test for i in range(2): assert_array_equal(self.d[i:] > 0, self.ed[i:]) assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:]) assert_array_equal(self.d[i:] == 0, ~self.ed[i:]) assert_array_equal(-self.d[i:] < 0, self.ed[i:]) assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:]) r = self.d[i:] != 0 assert_array_equal(r, self.ed[i:]) r2 = self.d[i:] != np.zeros_like(self.d[i:]) r3 = 0 != self.d[i:] assert_array_equal(r, r2) assert_array_equal(r, r3) # check bool == 0x1 assert_array_equal(r.view(np.int8), r.astype(np.int8)) assert_array_equal(r2.view(np.int8), r2.astype(np.int8)) assert_array_equal(r3.view(np.int8), r3.astype(np.int8)) # isnan on amd64 takes the same code path assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:]) assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:]) assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:]) assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:]) assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:]) class TestSeterr: def test_default(self): err = np.geterr() assert_equal(err, dict(divide='warn', invalid='warn', over='warn', under='ignore') ) def test_set(self): with np.errstate(): err = np.seterr() old = np.seterr(divide='print') assert_(err == old) new = np.seterr() assert_(new['divide'] == 'print') np.seterr(over='raise') assert_(np.geterr()['over'] == 'raise') assert_(new['divide'] == 'print') np.seterr(**old) assert_(np.geterr() == old) @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.") def test_divide_err(self): with np.errstate(divide='raise'): with assert_raises(FloatingPointError): np.array([1.]) / np.array([0.]) np.seterr(divide='ignore') np.array([1.]) / np.array([0.]) def test_errobj(self): olderrobj = np.geterrobj() self.called = 0 try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with np.errstate(divide='warn'): np.seterrobj([20000, 1, None]) np.array([1.]) / np.array([0.]) assert_equal(len(w), 1) def log_err(*args): self.called += 1 extobj_err = args assert_(len(extobj_err) == 2) assert_("divide" in extobj_err[0]) with np.errstate(divide='ignore'): np.seterrobj([20000, 3, log_err]) np.array([1.]) / np.array([0.]) assert_equal(self.called, 1) np.seterrobj(olderrobj) with np.errstate(divide='ignore'): np.divide(1., 0., extobj=[20000, 3, log_err]) assert_equal(self.called, 2) finally: np.seterrobj(olderrobj) del self.called def test_errobj_noerrmask(self): # errmask = 0 has a special code path for the default olderrobj = np.geterrobj() try: # set errobj to something non default np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT + 1, None]) # call a ufunc np.isnan(np.array([6])) # same with the default, lots of times to get rid of possible # pre-existing stack in the code for i in range(10000): np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT, None]) np.isnan(np.array([6])) finally: np.seterrobj(olderrobj) class TestFloatExceptions: def assert_raises_fpe(self, fpeerr, flop, x, y): ftype = type(x) try: flop(x, y) assert_(False, "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) except FloatingPointError as exc: assert_(str(exc).find(fpeerr) >= 0, "Type %s raised wrong fpe error '%s'." % (ftype, exc)) def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2): # Check that fpe exception is raised. # # Given a floating operation `flop` and two scalar values, check that # the operation raises the floating point exception specified by # `fpeerr`. Tests all variants with 0-d array scalars as well. self.assert_raises_fpe(fpeerr, flop, sc1, sc2) self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2) self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()]) self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()]) def test_floating_exceptions(self): # Test basic arithmetic function errors with np.errstate(all='raise'): # Test for all real and complex float types for typecode in np.typecodes['AllFloat']: ftype = np.obj2sctype(typecode) if np.dtype(ftype).kind == 'f': # Get some extreme values for the type fi = np.finfo(ftype) ft_tiny = fi.tiny ft_max = fi.max ft_eps = fi.eps underflow = 'underflow' divbyzero = 'divide by zero' else: # 'c', complex, corresponding real dtype rtype = type(ftype(0).real) fi = np.finfo(rtype) ft_tiny = ftype(fi.tiny) ft_max = ftype(fi.max) ft_eps = ftype(fi.eps) # The complex types raise different exceptions underflow = '' divbyzero = '' overflow = 'overflow' invalid = 'invalid' self.assert_raises_fpe(underflow, lambda a, b: a/b, ft_tiny, ft_max) self.assert_raises_fpe(underflow, lambda a, b: a*b, ft_tiny, ft_tiny) self.assert_raises_fpe(overflow, lambda a, b: a*b, ft_max, ftype(2)) self.assert_raises_fpe(overflow, lambda a, b: a/b, ft_max, ftype(0.5)) self.assert_raises_fpe(overflow, lambda a, b: a+b, ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, lambda a, b: a-b, -ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, np.power, ftype(2), ftype(2**fi.nexp)) self.assert_raises_fpe(divbyzero, lambda a, b: a/b, ftype(1), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b: a/b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a/b, ftype(0), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b: a-b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a+b, ftype(np.inf), ftype(-np.inf)) self.assert_raises_fpe(invalid, lambda a, b: a*b, ftype(0), ftype(np.inf)) def test_warnings(self): # test warning code path with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with np.errstate(all="warn"): np.divide(1, 0.) assert_equal(len(w), 1) assert_("divide by zero" in str(w[0].message)) np.array(1e300) * np.array(1e300) assert_equal(len(w), 2) assert_("overflow" in str(w[-1].message)) np.array(np.inf) - np.array(np.inf) assert_equal(len(w), 3) assert_("invalid value" in str(w[-1].message)) np.array(1e-300) * np.array(1e-300) assert_equal(len(w), 4) assert_("underflow" in str(w[-1].message)) class TestTypes: def check_promotion_cases(self, promote_func): # tests that the scalars get coerced correctly. b = np.bool_(0) i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0) u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0) f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0) c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0) # coercion within the same kind assert_equal(promote_func(i8, i16), np.dtype(np.int16)) assert_equal(promote_func(i32, i8), np.dtype(np.int32)) assert_equal(promote_func(i16, i64), np.dtype(np.int64)) assert_equal(promote_func(u8, u32), np.dtype(np.uint32)) assert_equal(promote_func(f32, f64), np.dtype(np.float64)) assert_equal(promote_func(fld, f32), np.dtype(np.longdouble)) assert_equal(promote_func(f64, fld), np.dtype(np.longdouble)) assert_equal(promote_func(c128, c64), np.dtype(np.complex128)) assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble)) assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble)) # coercion between kinds assert_equal(promote_func(b, i32), np.dtype(np.int32)) assert_equal(promote_func(b, u8), np.dtype(np.uint8)) assert_equal(promote_func(i8, u8), np.dtype(np.int16)) assert_equal(promote_func(u8, i32), np.dtype(np.int32)) assert_equal(promote_func(i64, u32), np.dtype(np.int64)) assert_equal(promote_func(u64, i32), np.dtype(np.float64)) assert_equal(promote_func(i32, f32), np.dtype(np.float64)) assert_equal(promote_func(i64, f32), np.dtype(np.float64)) assert_equal(promote_func(f32, i16), np.dtype(np.float32)) assert_equal(promote_func(f32, u32), np.dtype(np.float64)) assert_equal(promote_func(f32, c64), np.dtype(np.complex64)) assert_equal(promote_func(c128, f32), np.dtype(np.complex128)) assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble)) # coercion between scalars and 1-D arrays assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8)) assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8)) assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32)) assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32)) assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int8)) assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.int32)) assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.uint32)) assert_equal(promote_func(np.int32(-1), np.array([u64])), np.dtype(np.float64)) assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float32)) assert_equal(promote_func(fld, np.array([f32])), np.dtype(np.float32)) assert_equal(promote_func(np.array([f64]), fld), np.dtype(np.float64)) assert_equal(promote_func(fld, np.array([c64])), np.dtype(np.complex64)) assert_equal(promote_func(c64, np.array([f64])), np.dtype(np.complex128)) assert_equal(promote_func(np.complex64(3j), np.array([f64])), np.dtype(np.complex128)) # coercion between scalars and 1-D arrays, where # the scalar has greater kind than the array assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64)) assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64)) assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64)) assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64)) assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64)) # uint and int are treated as the same "kind" for # the purposes of array-scalar promotion. assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.uint16)) # float and complex are treated as the same "kind" for # the purposes of array-scalar promotion, so that you can do # (0j + float32array) to get a complex64 array instead of # a complex128 array. assert_equal(promote_func(np.array([f32]), c128), np.dtype(np.complex64)) def test_coercion(self): def res_type(a, b): return np.add(a, b).dtype self.check_promotion_cases(res_type) # Use-case: float/complex scalar * bool/int8 array # shouldn't narrow the float/complex type for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]: b = 1.234 * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.longdouble(1.234) * a assert_equal(b.dtype, np.dtype(np.longdouble), "array type %s" % a.dtype) b = np.float64(1.234) * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.float32(1.234) * a assert_equal(b.dtype, np.dtype('f4'), "array type %s" % a.dtype) b = np.float16(1.234) * a assert_equal(b.dtype, np.dtype('f2'), "array type %s" % a.dtype) b = 1.234j * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.clongdouble(1.234j) * a assert_equal(b.dtype, np.dtype(np.clongdouble), "array type %s" % a.dtype) b = np.complex128(1.234j) * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.complex64(1.234j) * a assert_equal(b.dtype, np.dtype('c8'), "array type %s" % a.dtype) # The following use-case is problematic, and to resolve its # tricky side-effects requires more changes. # # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is # a float32, shouldn't promote to float64 # # a = np.array([1.0, 1.5], dtype=np.float32) # t = np.array([True, False]) # b = t*a # assert_equal(b, [1.0, 0.0]) # assert_equal(b.dtype, np.dtype('f4')) # b = (1-t)*a # assert_equal(b, [0.0, 1.5]) # assert_equal(b.dtype, np.dtype('f4')) # # Probably ~t (bitwise negation) is more proper to use here, # but this is arguably less intuitive to understand at a glance, and # would fail if 't' is actually an integer array instead of boolean: # # b = (~t)*a # assert_equal(b, [0.0, 1.5]) # assert_equal(b.dtype, np.dtype('f4')) def test_result_type(self): self.check_promotion_cases(np.result_type) assert_(np.result_type(None) == np.dtype(None)) def test_promote_types_endian(self): # promote_types should always return native-endian types assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8')) assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8')) assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21')) assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21')) assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21')) assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21')) assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8')) assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8')) assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8')) assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8')) assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8')) assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8')) assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8')) assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8')) assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8')) assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8')) def test_promote_types_strings(self): assert_equal(np.promote_types('bool', 'S'), np.dtype('S5')) assert_equal(np.promote_types('b', 'S'), np.dtype('S4')) assert_equal(np.promote_types('u1', 'S'), np.dtype('S3')) assert_equal(np.promote_types('u2', 'S'), np.dtype('S5')) assert_equal(np.promote_types('u4', 'S'), np.dtype('S10')) assert_equal(np.promote_types('u8', 'S'), np.dtype('S20')) assert_equal(np.promote_types('i1', 'S'), np.dtype('S4')) assert_equal(np.promote_types('i2', 'S'), np.dtype('S6')) assert_equal(np.promote_types('i4', 'S'), np.dtype('S11')) assert_equal(np.promote_types('i8', 'S'), np.dtype('S21')) assert_equal(np.promote_types('bool', 'U'), np.dtype('U5')) assert_equal(np.promote_types('b', 'U'), np.dtype('U4')) assert_equal(np.promote_types('u1', 'U'), np.dtype('U3')) assert_equal(np.promote_types('u2', 'U'), np.dtype('U5')) assert_equal(np.promote_types('u4', 'U'), np.dtype('U10')) assert_equal(np.promote_types('u8', 'U'), np.dtype('U20')) assert_equal(np.promote_types('i1', 'U'), np.dtype('U4')) assert_equal(np.promote_types('i2', 'U'), np.dtype('U6')) assert_equal(np.promote_types('i4', 'U'), np.dtype('U11')) assert_equal(np.promote_types('i8', 'U'), np.dtype('U21')) assert_equal(np.promote_types('bool', 'S1'), np.dtype('S5')) assert_equal(np.promote_types('bool', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('b', 'S1'), np.dtype('S4')) assert_equal(np.promote_types('b', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u1', 'S1'), np.dtype('S3')) assert_equal(np.promote_types('u1', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u2', 'S1'), np.dtype('S5')) assert_equal(np.promote_types('u2', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u4', 'S1'), np.dtype('S10')) assert_equal(np.promote_types('u4', 'S30'), np.dtype('S30')) assert_equal(np.promote_types('u8', 'S1'), np.dtype('S20')) assert_equal(np.promote_types('u8', 'S30'), np.dtype('S30')) def test_can_cast(self): assert_(np.can_cast(np.int32, np.int64)) assert_(np.can_cast(np.float64, complex)) assert_(not np.can_cast(complex, float)) assert_(np.can_cast('i8', 'f8')) assert_(not np.can_cast('i8', 'f4')) assert_(np.can_cast('i4', 'S11')) assert_(np.can_cast('i8', 'i8', 'no')) assert_(not np.can_cast('<i8', '>i8', 'no')) assert_(np.can_cast('<i8', '>i8', 'equiv')) assert_(not np.can_cast('<i4', '>i8', 'equiv')) assert_(np.can_cast('<i4', '>i8', 'safe')) assert_(not np.can_cast('<i8', '>i4', 'safe')) assert_(np.can_cast('<i8', '>i4', 'same_kind')) assert_(not np.can_cast('<i8', '>u4', 'same_kind')) assert_(np.can_cast('<i8', '>u4', 'unsafe')) assert_(np.can_cast('bool', 'S5')) assert_(not np.can_cast('bool', 'S4')) assert_(np.can_cast('b', 'S4')) assert_(not np.can_cast('b', 'S3')) assert_(np.can_cast('u1', 'S3')) assert_(not np.can_cast('u1', 'S2')) assert_(np.can_cast('u2', 'S5')) assert_(not np.can_cast('u2', 'S4')) assert_(np.can_cast('u4', 'S10')) assert_(not np.can_cast('u4', 'S9')) assert_(np.can_cast('u8', 'S20')) assert_(not np.can_cast('u8', 'S19')) assert_(np.can_cast('i1', 'S4')) assert_(not np.can_cast('i1', 'S3')) assert_(np.can_cast('i2', 'S6')) assert_(not np.can_cast('i2', 'S5')) assert_(np.can_cast('i4', 'S11')) assert_(not np.can_cast('i4', 'S10')) assert_(np.can_cast('i8', 'S21')) assert_(not np.can_cast('i8', 'S20')) assert_(np.can_cast('bool', 'S5')) assert_(not np.can_cast('bool', 'S4')) assert_(np.can_cast('b', 'U4')) assert_(not np.can_cast('b', 'U3')) assert_(np.can_cast('u1', 'U3')) assert_(not np.can_cast('u1', 'U2')) assert_(np.can_cast('u2', 'U5')) assert_(not np.can_cast('u2', 'U4')) assert_(np.can_cast('u4', 'U10')) assert_(not np.can_cast('u4', 'U9')) assert_(np.can_cast('u8', 'U20')) assert_(not np.can_cast('u8', 'U19')) assert_(np.can_cast('i1', 'U4')) assert_(not np.can_cast('i1', 'U3')) assert_(np.can_cast('i2', 'U6')) assert_(not np.can_cast('i2', 'U5')) assert_(np.can_cast('i4', 'U11')) assert_(not np.can_cast('i4', 'U10')) assert_(np.can_cast('i8', 'U21')) assert_(not np.can_cast('i8', 'U20')) assert_raises(TypeError, np.can_cast, 'i4', None) assert_raises(TypeError, np.can_cast, None, 'i4') # Also test keyword arguments assert_(np.can_cast(from_=np.int32, to=np.int64)) def test_can_cast_simple_to_structured(self): # Non-structured can only be cast to structured in 'unsafe' mode. assert_(not np.can_cast('i4', 'i4,i4')) assert_(not np.can_cast('i4', 'i4,i2')) assert_(np.can_cast('i4', 'i4,i4', casting='unsafe')) assert_(np.can_cast('i4', 'i4,i2', casting='unsafe')) # Even if there is just a single field which is OK. assert_(not np.can_cast('i2', [('f1', 'i4')])) assert_(not np.can_cast('i2', [('f1', 'i4')], casting='same_kind')) assert_(np.can_cast('i2', [('f1', 'i4')], casting='unsafe')) # It should be the same for recursive structured or subarrays. assert_(not np.can_cast('i2', [('f1', 'i4,i4')])) assert_(np.can_cast('i2', [('f1', 'i4,i4')], casting='unsafe')) assert_(not np.can_cast('i2', [('f1', '(2,3)i4')])) assert_(np.can_cast('i2', [('f1', '(2,3)i4')], casting='unsafe')) def test_can_cast_structured_to_simple(self): # Need unsafe casting for structured to simple. assert_(not np.can_cast([('f1', 'i4')], 'i4')) assert_(np.can_cast([('f1', 'i4')], 'i4', casting='unsafe')) assert_(np.can_cast([('f1', 'i4')], 'i2', casting='unsafe')) # Since it is unclear what is being cast, multiple fields to # single should not work even for unsafe casting. assert_(not np.can_cast('i4,i4', 'i4', casting='unsafe')) # But a single field inside a single field is OK. assert_(not np.can_cast([('f1', [('x', 'i4')])], 'i4')) assert_(np.can_cast([('f1', [('x', 'i4')])], 'i4', casting='unsafe')) # And a subarray is fine too - it will just take the first element # (arguably not very consistently; might also take the first field). assert_(not np.can_cast([('f0', '(3,)i4')], 'i4')) assert_(np.can_cast([('f0', '(3,)i4')], 'i4', casting='unsafe')) # But a structured subarray with multiple fields should fail. assert_(not np.can_cast([('f0', ('i4,i4'), (2,))], 'i4', casting='unsafe')) def test_can_cast_values(self): # gh-5917 for dt in np.sctypes['int'] + np.sctypes['uint']: ii = np.iinfo(dt) assert_(np.can_cast(ii.min, dt)) assert_(np.can_cast(ii.max, dt)) assert_(not np.can_cast(ii.min - 1, dt)) assert_(not np.can_cast(ii.max + 1, dt)) for dt in np.sctypes['float']: fi = np.finfo(dt) assert_(np.can_cast(fi.min, dt)) assert_(np.can_cast(fi.max, dt)) # Custom exception class to test exception propagation in fromiter class NIterError(Exception): pass class TestFromiter: def makegen(self): return (x**2 for x in range(24)) def test_types(self): ai32 = np.fromiter(self.makegen(), np.int32) ai64 = np.fromiter(self.makegen(), np.int64) af = np.fromiter(self.makegen(), float) assert_(ai32.dtype == np.dtype(np.int32)) assert_(ai64.dtype == np.dtype(np.int64)) assert_(af.dtype == np.dtype(float)) def test_lengths(self): expected = np.array(list(self.makegen())) a = np.fromiter(self.makegen(), int) a20 = np.fromiter(self.makegen(), int, 20) assert_(len(a) == len(expected)) assert_(len(a20) == 20) assert_raises(ValueError, np.fromiter, self.makegen(), int, len(expected) + 10) def test_values(self): expected = np.array(list(self.makegen())) a = np.fromiter(self.makegen(), int) a20 = np.fromiter(self.makegen(), int, 20) assert_(np.alltrue(a == expected, axis=0)) assert_(np.alltrue(a20 == expected[:20], axis=0)) def load_data(self, n, eindex): # Utility method for the issue 2592 tests. # Raise an exception at the desired index in the iterator. for e in range(n): if e == eindex: raise NIterError('error at index %s' % eindex) yield e def test_2592(self): # Test iteration exceptions are correctly raised. count, eindex = 10, 5 assert_raises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) def test_2592_edge(self): # Test iter. exceptions, edge case (exception at end of iterator). count = 10 eindex = count-1 assert_raises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) class TestNonzero: def test_nonzero_trivial(self): assert_equal(np.count_nonzero(np.array([])), 0) assert_equal(np.count_nonzero(np.array([], dtype='?')), 0) assert_equal(np.nonzero(np.array([])), ([],)) assert_equal(np.count_nonzero(np.array([0])), 0) assert_equal(np.count_nonzero(np.array([0], dtype='?')), 0) assert_equal(np.nonzero(np.array([0])), ([],)) assert_equal(np.count_nonzero(np.array([1])), 1) assert_equal(np.count_nonzero(np.array([1], dtype='?')), 1) assert_equal(np.nonzero(np.array([1])), ([0],)) def test_nonzero_zerod(self): assert_equal(np.count_nonzero(np.array(0)), 0) assert_equal(np.count_nonzero(np.array(0, dtype='?')), 0) with assert_warns(DeprecationWarning): assert_equal(np.nonzero(np.array(0)), ([],)) assert_equal(np.count_nonzero(np.array(1)), 1) assert_equal(np.count_nonzero(np.array(1, dtype='?')), 1) with assert_warns(DeprecationWarning): assert_equal(np.nonzero(np.array(1)), ([0],)) def test_nonzero_onedim(self): x = np.array([1, 0, 2, -1, 0, 0, 8]) assert_equal(np.count_nonzero(x), 4) assert_equal(np.count_nonzero(x), 4) assert_equal(np.nonzero(x), ([0, 2, 3, 6],)) x = np.array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)], dtype=[('a', 'i4'), ('b', 'i2')]) assert_equal(np.count_nonzero(x['a']), 3) assert_equal(np.count_nonzero(x['b']), 4) assert_equal(np.nonzero(x['a']), ([0, 2, 3],)) assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],)) def test_nonzero_twodim(self): x = np.array([[0, 1, 0], [2, 0, 3]]) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2])) x = np.eye(3) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2])) x = np.array([[(0, 1), (0, 0), (1, 11)], [(1, 1), (1, 0), (0, 0)], [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')]) assert_equal(np.count_nonzero(x['a']), 4) assert_equal(np.count_nonzero(x['b']), 5) assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1])) assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2])) assert_(not x['a'].T.flags.aligned) assert_equal(np.count_nonzero(x['a'].T), 4) assert_equal(np.count_nonzero(x['b'].T), 5) assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0])) assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2])) def test_sparse(self): # test special sparse condition boolean code path for i in range(20): c = np.zeros(200, dtype=bool) c[i::20] = True assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20)) c = np.zeros(400, dtype=bool) c[10 + i:20 + i] = True c[20 + i*2] = True assert_equal(np.nonzero(c)[0], np.concatenate((np.arange(10 + i, 20 + i), [20 + i*2]))) def test_return_type(self): class C(np.ndarray): pass for view in (C, np.ndarray): for nd in range(1, 4): shape = tuple(range(2, 2+nd)) x = np.arange(np.prod(shape)).reshape(shape).view(view) for nzx in (np.nonzero(x), x.nonzero()): for nzx_i in nzx: assert_(type(nzx_i) is np.ndarray) assert_(nzx_i.flags.writeable) def test_count_nonzero_axis(self): # Basic check of functionality m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]]) expected = np.array([1, 1, 1, 1, 1]) assert_equal(np.count_nonzero(m, axis=0), expected) expected = np.array([2, 3]) assert_equal(np.count_nonzero(m, axis=1), expected) assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1)) assert_raises(TypeError, np.count_nonzero, m, axis='foo') assert_raises(np.AxisError, np.count_nonzero, m, axis=3) assert_raises(TypeError, np.count_nonzero, m, axis=np.array([[1], [2]])) def test_count_nonzero_axis_all_dtypes(self): # More thorough test that the axis argument is respected # for all dtypes and responds correctly when presented with # either integer or tuple arguments for axis msg = "Mismatch for dtype: %s" def assert_equal_w_dt(a, b, err_msg): assert_equal(a.dtype, b.dtype, err_msg=err_msg) assert_equal(a, b, err_msg=err_msg) for dt in np.typecodes['All']: err_msg = msg % (np.dtype(dt).name,) if dt != 'V': if dt != 'M': m = np.zeros((3, 3), dtype=dt) n = np.ones(1, dtype=dt) m[0, 0] = n[0] m[1, 0] = n[0] else: # np.zeros doesn't work for np.datetime64 m = np.array(['1970-01-01'] * 9) m = m.reshape((3, 3)) m[0, 0] = '1970-01-12' m[1, 0] = '1970-01-12' m = m.astype(dt) expected = np.array([2, 0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=0), expected, err_msg=err_msg) expected = np.array([1, 1, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=1), expected, err_msg=err_msg) expected = np.array(2) assert_equal(np.count_nonzero(m, axis=(0, 1)), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m, axis=None), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m), expected, err_msg=err_msg) if dt == 'V': # There are no 'nonzero' objects for np.void, so the testing # setup is slightly different for this dtype m = np.array([np.void(1)] * 6).reshape((2, 3)) expected = np.array([0, 0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=0), expected, err_msg=err_msg) expected = np.array([0, 0], dtype=np.intp) assert_equal_w_dt(np.count_nonzero(m, axis=1), expected, err_msg=err_msg) expected = np.array(0) assert_equal(np.count_nonzero(m, axis=(0, 1)), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m, axis=None), expected, err_msg=err_msg) assert_equal(np.count_nonzero(m), expected, err_msg=err_msg) def test_count_nonzero_axis_consistent(self): # Check that the axis behaviour for valid axes in # non-special cases is consistent (and therefore # correct) by checking it against an integer array # that is then casted to the generic object dtype from itertools import combinations, permutations axis = (0, 1, 2, 3) size = (5, 5, 5, 5) msg = "Mismatch for axis: %s" rng = np.random.RandomState(1234) m = rng.randint(-100, 100, size=size) n = m.astype(object) for length in range(len(axis)): for combo in combinations(axis, length): for perm in permutations(combo): assert_equal( np.count_nonzero(m, axis=perm), np.count_nonzero(n, axis=perm), err_msg=msg % (perm,)) def test_countnonzero_axis_empty(self): a = np.array([[0, 0, 1], [1, 0, 1]]) assert_equal(np.count_nonzero(a, axis=()), a.astype(bool)) def test_array_method(self): # Tests that the array method # call to nonzero works m = np.array([[1, 0, 0], [4, 0, 6]]) tgt = [[0, 1, 1], [0, 0, 2]] assert_equal(m.nonzero(), tgt) def test_nonzero_invalid_object(self): # gh-9295 a = np.array([np.array([1, 2]), 3], dtype=object) assert_raises(ValueError, np.nonzero, a) class BoolErrors: def __bool__(self): raise ValueError("Not allowed") assert_raises(ValueError, np.nonzero, np.array([BoolErrors()])) def test_nonzero_sideeffect_safety(self): # gh-13631 class FalseThenTrue: _val = False def __bool__(self): try: return self._val finally: self._val = True class TrueThenFalse: _val = True def __bool__(self): try: return self._val finally: self._val = False # result grows on the second pass a = np.array([True, FalseThenTrue()]) assert_raises(RuntimeError, np.nonzero, a) a = np.array([[True], [FalseThenTrue()]]) assert_raises(RuntimeError, np.nonzero, a) # result shrinks on the second pass a = np.array([False, TrueThenFalse()]) assert_raises(RuntimeError, np.nonzero, a) a = np.array([[False], [TrueThenFalse()]]) assert_raises(RuntimeError, np.nonzero, a) def test_nonzero_exception_safe(self): # gh-13930 class ThrowsAfter: def __init__(self, iters): self.iters_left = iters def __bool__(self): if self.iters_left == 0: raise ValueError("called `iters` times") self.iters_left -= 1 return True """ Test that a ValueError is raised instead of a SystemError If the __bool__ function is called after the error state is set, Python (cpython) will raise a SystemError. """ # assert that an exception in first pass is handled correctly a = np.array([ThrowsAfter(5)]*10) assert_raises(ValueError, np.nonzero, a) # raise exception in second pass for 1-dimensional loop a = np.array([ThrowsAfter(15)]*10) assert_raises(ValueError, np.nonzero, a) # raise exception in second pass for n-dimensional loop a = np.array([[ThrowsAfter(15)]]*10) assert_raises(ValueError, np.nonzero, a) class TestIndex: def test_boolean(self): a = rand(3, 5, 8) V = rand(5, 8) g1 = randint(0, 5, size=15) g2 = randint(0, 8, size=15) V[g1, g2] = -V[g1, g2] assert_((np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all()) def test_boolean_edgecase(self): a = np.array([], dtype='int32') b = np.array([], dtype='bool') c = a[b] assert_equal(c, []) assert_equal(c.dtype, np.dtype('int32')) class TestBinaryRepr: def test_zero(self): assert_equal(np.binary_repr(0), '0') def test_positive(self): assert_equal(np.binary_repr(10), '1010') assert_equal(np.binary_repr(12522), '11000011101010') assert_equal(np.binary_repr(10736848), '101000111101010011010000') def test_negative(self): assert_equal(np.binary_repr(-1), '-1') assert_equal(np.binary_repr(-10), '-1010') assert_equal(np.binary_repr(-12522), '-11000011101010') assert_equal(np.binary_repr(-10736848), '-101000111101010011010000') def test_sufficient_width(self): assert_equal(np.binary_repr(0, width=5), '00000') assert_equal(np.binary_repr(10, width=7), '0001010') assert_equal(np.binary_repr(-5, width=7), '1111011') def test_neg_width_boundaries(self): # see gh-8670 # Ensure that the example in the issue does not # break before proceeding to a more thorough test. assert_equal(np.binary_repr(-128, width=8), '10000000') for width in range(1, 11): num = -2**(width - 1) exp = '1' + (width - 1) * '0' assert_equal(np.binary_repr(num, width=width), exp) def test_large_neg_int64(self): # See gh-14289. assert_equal(np.binary_repr(np.int64(-2**62), width=64), '11' + '0'*62) class TestBaseRepr: def test_base3(self): assert_equal(np.base_repr(3**5, 3), '100000') def test_positive(self): assert_equal(np.base_repr(12, 10), '12') assert_equal(np.base_repr(12, 10, 4), '000012') assert_equal(np.base_repr(12, 4), '30') assert_equal(np.base_repr(3731624803700888, 36), '10QR0ROFCEW') def test_negative(self): assert_equal(np.base_repr(-12, 10), '-12') assert_equal(np.base_repr(-12, 10, 4), '-000012') assert_equal(np.base_repr(-12, 4), '-30') def test_base_range(self): with assert_raises(ValueError): np.base_repr(1, 1) with assert_raises(ValueError): np.base_repr(1, 37) class TestArrayComparisons: def test_array_equal(self): res = np.array_equal(np.array([1, 2]), np.array([1, 2])) assert_(res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([3, 4])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array([1, 2]), np.array([1, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equal(np.array(['a'], dtype='S1'), np.array(['a'], dtype='S1')) assert_(res) assert_(type(res) is bool) res = np.array_equal(np.array([('a', 1)], dtype='S1,u4'), np.array([('a', 1)], dtype='S1,u4')) assert_(res) assert_(type(res) is bool) def test_none_compares_elementwise(self): a = np.array([None, 1, None], dtype=object) assert_equal(a == None, [True, False, True]) assert_equal(a != None, [False, True, False]) a = np.ones(3) assert_equal(a == None, [False, False, False]) assert_equal(a != None, [True, True, True]) def test_array_equiv(self): res = np.array_equiv(np.array([1, 2]), np.array([1, 2])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([3, 4])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([1, 3])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 1]), np.array([1])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]])) assert_(res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([2])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]])) assert_(not res) assert_(type(res) is bool) res = np.array_equiv(np.array([1, 2]), np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) assert_(not res) assert_(type(res) is bool) def assert_array_strict_equal(x, y): assert_array_equal(x, y) # Check flags, 32 bit arches typically don't provide 16 byte alignment if ((x.dtype.alignment <= 8 or np.intp().dtype.itemsize != 4) and sys.platform != 'win32'): assert_(x.flags == y.flags) else: assert_(x.flags.owndata == y.flags.owndata) assert_(x.flags.writeable == y.flags.writeable) assert_(x.flags.c_contiguous == y.flags.c_contiguous) assert_(x.flags.f_contiguous == y.flags.f_contiguous) assert_(x.flags.writebackifcopy == y.flags.writebackifcopy) # check endianness assert_(x.dtype.isnative == y.dtype.isnative) class TestClip: def setup(self): self.nr = 5 self.nc = 3 def fastclip(self, a, m, M, out=None, casting=None): if out is None: if casting is None: return a.clip(m, M) else: return a.clip(m, M, casting=casting) else: if casting is None: return a.clip(m, M, out) else: return a.clip(m, M, out, casting=casting) def clip(self, a, m, M, out=None): # use slow-clip selector = np.less(a, m) + 2*np.greater(a, M) return selector.choose((a, m, M), out=out) # Handy functions def _generate_data(self, n, m): return randn(n, m) def _generate_data_complex(self, n, m): return randn(n, m) + 1.j * rand(n, m) def _generate_flt_data(self, n, m): return (randn(n, m)).astype(np.float32) def _neg_byteorder(self, a): a = np.asarray(a) if sys.byteorder == 'little': a = a.astype(a.dtype.newbyteorder('>')) else: a = a.astype(a.dtype.newbyteorder('<')) return a def _generate_non_native_data(self, n, m): data = randn(n, m) data = self._neg_byteorder(data) assert_(not data.dtype.isnative) return data def _generate_int_data(self, n, m): return (10 * rand(n, m)).astype(np.int64) def _generate_int32_data(self, n, m): return (10 * rand(n, m)).astype(np.int32) # Now the real test cases @pytest.mark.parametrize("dtype", '?bhilqpBHILQPefdgFDGO') def test_ones_pathological(self, dtype): # for preservation of behavior described in # gh-12519; amin > amax behavior may still change # in the future arr = np.ones(10, dtype=dtype) expected = np.zeros(10, dtype=dtype) actual = np.clip(arr, 1, 0) if dtype == 'O': assert actual.tolist() == expected.tolist() else: assert_equal(actual, expected) def test_simple_double(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.1 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_int(self): # Test native int input with scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(int) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_array_double(self): # Test native double input with array min/max. a = self._generate_data(self.nr, self.nc) m = np.zeros(a.shape) M = m + 0.5 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_nonnative(self): # Test non native double input with scalar min/max. # Test native double input with non native double scalar min/max. a = self._generate_non_native_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) # Test native double input with non native double scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = self._neg_byteorder(0.6) assert_(not M.dtype.isnative) ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) def test_simple_complex(self): # Test native complex input with native double scalar min/max. # Test native input with complex double scalar min/max. a = 3 * self._generate_data_complex(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) # Test native input with complex double scalar min/max. a = 3 * self._generate_data(self.nr, self.nc) m = -0.5 + 1.j M = 1. + 2.j ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_clip_complex(self): # Address Issue gh-5354 for clipping complex arrays # Test native complex input without explicit min/max # ie, either min=None or max=None a = np.ones(10, dtype=complex) m = a.min() M = a.max() am = self.fastclip(a, m, None) aM = self.fastclip(a, None, M) assert_array_strict_equal(am, a) assert_array_strict_equal(aM, a) def test_clip_non_contig(self): # Test clip for non contiguous native input and native scalar min/max. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = self.fastclip(a, -1.6, 1.7) act = self.clip(a, -1.6, 1.7) assert_array_strict_equal(ac, act) def test_simple_out(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = np.zeros(a.shape) act = np.zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) @pytest.mark.parametrize("casting", [None, "unsafe"]) def test_simple_int32_inout(self, casting): # Test native int32 input with double min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = np.float64(0) M = np.float64(2) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() if casting is None: with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac, casting=casting) else: # explicitly passing "unsafe" will silence warning self.fastclip(a, m, M, ac, casting=casting) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_out(self): # Test native int32 input with int32 scalar min/max and int64 out. a = self._generate_int32_data(self.nr, self.nc) m = np.int32(-1) M = np.int32(1) ac = np.zeros(a.shape, dtype=np.int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_inout(self): # Test native int32 input with double array min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = np.zeros(a.shape, np.float64) M = np.float64(1) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int32_out(self): # Test native double input with scalar min/max and int out. a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_inplace_01(self): # Test native double input with array min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = np.zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_simple_inplace_02(self): # Test native double input with scalar min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(ac, m, M, ac) assert_array_strict_equal(a, ac) def test_noncontig_inplace(self): # Test non contiguous double input with double scalar min/max in-place. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(ac, m, M, ac) assert_array_equal(a, ac) def test_type_cast_01(self): # Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_02(self): # Test native int32 input with int32 scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(np.int32) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_03(self): # Test native int32 input with float64 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = -2 M = 4 ac = self.fastclip(a, np.float64(m), np.float64(M)) act = self.clip(a, np.float64(m), np.float64(M)) assert_array_strict_equal(ac, act) def test_type_cast_04(self): # Test native int32 input with float32 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = np.float32(-2) M = np.float32(4) act = self.fastclip(a, m, M) ac = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_05(self): # Test native int32 with double arrays min/max. a = self._generate_int_data(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m * np.zeros(a.shape), M) act = self.clip(a, m * np.zeros(a.shape), M) assert_array_strict_equal(ac, act) def test_type_cast_06(self): # Test native with NON native scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.5 m_s = self._neg_byteorder(m) M = 1. act = self.clip(a, m_s, M) ac = self.fastclip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_07(self): # Test NON native with native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * np.ones(a.shape) M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) act = a_s.clip(m, M) ac = self.fastclip(a_s, m, M) assert_array_strict_equal(ac, act) def test_type_cast_08(self): # Test NON native with native scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) ac = self.fastclip(a_s, m, M) act = a_s.clip(m, M) assert_array_strict_equal(ac, act) def test_type_cast_09(self): # Test native with NON native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * np.ones(a.shape) M = 1. m_s = self._neg_byteorder(m) assert_(not m_s.dtype.isnative) ac = self.fastclip(a, m_s, M) act = self.clip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_10(self): # Test native int32 with float min/max and float out for output argument. a = self._generate_int_data(self.nr, self.nc) b = np.zeros(a.shape, dtype=np.float32) m = np.float32(-0.5) M = np.float32(1) act = self.clip(a, m, M, out=b) ac = self.fastclip(a, m, M, out=b) assert_array_strict_equal(ac, act) def test_type_cast_11(self): # Test non native with native scalar, min/max, out non native a = self._generate_non_native_data(self.nr, self.nc) b = a.copy() b = b.astype(b.dtype.newbyteorder('>')) bt = b.copy() m = -0.5 M = 1. self.fastclip(a, m, M, out=b) self.clip(a, m, M, out=bt) assert_array_strict_equal(b, bt) def test_type_cast_12(self): # Test native int32 input and min/max and float out a = self._generate_int_data(self.nr, self.nc) b = np.zeros(a.shape, dtype=np.float32) m = np.int32(0) M = np.int32(1) act = self.clip(a, m, M, out=b) ac = self.fastclip(a, m, M, out=b) assert_array_strict_equal(ac, act) def test_clip_with_out_simple(self): # Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = np.zeros(a.shape) act = np.zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple2(self): # Test native int32 input with double min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = np.float64(0) M = np.float64(2) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple_int32(self): # Test native int32 input with int32 scalar min/max and int64 out a = self._generate_int32_data(self.nr, self.nc) m = np.int32(-1) M = np.int32(1) ac = np.zeros(a.shape, dtype=np.int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_int32(self): # Test native int32 input with double array min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = np.zeros(a.shape, np.float64) M = np.float64(1) ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_outint32(self): # Test native double input with scalar min/max and int out a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = np.zeros(a.shape, dtype=np.int32) act = ac.copy() with assert_warns(DeprecationWarning): # NumPy 1.17.0, 2018-02-24 - casting is unsafe self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_transposed(self): # Test that the out argument works when transposed a = np.arange(16).reshape(4, 4) out = np.empty_like(a).T a.clip(4, 10, out=out) expected = self.clip(a, 4, 10) assert_array_equal(out, expected) def test_clip_with_out_memory_overlap(self): # Test that the out argument works when it has memory overlap a = np.arange(16).reshape(4, 4) ac = a.copy() a[:-1].clip(4, 10, out=a[1:]) expected = self.clip(ac[:-1], 4, 10) assert_array_equal(a[1:], expected) def test_clip_inplace_array(self): # Test native double input with array min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = np.zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_inplace_simple(self): # Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_func_takes_out(self): # Ensure that the clip() function takes an out=argument. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 a2 = np.clip(a, m, M, out=a) self.clip(a, m, M, ac) assert_array_strict_equal(a2, ac) assert_(a2 is a) def test_clip_nan(self): d = np.arange(7.) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan, max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=-2, max=np.nan), d) with assert_warns(DeprecationWarning): assert_equal(d.clip(min=np.nan, max=10), d) def test_object_clip(self): a = np.arange(10, dtype=object) actual = np.clip(a, 1, 5) expected = np.array([1, 1, 2, 3, 4, 5, 5, 5, 5, 5]) assert actual.tolist() == expected.tolist() def test_clip_all_none(self): a = np.arange(10, dtype=object) with assert_raises_regex(ValueError, 'max or min'): np.clip(a, None, None) def test_clip_invalid_casting(self): a = np.arange(10, dtype=object) with assert_raises_regex(ValueError, 'casting must be one of'): self.fastclip(a, 1, 8, casting="garbage") @pytest.mark.parametrize("amin, amax", [ # two scalars (1, 0), # mix scalar and array (1, np.zeros(10)), # two arrays (np.ones(10), np.zeros(10)), ]) def test_clip_value_min_max_flip(self, amin, amax): a = np.arange(10, dtype=np.int64) # requirement from ufunc_docstrings.py expected = np.minimum(np.maximum(a, amin), amax) actual = np.clip(a, amin, amax) assert_equal(actual, expected) @pytest.mark.parametrize("arr, amin, amax, exp", [ # for a bug in npy_ObjectClip, based on a # case produced by hypothesis (np.zeros(10, dtype=np.int64), 0, -2**64+1, np.full(10, -2**64+1, dtype=object)), # for bugs in NPY_TIMEDELTA_MAX, based on a case # produced by hypothesis (np.zeros(10, dtype='m8') - 1, 0, 0, np.zeros(10, dtype='m8')), ]) def test_clip_problem_cases(self, arr, amin, amax, exp): actual = np.clip(arr, amin, amax) assert_equal(actual, exp) @pytest.mark.xfail(reason="no scalar nan propagation yet", raises=AssertionError, strict=True) @pytest.mark.parametrize("arr, amin, amax", [ # problematic scalar nan case from hypothesis (np.zeros(10, dtype=np.int64), np.array(np.nan), np.zeros(10, dtype=np.int32)), ]) @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_clip_scalar_nan_propagation(self, arr, amin, amax): # enforcement of scalar nan propagation for comparisons # called through clip() expected = np.minimum(np.maximum(arr, amin), amax) actual = np.clip(arr, amin, amax) assert_equal(actual, expected) @pytest.mark.xfail(reason="propagation doesn't match spec") @pytest.mark.parametrize("arr, amin, amax", [ (np.array([1] * 10, dtype='m8'), np.timedelta64('NaT'), np.zeros(10, dtype=np.int32)), ]) @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_NaT_propagation(self, arr, amin, amax): # NOTE: the expected function spec doesn't # propagate NaT, but clip() now does expected = np.minimum(np.maximum(arr, amin), amax) actual = np.clip(arr, amin, amax) assert_equal(actual, expected) @given(data=st.data(), shape=hynp.array_shapes()) def test_clip_property(self, data, shape): """A property-based test using Hypothesis. This aims for maximum generality: it could in principle generate *any* valid inputs to np.clip, and in practice generates much more varied inputs than human testers come up with. Because many of the inputs have tricky dependencies - compatible dtypes and mutually-broadcastable shapes - we use `st.data()` strategy draw values *inside* the test function, from strategies we construct based on previous values. An alternative would be to define a custom strategy with `@st.composite`, but until we have duplicated code inline is fine. That accounts for most of the function; the actual test is just three lines to calculate and compare actual vs expected results! """ # Our base array and bounds should not need to be of the same type as # long as they are all compatible - so we allow any int or float type. dtype_strategy = hynp.integer_dtypes() | hynp.floating_dtypes() # The following line is a total hack to disable the varied-dtypes # component of this test, because result != expected if dtypes can vary. dtype_strategy = st.just(data.draw(dtype_strategy)) # Generate an arbitrary array of the chosen shape and dtype # This is the value that we clip. arr = data.draw(hynp.arrays(dtype=dtype_strategy, shape=shape)) # Generate shapes for the bounds which can be broadcast with each other # and with the base shape. Below, we might decide to use scalar bounds, # but it's clearer to generate these shapes unconditionally in advance. in_shapes, result_shape = data.draw( hynp.mutually_broadcastable_shapes( num_shapes=2, base_shape=shape, # Commenting out the min_dims line allows zero-dimensional arrays, # and zero-dimensional arrays containing NaN make the test fail. min_dims=1 ) ) amin = data.draw( dtype_strategy.flatmap(hynp.from_dtype) | hynp.arrays(dtype=dtype_strategy, shape=in_shapes[0]) ) amax = data.draw( dtype_strategy.flatmap(hynp.from_dtype) | hynp.arrays(dtype=dtype_strategy, shape=in_shapes[1]) ) # If we allow either bound to be a scalar `nan`, the test will fail - # so we just "assume" that away (if it is, this raises a special # exception and Hypothesis will try again with different inputs) assume(not np.isscalar(amin) or not np.isnan(amin)) assume(not np.isscalar(amax) or not np.isnan(amax)) # Then calculate our result and expected result and check that they're # equal! See gh-12519 for discussion deciding on this property. result = np.clip(arr, amin, amax) expected = np.minimum(amax, np.maximum(arr, amin)) assert_array_equal(result, expected) class TestAllclose: rtol = 1e-5 atol = 1e-8 def setup(self): self.olderr = np.seterr(invalid='ignore') def teardown(self): np.seterr(**self.olderr) def tst_allclose(self, x, y): assert_(np.allclose(x, y), "%s and %s not close" % (x, y)) def tst_not_allclose(self, x, y): assert_(not np.allclose(x, y), "%s and %s shouldn't be close" % (x, y)) def test_ip_allclose(self): # Parametric test factory. arr = np.array([100, 1000]) aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([1, 0], [1, 0]), ([atol], [0]), ([1], [1+rtol+atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol*2), (aran, aran + aran*rtol), (np.inf, np.inf), (np.inf, [np.inf])] for (x, y) in data: self.tst_allclose(x, y) def test_ip_not_allclose(self): # Parametric test factory. aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([np.inf, 0], [1, np.inf]), ([np.inf, 0], [1, 0]), ([np.inf, np.inf], [1, np.inf]), ([np.inf, np.inf], [1, 0]), ([-np.inf, 0], [np.inf, 0]), ([np.nan, 0], [np.nan, 0]), ([atol*2], [0]), ([1], [1+rtol+atol*2]), (aran, aran + aran*atol + atol*2), (np.array([np.inf, 1]), np.array([0, np.inf]))] for (x, y) in data: self.tst_not_allclose(x, y) def test_no_parameter_modification(self): x = np.array([np.inf, 1]) y = np.array([0, np.inf]) np.allclose(x, y) assert_array_equal(x, np.array([np.inf, 1])) assert_array_equal(y, np.array([0, np.inf])) def test_min_int(self): # Could make problems because of abs(min_int) == min_int min_int = np.iinfo(np.int_).min a = np.array([min_int], dtype=np.int_) assert_(np.allclose(a, a)) def test_equalnan(self): x = np.array([1.0, np.nan]) assert_(np.allclose(x, x, equal_nan=True)) def test_return_class_is_ndarray(self): # Issue gh-6475 # Check that allclose does not preserve subtypes class Foo(np.ndarray): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) a = Foo([1]) assert_(type(np.allclose(a, a)) is bool) class TestIsclose: rtol = 1e-5 atol = 1e-8 def setup(self): atol = self.atol rtol = self.rtol arr = np.array([100, 1000]) aran = np.arange(125).reshape((5, 5, 5)) self.all_close_tests = [ ([1, 0], [1, 0]), ([atol], [0]), ([1], [1 + rtol + atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol), (aran, aran + aran*rtol), (np.inf, np.inf), (np.inf, [np.inf]), ([np.inf, -np.inf], [np.inf, -np.inf]), ] self.none_close_tests = [ ([np.inf, 0], [1, np.inf]), ([np.inf, -np.inf], [1, 0]), ([np.inf, np.inf], [1, -np.inf]), ([np.inf, np.inf], [1, 0]), ([np.nan, 0], [np.nan, -np.inf]), ([atol*2], [0]), ([1], [1 + rtol + atol*2]), (aran, aran + rtol*1.1*aran + atol*1.1), (np.array([np.inf, 1]), np.array([0, np.inf])), ] self.some_close_tests = [ ([np.inf, 0], [np.inf, atol*2]), ([atol, 1, 1e6*(1 + 2*rtol) + atol], [0, np.nan, 1e6]), (np.arange(3), [0, 1, 2.1]), (np.nan, [np.nan, np.nan, np.nan]), ([0], [atol, np.inf, -np.inf, np.nan]), (0, [atol, np.inf, -np.inf, np.nan]), ] self.some_close_results = [ [True, False], [True, False, False], [True, True, False], [False, False, False], [True, False, False, False], [True, False, False, False], ] def test_ip_isclose(self): self.setup() tests = self.some_close_tests results = self.some_close_results for (x, y), result in zip(tests, results): assert_array_equal(np.isclose(x, y), result) def tst_all_isclose(self, x, y): assert_(np.all(np.isclose(x, y)), "%s and %s not close" % (x, y)) def tst_none_isclose(self, x, y): msg = "%s and %s shouldn't be close" assert_(not np.any(np.isclose(x, y)), msg % (x, y)) def tst_isclose_allclose(self, x, y): msg = "isclose.all() and allclose aren't same for %s and %s" msg2 = "isclose and allclose aren't same for %s and %s" if np.isscalar(x) and np.isscalar(y): assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y)) else: assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y)) def test_ip_all_isclose(self): self.setup() for (x, y) in self.all_close_tests: self.tst_all_isclose(x, y) def test_ip_none_isclose(self): self.setup() for (x, y) in self.none_close_tests: self.tst_none_isclose(x, y) def test_ip_isclose_allclose(self): self.setup() tests = (self.all_close_tests + self.none_close_tests + self.some_close_tests) for (x, y) in tests: self.tst_isclose_allclose(x, y) def test_equal_nan(self): assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True]) arr = np.array([1.0, np.nan]) assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True]) def test_masked_arrays(self): # Make sure to test the output type when arguments are interchanged. x = np.ma.masked_where([True, True, False], np.arange(3)) assert_(type(x) is type(np.isclose(2, x))) assert_(type(x) is type(np.isclose(x, 2))) x = np.ma.masked_where([True, True, False], [np.nan, np.inf, np.nan]) assert_(type(x) is type(np.isclose(np.inf, x))) assert_(type(x) is type(np.isclose(x, np.inf))) x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan]) y = np.isclose(np.nan, x, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) y = np.isclose(x, np.nan, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan]) y = np.isclose(x, x, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) def test_scalar_return(self): assert_(np.isscalar(np.isclose(1, 1))) def test_no_parameter_modification(self): x = np.array([np.inf, 1]) y = np.array([0, np.inf]) np.isclose(x, y) assert_array_equal(x, np.array([np.inf, 1])) assert_array_equal(y, np.array([0, np.inf])) def test_non_finite_scalar(self): # GH7014, when two scalars are compared the output should also be a # scalar assert_(np.isclose(np.inf, -np.inf) is np.False_) assert_(np.isclose(0, np.inf) is np.False_) assert_(type(np.isclose(0, np.inf)) is np.bool_) class TestStdVar: def setup(self): self.A = np.array([1, -1, 1, -1]) self.real_var = 1 def test_basic(self): assert_almost_equal(np.var(self.A), self.real_var) assert_almost_equal(np.std(self.A)**2, self.real_var) def test_scalars(self): assert_equal(np.var(1), 0) assert_equal(np.std(1), 0) def test_ddof1(self): assert_almost_equal(np.var(self.A, ddof=1), self.real_var*len(self.A)/float(len(self.A)-1)) assert_almost_equal(np.std(self.A, ddof=1)**2, self.real_var*len(self.A)/float(len(self.A)-1)) def test_ddof2(self): assert_almost_equal(np.var(self.A, ddof=2), self.real_var*len(self.A)/float(len(self.A)-2)) assert_almost_equal(np.std(self.A, ddof=2)**2, self.real_var*len(self.A)/float(len(self.A)-2)) def test_out_scalar(self): d = np.arange(10) out = np.array(0.) r = np.std(d, out=out) assert_(r is out) assert_array_equal(r, out) r = np.var(d, out=out) assert_(r is out) assert_array_equal(r, out) r = np.mean(d, out=out) assert_(r is out) assert_array_equal(r, out) class TestStdVarComplex: def test_basic(self): A = np.array([1, 1.j, -1, -1.j]) real_var = 1 assert_almost_equal(np.var(A), real_var) assert_almost_equal(np.std(A)**2, real_var) def test_scalars(self): assert_equal(np.var(1j), 0) assert_equal(np.std(1j), 0) class TestCreationFuncs: # Test ones, zeros, empty and full. def setup(self): dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())} # void, bytes, str variable_sized = {tp for tp in dtypes if tp.str.endswith('0')} self.dtypes = sorted(dtypes - variable_sized | {np.dtype(tp.str.replace("0", str(i))) for tp in variable_sized for i in range(1, 10)}, key=lambda dtype: dtype.str) self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'} self.ndims = 10 def check_function(self, func, fill_value=None): par = ((0, 1, 2), range(self.ndims), self.orders, self.dtypes) fill_kwarg = {} if fill_value is not None: fill_kwarg = {'fill_value': fill_value} for size, ndims, order, dtype in itertools.product(*par): shape = ndims * [size] # do not fill void type if fill_kwarg and dtype.str.startswith('|V'): continue arr = func(shape, order=order, dtype=dtype, **fill_kwarg) assert_equal(arr.dtype, dtype) assert_(getattr(arr.flags, self.orders[order])) if fill_value is not None: if dtype.str.startswith('|S'): val = str(fill_value) else: val = fill_value assert_equal(arr, dtype.type(val)) def test_zeros(self): self.check_function(np.zeros) def test_ones(self): self.check_function(np.zeros) def test_empty(self): self.check_function(np.empty) def test_full(self): self.check_function(np.full, 0) self.check_function(np.full, 1) @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") def test_for_reference_leak(self): # Make sure we have an object for reference dim = 1 beg = sys.getrefcount(dim) np.zeros([dim]*10) assert_(sys.getrefcount(dim) == beg) np.ones([dim]*10) assert_(sys.getrefcount(dim) == beg) np.empty([dim]*10) assert_(sys.getrefcount(dim) == beg) np.full([dim]*10, 0) assert_(sys.getrefcount(dim) == beg) class TestLikeFuncs: '''Test ones_like, zeros_like, empty_like and full_like''' def setup(self): self.data = [ # Array scalars (np.array(3.), None), (np.array(3), 'f8'), # 1D arrays (np.arange(6, dtype='f4'), None), (np.arange(6), 'c16'), # 2D C-layout arrays (np.arange(6).reshape(2, 3), None), (np.arange(6).reshape(3, 2), 'i1'), # 2D F-layout arrays (np.arange(6).reshape((2, 3), order='F'), None), (np.arange(6).reshape((3, 2), order='F'), 'i1'), # 3D C-layout arrays (np.arange(24).reshape(2, 3, 4), None), (np.arange(24).reshape(4, 3, 2), 'f4'), # 3D F-layout arrays (np.arange(24).reshape((2, 3, 4), order='F'), None), (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'), # 3D non-C/F-layout arrays (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None), (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'), ] self.shapes = [(5,), (5,6,), (5,6,7,)] def compare_array_value(self, dz, value, fill_value): if value is not None: if fill_value: try: z = dz.dtype.type(value) except OverflowError: pass else: assert_(np.all(dz == z)) else: assert_(np.all(dz == value)) def check_like_function(self, like_function, value, fill_value=False): if fill_value: fill_kwarg = {'fill_value': value} else: fill_kwarg = {} for d, dtype in self.data: # default (K) order, dtype dz = like_function(d, dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_equal(np.array(dz.strides)*d.dtype.itemsize, np.array(d.strides)*dz.dtype.itemsize) assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous) assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # C order, default dtype dz = like_function(d, order='C', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # F order, default dtype dz = like_function(d, order='F', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # A order dz = like_function(d, order='A', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) if d.flags.f_contiguous: assert_(dz.flags.f_contiguous) else: assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # Test the 'shape' parameter for s in self.shapes: for o in 'CFA': sz = like_function(d, dtype=dtype, shape=s, order=o, **fill_kwarg) assert_equal(sz.shape, s) if dtype is None: assert_equal(sz.dtype, d.dtype) else: assert_equal(sz.dtype, np.dtype(dtype)) if o == 'C' or (o == 'A' and d.flags.c_contiguous): assert_(sz.flags.c_contiguous) elif o == 'F' or (o == 'A' and d.flags.f_contiguous): assert_(sz.flags.f_contiguous) self.compare_array_value(sz, value, fill_value) if (d.ndim != len(s)): assert_equal(np.argsort(like_function(d, dtype=dtype, shape=s, order='K', **fill_kwarg).strides), np.argsort(np.empty(s, dtype=dtype, order='C').strides)) else: assert_equal(np.argsort(like_function(d, dtype=dtype, shape=s, order='K', **fill_kwarg).strides), np.argsort(d.strides)) # Test the 'subok' parameter class MyNDArray(np.ndarray): pass a = np.array([[1, 2], [3, 4]]).view(MyNDArray) b = like_function(a, **fill_kwarg) assert_(type(b) is MyNDArray) b = like_function(a, subok=False, **fill_kwarg) assert_(type(b) is not MyNDArray) def test_ones_like(self): self.check_like_function(np.ones_like, 1) def test_zeros_like(self): self.check_like_function(np.zeros_like, 0) def test_empty_like(self): self.check_like_function(np.empty_like, None) def test_filled_like(self): self.check_like_function(np.full_like, 0, True) self.check_like_function(np.full_like, 1, True) self.check_like_function(np.full_like, 1000, True) self.check_like_function(np.full_like, 123.456, True) self.check_like_function(np.full_like, np.inf, True) class TestCorrelate: def _setup(self, dt): self.x = np.array([1, 2, 3, 4, 5], dtype=dt) self.xs = np.arange(1, 20)[::3] self.y = np.array([-1, -2, -3], dtype=dt) self.z1 = np.array([ -3., -8., -14., -20., -26., -14., -5.], dtype=dt) self.z1_4 = np.array([-2., -5., -8., -11., -14., -5.], dtype=dt) self.z1r = np.array([-15., -22., -22., -16., -10., -4., -1.], dtype=dt) self.z2 = np.array([-5., -14., -26., -20., -14., -8., -3.], dtype=dt) self.z2r = np.array([-1., -4., -10., -16., -22., -22., -15.], dtype=dt) self.zs = np.array([-3., -14., -30., -48., -66., -84., -102., -54., -19.], dtype=dt) def test_float(self): self._setup(float) z = np.correlate(self.x, self.y, 'full') assert_array_almost_equal(z, self.z1) z = np.correlate(self.x, self.y[:-1], 'full') assert_array_almost_equal(z, self.z1_4) z = np.correlate(self.y, self.x, 'full') assert_array_almost_equal(z, self.z2) z = np.correlate(self.x[::-1], self.y, 'full') assert_array_almost_equal(z, self.z1r) z = np.correlate(self.y, self.x[::-1], 'full') assert_array_almost_equal(z, self.z2r) z = np.correlate(self.xs, self.y, 'full') assert_array_almost_equal(z, self.zs) def test_object(self): self._setup(Decimal) z = np.correlate(self.x, self.y, 'full') assert_array_almost_equal(z, self.z1) z = np.correlate(self.y, self.x, 'full') assert_array_almost_equal(z, self.z2) def test_no_overwrite(self): d = np.ones(100) k = np.ones(3) np.correlate(d, k) assert_array_equal(d, np.ones(100)) assert_array_equal(k, np.ones(3)) def test_complex(self): x = np.array([1, 2, 3, 4+1j], dtype=complex) y = np.array([-1, -2j, 3+1j], dtype=complex) r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex) r_z = r_z[::-1].conjugate() z = np.correlate(y, x, mode='full') assert_array_almost_equal(z, r_z) def test_zero_size(self): with pytest.raises(ValueError): np.correlate(np.array([]), np.ones(1000), mode='full') with pytest.raises(ValueError): np.correlate(np.ones(1000), np.array([]), mode='full') class TestConvolve: def test_object(self): d = [1.] * 100 k = [1.] * 3 assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3)) def test_no_overwrite(self): d = np.ones(100) k = np.ones(3) np.convolve(d, k) assert_array_equal(d, np.ones(100)) assert_array_equal(k, np.ones(3)) class TestArgwhere: @pytest.mark.parametrize('nd', [0, 1, 2]) def test_nd(self, nd): # get an nd array with multiple elements in every dimension x = np.empty((2,)*nd, bool) # none x[...] = False assert_equal(np.argwhere(x).shape, (0, nd)) # only one x[...] = False x.flat[0] = True assert_equal(np.argwhere(x).shape, (1, nd)) # all but one x[...] = True x.flat[0] = False assert_equal(np.argwhere(x).shape, (x.size - 1, nd)) # all x[...] = True assert_equal(np.argwhere(x).shape, (x.size, nd)) def test_2D(self): x = np.arange(6).reshape((2, 3)) assert_array_equal(np.argwhere(x > 1), [[0, 2], [1, 0], [1, 1], [1, 2]]) def test_list(self): assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]]) class TestStringFunction: def test_set_string_function(self): a = np.array([1]) np.set_string_function(lambda x: "FOO", repr=True) assert_equal(repr(a), "FOO") np.set_string_function(None, repr=True) assert_equal(repr(a), "array([1])") np.set_string_function(lambda x: "FOO", repr=False) assert_equal(str(a), "FOO") np.set_string_function(None, repr=False) assert_equal(str(a), "[1]") class TestRoll: def test_roll1d(self): x = np.arange(10) xr = np.roll(x, 2) assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) def test_roll2d(self): x2 = np.reshape(np.arange(10), (2, 5)) x2r = np.roll(x2, 1) assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]])) x2r = np.roll(x2, 1, axis=0) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, 1, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) # Roll multiple axes at once. x2r = np.roll(x2, 1, axis=(0, 1)) assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]])) x2r = np.roll(x2, (1, 0), axis=(0, 1)) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, (-1, 0), axis=(0, 1)) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, (0, 1), axis=(0, 1)) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) x2r = np.roll(x2, (0, -1), axis=(0, 1)) assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]])) x2r = np.roll(x2, (1, 1), axis=(0, 1)) assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]])) x2r = np.roll(x2, (-1, -1), axis=(0, 1)) assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]])) # Roll the same axis multiple times. x2r = np.roll(x2, 1, axis=(0, 0)) assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])) x2r = np.roll(x2, 1, axis=(1, 1)) assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]])) # Roll more than one turn in either direction. x2r = np.roll(x2, 6, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) x2r = np.roll(x2, -4, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) def test_roll_empty(self): x = np.array([]) assert_equal(np.roll(x, 1), np.array([])) class TestRollaxis: # expected shape indexed by (axis, start) for array of # shape (1, 2, 3, 4) tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4), (0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4), (0, 4): (2, 3, 4, 1), (1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4), (1, 2): (1, 2, 3, 4), (1, 3): (1, 3, 2, 4), (1, 4): (1, 3, 4, 2), (2, 0): (3, 1, 2, 4), (2, 1): (1, 3, 2, 4), (2, 2): (1, 2, 3, 4), (2, 3): (1, 2, 3, 4), (2, 4): (1, 2, 4, 3), (3, 0): (4, 1, 2, 3), (3, 1): (1, 4, 2, 3), (3, 2): (1, 2, 4, 3), (3, 3): (1, 2, 3, 4), (3, 4): (1, 2, 3, 4)} def test_exceptions(self): a = np.arange(1*2*3*4).reshape(1, 2, 3, 4) assert_raises(np.AxisError, np.rollaxis, a, -5, 0) assert_raises(np.AxisError, np.rollaxis, a, 0, -5) assert_raises(np.AxisError, np.rollaxis, a, 4, 0) assert_raises(np.AxisError, np.rollaxis, a, 0, 5) def test_results(self): a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy() aind = np.indices(a.shape) assert_(a.flags['OWNDATA']) for (i, j) in self.tgtshape: # positive axis, positive start res = np.rollaxis(a, axis=i, start=j) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(i, j)], str((i,j))) assert_(not res.flags['OWNDATA']) # negative axis, positive start ip = i + 1 res = np.rollaxis(a, axis=-ip, start=j) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(4 - ip, j)]) assert_(not res.flags['OWNDATA']) # positive axis, negative start jp = j + 1 if j < 4 else j res = np.rollaxis(a, axis=i, start=-jp) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(i, 4 - jp)]) assert_(not res.flags['OWNDATA']) # negative axis, negative start ip = i + 1 jp = j + 1 if j < 4 else j res = np.rollaxis(a, axis=-ip, start=-jp) i0, i1, i2, i3 = aind[np.array(res.shape) - 1] assert_(np.all(res[i0, i1, i2, i3] == a)) assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)]) assert_(not res.flags['OWNDATA']) class TestMoveaxis: def test_move_to_end(self): x = np.random.randn(5, 6, 7) for source, expected in [(0, (6, 7, 5)), (1, (5, 7, 6)), (2, (5, 6, 7)), (-1, (5, 6, 7))]: actual = np.moveaxis(x, source, -1).shape assert_(actual, expected) def test_move_new_position(self): x = np.random.randn(1, 2, 3, 4) for source, destination, expected in [ (0, 1, (2, 1, 3, 4)), (1, 2, (1, 3, 2, 4)), (1, -1, (1, 3, 4, 2)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, expected) def test_preserve_order(self): x = np.zeros((1, 2, 3, 4)) for source, destination in [ (0, 0), (3, -1), (-1, 3), ([0, -1], [0, -1]), ([2, 0], [2, 0]), (range(4), range(4)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, (1, 2, 3, 4)) def test_move_multiples(self): x = np.zeros((0, 1, 2, 3)) for source, destination, expected in [ ([0, 1], [2, 3], (2, 3, 0, 1)), ([2, 3], [0, 1], (2, 3, 0, 1)), ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)), ([3, 0], [1, 0], (0, 3, 1, 2)), ([0, 3], [0, 1], (0, 3, 1, 2)), ]: actual = np.moveaxis(x, source, destination).shape assert_(actual, expected) def test_errors(self): x = np.random.randn(1, 2, 3) assert_raises_regex(np.AxisError, 'source.*out of bounds', np.moveaxis, x, 3, 0) assert_raises_regex(np.AxisError, 'source.*out of bounds', np.moveaxis, x, -4, 0) assert_raises_regex(np.AxisError, 'destination.*out of bounds', np.moveaxis, x, 0, 5) assert_raises_regex(ValueError, 'repeated axis in `source`', np.moveaxis, x, [0, 0], [0, 1]) assert_raises_regex(ValueError, 'repeated axis in `destination`', np.moveaxis, x, [0, 1], [1, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, 0, [0, 1]) assert_raises_regex(ValueError, 'must have the same number', np.moveaxis, x, [0, 1], [0]) def test_array_likes(self): x = np.ma.zeros((1, 2, 3)) result = np.moveaxis(x, 0, 0) assert_(x.shape, result.shape) assert_(isinstance(result, np.ma.MaskedArray)) x = [1, 2, 3] result = np.moveaxis(x, 0, 0) assert_(x, list(result)) assert_(isinstance(result, np.ndarray)) class TestCross: def test_2x2(self): u = [1, 2] v = [3, 4] z = -2 cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_2x3(self): u = [1, 2] v = [3, 4, 5] z = np.array([10, -5, -2]) cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_3x3(self): u = [1, 2, 3] v = [4, 5, 6] z = np.array([-3, 6, -3]) cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_broadcasting(self): # Ticket #2624 (Trac #2032) u = np.tile([1, 2], (11, 1)) v = np.tile([3, 4], (11, 1)) z = -2 assert_equal(np.cross(u, v), z) assert_equal(np.cross(v, u), -z) assert_equal(np.cross(u, u), 0) u = np.tile([1, 2], (11, 1)).T v = np.tile([3, 4, 5], (11, 1)) z = np.tile([10, -5, -2], (11, 1)) assert_equal(np.cross(u, v, axisa=0), z) assert_equal(np.cross(v, u.T), -z) assert_equal(np.cross(v, v), 0) u = np.tile([1, 2, 3], (11, 1)).T v = np.tile([3, 4], (11, 1)).T z = np.tile([-12, 9, -2], (11, 1)) assert_equal(np.cross(u, v, axisa=0, axisb=0), z) assert_equal(np.cross(v.T, u.T), -z) assert_equal(np.cross(u.T, u.T), 0) u = np.tile([1, 2, 3], (5, 1)) v = np.tile([4, 5, 6], (5, 1)).T z = np.tile([-3, 6, -3], (5, 1)) assert_equal(np.cross(u, v, axisb=0), z) assert_equal(np.cross(v.T, u), -z) assert_equal(np.cross(u, u), 0) def test_broadcasting_shapes(self): u = np.ones((2, 1, 3)) v = np.ones((5, 3)) assert_equal(np.cross(u, v).shape, (2, 5, 3)) u = np.ones((10, 3, 5)) v = np.ones((2, 5)) assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3)) assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=2) assert_raises(np.AxisError, np.cross, u, v, axisa=3, axisb=0) u = np.ones((10, 3, 5, 7)) v = np.ones((5, 7, 2)) assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7)) assert_raises(np.AxisError, np.cross, u, v, axisa=-5, axisb=2) assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=-4) # gh-5885 u = np.ones((3, 4, 2)) for axisc in range(-2, 2): assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4)) def test_outer_out_param(): arr1 = np.ones((5,)) arr2 = np.ones((2,)) arr3 = np.linspace(-2, 2, 5) out1 = np.ndarray(shape=(5,5)) out2 = np.ndarray(shape=(2, 5)) res1 = np.outer(arr1, arr3, out1) assert_equal(res1, out1) assert_equal(np.outer(arr2, arr3, out2), out2) class TestIndices: def test_simple(self): [x, y] = np.indices((4, 3)) assert_array_equal(x, np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]])) assert_array_equal(y, np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]])) def test_single_input(self): [x] = np.indices((4,)) assert_array_equal(x, np.array([0, 1, 2, 3])) [x] = np.indices((4,), sparse=True) assert_array_equal(x, np.array([0, 1, 2, 3])) def test_scalar_input(self): assert_array_equal([], np.indices(())) assert_array_equal([], np.indices((), sparse=True)) assert_array_equal([[]], np.indices((0,))) assert_array_equal([[]], np.indices((0,), sparse=True)) def test_sparse(self): [x, y] = np.indices((4,3), sparse=True) assert_array_equal(x, np.array([[0], [1], [2], [3]])) assert_array_equal(y, np.array([[0, 1, 2]])) @pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) @pytest.mark.parametrize("dims", [(), (0,), (4, 3)]) def test_return_type(self, dtype, dims): inds = np.indices(dims, dtype=dtype) assert_(inds.dtype == dtype) for arr in np.indices(dims, dtype=dtype, sparse=True): assert_(arr.dtype == dtype) class TestRequire: flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS', 'F', 'F_CONTIGUOUS', 'FORTRAN', 'A', 'ALIGNED', 'W', 'WRITEABLE', 'O', 'OWNDATA'] def generate_all_false(self, dtype): arr = np.zeros((2, 2), [('junk', 'i1'), ('a', dtype)]) arr.setflags(write=False) a = arr['a'] assert_(not a.flags['C']) assert_(not a.flags['F']) assert_(not a.flags['O']) assert_(not a.flags['W']) assert_(not a.flags['A']) return a def set_and_check_flag(self, flag, dtype, arr): if dtype is None: dtype = arr.dtype b = np.require(arr, dtype, [flag]) assert_(b.flags[flag]) assert_(b.dtype == dtype) # a further call to np.require ought to return the same array # unless OWNDATA is specified. c = np.require(b, None, [flag]) if flag[0] != 'O': assert_(c is b) else: assert_(c.flags[flag]) def test_require_each(self): id = ['f8', 'i4'] fd = [None, 'f8', 'c16'] for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names): a = self.generate_all_false(idtype) self.set_and_check_flag(flag, fdtype, a) def test_unknown_requirement(self): a = self.generate_all_false('f8') assert_raises(KeyError, np.require, a, None, 'Q') def test_non_array_input(self): a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O']) assert_(a.flags['O']) assert_(a.flags['C']) assert_(a.flags['A']) assert_(a.dtype == 'i4') assert_equal(a, [1, 2, 3, 4]) def test_C_and_F_simul(self): a = self.generate_all_false('f8') assert_raises(ValueError, np.require, a, None, ['C', 'F']) def test_ensure_array(self): class ArraySubclass(np.ndarray): pass a = ArraySubclass((2, 2)) b = np.require(a, None, ['E']) assert_(type(b) is np.ndarray) def test_preserve_subtype(self): class ArraySubclass(np.ndarray): pass for flag in self.flag_names: a = ArraySubclass((2, 2)) self.set_and_check_flag(flag, None, a) class TestBroadcast: def test_broadcast_in_args(self): # gh-5881 arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)), np.empty((5, 1, 7))] mits = [np.broadcast(*arrs), np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])), np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])), np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])), np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])] for mit in mits: assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 4) for a, ia in zip(arrs, mit.iters): assert_(a is ia.base) def test_broadcast_single_arg(self): # gh-6899 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 1) assert_(arrs[0] is mit.iters[0].base) def test_number_of_arguments(self): arr = np.empty((5,)) for j in range(35): arrs = [arr] * j if j > 32: assert_raises(ValueError, np.broadcast, *arrs) else: mit = np.broadcast(*arrs) assert_equal(mit.numiter, j) def test_broadcast_error_kwargs(self): #gh-13455 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) mit2 = np.broadcast(*arrs, **{}) assert_equal(mit.shape, mit2.shape) assert_equal(mit.ndim, mit2.ndim) assert_equal(mit.nd, mit2.nd) assert_equal(mit.numiter, mit2.numiter) assert_(mit.iters[0].base is mit2.iters[0].base) assert_raises(ValueError, np.broadcast, 1, **{'x': 1}) class TestKeepdims: class sub_array(np.ndarray): def sum(self, axis=None, dtype=None, out=None): return np.ndarray.sum(self, axis, dtype, out, keepdims=True) def test_raise(self): sub_class = self.sub_array x = np.arange(30).view(sub_class) assert_raises(TypeError, np.sum, x, keepdims=True) class TestTensordot: def test_zero_dimension(self): # Test resolution to issue #5663 a = np.ndarray((3,0)) b = np.ndarray((0,4)) td = np.tensordot(a, b, (1, 0)) assert_array_equal(td, np.dot(a, b)) assert_array_equal(td, np.einsum('ij,jk', a, b)) def test_zero_dimensional(self): # gh-12130 arr_0d = np.array(1) ret = np.tensordot(arr_0d, arr_0d, ([], [])) # contracting no axes is well defined assert_array_equal(ret, arr_0d)
pdebuyl/numpy
numpy/core/tests/test_numeric.py
numpy/distutils/cpuinfo.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Foundational classes and functions. """ import re import six from ipalib.constants import NAME_REGEX, NAME_ERROR from ipalib.constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR class ReadOnly(object): """ Base class for classes that can be locked into a read-only state. Be forewarned that Python does not offer true read-only attributes for user-defined classes. Do *not* rely upon the read-only-ness of this class for security purposes! The point of this class is not to make it impossible to set or to delete attributes after an instance is locked, but to make it impossible to do so *accidentally*. Rather than constantly reminding our programmers of things like, for example, "Don't set any attributes on this ``FooBar`` instance because doing so wont be thread-safe", this class offers a real way to enforce read-only attribute usage. For example, before a `ReadOnly` instance is locked, you can set and delete its attributes as normal: >>> class Person(ReadOnly): ... pass ... >>> p = Person() >>> p.name = 'John Doe' >>> p.phone = '123-456-7890' >>> del p.phone But after an instance is locked, you cannot set its attributes: >>> p.__islocked__() # Is this instance locked? False >>> p.__lock__() # This will lock the instance >>> p.__islocked__() True >>> p.department = 'Engineering' Traceback (most recent call last): ... AttributeError: locked: cannot set Person.department to 'Engineering' Nor can you deleted its attributes: >>> del p.name Traceback (most recent call last): ... AttributeError: locked: cannot delete Person.name However, as noted at the start, there are still obscure ways in which attributes can be set or deleted on a locked `ReadOnly` instance. For example: >>> object.__setattr__(p, 'department', 'Engineering') >>> p.department 'Engineering' >>> object.__delattr__(p, 'name') >>> hasattr(p, 'name') False But again, the point is that a programmer would never employ the above techniques *accidentally*. Lastly, this example aside, you should use the `lock()` function rather than the `ReadOnly.__lock__()` method. And likewise, you should use the `islocked()` function rather than the `ReadOnly.__islocked__()` method. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> lock(readonly) is readonly # lock() returns the instance True >>> islocked(readonly) True """ __locked = False def __lock__(self): """ Put this instance into a read-only state. After the instance has been locked, attempting to set or delete an attribute will raise an AttributeError. """ assert self.__locked is False, '__lock__() can only be called once' self.__locked = True def __islocked__(self): """ Return True if instance is locked, otherwise False. """ return self.__locked def __setattr__(self, name, value): """ If unlocked, set attribute named ``name`` to ``value``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to set. :param value: Value to assign to attribute. """ if self.__locked: raise AttributeError( SET_ERROR % (self.__class__.__name__, name, value) ) return object.__setattr__(self, name, value) def __delattr__(self, name): """ If unlocked, delete attribute named ``name``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to delete. """ if self.__locked: raise AttributeError( DEL_ERROR % (self.__class__.__name__, name) ) return object.__delattr__(self, name) def lock(instance): """ Lock an instance of the `ReadOnly` class or similar. This function can be used to lock instances of any class that implements the same locking API as the `ReadOnly` class. For example, this function can lock instances of the `config.Env` class. So that this function can be easily used within an assignment, ``instance`` is returned after it is locked. For example: >>> readonly = ReadOnly() >>> readonly is lock(readonly) True >>> readonly.attr = 'This wont work' Traceback (most recent call last): ... AttributeError: locked: cannot set ReadOnly.attr to 'This wont work' Also see the `islocked()` function. :param instance: The instance of `ReadOnly` (or similar) to lock. """ assert instance.__islocked__() is False, 'already locked: %r' % instance instance.__lock__() assert instance.__islocked__() is True, 'failed to lock: %r' % instance return instance def islocked(instance): """ Return ``True`` if ``instance`` is locked. This function can be used on an instance of the `ReadOnly` class or an instance of any other class implemented the same locking API. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> readonly.__lock__() >>> islocked(readonly) True Also see the `lock()` function. :param instance: The instance of `ReadOnly` (or similar) to interrogate. """ assert ( hasattr(instance, '__lock__') and callable(instance.__lock__) ), 'no __lock__() method: %r' % instance return instance.__islocked__() def check_name(name): """ Verify that ``name`` is suitable for a `NameSpace` member name. In short, ``name`` must be a valid lower-case Python identifier that neither starts nor ends with an underscore. Otherwise an exception is raised. This function will raise a ``ValueError`` if ``name`` does not match the `constants.NAME_REGEX` regular expression. For example: >>> check_name('MyName') Traceback (most recent call last): ... ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'MyName' Also, this function will raise a ``TypeError`` if ``name`` is not an ``str`` instance. For example: >>> check_name(u'my_name') Traceback (most recent call last): ... TypeError: name: need a <type 'str'>; got u'my_name' (a <type 'unicode'>) So that `check_name()` can be easily used within an assignment, ``name`` is returned unchanged if it passes the check. For example: >>> n = check_name('my_name') >>> n 'my_name' :param name: Identifier to test. """ if type(name) is not str: raise TypeError( TYPE_ERROR % ('name', str, name, type(name)) ) if re.match(NAME_REGEX, name) is None: raise ValueError( NAME_ERROR % (NAME_REGEX, name) ) return name class NameSpace(ReadOnly): """ A read-only name-space with handy container behaviours. A `NameSpace` instance is an ordered, immutable mapping object whose values can also be accessed as attributes. A `NameSpace` instance is constructed from an iterable providing its *members*, which are simply arbitrary objects with a ``name`` attribute whose value: 1. Is unique among the members 2. Passes the `check_name()` function Beyond that, no restrictions are placed on the members: they can be classes or instances, and of any type. The members can be accessed as attributes on the `NameSpace` instance or through a dictionary interface. For example, say we create a `NameSpace` instance from a list containing a single member, like this: >>> class my_member(object): ... name = 'my_name' ... >>> namespace = NameSpace([my_member]) >>> namespace NameSpace(<1 member>, sort=True) We can then access ``my_member`` both as an attribute and as a dictionary item: >>> my_member is namespace.my_name # As an attribute True >>> my_member is namespace['my_name'] # As dictionary item True For a more detailed example, say we create a `NameSpace` instance from a generator like this: >>> class Member(object): ... def __init__(self, i): ... self.i = i ... self.name = self.__name__ = 'member%d' % i ... def __repr__(self): ... return 'Member(%d)' % self.i ... >>> ns = NameSpace(Member(i) for i in range(3)) >>> ns NameSpace(<3 members>, sort=True) As above, the members can be accessed as attributes and as dictionary items: >>> ns.member0 is ns['member0'] True >>> ns.member1 is ns['member1'] True >>> ns.member2 is ns['member2'] True Members can also be accessed by index and by slice. For example: >>> ns[0] Member(0) >>> ns[-1] Member(2) >>> ns[1:] (Member(1), Member(2)) (Note that slicing a `NameSpace` returns a ``tuple``.) `NameSpace` instances provide standard container emulation for membership testing, counting, and iteration. For example: >>> 'member3' in ns # Is there a member named 'member3'? False >>> 'member2' in ns # But there is a member named 'member2' True >>> len(ns) # The number of members 3 >>> list(ns) # Iterate through the member names ['member0', 'member1', 'member2'] Although not a standard container feature, the `NameSpace.__call__()` method provides a convenient (and efficient) way to iterate through the *members* (as opposed to the member names). Think of it like an ordered version of the ``dict.itervalues()`` method. For example: >>> list(ns[name] for name in ns) # One way to do it [Member(0), Member(1), Member(2)] >>> list(ns()) # A more efficient, simpler way to do it [Member(0), Member(1), Member(2)] Another convenience method is `NameSpace.__todict__()`, which will return a copy of the ``dict`` mapping the member names to the members. For example: >>> ns.__todict__() {'member1': Member(1), 'member0': Member(0), 'member2': Member(2)} As `NameSpace.__init__()` locks the instance, `NameSpace` instances are read-only from the get-go. An ``AttributeError`` is raised if you try to set *any* attribute on a `NameSpace` instance. For example: >>> ns.member3 = Member(3) # Lets add that missing 'member3' Traceback (most recent call last): ... AttributeError: locked: cannot set NameSpace.member3 to Member(3) (For information on the locking protocol, see the `ReadOnly` class, of which `NameSpace` is a subclass.) By default the members will be sorted alphabetically by the member name. For example: >>> sorted_ns = NameSpace([Member(7), Member(3), Member(5)]) >>> sorted_ns NameSpace(<3 members>, sort=True) >>> list(sorted_ns) ['member3', 'member5', 'member7'] >>> sorted_ns[0] Member(3) But if the instance is created with the ``sort=False`` keyword argument, the original order of the members is preserved. For example: >>> unsorted_ns = NameSpace([Member(7), Member(3), Member(5)], sort=False) >>> unsorted_ns NameSpace(<3 members>, sort=False) >>> list(unsorted_ns) ['member7', 'member3', 'member5'] >>> unsorted_ns[0] Member(7) As a special extension, NameSpace objects can be indexed by objects that have a "__name__" attribute (e.g. classes). These lookups are converted to lookups on the name: >>> class_ns = NameSpace([Member(7), Member(3), Member(5)], sort=False) >>> unsorted_ns[Member(3)] Member(3) The `NameSpace` class is used in many places throughout freeIPA. For a few examples, see the `plugable.API` and the `frontend.Command` classes. """ def __init__(self, members, sort=True, name_attr='name'): """ :param members: An iterable providing the members. :param sort: Whether to sort the members by member name. """ if type(sort) is not bool: raise TypeError( TYPE_ERROR % ('sort', bool, sort, type(sort)) ) self.__sort = sort if sort: self.__members = tuple( sorted(members, key=lambda m: getattr(m, name_attr)) ) else: self.__members = tuple(members) self.__names = tuple(getattr(m, name_attr) for m in self.__members) self.__map = dict() for member in self.__members: name = check_name(getattr(member, name_attr)) if name in self.__map: raise AttributeError(OVERRIDE_ERROR % (self.__class__.__name__, name, self.__map[name], member) ) assert not hasattr(self, name), 'Ouch! Has attribute %r' % name self.__map[name] = member setattr(self, name, member) lock(self) def __len__(self): """ Return the number of members. """ return len(self.__members) def __iter__(self): """ Iterate through the member names. If this instance was created with ``sort=False``, the names will be in the same order as the members were passed to the constructor; otherwise the names will be in alphabetical order (which is the default). This method is like an ordered version of ``dict.iterkeys()``. """ for name in self.__names: yield name def __call__(self): """ Iterate through the members. If this instance was created with ``sort=False``, the members will be in the same order as they were passed to the constructor; otherwise the members will be in alphabetical order by name (which is the default). This method is like an ordered version of ``dict.itervalues()``. """ for member in self.__members: yield member def __contains__(self, name): """ Return ``True`` if namespace has a member named ``name``. """ name = getattr(name, '__name__', name) return name in self.__map def __getitem__(self, key): """ Return a member by name or index, or return a slice of members. :param key: The name or index of a member, or a slice object. """ key = getattr(key, '__name__', key) if isinstance(key, six.string_types): return self.__map[key] if type(key) in (int, slice): return self.__members[key] raise TypeError( TYPE_ERROR % ('key', (str, int, slice, 'object with __name__'), key, type(key)) ) def __repr__(self): """ Return a pseudo-valid expression that could create this instance. """ cnt = len(self) if cnt == 1: m = 'member' else: m = 'members' return '%s(<%d %s>, sort=%r)' % ( self.__class__.__name__, cnt, m, self.__sort, ) def __todict__(self): """ Return a copy of the private dict mapping member name to member. """ return dict(self.__map)
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.x509` module. """ import base64 import datetime import pytest from ipalib import x509 from ipapython.dn import DN pytestmark = pytest.mark.tier0 # certutil - # certificate for CN=ipa.example.com,O=IPA goodcert = 'MIICAjCCAWugAwIBAgICBEUwDQYJKoZIhvcNAQEFBQAwKTEnMCUGA1UEAxMeSVBBIFRlc3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTEwMDYyNTEzMDA0MloXDTE1MDYyNTEzMDA0MlowKDEMMAoGA1UEChMDSVBBMRgwFgYDVQQDEw9pcGEuZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJcZ+H6+cQaN/BlzR8OYkVeJgaU5tCaV9FF1m7Ws/ftPtTJUaSL1ncp6603rjA4tH1aa/B8i8xdC46+ZbY2au8b9ryGcOsx2uaRpNLEQ2Fy//q1kQC8oM+iD8Nd6osF0a2wnugsgnJHPuJzhViaWxYgzk5DRdP81debokF3f3FX/AgMBAAGjOjA4MBEGCWCGSAGG+EIBAQQEAwIGQDATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEALD6X9V9w381AzzQPcHsjIjiX3B/AF9RCGocKZUDXkdDhsD9NZ3PLPEf1AMjkraKG963HPB8scyiBbbSuSh6m7TCp0eDgRpo77zNuvd3U4Qpm0Qk+KEjtHQDjNNG6N4ZnCQPmjFPScElvc/GgW7XMbywJy2euF+3/Uip8cnPgSH4=' # The base64-encoded string 'bad cert' badcert = 'YmFkIGNlcnQ=' class test_x509(object): """ Test `ipalib.x509` I created the contents of this certificate with a self-signed CA with: % certutil -R -s "CN=ipa.example.com,O=IPA" -d . -a -o example.csr % ./ipa host-add ipa.example.com % ./ipa cert-request --add --principal=test/ipa.example.com example.csr """ def test_1_load_base64_cert(self): """ Test loading a base64-encoded certificate. """ # Load a good cert x509.load_certificate(goodcert) # Should handle list/tuple x509.load_certificate((goodcert,)) x509.load_certificate([goodcert]) # Load a good cert with headers newcert = '-----BEGIN CERTIFICATE-----' + goodcert + '-----END CERTIFICATE-----' x509.load_certificate(newcert) # Should handle list/tuple x509.load_certificate((newcert,)) x509.load_certificate([newcert]) # Load a good cert with headers and leading text newcert = ( 'leading text\n-----BEGIN CERTIFICATE-----' + goodcert + '-----END CERTIFICATE-----') x509.load_certificate(newcert) # Should handle list/tuple x509.load_certificate((newcert,)) x509.load_certificate([newcert]) # Load a good cert with bad headers newcert = '-----BEGIN CERTIFICATE-----' + goodcert with pytest.raises((TypeError, ValueError)): x509.load_certificate(newcert) # Load a bad cert with pytest.raises(ValueError): x509.load_certificate(badcert) def test_1_load_der_cert(self): """ Test loading a DER certificate. """ der = base64.b64decode(goodcert) # Load a good cert x509.load_certificate(der, x509.DER) # Should handle list/tuple x509.load_certificate((der,), x509.DER) x509.load_certificate([der], x509.DER) def test_3_cert_contents(self): """ Test the contents of a certificate """ # Verify certificate contents. This exercises python-cryptography # more than anything but confirms our usage of it. not_before = datetime.datetime(2010, 6, 25, 13, 0, 42) not_after = datetime.datetime(2015, 6, 25, 13, 0, 42) cert = x509.load_certificate(goodcert) assert DN(cert.subject) == DN(('CN', 'ipa.example.com'), ('O', 'IPA')) assert DN(cert.issuer) == DN(('CN', 'IPA Test Certificate Authority')) assert cert.serial_number == 1093 assert cert.not_valid_before == not_before assert cert.not_valid_after == not_after
realsobek/freeipa
ipatests/test_ipalib/test_x509.py
ipalib/base.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from sqlalchemy import Column, Integer, String from sqlalchemy.orm import backref, relationship from sqlalchemy.schema import ForeignKey, Table from ..alchemy import Base class Publication(Base): __tablename__ = 'many_to_many_publication' id = Column(Integer, primary_key=True) title = Column(String(30)) @property def pk(self): return self.id publication_article_association_table = Table( 'many_to_many_article_publications', Base.metadata, Column('id', Integer), Column('publication_id', Integer, ForeignKey('many_to_many_publication.id')), Column('article_id', Integer, ForeignKey('many_to_many_article.id')), ) class Article(Base): __tablename__ = 'many_to_many_article' id = Column(Integer, primary_key=True) headline = Column(String(100)) publications = relationship( Publication, secondary=publication_article_association_table, backref=backref('articles', uselist=True), uselist=True, ) @property def pk(self): return self.id
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import pytest from django import forms from sqlalchemy.orm.properties import ColumnProperty from sqlalchemy.sql.schema import Column from sqlalchemy.sql.type_api import TypeEngine from sqlalchemy.types import Integer, String from test_project.many_to_many.alchemy import Article as M2MArticle, Publication from test_project.many_to_one.alchemy import Article as M2OArticle from test_project.one_to_one.alchemy import Place, Restaurant from url_filter.exceptions import SkipFilter from url_filter.filters import Filter from url_filter.filtersets.sqlalchemy import SQLAlchemyModelFilterSet class TestSQLAlchemyModelFilterSet(object): def test_get_filters_no_model(self): class PlaceFilterSet(SQLAlchemyModelFilterSet): pass with pytest.raises(AssertionError): PlaceFilterSet().get_filters() def test_get_filters_no_relations_place(self): class PlaceFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = Place allow_related = False filters = PlaceFilterSet().get_filters() assert set(filters.keys()) == { 'id', 'name', 'address', } assert isinstance(filters['id'], Filter) assert isinstance(filters['id'].form_field, forms.IntegerField) assert isinstance(filters['name'], Filter) assert isinstance(filters['name'].form_field, forms.CharField) assert isinstance(filters['address'], Filter) assert isinstance(filters['address'].form_field, forms.CharField) def test_get_filters_no_relations_restaurant(self): class RestaurantFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = Restaurant allow_related = False filters = RestaurantFilterSet().get_filters() assert set(filters.keys()) == { 'serves_pizza', 'serves_hot_dogs', 'place_id', } assert isinstance(filters['serves_pizza'], Filter) assert isinstance(filters['serves_pizza'].form_field, forms.BooleanField) assert isinstance(filters['place_id'], Filter) assert isinstance(filters['place_id'].form_field, forms.IntegerField) assert isinstance(filters['serves_hot_dogs'], Filter) assert isinstance(filters['serves_hot_dogs'].form_field, forms.BooleanField) def test_get_filters_with_only_reverse_relations(self): class PlaceFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = Place filters = PlaceFilterSet().get_filters() assert set(filters.keys()) == { 'id', 'name', 'address', 'restaurant', } assert set(filters['restaurant'].filters.keys()) == { 'serves_pizza', 'serves_hot_dogs', 'waiter_set', 'place_id' } assert isinstance(filters['id'], Filter) assert isinstance(filters['id'].form_field, forms.IntegerField) assert isinstance(filters['name'], Filter) assert isinstance(filters['name'].form_field, forms.CharField) assert isinstance(filters['address'], Filter) assert isinstance(filters['address'].form_field, forms.CharField) assert isinstance(filters['restaurant'], SQLAlchemyModelFilterSet) def test_get_filters_with_both_reverse_and_direct_relations(self): class RestaurantFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = Restaurant filters = RestaurantFilterSet().get_filters() assert set(filters.keys()) == { 'place', 'place_id', 'waiter_set', 'serves_hot_dogs', 'serves_pizza', } assert set(filters['place'].filters.keys()) == { 'id', 'name', 'address', } assert set(filters['waiter_set'].filters.keys()) == { 'id', 'name', 'restaurant_id' } assert isinstance(filters['serves_hot_dogs'], Filter) assert isinstance(filters['serves_hot_dogs'].form_field, forms.BooleanField) assert isinstance(filters['serves_pizza'], Filter) assert isinstance(filters['serves_pizza'].form_field, forms.BooleanField) assert isinstance(filters['place'], SQLAlchemyModelFilterSet) assert isinstance(filters['waiter_set'], SQLAlchemyModelFilterSet) def test_get_filters_with_reverse_many_to_many_relations(self): class PublicationFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = Publication filters = PublicationFilterSet().get_filters() assert set(filters.keys()) == { 'id', 'title', 'articles', } assert set(filters['articles'].filters.keys()) == { 'id', 'headline', } assert isinstance(filters['id'], Filter) assert isinstance(filters['id'].form_field, forms.IntegerField) assert isinstance(filters['title'], Filter) assert isinstance(filters['title'].form_field, forms.CharField) assert isinstance(filters['articles'], SQLAlchemyModelFilterSet) def test_get_filters_with_many_to_many_relations(self): class ArticleFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = M2MArticle filters = ArticleFilterSet().get_filters() assert set(filters.keys()) == { 'id', 'headline', 'publications', } assert set(filters['publications'].filters.keys()) == { 'id', 'title', } assert isinstance(filters['id'], Filter) assert isinstance(filters['id'].form_field, forms.IntegerField) assert isinstance(filters['headline'], Filter) assert isinstance(filters['headline'].form_field, forms.CharField) assert isinstance(filters['publications'], SQLAlchemyModelFilterSet) def test_get_filters_with_many_to_one_relations(self): class ArticleFilterSet(SQLAlchemyModelFilterSet): class Meta(object): model = M2OArticle filters = ArticleFilterSet().get_filters() assert set(filters.keys()) == { 'id', 'headline', 'pub_date', 'reporter', 'reporter_id', } assert set(filters['reporter'].filters.keys()) == { 'id', 'email', 'first_name', 'last_name', } assert isinstance(filters['id'], Filter) assert isinstance(filters['id'].form_field, forms.IntegerField) assert isinstance(filters['headline'], Filter) assert isinstance(filters['headline'].form_field, forms.CharField) assert isinstance(filters['pub_date'], Filter) assert isinstance(filters['pub_date'].form_field, forms.DateField) assert isinstance(filters['reporter'], SQLAlchemyModelFilterSet) def test_get_form_field_for_field(self): fs = SQLAlchemyModelFilterSet() assert isinstance( fs.get_form_field_for_field(ColumnProperty(Column('name', String(50)))), forms.CharField ) assert isinstance( fs.get_form_field_for_field(ColumnProperty(Column('name', Integer))), forms.IntegerField ) with pytest.raises(SkipFilter): fs.get_form_field_for_field(ColumnProperty(Column('name', TypeEngine)))
pombredanne/django-url-filter
tests/filtersets/test_sqlalchemy.py
test_project/many_to_many/alchemy.py
# -*- coding: utf-8 -*- u"""synergia simulation data operations :copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern.pkcollections import PKDict from pykern.pkdebug import pkdc, pkdlog, pkdp import sirepo.sim_data class SimData(sirepo.sim_data.SimDataBase): @classmethod def fixup_old_data(cls, data): dm = data.models cls._init_models( dm, ( 'beamEvolutionAnimation', 'bunch', 'bunchAnimation', 'bunchTwiss', 'simulationSettings', 'turnComparisonAnimation', 'twissReport', 'twissReport2', ), ) if 'bunchReport' in dm: del dm['bunchReport'] for i in range(1, 5): m = dm['bunchReport{}'.format(i)] = PKDict() cls.update_model_defaults(m, 'bunchReport') if i == 1: m.y = 'xp' elif i == 2: m.x = 'y' m.y = 'yp' elif i == 4: m.x = 'z' m.y = 'zp' cls._organize_example(data) @classmethod def _compute_model(cls, analysis_model, *args, **kwargs): if 'bunchReport' in analysis_model: return 'bunchReport' # twissReport2 and twissReport are compute_models return super(SimData, cls)._compute_model(analysis_model, *args, **kwargs) @classmethod def _compute_job_fields(cls, data, r, compute_model): res = ['beamlines', 'elements'] if 'bunchReport' in r: res += ['bunch', 'simulation.visualizationBeamlineId'] elif r == 'twissReport': res += ['simulation.activeBeamlineId'] elif 'twissReport' in r: res += ['simulation.visualizationBeamlineId'] return res @classmethod def _lib_file_basenames(cls, data): res = [] b = data.models.bunch if b.distribution == 'file': res.append(cls.lib_file_name_with_model_field('bunch', 'particleFile', b.particleFile)) return res
# -*- coding: utf-8 -*- u"""animations that read data dynamically :copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_synergia(fc): from pykern.pkcollections import PKDict from pykern.pkdebug import pkdp, pkdlog from pykern.pkunit import pkre import sirepo.sim_data import time data = fc.sr_sim_data('IOTA 6-6 with NL Element') cancel = None # this provokes an 'invalid data error' # data.models.simulationSettings.space_charge = '2d-bassetti_erskine' s = sirepo.sim_data.get_class(fc.sr_sim_type) try: r = fc.sr_post( 'runSimulation', PKDict( forceRun=True, models=data.models, report='animation', simulationId=data.models.simulation.simulationId, simulationType=data.simulationType, ), ) cancel = r.nextRequest for _ in range(100): if r.state in ('completed', 'error'): pkdlog(r.state) cancel = None break r = fc.sr_post('runStatus', r.nextRequest) if r.frameCount > 0: for i in range(r.frameCount, r.frameCount - 5, -1): f = fc.sr_get_json( 'simulationFrame', PKDict(frame_id=s.frame_id(data, r, 'beamEvolutionAnimation', r.frameCount - i)), ) if f.get('error'): pkdlog(f.error) pkre('not generated', f.error) # cannot guarantee this happens, but exit if it does break time.sleep(0.1) finally: try: if cancel: fc.sr_post('runCancel', cancel) except Exception: pass
mrakitin/sirepo
tests/partial_animation_test.py
sirepo/sim_data/synergia.py
# -*- coding: utf-8 -*- """ h2/utilities ~~~~~~~~~~~~ Utility functions that do not belong in a separate module. """ import collections import re from string import whitespace import sys from hpack import HeaderTuple, NeverIndexedHeaderTuple from .exceptions import ProtocolError, FlowControlError UPPER_RE = re.compile(b"[A-Z]") # A set of headers that are hop-by-hop or connection-specific and thus # forbidden in HTTP/2. This list comes from RFC 7540 § 8.1.2.2. CONNECTION_HEADERS = frozenset([ b'connection', u'connection', b'proxy-connection', u'proxy-connection', b'keep-alive', u'keep-alive', b'transfer-encoding', u'transfer-encoding', b'upgrade', u'upgrade', ]) _ALLOWED_PSEUDO_HEADER_FIELDS = frozenset([ b':method', u':method', b':scheme', u':scheme', b':authority', u':authority', b':path', u':path', b':status', u':status', ]) _SECURE_HEADERS = frozenset([ # May have basic credentials which are vulnerable to dictionary attacks. b'authorization', u'authorization', b'proxy-authorization', u'proxy-authorization', ]) if sys.version_info[0] == 2: # Python 2.X _WHITESPACE = frozenset(whitespace) else: # Python 3.3+ _WHITESPACE = frozenset(map(ord, whitespace)) def _secure_headers(headers, hdr_validation_flags): """ Certain headers are at risk of being attacked during the header compression phase, and so need to be kept out of header compression contexts. This function automatically transforms certain specific headers into HPACK never-indexed fields to ensure they don't get added to header compression contexts. This function currently implements two rules: - 'authorization' and 'proxy-authorization' fields are automatically made never-indexed. - Any 'cookie' header field shorter than 20 bytes long is made never-indexed. These fields are the most at-risk. These rules are inspired by Firefox and nghttp2. """ for header in headers: if header[0] in _SECURE_HEADERS: yield NeverIndexedHeaderTuple(*header) elif header[0] in (b'cookie', u'cookie') and len(header[1]) < 20: yield NeverIndexedHeaderTuple(*header) else: yield header def extract_method_header(headers): """ Extracts the request method from the headers list. """ for k, v in headers: if k in (b':method', u':method'): if not isinstance(v, bytes): return v.encode('utf-8') else: return v def is_informational_response(headers): """ Searches a header block for a :status header to confirm that a given collection of headers are an informational response. Assumes the header block is well formed: that is, that the HTTP/2 special headers are first in the block, and so that it can stop looking when it finds the first header field whose name does not begin with a colon. :param headers: The HTTP/2 header block. :returns: A boolean indicating if this is an informational response. """ for n, v in headers: if isinstance(n, bytes): sigil = b':' status = b':status' informational_start = b'1' else: sigil = u':' status = u':status' informational_start = u'1' # If we find a non-special header, we're done here: stop looping. if not n.startswith(sigil): return False # This isn't the status header, bail. if n != status: continue # If the first digit is a 1, we've got informational headers. return v.startswith(informational_start) def guard_increment_window(current, increment): """ Increments a flow control window, guarding against that window becoming too large. :param current: The current value of the flow control window. :param increment: The increment to apply to that window. :returns: The new value of the window. :raises: ``FlowControlError`` """ # The largest value the flow control window may take. LARGEST_FLOW_CONTROL_WINDOW = 2**31 - 1 new_size = current + increment if new_size > LARGEST_FLOW_CONTROL_WINDOW: raise FlowControlError( "May not increment flow control window past %d" % LARGEST_FLOW_CONTROL_WINDOW ) return new_size def authority_from_headers(headers): """ Given a header set, searches for the authority header and returns the value. Note that this doesn't terminate early, so should only be called if the headers are for a client request. Otherwise, will loop over the entire header set, which is potentially unwise. :param headers: The HTTP header set. :returns: The value of the authority header, or ``None``. :rtype: ``bytes`` or ``None``. """ for n, v in headers: # This gets run against headers that come both from HPACK and from the # user, so we may have unicode floating around in here. We only want # bytes. if n in (b':authority', u':authority'): return v.encode('utf-8') if not isinstance(v, bytes) else v return None # Flags used by the validate_headers pipeline to determine which checks # should be applied to a given set of headers. HeaderValidationFlags = collections.namedtuple( 'HeaderValidationFlags', ['is_client', 'is_trailer', 'is_response_header', 'is_push_promise'] ) def validate_headers(headers, hdr_validation_flags): """ Validates a header sequence against a set of constraints from RFC 7540. :param headers: The HTTP header set. :param hdr_validation_flags: An instance of HeaderValidationFlags. """ # This validation logic is built on a sequence of generators that are # iterated over to provide the final header list. This reduces some of the # overhead of doing this checking. However, it's worth noting that this # checking remains somewhat expensive, and attempts should be made wherever # possible to reduce the time spent doing them. # # For example, we avoid tuple upacking in loops because it represents a # fixed cost that we don't want to spend, instead indexing into the header # tuples. headers = _reject_uppercase_header_fields( headers, hdr_validation_flags ) headers = _reject_surrounding_whitespace( headers, hdr_validation_flags ) headers = _reject_te( headers, hdr_validation_flags ) headers = _reject_connection_header( headers, hdr_validation_flags ) headers = _reject_pseudo_header_fields( headers, hdr_validation_flags ) headers = _check_host_authority_header( headers, hdr_validation_flags ) return list(headers) def _reject_uppercase_header_fields(headers, hdr_validation_flags): """ Raises a ProtocolError if any uppercase character is found in a header block. """ for header in headers: if UPPER_RE.search(header[0]): raise ProtocolError( "Received uppercase header name %s." % header[0]) yield header def _reject_surrounding_whitespace(headers, hdr_validation_flags): """ Raises a ProtocolError if any header name or value is surrounded by whitespace characters. """ # For compatibility with RFC 7230 header fields, we need to allow the field # value to be an empty string. This is ludicrous, but technically allowed. # The field name may not be empty, though, so we can safely assume that it # must have at least one character in it and throw exceptions if it # doesn't. for header in headers: if header[0][0] in _WHITESPACE or header[0][-1] in _WHITESPACE: raise ProtocolError( "Received header name surrounded by whitespace %r" % header[0]) if header[1] and ((header[1][0] in _WHITESPACE) or (header[1][-1] in _WHITESPACE)): raise ProtocolError( "Received header value surrounded by whitespace %r" % header[1] ) yield header def _reject_te(headers, hdr_validation_flags): """ Raises a ProtocolError if the TE header is present in a header block and its value is anything other than "trailers". """ for header in headers: if header[0] in (b'te', u'te'): if header[1].lower() not in (b'trailers', u'trailers'): raise ProtocolError( "Invalid value for Transfer-Encoding header: %s" % header[1] ) yield header def _reject_connection_header(headers, hdr_validation_flags): """ Raises a ProtocolError if the Connection header is present in a header block. """ for header in headers: if header[0] in CONNECTION_HEADERS: raise ProtocolError( "Connection-specific header field present: %s." % header[0] ) yield header def _custom_startswith(test_string, bytes_prefix, unicode_prefix): """ Given a string that might be a bytestring or a Unicode string, return True if it starts with the appropriate prefix. """ if isinstance(test_string, bytes): return test_string.startswith(bytes_prefix) else: return test_string.startswith(unicode_prefix) def _reject_pseudo_header_fields(headers, hdr_validation_flags): """ Raises a ProtocolError if duplicate pseudo-header fields are found in a header block or if a pseudo-header field appears in a block after an ordinary header field. Raises a ProtocolError if pseudo-header fields are found in trailers. """ seen_pseudo_header_fields = set() seen_regular_header = False for header in headers: if _custom_startswith(header[0], b':', u':'): if header[0] in seen_pseudo_header_fields: raise ProtocolError( "Received duplicate pseudo-header field %s" % header[0] ) seen_pseudo_header_fields.add(header[0]) if seen_regular_header: raise ProtocolError( "Received pseudo-header field out of sequence: %s" % header[0] ) if header[0] not in _ALLOWED_PSEUDO_HEADER_FIELDS: raise ProtocolError( "Received custom pseudo-header field %s" % header[0] ) else: seen_regular_header = True yield header # Pseudo-header fields MUST NOT appear in trailers - RFC 7540 § 8.1.2.1 if hdr_validation_flags.is_trailer and seen_pseudo_header_fields: raise ProtocolError( "Received pseudo-header in trailer %s" % seen_pseudo_header_fields ) # If ':status' pseudo-header is not there in a response header, reject it # Relevant RFC section: RFC 7540 § 8.1.2.4 # https://tools.ietf.org/html/rfc7540#section-8.1.2.4 if hdr_validation_flags.is_response_header: seen_status_field = ( b':status' in seen_pseudo_header_fields or u':status' in seen_pseudo_header_fields ) if not seen_status_field: raise ProtocolError( "Response header block does not have a :status header" ) def _validate_host_authority_header(headers): """ Given the :authority and Host headers from a request block that isn't a trailer, check that: 1. At least one of these headers is set. 2. If both headers are set, they match. :param headers: The HTTP header set. :raises: ``ProtocolError`` """ # We use None as a sentinel value. Iterate over the list of headers, # and record the value of these headers (if present). We don't need # to worry about receiving duplicate :authority headers, as this is # enforced by the _reject_pseudo_header_fields() pipeline. # # TODO: We should also guard against receiving duplicate Host headers, # and against sending duplicate headers. authority_header_val = None host_header_val = None for header in headers: if header[0] in (b':authority', u':authority'): authority_header_val = header[1] elif header[0] in (b'host', u'host'): host_header_val = header[1] yield header # If we have not-None values for these variables, then we know we saw # the corresponding header. authority_present = (authority_header_val is not None) host_present = (host_header_val is not None) # It is an error for a request header block to contain neither # an :authority header nor a Host header. if not authority_present and not host_present: raise ProtocolError( "Request header block does not have an :authority or Host header." ) # If we receive both headers, they should definitely match. if authority_present and host_present: if authority_header_val != host_header_val: raise ProtocolError( "Request header block has mismatched :authority and " "Host headers: %r / %r" % (authority_header_val, host_header_val) ) def _check_host_authority_header(headers, hdr_validation_flags): """ Raises a ProtocolError if a header block arrives that does not contain an :authority or a Host header, or if a header block contains both fields, but their values do not match. """ # We only expect to see :authority and Host headers on request header # blocks that aren't trailers, so skip this validation if this is a # response header or we're looking at trailer blocks. skip_validation = ( hdr_validation_flags.is_response_header or hdr_validation_flags.is_trailer ) if skip_validation: return headers return _validate_host_authority_header(headers) def _lowercase_header_names(headers, hdr_validation_flags): """ Given an iterable of header two-tuples, rebuilds that iterable with the header names lowercased. This generator produces tuples that preserve the original type of the header tuple for tuple and any ``HeaderTuple``. """ for header in headers: if isinstance(header, HeaderTuple): yield header.__class__(header[0].lower(), header[1]) else: yield (header[0].lower(), header[1]) def _strip_surrounding_whitespace(headers, hdr_validation_flags): """ Given an iterable of header two-tuples, strip both leading and trailing whitespace from both header names and header values. This generator produces tuples that preserve the original type of the header tuple for tuple and any ``HeaderTuple``. """ for header in headers: if isinstance(header, HeaderTuple): yield header.__class__(header[0].strip(), header[1].strip()) else: yield (header[0].strip(), header[1].strip()) def _strip_connection_headers(headers, hdr_validation_flags): """ Strip any connection headers as per RFC7540 § 8.1.2.2. """ for header in headers: if header[0] not in CONNECTION_HEADERS: yield header def _check_sent_host_authority_header(headers, hdr_validation_flags): """ Raises an InvalidHeaderBlockError if we try to send a header block that does not contain an :authority or a Host header, or if the header block contains both fields, but their values do not match. """ # We only expect to see :authority and Host headers on request header # blocks that aren't trailers, so skip this validation if this is a # response header or we're looking at trailer blocks. skip_validation = ( hdr_validation_flags.is_response_header or hdr_validation_flags.is_trailer ) if skip_validation: return headers return _validate_host_authority_header(headers) def normalize_outbound_headers(headers, hdr_validation_flags): """ Normalizes a header sequence that we are about to send. :param headers: The HTTP header set. :param hdr_validation_flags: An instance of HeaderValidationFlags. """ headers = _lowercase_header_names(headers, hdr_validation_flags) headers = _strip_surrounding_whitespace(headers, hdr_validation_flags) headers = _strip_connection_headers(headers, hdr_validation_flags) headers = _secure_headers(headers, hdr_validation_flags) return headers def validate_outbound_headers(headers, hdr_validation_flags): """ Validates and normalizes a header sequence that we are about to send. :param headers: The HTTP header set. :param hdr_validation_flags: An instance of HeaderValidationFlags. """ headers = _reject_te( headers, hdr_validation_flags ) headers = _reject_connection_header( headers, hdr_validation_flags ) headers = _reject_pseudo_header_fields( headers, hdr_validation_flags ) headers = _check_sent_host_authority_header( headers, hdr_validation_flags ) return headers
# -*- coding: utf-8 -*- """ test_complex_logic ~~~~~~~~~~~~~~~~ More complex tests that try to do more. Certain tests don't really eliminate incorrect behaviour unless they do quite a bit. These tests should live here, to keep the pain in once place rather than hide it in the other parts of the test suite. """ import pytest import h2 import h2.connection class TestComplexClient(object): """ Complex tests for client-side stacks. """ example_request_headers = [ (':authority', 'example.com'), (':path', '/'), (':scheme', 'https'), (':method', 'GET'), ] example_response_headers = [ (':status', '200'), ('server', 'fake-serv/0.1.0') ] def test_correctly_count_server_streams(self, frame_factory): """ We correctly count the number of server streams, both inbound and outbound. """ # This test makes no sense unless you do both inbound and outbound, # because it's important to confirm that we count them correctly. c = h2.connection.H2Connection(client_side=True) c.initiate_connection() expected_inbound_streams = expected_outbound_streams = 0 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams for stream_id in range(1, 15, 2): # Open an outbound stream c.send_headers(stream_id, self.example_request_headers) expected_outbound_streams += 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams # Receive a pushed stream (to create an inbound one). This doesn't # open until we also receive headers. f = frame_factory.build_push_promise_frame( stream_id=stream_id, promised_stream_id=stream_id+1, headers=self.example_request_headers, ) c.receive_data(f.serialize()) assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams f = frame_factory.build_headers_frame( stream_id=stream_id+1, headers=self.example_response_headers, ) c.receive_data(f.serialize()) expected_inbound_streams += 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams for stream_id in range(13, 0, -2): # Close an outbound stream. c.end_stream(stream_id) # Stream doesn't close until both sides close it. assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams f = frame_factory.build_headers_frame( stream_id=stream_id, headers=self.example_response_headers, flags=['END_STREAM'], ) c.receive_data(f.serialize()) expected_outbound_streams -= 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams # Pushed streams can only be closed remotely. f = frame_factory.build_data_frame( stream_id=stream_id+1, data=b'the content', flags=['END_STREAM'], ) c.receive_data(f.serialize()) expected_inbound_streams -= 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams assert c.open_inbound_streams == 0 assert c.open_outbound_streams == 0 class TestComplexServer(object): """ Complex tests for server-side stacks. """ example_request_headers = [ (':authority', 'example.com'), (':path', '/'), (':scheme', 'https'), (':method', 'GET'), ] example_response_headers = [ (':status', '200'), ('server', 'fake-serv/0.1.0') ] def test_correctly_count_server_streams(self, frame_factory): """ We correctly count the number of server streams, both inbound and outbound. """ # This test makes no sense unless you do both inbound and outbound, # because it's important to confirm that we count them correctly. c = h2.connection.H2Connection(client_side=False) c.receive_data(frame_factory.preamble()) expected_inbound_streams = expected_outbound_streams = 0 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams for stream_id in range(1, 15, 2): # Receive an inbound stream. f = frame_factory.build_headers_frame( headers=self.example_request_headers, stream_id=stream_id, ) c.receive_data(f.serialize()) expected_inbound_streams += 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams # Push a stream (to create a outbound one). This doesn't open # until we send our response headers. c.push_stream(stream_id, stream_id+1, self.example_request_headers) assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams c.send_headers(stream_id+1, self.example_response_headers) expected_outbound_streams += 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams for stream_id in range(13, 0, -2): # Close an inbound stream. f = frame_factory.build_data_frame( data=b'', flags=['END_STREAM'], stream_id=stream_id, ) c.receive_data(f.serialize()) # Stream doesn't close until both sides close it. assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams c.send_data(stream_id, b'', end_stream=True) expected_inbound_streams -= 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams # Pushed streams, however, we can close ourselves. c.send_data( stream_id=stream_id+1, data=b'', end_stream=True, ) expected_outbound_streams -= 1 assert c.open_inbound_streams == expected_inbound_streams assert c.open_outbound_streams == expected_outbound_streams assert c.open_inbound_streams == 0 assert c.open_outbound_streams == 0 class TestContinuationFrames(object): """ Tests for the relatively complex CONTINUATION frame logic. """ example_request_headers = [ (':authority', 'example.com'), (':path', '/'), (':scheme', 'https'), (':method', 'GET'), ] def _build_continuation_sequence(self, headers, block_size, frame_factory): f = frame_factory.build_headers_frame(headers) header_data = f.data chunks = [ header_data[x:x+block_size] for x in range(0, len(header_data), block_size) ] f.data = chunks.pop(0) frames = [ frame_factory.build_continuation_frame(c) for c in chunks ] f.flags = {'END_STREAM'} frames[-1].flags.add('END_HEADERS') frames.insert(0, f) return frames def test_continuation_frame_basic(self, frame_factory): """ Test that we correctly decode a header block split across continuation frames. """ c = h2.connection.H2Connection(client_side=False) c.initiate_connection() c.receive_data(frame_factory.preamble()) frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) data = b''.join(f.serialize() for f in frames) events = c.receive_data(data) assert len(events) == 2 first_event, second_event = events assert isinstance(first_event, h2.events.RequestReceived) assert first_event.headers == self.example_request_headers assert first_event.stream_id == 1 assert isinstance(second_event, h2.events.StreamEnded) assert second_event.stream_id == 1 @pytest.mark.parametrize('stream_id', [3, 1]) def test_continuation_cannot_interleave_headers(self, frame_factory, stream_id): """ We cannot interleave a new headers block with a CONTINUATION sequence. """ c = h2.connection.H2Connection(client_side=False) c.initiate_connection() c.receive_data(frame_factory.preamble()) c.clear_outbound_data_buffer() frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_headers_frame( headers=self.example_request_headers, stream_id=stream_id, flags=['END_STREAM'], ) frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() def test_continuation_cannot_interleave_data(self, frame_factory): """ We cannot interleave a data frame with a CONTINUATION sequence. """ c = h2.connection.H2Connection(client_side=False) c.initiate_connection() c.receive_data(frame_factory.preamble()) c.clear_outbound_data_buffer() frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_data_frame( data=b'hello', stream_id=1, ) frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() def test_continuation_cannot_interleave_unknown_frame(self, frame_factory): """ We cannot interleave an unknown frame with a CONTINUATION sequence. """ c = h2.connection.H2Connection(client_side=False) c.initiate_connection() c.receive_data(frame_factory.preamble()) c.clear_outbound_data_buffer() frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_data_frame( data=b'hello', stream_id=1, ) bogus_frame.type = 88 frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() def test_continuation_frame_multiple_blocks(self, frame_factory): """ Test that we correctly decode several header blocks split across continuation frames. """ c = h2.connection.H2Connection(client_side=False) c.initiate_connection() c.receive_data(frame_factory.preamble()) for stream_id in range(1, 7, 2): frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=2, frame_factory=frame_factory, ) for frame in frames: frame.stream_id = stream_id data = b''.join(f.serialize() for f in frames) events = c.receive_data(data) assert len(events) == 2 first_event, second_event = events assert isinstance(first_event, h2.events.RequestReceived) assert first_event.headers == self.example_request_headers assert first_event.stream_id == stream_id assert isinstance(second_event, h2.events.StreamEnded) assert second_event.stream_id == stream_id class TestContinuationFramesPushPromise(object): """ Tests for the relatively complex CONTINUATION frame logic working with PUSH_PROMISE frames. """ example_request_headers = [ (':authority', 'example.com'), (':path', '/'), (':scheme', 'https'), (':method', 'GET'), ] example_response_headers = [ (':status', '200'), ('server', 'fake-serv/0.1.0') ] def _build_continuation_sequence(self, headers, block_size, frame_factory): f = frame_factory.build_push_promise_frame( stream_id=1, promised_stream_id=2, headers=headers ) header_data = f.data chunks = [ header_data[x:x+block_size] for x in range(0, len(header_data), block_size) ] f.data = chunks.pop(0) frames = [ frame_factory.build_continuation_frame(c) for c in chunks ] f.flags = {'END_STREAM'} frames[-1].flags.add('END_HEADERS') frames.insert(0, f) return frames def test_continuation_frame_basic_push_promise(self, frame_factory): """ Test that we correctly decode a header block split across continuation frames when that header block is initiated with a PUSH_PROMISE. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers(stream_id=1, headers=self.example_request_headers) frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) data = b''.join(f.serialize() for f in frames) events = c.receive_data(data) assert len(events) == 1 event = events[0] assert isinstance(event, h2.events.PushedStreamReceived) assert event.headers == self.example_request_headers assert event.parent_stream_id == 1 assert event.pushed_stream_id == 2 @pytest.mark.parametrize('stream_id', [3, 1, 2]) def test_continuation_cannot_interleave_headers_pp(self, frame_factory, stream_id): """ We cannot interleave a new headers block with a CONTINUATION sequence when the headers block is based on a PUSH_PROMISE frame. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers(stream_id=1, headers=self.example_request_headers) frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_headers_frame( headers=self.example_response_headers, stream_id=stream_id, flags=['END_STREAM'], ) frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() def test_continuation_cannot_interleave_data(self, frame_factory): """ We cannot interleave a data frame with a CONTINUATION sequence when that sequence began with a PUSH_PROMISE frame. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers(stream_id=1, headers=self.example_request_headers) frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_data_frame( data=b'hello', stream_id=1, ) frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() def test_continuation_cannot_interleave_unknown_frame(self, frame_factory): """ We cannot interleave an unknown frame with a CONTINUATION sequence when that sequence began with a PUSH_PROMISE frame. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers(stream_id=1, headers=self.example_request_headers) frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=5, frame_factory=frame_factory, ) assert len(frames) > 2 # This is mostly defensive. bogus_frame = frame_factory.build_data_frame( data=b'hello', stream_id=1, ) bogus_frame.type = 88 frames.insert(len(frames) - 2, bogus_frame) data = b''.join(f.serialize() for f in frames) with pytest.raises(h2.exceptions.ProtocolError) as e: c.receive_data(data) assert "invalid frame" in str(e.value).lower() @pytest.mark.parametrize('evict', [True, False]) def test_stream_remotely_closed_disallows_push_promise(self, evict, frame_factory): """ Streams closed normally by the remote peer disallow PUSH_PROMISE frames, and cause a GOAWAY. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers( stream_id=1, headers=self.example_request_headers, end_stream=True ) f = frame_factory.build_headers_frame( stream_id=1, headers=self.example_response_headers, flags=['END_STREAM'] ) c.receive_data(f.serialize()) c.clear_outbound_data_buffer() if evict: # This is annoyingly stateful, but enumerating the list of open # streams will force us to flush state. assert not c.open_outbound_streams f = frame_factory.build_push_promise_frame( stream_id=1, promised_stream_id=2, headers=self.example_request_headers, ) with pytest.raises(h2.exceptions.ProtocolError): c.receive_data(f.serialize()) f = frame_factory.build_goaway_frame( last_stream_id=0, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR, ) assert c.data_to_send() == f.serialize() def test_continuation_frame_multiple_push_promise(self, frame_factory): """ Test that we correctly decode header blocks split across continuation frames when those header block is initiated with a PUSH_PROMISE, for more than one pushed stream. """ c = h2.connection.H2Connection(client_side=True) c.initiate_connection() c.send_headers(stream_id=1, headers=self.example_request_headers) for promised_stream_id in range(2, 8, 2): frames = self._build_continuation_sequence( headers=self.example_request_headers, block_size=2, frame_factory=frame_factory, ) frames[0].promised_stream_id = promised_stream_id data = b''.join(f.serialize() for f in frames) events = c.receive_data(data) assert len(events) == 1 event = events[0] assert isinstance(event, h2.events.PushedStreamReceived) assert event.headers == self.example_request_headers assert event.parent_stream_id == 1 assert event.pushed_stream_id == promised_stream_id
bhavishyagopesh/hyper-h2
test/test_complex_logic.py
h2/utilities.py
# -*- coding: utf-8 -*- """ FTP manipulation library @author: Milan Falešník <mfalesni@redhat.com> """ import fauxfactory import ftplib import re from datetime import datetime from time import strptime, mktime try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class FTPException(Exception): pass class FTPDirectory(object): """ FTP FS Directory encapsulation This class represents one directory. Contains pointers to all child directories (self.directories) and also all files in current directory (self.files) """ def __init__(self, client, name, items, parent_dir=None, time=None): """ Constructor Args: client: ftplib.FTP instance name: Name of this directory items: Content of this directory parent_dir: Pointer to a parent directory to maintain hierarchy. None if root time: Time of this object """ self.client = client self.parent_dir = parent_dir self.time = time self.name = name self.files = [] self.directories = [] for item in items: if isinstance(item, dict): # Is a directory self.directories.append(FTPDirectory(self.client, item["dir"], item["content"], parent_dir=self, time=item["time"])) else: self.files.append(FTPFile(self.client, item[0], self, item[1])) @property def path(self): """ Returns: whole path for this directory """ if self.parent_dir: return self.parent_dir.path + self.name + "/" else: return self.name def __repr__(self): return "<FTPDirectory {}>".format(self.path) def cd(self, path): """ Change to a directory Changes directory to a path specified by parameter path. There are three special cases: / - climbs by self.parent_dir up in the hierarchy until it reaches root element. . - does nothing .. - climbs one level up in hierarchy, if present, otherwise does the same as preceeding. Args: path: Path to change """ if path == ".": return self elif path == "..": result = self if result.parent_dir: result = result.parent_dir return result elif path == "/": result = self while result.parent_dir: result = result.parent_dir return result enter = path.strip("/").split("/", 1) remainder = None if len(enter) == 2: enter, remainder = enter for item in self.directories: if item.name == enter: if remainder: return item.cd("/".join(remainder)) else: return item raise FTPException("Directory {}{} does not exist!".format(self.path, enter)) def search(self, by, files=True, directories=True): """ Recursive search by string or regexp. Searches throughout all the filesystem structure from top till the bottom until it finds required files or dirctories. You can specify either plain string or regexp. String search does classic ``in``, regexp matching is done by exact matching (by.match). Args: by: Search string or regexp files: Whether look for files directories: Whether look for directories Returns: List of all objects found in FS """ def _scan(what, in_what): if isinstance(what, re._pattern_type): return what.match(in_what) is not None else: return what in in_what results = [] if files: for f in self.files: if _scan(by, f.name): results.append(f) for d in self.directories: if directories: if _scan(by, d.name): results.append(d) results.extend(d.search(by, files=files, directories=directories)) return results class FTPFile(object): """ FTP FS File encapsulation This class represents one file in the FS hierarchy. It encapsulates mainly its position in FS and adds the possibility of downloading the file. """ def __init__(self, client, name, parent_dir, time): """ Constructor Args: client: ftplib.FTP instance name: File name (without path) parent_dir: Directory in which this file is """ self.client = client self.parent_dir = parent_dir self.name = name self.time = time @property def path(self): """ Returns: whole path for this file """ if self.parent_dir: return self.parent_dir.path + self.name else: return self.name @property def local_time(self): """ Returns: time modified to match local computer's time zone """ return self.client.dt + self.time def __repr__(self): return "<FTPFile {}>".format(self.path) def retr(self, callback): """ Retrieve file Wrapper around ftplib.FTP.retrbinary(). This function cd's to the directory where this file is present, then calls the FTP's retrbinary() function with provided callable and then cd's back where it started to keep it consistent. Args: callback: Any callable that accepts one parameter as the data Raises: AssertionError: When any of the CWD or CDUP commands fail. ftplib.error_perm: When retrbinary call of ftplib fails """ dirs, f = self.path.rsplit("/", 1) dirs = dirs.lstrip("/").split("/") # Dive in for d in dirs: assert self.client.cwd(d), "Could not change into the directory {}!".format(d) self.client.retrbinary(f, callback) # Dive out for d in dirs: assert self.client.cdup(), "Could not get out of directory {}!".format(d) def download(self, target=None): """ Download file into this machine Wrapper around self.retr function. It downloads the file from remote filesystem into local filesystem. Name is either preserved original, or can be changed. Args: target: Target file name (None to preserver the original) """ if target is None: target = self.name with open(target, "wb") as output: self.retr(output.write) class FTPClient(object): """ FTP Client encapsulation This class provides basic encapsulation around ftplib's FTP class. It wraps some methods and allows to easily delete whole directory or walk through the directory tree. Usage: >>> from utils.ftp import FTPClient >>> ftp = FTPClient("host", "user", "password") >>> only_files_with_EVM_in_name = ftp.filesystem.search("EVM", directories=False) >>> only_files_by_regexp = ftp.filesystem.search(re.compile("regexp"), directories=False) >>> some_directory = ftp.filesystem.cd("a/b/c") # cd's to this directory >>> root = some_directory.cd("/") Always going through filesystem property is a bit slow as it parses the structure on each use. If you are sure that the structure will remain intact between uses, you can do as follows to save the time:: >>> fs = ftp.filesystem Let's download some files:: >>> for f in ftp.filesystem.search("IMPORTANT_FILE", directories=False): ... f.download() # To pickup its original name ... f.download("custom_name") We finished the testing, so we don't need the content of the directory:: >>> ftp.recursively_delete() And it's gone. """ def __init__(self, host, login, password, upload_dir="/"): """ Constructor Args: host: FTP server host login: FTP login password: FTP password """ self.host = host self.login = login self.password = password self.ftp = None self.dt = None self.upload_dir = upload_dir self.connect() self.update_time_difference() def connect(self): self.ftp = ftplib.FTP(self.host) self.ftp.login(self.login, self.password) def update_time_difference(self): """ Determine the time difference between the FTP server and this computer. This is done by uploading a fake file, reading its time and deleting it. Then the self.dt variable captures the time you need to ADD to the remote time or SUBTRACT from local time. The FTPFile object carries this automatically as it has .local_time property which adds the client's .dt to its time. """ TIMECHECK_FILE_NAME = fauxfactory.gen_alphanumeric(length=16) void_file = StringIO(fauxfactory.gen_alpha()) self.cwd(self.upload_dir) assert "Transfer complete" in self.storbinary(TIMECHECK_FILE_NAME, void_file),\ "Could not upload a file for time checking with name {}!".format(TIMECHECK_FILE_NAME) void_file.close() now = datetime.now() for d, name, time in self.ls(): if name == TIMECHECK_FILE_NAME: self.dt = now - time self.dele(TIMECHECK_FILE_NAME) self.cwd("/") return True raise FTPException("The timecheck file was not found in the current FTP directory") def ls(self): """ Lists the content of a directory. Returns: List of all items in current directory Return format is [(is_dir?, "name", remote_time), ...] """ result = [] def _callback(line): is_dir = line.upper().startswith("D") # Max 8, then the final is file which can contain something blank fields = re.split(r"\s+", line, maxsplit=8) # This is because how informations in LIST are presented # Nov 11 12:34 filename (from the end) date = strptime(str(datetime.now().year) + " " + fields[-4] + " " + fields[-3] + " " + fields[-2], "%Y %b %d %H:%M") # convert time.struct_time into datetime date = datetime.fromtimestamp(mktime(date)) result.append((is_dir, fields[-1], date)) self.ftp.dir(_callback) return result def pwd(self): """ Get current directory Returns: Current directory Raises: AssertionError: PWD command fails """ result = self.ftp.sendcmd("PWD") assert "is the current directory" in result, "PWD command failed" x, d, y = result.strip().split("\"") return d.strip() def cdup(self): """ Goes one level up in directory hierarchy (cd ..) """ return self.ftp.sendcmd("CDUP") def mkd(self, d): """ Create a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("MKD {}".format(d)).startswith("250") except ftplib.error_perm: return False def rmd(self, d): """ Remove a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("RMD {}".format(d)).startswith("250") except ftplib.error_perm: return False def dele(self, f): """ Remove a file Args: f: File name Returns: Success of the action """ try: return self.ftp.sendcmd("DELE {}".format(f)).startswith("250") except ftplib.error_perm: return False def cwd(self, d): """ Enter a directory Args: d: Directory name Returns: Success of the action """ try: return self.ftp.sendcmd("CWD {}".format(d)).startswith("250") except ftplib.error_perm: return False def close(self): """ Finish work and close connection """ self.ftp.quit() self.ftp.close() self.ftp = None def retrbinary(self, f, callback): """ Download file You need to specify the callback function, which accepts one parameter (data), to be processed. Args: f: Requested file name callback: Callable with one parameter accepting the data """ return self.ftp.retrbinary("RETR {}".format(f), callback) def storbinary(self, f, file_obj): """ Store file You need to specify the file object. Args: f: Requested file name file_obj: File object to be stored """ return self.ftp.storbinary("STOR {}".format(f), file_obj) def recursively_delete(self, d=None): """ Recursively deletes content of pwd WARNING: Destructive! Args: d: Directory to enter (None for not entering - root directory) d: str or None Raises: AssertionError: When some of the FTP commands fail. """ # Enter the directory if d: assert self.cwd(d), "Could not enter directory {}".format(d) # Work in it for isdir, name, time in self.ls(): if isdir: self.recursively_delete(name) else: assert self.dele(name), "Could not delete {}!".format(name) # Go out of it if d: # Go to parent directory assert self.cdup(), "Could not go to parent directory of {}!".format(d) # And delete it assert self.rmd(d), "Could not remove directory {}!".format(d) def tree(self, d=None): """ Walks the tree recursively and creates a tree Base structure is a list. List contains directory content and the type decides whether it's a directory or a file: - tuple: it's a file, therefore it represents file's name and time - dict: it's a directory. Then the dict structure is as follows:: dir: directory name content: list of directory content (recurse) Args: d: Directory to enter(None for no entering - root directory) Returns: Directory structure in lists nad dicts. Raises: AssertionError: When some of the FTP commands fail. """ # Enter the directory items = [] if d: assert self.cwd(d), "Could not enter directory {}".format(d) # Work in it for isdir, name, time in self.ls(): if isdir: items.append({"dir": name, "content": self.tree(name), "time": time}) else: items.append((name, time)) # Go out of it if d: # Go to parent directory assert self.cdup(), "Could not go to parent directory of {}!".format(d) return items @property def filesystem(self): """ Returns the object structure of the filesystem Returns: Root directory """ return FTPDirectory(self, "/", self.tree()) # Context management methods def __enter__(self): """ Entering the context does nothing, because the client is already connected """ return self def __exit__(self, type, value, traceback): """ Exiting the context means just calling .close() on the client. """ self.close()
# -*- coding: utf-8 -*- """Tests around the appliance""" import pytest from fixtures.pytest_store import store from utils import db, version pytestmark = [pytest.mark.smoke, pytest.mark.tier(1)] def _rpms_present_packages(): # autogenerate the rpms to test based on the current appliance version # and the list of possible packages that can be installed current_version = version.current_version() possible_packages = [ 'cfme', 'cfme-appliance', 'cfme-lib', 'nfs-utils', 'nfs-utils-lib', 'libnfsidmap', 'mingw32-cfme-host', 'ipmitool', 'prince', 'netapp-manageability-sdk', 'rhn-client-tools', 'rhn-check', 'rhnlib' ] def package_filter(package): package_tests = [ # stopped shipping this with 5.4 package == 'mingw32-cfme-host' and current_version >= '5.4', # stopped shipping these with 5.5 package in ('cfme-lib', 'netapp-manageability-sdk') and current_version >= 5.5, # nfs-utils-lib was superseded by libnfsidmap in el7/cfme 5.5 # so filter out nfs-utils-lib on 5.5 and up, and libnfsidmap below 5.5 package == 'nfs-utils-lib' and current_version >= '5.5', package == 'libnfsidmap' and current_version < '5.5', ] # If any of the package tests eval'd to true, filter this package out return not any(package_tests) return filter(package_filter, possible_packages) def test_product_name(): if store.current_appliance.is_downstream: assert store.current_appliance.product_name == 'CFME' else: assert store.current_appliance.product_name == 'ManageIQ' @pytest.mark.ignore_stream("upstream") @pytest.mark.parametrize(('package'), _rpms_present_packages()) def test_rpms_present(ssh_client, package): """Verifies nfs-util rpms are in place needed for pxe & nfs operations""" exit, stdout = ssh_client.run_command('rpm -q {}'.format(package)) assert 'is not installed' not in stdout assert exit == 0 # this is going to fail on 5.1 def test_selinux_enabled(ssh_client): """Verifies selinux is enabled""" stdout = ssh_client.run_command('getenforce')[1] assert 'Enforcing' in stdout @pytest.mark.uncollectif(lambda: version.current_version() >= '5.6', reason='Only valid for <5.6') def test_iptables_running(ssh_client): """Verifies iptables service is running on the appliance""" stdout = ssh_client.run_command('service iptables status')[1] assert 'is not running' not in stdout @pytest.mark.uncollectif(lambda: version.current_version() < '5.6', reason='Only valid for >5.7') def test_firewalld_running(ssh_client): """Verifies iptables service is running on the appliance""" stdout = ssh_client.run_command('service firewalld status')[1] assert 'active (running)' in stdout def test_evm_running(ssh_client): """Verifies overall evm service is running on the appliance""" stdout = ssh_client.run_command('systemctl status evmserverd')[1] assert 'active (running)' in stdout @pytest.mark.parametrize(('service'), [ 'evmserverd', 'evminit', 'sshd', 'postgresql', ]) def test_service_enabled(ssh_client, service): """Verifies if key services are configured to start on boot up""" if service == 'postgresql': service = '{}-postgresql'.format(db.scl_name()) if pytest.store.current_appliance.os_version >= '7': cmd = 'systemctl is-enabled {}'.format(service) else: cmd = 'chkconfig | grep {} | grep -q "5:on"'.format(service) result = ssh_client.run_command(cmd) assert result.rc == 0, result.output @pytest.mark.ignore_stream("upstream") @pytest.mark.parametrize(('proto,port'), [ ('tcp', 22), ('tcp', 80), ('tcp', 443), ]) def test_iptables_rules(ssh_client, proto, port): """Verifies key iptable rules are in place""" # get the current iptables state, nicely formatted for us by iptables-save res = ssh_client.run_command('iptables-save') # get everything from the input chain input_rules = filter(lambda line: line.startswith('-A IN'), res.output.splitlines()) # filter to make sure we have a rule that matches the given proto and port def rule_filter(rule): # iptables-save should put all of these in order for us # if not, this can be broken up into its individual components matches = [ '-p {proto}', '-m {proto} --dport {port}', '-j ACCEPT' ] return all([match.format(proto=proto, port=port) in rule for match in matches]) assert filter(rule_filter, input_rules) # this is based on expected changes tracked in github/ManageIQ/cfme_build repo def test_memory_total(ssh_client): """Verifies that the total memory on the box is >= 6GB""" stdout = ssh_client.run_command( 'free -g | grep Mem: | awk \'{ print $2 }\'')[1] assert stdout >= 6 # this is based on expected changes tracked in github/ManageIQ/cfme_build repo def test_cpu_total(ssh_client): """Verifies that the total number of cpus is >= 4""" stdout = ssh_client.run_command( 'lscpu | grep ^CPU\(s\): | awk \'{ print $2 }\'')[1] assert stdout >= 4 @pytest.mark.ignore_stream("upstream") def test_certificates_present(ssh_client, soft_assert): """Test whether the required product certificates are present.""" known_certs = ["/etc/rhsm/ca/redhat-uep.pem", "/etc/rhsm/ca/candlepin-stage.pem", "/etc/pki/product-default/69.pem", "/etc/pki/product/167.pem", "/etc/pki/product/201.pem"] for cert in known_certs: cert_path_vaild = ssh_client.run_command("test -f '{}'".format(cert))[0] == 0 if cert_path_vaild: rc, output = ssh_client.run_command( "openssl verify -CAfile /etc/rhsm/ca/redhat-uep.pem '{}'".format(cert)) assert rc == 0 @pytest.mark.ignore_stream("upstream") def test_db_connection(db): """Test that the pgsql db is listening externally This looks for a row in the miq_databases table, which should always exist on an appliance with a working database and UI """ databases = db.session.query(db['miq_databases']).all() assert len(databases) > 0 def test_asset_precompiled(ssh_client): file_exists = ssh_client.run_command("test -d /var/www/miq/vmdb/public/assets").rc == 0 assert file_exists, "Assets not precompiled" @pytest.mark.ignore_stream("upstream") def test_keys_included(ssh_client, soft_assert): keys = ['v0_key', 'v1_key', 'v2_key'] for k in keys: file_exists = ssh_client.run_command("test -e /var/www/miq/vmdb/certs/{}".format(k))[0] == 0 soft_assert(file_exists, "{} was not included in the build".format(k))
rananda/cfme_tests
cfme/tests/test_appliance.py
utils/ftp.py
import numpy as np import attr import tectosaur.util.gpu as gpu from tectosaur.util.quadrature import gauss4d_tri from tectosaur.kernels import kernels from tectosaur.mesh.mesh_gen import make_sphere from tectosaur.fmm.surrounding_surf import surrounding_surf from tectosaur.util.cpp import imp traversal_ext = imp("tectosaur.fmm.traversal_wrapper") def get_dim_module(dim): return traversal_ext.two if dim == 2 else traversal_ext.three def get_traversal_module(K): if type(K.scale_type) is int: return get_dim_module(K.spatial_dim).kdtree else: return get_dim_module(K.spatial_dim).octree def get_gpu_module(surf, quad, K, float_type, n_workers_per_block): args = dict( n_workers_per_block = n_workers_per_block, gpu_float_type = gpu.np_to_c_type(float_type), surf_pts = surf[0], surf_tris = surf[1], quad_pts = quad[0], quad_wts = quad[1], K = K ) gpu_module = gpu.load_gpu( 'fmm/tri_gpu_kernels.cl', tmpl_args = args ) return gpu_module @attr.s class FMMConfig: K = attr.ib() params = attr.ib() surf = attr.ib() quad = attr.ib() outer_r = attr.ib() inner_r = attr.ib() alpha = attr.ib() float_type = attr.ib() gpu_module = attr.ib() traversal_module = attr.ib() n_workers_per_block = attr.ib() treecode = attr.ib() order = attr.ib() def make_config(K_name, params, inner_r, outer_r, order, quad_order, float_type, alpha = 1e-5, n_workers_per_block = 256, treecode = False, force_order = None): K = kernels[K_name] quad = gauss4d_tri(quad_order, quad_order) surf = make_sphere((0.0, 0.0, 0.0), 1.0, order) order = surf[1].shape[0] if force_order is not None: order = force_order if len(params) == 0: params = [0.0] return FMMConfig( K = K, params = np.array(params), surf = surf, quad = quad, outer_r = outer_r, inner_r = inner_r, alpha = alpha, float_type = float_type, gpu_module = get_gpu_module(surf, quad, K, float_type, n_workers_per_block), traversal_module = get_traversal_module(K), n_workers_per_block = n_workers_per_block, treecode = treecode, order = order )
import numpy as np from dimension import dim from tectosaur.fmm.cfg import get_dim_module from tectosaur.util.test_decorators import slow import pytest @pytest.fixture(params = ['kd', 'oct']) def tree_type(request): return request.param def make_tree(tree_type, pts, Rs, n_per_cell): dim = pts.shape[1] if tree_type == 'kd': return get_dim_module(dim).kdtree.Tree.build(pts, Rs, n_per_cell) elif tree_type == 'oct': return get_dim_module(dim).octree.Tree.build(pts, Rs, n_per_cell) def simple_setup(n, tree_type, dim): pts = np.random.rand(n, dim) Rs = np.random.rand(n) * 0.01 t = make_tree(tree_type, pts, Rs, 1) return pts, Rs, t def test_bisects(tree_type, dim): pts, Rs, t = simple_setup(100, tree_type, dim) pts = np.array([b.center for b in t.balls]) for n in t.nodes: if n.is_leaf: continue idx_list = set(range(n.start, n.end)) for child_i in range(t.split): child_n = t.nodes[n.children[child_i]] child_idx_list = set(range(child_n.start, child_n.end)) assert(child_idx_list.issubset(idx_list)) idx_list -= child_idx_list assert(len(idx_list) == 0) def test_contains_pts(tree_type, dim): pts, Rs, t = simple_setup(100, tree_type, dim) pts = np.array([b.center for b in t.balls]) for n in t.nodes: for i in range(n.start, n.end): dist = np.sqrt(np.sum((n.bounds.center - pts[i,:]) ** 2)) assert(dist <= n.bounds.R) def test_height_depth(tree_type, dim): pts, Rs, t = simple_setup(100, tree_type, dim) for n in t.nodes: if n.is_leaf: continue for c in range(t.split): assert(n.depth == t.nodes[n.children[c]].depth - 1) assert(n.height == max([t.nodes[n.children[c]].height for c in range(t.split)]) + 1) def test_one_level(tree_type, dim): pts = np.random.rand(dim, dim) t = make_tree(tree_type, pts, np.full(pts.shape[0], 0.01), dim + 1) assert(t.max_height == 0); assert(len(t.nodes) == 1); assert(t.root().is_leaf); assert(t.root().end - t.root().start); assert(t.root().depth == 0); assert(t.root().height == 0); def test_orig_idxs(tree_type, dim): pts = np.random.rand(1000, dim) Rs = np.random.rand(1000) * 0.01 t = make_tree(tree_type, pts, Rs, 50) pts_new = np.array([b.center for b in t.balls]) np.testing.assert_almost_equal(pts_new, pts[np.array(t.orig_idxs), :]) def test_idx(tree_type, dim): pts, Rs, t = simple_setup(100, tree_type, dim) for i, n in enumerate(t.nodes): assert(n.idx == i) def test_law_of_large_numbers(): n = 10000 pts = np.random.rand(n, 3) Rs = np.random.rand(n) * 0.01 t = get_dim_module(3).octree.Tree.build(pts, Rs, 100); for i in range(8): child = t.nodes[t.root().children[i]] n_pts = child.end - child.start diff = np.abs(n_pts - (n / 8)); assert(diff < (n / 16));
tbenthompson/tectosaur
tests/fmm/test_tree.py
tectosaur/fmm/cfg.py
import logging import pprint import os import sys import time import numbers from jmbase import get_log, jmprint, bintohex, hextobin from .configure import jm_single, validate_address, is_burn_destination from .schedule import human_readable_schedule_entry, tweak_tumble_schedule,\ schedule_to_text from .wallet import BaseWallet, estimate_tx_fee, compute_tx_locktime, \ FidelityBondMixin from jmbitcoin import make_shuffled_tx, amount_to_str, mk_burn_script,\ PartiallySignedTransaction, CMutableTxOut,\ human_readable_transaction, Hash160 from jmbase.support import EXIT_SUCCESS log = get_log() """ Utility functions for tumbler-style takers; Currently re-used by CLI script tumbler.py and joinmarket-qt """ def direct_send(wallet_service, amount, mixdepth, destination, answeryes=False, accept_callback=None, info_callback=None, error_callback=None, return_transaction=False, with_final_psbt=False, optin_rbf=False, custom_change_addr=None): """Send coins directly from one mixdepth to one destination address; does not need IRC. Sweep as for normal sendpayment (set amount=0). If answeryes is True, callback/command line query is not performed. If optin_rbf is True, the nSequence values are changed as appropriate. If accept_callback is None, command line input for acceptance is assumed, else this callback is called: accept_callback: ==== args: deserialized tx, destination address, amount in satoshis, fee in satoshis, custom change address returns: True if accepted, False if not ==== info_callback and error_callback takes one parameter, the information message (when tx is pushed or error occured), and returns nothing. This function returns: 1. False if there is any failure. 2. The txid if transaction is pushed, and return_transaction is False, and with_final_psbt is False. 3. The full CMutableTransaction if return_transaction is True and with_final_psbt is False. 4. The PSBT object if with_final_psbt is True, and in this case the transaction is *NOT* broadcast. """ #Sanity checks assert validate_address(destination)[0] or is_burn_destination(destination) assert custom_change_addr is None or validate_address(custom_change_addr)[0] assert amount > 0 or custom_change_addr is None assert isinstance(mixdepth, numbers.Integral) assert mixdepth >= 0 assert isinstance(amount, numbers.Integral) assert amount >=0 assert isinstance(wallet_service.wallet, BaseWallet) if is_burn_destination(destination): #Additional checks if not isinstance(wallet_service.wallet, FidelityBondMixin): log.error("Only fidelity bond wallets can burn coins") return if answeryes: log.error("Burning coins not allowed without asking for confirmation") return if mixdepth != FidelityBondMixin.FIDELITY_BOND_MIXDEPTH: log.error("Burning coins only allowed from mixdepth " + str( FidelityBondMixin.FIDELITY_BOND_MIXDEPTH)) return if amount != 0: log.error("Only sweeping allowed when burning coins, to keep the tx " + "small. Tip: use the coin control feature to freeze utxos") return txtype = wallet_service.get_txtype() if amount == 0: #doing a sweep utxos = wallet_service.get_utxos_by_mixdepth()[mixdepth] if utxos == {}: log.error( "There are no available utxos in mixdepth: " + str(mixdepth) + ", quitting.") return total_inputs_val = sum([va['value'] for u, va in utxos.items()]) if is_burn_destination(destination): if len(utxos) > 1: log.error("Only one input allowed when burning coins, to keep " + "the tx small. Tip: use the coin control feature to freeze utxos") return address_type = FidelityBondMixin.BIP32_BURN_ID index = wallet_service.wallet.get_next_unused_index(mixdepth, address_type) path = wallet_service.wallet.get_path(mixdepth, address_type, index) privkey, engine = wallet_service.wallet._get_key_from_path(path) pubkey = engine.privkey_to_pubkey(privkey) pubkeyhash = Hash160(pubkey) #size of burn output is slightly different from regular outputs burn_script = mk_burn_script(pubkeyhash) fee_est = estimate_tx_fee(len(utxos), 0, txtype=txtype, extra_bytes=len(burn_script)/2) outs = [{"script": burn_script, "value": total_inputs_val - fee_est}] destination = "BURNER OUTPUT embedding pubkey at " \ + wallet_service.wallet.get_path_repr(path) \ + "\n\nWARNING: This transaction if broadcasted will PERMANENTLY DESTROY your bitcoins\n" else: #regular sweep (non-burn) fee_est = estimate_tx_fee(len(utxos), 1, txtype=txtype) outs = [{"address": destination, "value": total_inputs_val - fee_est}] else: #not doing a sweep; we will have change #8 inputs to be conservative initial_fee_est = estimate_tx_fee(8,2, txtype=txtype) utxos = wallet_service.select_utxos(mixdepth, amount + initial_fee_est) if len(utxos) < 8: fee_est = estimate_tx_fee(len(utxos), 2, txtype=txtype) else: fee_est = initial_fee_est total_inputs_val = sum([va['value'] for u, va in utxos.items()]) changeval = total_inputs_val - fee_est - amount outs = [{"value": amount, "address": destination}] change_addr = wallet_service.get_internal_addr(mixdepth) if custom_change_addr is None \ else custom_change_addr outs.append({"value": changeval, "address": change_addr}) #compute transaction locktime, has special case for spending timelocked coins tx_locktime = compute_tx_locktime() if mixdepth == FidelityBondMixin.FIDELITY_BOND_MIXDEPTH and \ isinstance(wallet_service.wallet, FidelityBondMixin): for outpoint, utxo in utxos.items(): path = wallet_service.script_to_path( wallet_service.addr_to_script(utxo["address"])) if not FidelityBondMixin.is_timelocked_path(path): continue path_locktime = path[-1] tx_locktime = max(tx_locktime, path_locktime+1) #compute_tx_locktime() gives a locktime in terms of block height #timelocked addresses use unix time instead #OP_CHECKLOCKTIMEVERIFY can only compare like with like, so we #must use unix time as the transaction locktime #Now ready to construct transaction log.info("Using a fee of: " + amount_to_str(fee_est) + ".") if amount != 0: log.info("Using a change value of: " + amount_to_str(changeval) + ".") tx = make_shuffled_tx(list(utxos.keys()), outs, 2, tx_locktime) if optin_rbf: for inp in tx.vin: inp.nSequence = 0xffffffff - 2 inscripts = {} spent_outs = [] for i, txinp in enumerate(tx.vin): u = (txinp.prevout.hash[::-1], txinp.prevout.n) inscripts[i] = (utxos[u]["script"], utxos[u]["value"]) spent_outs.append(CMutableTxOut(utxos[u]["value"], utxos[u]["script"])) if with_final_psbt: # here we have the PSBTWalletMixin do the signing stage # for us: new_psbt = wallet_service.create_psbt_from_tx(tx, spent_outs=spent_outs) serialized_psbt, err = wallet_service.sign_psbt(new_psbt.serialize()) if err: log.error("Failed to sign PSBT, quitting. Error message: " + err) return False new_psbt_signed = PartiallySignedTransaction.deserialize(serialized_psbt) print("Completed PSBT created: ") print(wallet_service.human_readable_psbt(new_psbt_signed)) return new_psbt_signed else: success, msg = wallet_service.sign_tx(tx, inscripts) if not success: log.error("Failed to sign transaction, quitting. Error msg: " + msg) return log.info("Got signed transaction:\n") log.info(human_readable_transaction(tx)) actual_amount = amount if amount != 0 else total_inputs_val - fee_est sending_info = "Sends: " + amount_to_str(actual_amount) + \ " to destination: " + destination if custom_change_addr: sending_info += ", custom change to: " + custom_change_addr log.info(sending_info) if not answeryes: if not accept_callback: if input('Would you like to push to the network? (y/n):')[0] != 'y': log.info("You chose not to broadcast the transaction, quitting.") return False else: accepted = accept_callback(human_readable_transaction(tx), destination, actual_amount, fee_est, custom_change_addr) if not accepted: return False if jm_single().bc_interface.pushtx(tx.serialize()): txid = bintohex(tx.GetTxid()[::-1]) successmsg = "Transaction sent: " + txid cb = log.info if not info_callback else info_callback cb(successmsg) txinfo = txid if not return_transaction else tx return txinfo else: errormsg = "Transaction broadcast failed!" cb = log.error if not error_callback else error_callback cb(errormsg) return False def get_tumble_log(logsdir): tumble_log = logging.getLogger('tumbler') tumble_log.setLevel(logging.DEBUG) logFormatter = logging.Formatter( ('%(asctime)s %(message)s')) fileHandler = logging.FileHandler(os.path.join(logsdir, 'TUMBLE.log')) fileHandler.setFormatter(logFormatter) tumble_log.addHandler(fileHandler) return tumble_log def restart_wait(txid): """ Returns true only if the transaction txid is seen in the wallet, and confirmed (it must be an in-wallet transaction since it always spends coins from the wallet). """ res = jm_single().bc_interface.get_transaction(hextobin(txid)) if not res: return False if res["confirmations"] == 0: return False if res["confirmations"] < 0: log.warn("Tx: " + txid + " has a conflict, abandoning.") sys.exit(EXIT_SUCCESS) else: log.debug("Tx: " + str(txid) + " has " + str( res["confirmations"]) + " confirmations.") return True def restart_waiter(txid): """Given a txid, wait for confirmation by polling the blockchain interface instance. Note that this is currently blocking, so only used by the CLI version; the Qt/GUI uses the underlying restart_wait() fn. """ ctr = 0 log.info("Waiting for confirmation of last transaction: " + str(txid)) while True: time.sleep(10) ctr += 1 if not (ctr % 12): log.debug("Still waiting for confirmation of last transaction ...") if restart_wait(txid): break log.info("The previous transaction is now in a block; continuing.") def unconf_update(taker, schedulefile, tumble_log, addtolog=False): """Provide a Taker object, a schedulefile path for the current schedule, a logging instance for TUMBLE.log, and a parameter for whether to update TUMBLE.log. Makes the necessary state updates explained below, including to the wallet. Note that this is re-used for confirmation with addtolog=False, to avoid a repeated entry in the log. """ #on taker side, cache index update is only required after tx #push, to avoid potential of address reuse in case of a crash, #because addresses are not public until broadcast (whereas for makers, #they are public *during* negotiation). So updating the cache here #is sufficient taker.wallet_service.save_wallet() #If honest-only was set, and we are going to continue (e.g. Tumbler), #we switch off the honest-only filter. We also wipe the honest maker #list, because the intention is to isolate the source of liquidity #to exactly those that participated, in 1 transaction (i.e. it's a 1 #transaction feature). This code is here because it *must* be called #before any continuation, even if confirm_callback happens before #unconfirm_callback taker.set_honest_only(False) taker.honest_makers = [] #We persist the fact that the transaction is complete to the #schedule file. Note that if a tweak to the schedule occurred, #it only affects future (non-complete) transactions, so the final #full record should always be accurate; but TUMBLE.log should be #used for checking what actually happened. completion_flag = 1 if not addtolog else taker.txid taker.schedule[taker.schedule_index][-1] = completion_flag with open(schedulefile, "wb") as f: f.write(schedule_to_text(taker.schedule)) if addtolog: tumble_log.info("Completed successfully this entry:") #the log output depends on if it's to INTERNAL hrdestn = None if taker.schedule[taker.schedule_index][3] in ["INTERNAL", "addrask"]: hrdestn = taker.my_cj_addr #Whether sweep or not, the amt is not in satoshis; use taker data hramt = taker.cjamount tumble_log.info(human_readable_schedule_entry( taker.schedule[taker.schedule_index], hramt, hrdestn)) tumble_log.info("Txid was: " + taker.txid) def tumbler_taker_finished_update(taker, schedulefile, tumble_log, options, res, fromtx=False, waittime=0.0, txdetails=None): """on_finished_callback processing for tumbler. Note that this is *not* the full callback, but provides common processing across command line and other GUI versions. """ if fromtx == "unconfirmed": #unconfirmed event means transaction has been propagated, #we update state to prevent accidentally re-creating it in #any crash/restart condition unconf_update(taker, schedulefile, tumble_log, True) return if fromtx: if res: #this has no effect except in the rare case that confirmation #is immediate; also it does not repeat the log entry. unconf_update(taker, schedulefile, tumble_log, False) #note that Qt does not yet support 'addrask', so this is only #for command line script TODO if taker.schedule[taker.schedule_index+1][3] == 'addrask': jm_single().debug_silence[0] = True jmprint('\n'.join(['=' * 60] * 3)) jmprint('Tumbler requires more addresses to stop amount correlation') jmprint('Obtain a new destination address from your bitcoin recipient') jmprint(' for example click the button that gives a new deposit address') jmprint('\n'.join(['=' * 60] * 1)) while True: destaddr = input('insert new address: ') addr_valid, errormsg = validate_address(destaddr) if addr_valid: break jmprint( 'Address ' + destaddr + ' invalid. ' + errormsg + ' try again', "warning") jm_single().debug_silence[0] = False taker.schedule[taker.schedule_index+1][3] = destaddr taker.tdestaddrs.append(destaddr) waiting_message = "Waiting for: " + str(waittime) + " minutes." tumble_log.info(waiting_message) log.info(waiting_message) else: # a transaction failed, either because insufficient makers # (acording to minimum_makers) responded in Phase 1, or not all # makers responded in Phase 2, or the tx was a mempool conflict. # If the tx was a mempool conflict, we should restart with random # maker choice as usual. If someone didn't respond, we'll try to # repeat without the troublemakers. log.info("Schedule entry: " + str( taker.schedule[taker.schedule_index]) + \ " failed after timeout, trying again") taker.add_ignored_makers(taker.nonrespondants) #Is the failure in Phase 2? if not taker.latest_tx is None: if len(taker.nonrespondants) == 0: # transaction was created validly but conflicted in the # mempool; just try again without honest settings; # i.e. fallback to same as Phase 1 failure. log.info("Invalid transaction; possible mempool conflict.") else: #Now we have to set the specific group we want to use, and hopefully #they will respond again as they showed honesty last time. #Note that we must wipe the list first; other honest makers needn't #have the right settings (e.g. max cjamount), so can't be carried #over from earlier transactions. taker.honest_makers = [] taker.add_honest_makers(list(set( taker.maker_utxo_data.keys()).symmetric_difference( set(taker.nonrespondants)))) #If insufficient makers were honest, we can only tweak the schedule. #If enough were, we prefer to restart with them only: log.info("Inside a Phase 2 failure; number of honest " "respondants was: " + str(len(taker.honest_makers))) log.info("They were: " + str(taker.honest_makers)) if len(taker.honest_makers) >= jm_single().config.getint( "POLICY", "minimum_makers"): tumble_log.info("Transaction attempt failed, attempting to " "restart with subset.") tumble_log.info("The paramaters of the failed attempt: ") tumble_log.info(str(taker.schedule[taker.schedule_index])) #we must reset the number of counterparties, as well as fix who they #are; this is because the number is used to e.g. calculate fees. #cleanest way is to reset the number in the schedule before restart. taker.schedule[taker.schedule_index][2] = len(taker.honest_makers) retry_str = "Retrying with: " + str(taker.schedule[ taker.schedule_index][2]) + " counterparties." tumble_log.info(retry_str) log.info(retry_str) taker.set_honest_only(True) taker.schedule_index -= 1 return #There were not enough honest counterparties. #Tumbler is aggressive in trying to complete; we tweak the schedule #from this point in the mixdepth, then try again. tumble_log.info("Transaction attempt failed, tweaking schedule" " and trying again.") tumble_log.info("The paramaters of the failed attempt: ") tumble_log.info(str(taker.schedule[taker.schedule_index])) taker.schedule_index -= 1 taker.schedule = tweak_tumble_schedule(options, taker.schedule, taker.schedule_index, taker.tdestaddrs) tumble_log.info("We tweaked the schedule, the new schedule is:") tumble_log.info(pprint.pformat(taker.schedule)) else: if not res: failure_msg = "Did not complete successfully, shutting down" tumble_log.info(failure_msg) log.info(failure_msg) else: log.info("All transactions completed correctly") tumble_log.info("Completed successfully the last entry:") #Whether sweep or not, the amt is not in satoshis; use taker data hramt = taker.cjamount tumble_log.info(human_readable_schedule_entry( taker.schedule[taker.schedule_index], hramt)) #copy of above, TODO refactor out taker.schedule[taker.schedule_index][5] = 1 with open(schedulefile, "wb") as f: f.write(schedule_to_text(taker.schedule)) def tumbler_filter_orders_callback(orders_fees, cjamount, taker): """Since the tumbler does not use interactive fee checking, we use the -x values from the command line instead. """ orders, total_cj_fee = orders_fees abs_cj_fee = 1.0 * total_cj_fee / taker.n_counterparties rel_cj_fee = abs_cj_fee / cjamount log.info('rel/abs average fee = ' + str(rel_cj_fee) + ' / ' + str( abs_cj_fee)) if rel_cj_fee > taker.max_cj_fee[0] and abs_cj_fee > taker.max_cj_fee[1]: log.info("Rejected fees as too high according to options, will " "retry.") return "retry" return True
"""Blockchaininterface functionality tests.""" import binascii from commontest import create_wallet_for_sync import pytest from jmbase import get_log from jmclient import load_test_config, jm_single, BaseWallet log = get_log() def sync_test_wallet(fast, wallet_service): sync_count = 0 wallet_service.synced = False while not wallet_service.synced: wallet_service.sync_wallet(fast=fast) sync_count += 1 # avoid infinite loop assert sync_count < 10 log.debug("Tried " + str(sync_count) + " times") @pytest.mark.parametrize('fast', (False, True)) def test_empty_wallet_sync(setup_wallets, fast): wallet_service = create_wallet_for_sync([0, 0, 0, 0, 0], ['test_empty_wallet_sync']) sync_test_wallet(fast, wallet_service) broken = True for md in range(wallet_service.max_mixdepth + 1): for internal in (BaseWallet.ADDRESS_TYPE_INTERNAL, BaseWallet.ADDRESS_TYPE_EXTERNAL): broken = False assert 0 == wallet_service.get_next_unused_index(md, internal) assert not broken @pytest.mark.parametrize('fast,internal', ( (False, BaseWallet.ADDRESS_TYPE_EXTERNAL), (False, BaseWallet.ADDRESS_TYPE_INTERNAL), (True, BaseWallet.ADDRESS_TYPE_EXTERNAL), (True, BaseWallet.ADDRESS_TYPE_INTERNAL))) def test_sequentially_used_wallet_sync(setup_wallets, fast, internal): used_count = [1, 3, 6, 2, 23] wallet_service = create_wallet_for_sync( used_count, ['test_sequentially_used_wallet_sync'], populate_internal=internal) sync_test_wallet(fast, wallet_service) broken = True for md in range(len(used_count)): broken = False assert used_count[md] == wallet_service.get_next_unused_index(md, internal) assert not broken @pytest.mark.parametrize('fast', (False,)) def test_gap_used_wallet_sync(setup_wallets, fast): """ After careful examination this test now only includes the Recovery sync. Note: pre-Aug 2019, because of a bug, this code was not in fact testing both Fast and Recovery sync, but only Recovery (twice). Also, the scenario set out in this test (where coins are funded to a wallet which has no index-cache, and initially no imports) is only appropriate for recovery-mode sync, not for fast-mode (the now default). """ used_count = [1, 3, 6, 2, 23] wallet_service = create_wallet_for_sync(used_count, ['test_gap_used_wallet_sync']) wallet_service.gap_limit = 20 for md in range(len(used_count)): x = -1 for x in range(md): assert x <= wallet_service.gap_limit, "test broken" # create some unused addresses wallet_service.get_new_script(md, BaseWallet.ADDRESS_TYPE_INTERNAL) wallet_service.get_new_script(md, BaseWallet.ADDRESS_TYPE_EXTERNAL) used_count[md] += x + 2 jm_single().bc_interface.grab_coins(wallet_service.get_new_addr(md, BaseWallet.ADDRESS_TYPE_INTERNAL), 1) jm_single().bc_interface.grab_coins(wallet_service.get_new_addr(md, BaseWallet.ADDRESS_TYPE_EXTERNAL), 1) # reset indices to simulate completely unsynced wallet for md in range(wallet_service.max_mixdepth + 1): wallet_service.set_next_index(md, BaseWallet.ADDRESS_TYPE_INTERNAL, 0) wallet_service.set_next_index(md, BaseWallet.ADDRESS_TYPE_EXTERNAL, 0) sync_test_wallet(fast, wallet_service) broken = True for md in range(len(used_count)): broken = False assert md + 1 == wallet_service.get_next_unused_index(md, BaseWallet.ADDRESS_TYPE_INTERNAL) assert used_count[md] == wallet_service.get_next_unused_index(md, BaseWallet.ADDRESS_TYPE_EXTERNAL) assert not broken @pytest.mark.parametrize('fast', (False,)) def test_multigap_used_wallet_sync(setup_wallets, fast): """ See docstring for test_gap_used_wallet_sync; exactly the same applies here. """ start_index = 5 used_count = [start_index, 0, 0, 0, 0] wallet_service = create_wallet_for_sync(used_count, ['test_multigap_used_wallet_sync']) wallet_service.gap_limit = 5 mixdepth = 0 for w in range(5): for x in range(int(wallet_service.gap_limit * 0.6)): assert x <= wallet_service.gap_limit, "test broken" # create some unused addresses wallet_service.get_new_script(mixdepth, BaseWallet.ADDRESS_TYPE_INTERNAL) wallet_service.get_new_script(mixdepth, BaseWallet.ADDRESS_TYPE_EXTERNAL) used_count[mixdepth] += x + 2 jm_single().bc_interface.grab_coins(wallet_service.get_new_addr( mixdepth, BaseWallet.ADDRESS_TYPE_INTERNAL), 1) jm_single().bc_interface.grab_coins(wallet_service.get_new_addr( mixdepth, BaseWallet.ADDRESS_TYPE_EXTERNAL), 1) # reset indices to simulate completely unsynced wallet for md in range(wallet_service.max_mixdepth + 1): wallet_service.set_next_index(md, BaseWallet.ADDRESS_TYPE_INTERNAL, 0) wallet_service.set_next_index(md, BaseWallet.ADDRESS_TYPE_EXTERNAL, 0) sync_test_wallet(fast, wallet_service) assert used_count[mixdepth] - start_index == \ wallet_service.get_next_unused_index(mixdepth, BaseWallet.ADDRESS_TYPE_INTERNAL) assert used_count[mixdepth] == wallet_service.get_next_unused_index( mixdepth, BaseWallet.ADDRESS_TYPE_EXTERNAL) @pytest.mark.parametrize('fast', (False, True)) def test_retain_unused_indices_wallet_sync(setup_wallets, fast): used_count = [0, 0, 0, 0, 0] wallet_service = create_wallet_for_sync(used_count, ['test_retain_unused_indices_wallet_sync']) for x in range(9): wallet_service.get_new_script(0, BaseWallet.ADDRESS_TYPE_INTERNAL) sync_test_wallet(fast, wallet_service) assert wallet_service.get_next_unused_index(0, BaseWallet.ADDRESS_TYPE_INTERNAL) == 9 @pytest.mark.parametrize('fast', (False, True)) def test_imported_wallet_sync(setup_wallets, fast): used_count = [0, 0, 0, 0, 0] wallet_service = create_wallet_for_sync(used_count, ['test_imported_wallet_sync']) source_wallet_service = create_wallet_for_sync(used_count, ['test_imported_wallet_sync_origin']) address = source_wallet_service.get_internal_addr(0) wallet_service.import_private_key(0, source_wallet_service.get_wif(0, 1, 0)) txid = binascii.unhexlify(jm_single().bc_interface.grab_coins(address, 1)) sync_test_wallet(fast, wallet_service) assert wallet_service._utxos.have_utxo(txid, 0) == 0 @pytest.fixture(scope='module') def setup_wallets(): load_test_config() jm_single().bc_interface.tick_forward_chain_interval = 1
undeath/joinmarket-clientserver
jmclient/test/test_blockchaininterface.py
jmclient/jmclient/taker_utils.py
""" masked_reductions.py is for reduction algorithms using a mask-based approach for missing values. """ from typing import Callable import numpy as np from pandas._libs import missing as libmissing from pandas.compat.numpy import np_version_under1p17 from pandas.core.nanops import check_below_min_count def _sumprod( func: Callable, values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0, ): """ Sum or product for 1D masked array. Parameters ---------- func : np.sum or np.prod values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). mask : np.ndarray Boolean numpy array (True values indicate missing values). skipna : bool, default True Whether to skip NA. min_count : int, default 0 The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. """ if not skipna: if mask.any() or check_below_min_count(values.shape, None, min_count): return libmissing.NA else: return func(values) else: if check_below_min_count(values.shape, mask, min_count): return libmissing.NA if np_version_under1p17: return func(values[~mask]) else: return func(values, where=~mask) def sum(values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0): return _sumprod( np.sum, values=values, mask=mask, skipna=skipna, min_count=min_count ) def prod(values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0): return _sumprod( np.prod, values=values, mask=mask, skipna=skipna, min_count=min_count ) def _minmax(func: Callable, values: np.ndarray, mask: np.ndarray, skipna: bool = True): """ Reduction for 1D masked array. Parameters ---------- func : np.min or np.max values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). mask : np.ndarray Boolean numpy array (True values indicate missing values). skipna : bool, default True Whether to skip NA. """ if not skipna: if mask.any() or not values.size: # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA else: return func(values) else: subset = values[~mask] if subset.size: return func(subset) else: # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA def min(values: np.ndarray, mask: np.ndarray, skipna: bool = True): return _minmax(np.min, values=values, mask=mask, skipna=skipna) def max(values: np.ndarray, mask: np.ndarray, skipna: bool = True): return _minmax(np.max, values=values, mask=mask, skipna=skipna)
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Series, date_range, offsets import pandas._testing as tm class TestDataFrameShift: def test_shift(self, datetime_frame, int_frame): # naive shift shiftedFrame = datetime_frame.shift(5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) shiftedFrame = datetime_frame.shift(-5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(-5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 unshifted = datetime_frame.shift(0) tm.assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) assert len(shiftedFrame) == len(datetime_frame) shiftedFrame2 = datetime_frame.shift(5, freq="B") tm.assert_frame_equal(shiftedFrame, shiftedFrame2) d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) tm.assert_series_equal( datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) # shift int frame int_shifted = int_frame.shift(1) # noqa # Shifting with PeriodIndex ps = tm.makePeriodFrame() shifted = ps.shift(1) unshifted = shifted.shift(-1) tm.assert_index_equal(shifted.index, ps.index) tm.assert_index_equal(unshifted.index, ps.index) tm.assert_numpy_array_equal( unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values ) shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, offsets.BDay()) tm.assert_frame_equal(shifted2, shifted3) tm.assert_frame_equal(ps, shifted2.shift(-1, "B")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): ps.shift(freq="D") # shift other axis # GH#6371 df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis=1) tm.assert_frame_equal(result, expected) # shift named axis df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis="columns") tm.assert_frame_equal(result, expected) def test_shift_bool(self): df = DataFrame({"high": [True, False], "low": [False, False]}) rs = df.shift(1) xp = DataFrame( np.array([[np.nan, np.nan], [True, False]], dtype=object), columns=["high", "low"], ) tm.assert_frame_equal(rs, xp) def test_shift_categorical(self): # GH#9416 s1 = pd.Series(["a", "b", "c"], dtype="category") s2 = pd.Series(["A", "B", "C"], dtype="category") df = DataFrame({"one": s1, "two": s2}) rs = df.shift(1) xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) tm.assert_frame_equal(rs, xp) def test_shift_fill_value(self): # GH#24128 df = DataFrame( [1, 2, 3, 4, 5], index=date_range("1/1/2000", periods=5, freq="H") ) exp = DataFrame( [0, 1, 2, 3, 4], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(1, fill_value=0) tm.assert_frame_equal(result, exp) exp = DataFrame( [0, 0, 1, 2, 3], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(2, fill_value=0) tm.assert_frame_equal(result, exp) def test_shift_empty(self): # Regression test for GH#8019 df = DataFrame({"foo": []}) rs = df.shift(-1) tm.assert_frame_equal(df, rs) def test_shift_duplicate_columns(self): # GH#9092; verify that position-based shifting works # in the presence of duplicate columns column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]] data = np.random.randn(20, 5) shifted = [] for columns in column_lists: df = pd.DataFrame(data.copy(), columns=columns) for s in range(5): df.iloc[:, s] = df.iloc[:, s].shift(s + 1) df.columns = range(5) shifted.append(df) # sanity check the base case nulls = shifted[0].isna().sum() tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) # check all answers are the same tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) def test_shift_axis1_multiple_blocks(self): # GH#35488 df1 = pd.DataFrame(np.random.randint(1000, size=(5, 3))) df2 = pd.DataFrame(np.random.randint(1000, size=(5, 2))) df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(2, axis=1) expected = df3.take([-1, -1, 0, 1, 2], axis=1) expected.iloc[:, :2] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) # Case with periods < 0 # rebuild df3 because `take` call above consolidated df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(-2, axis=1) expected = df3.take([2, 3, 4, -1, -1], axis=1) expected.iloc[:, -2:] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): # TODO: remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.tshift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.tshift(freq="M") # DatetimeIndex shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.tshift(1) expected = datetime_frame.tshift(1) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() def test_tshift_deprecated(self, datetime_frame): # GH#11631 with tm.assert_produces_warning(FutureWarning): datetime_frame.tshift() def test_period_index_frame_shift_with_freq(self): ps = tm.makePeriodFrame() shifted = ps.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, ps) shifted2 = ps.shift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.shift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) def test_datetime_frame_shift_with_freq(self, datetime_frame): shifted = datetime_frame.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.shift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.shift(1, freq="infer") expected = datetime_frame.shift(1, freq="infer") expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, inferred_ts) def test_period_index_frame_shift_with_freq_error(self): ps = tm.makePeriodFrame() msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.shift(freq="M") def test_datetime_frame_shift_with_freq_error(self, datetime_frame): no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.shift(freq="infer") def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) df = ser.to_frame() with tm.assert_produces_warning(FutureWarning): result = df.shift(1, fill_value=0) expected = pd.Series([pd.Timestamp(0), ser[0]]).to_frame() tm.assert_frame_equal(result, expected) # axis = 1 df2 = pd.DataFrame({"A": ser, "B": ser}) df2._consolidate_inplace() with tm.assert_produces_warning(FutureWarning): result = df2.shift(1, axis=1, fill_value=0) expected = pd.DataFrame( {"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]} ) tm.assert_frame_equal(result, expected)
rs2/pandas
pandas/tests/frame/methods/test_shift.py
pandas/core/array_algos/masked_reductions.py
import numpy as np import pytest import pandas as pd from pandas.core.internals import ObjectBlock from .base import BaseExtensionTests class BaseCastingTests(BaseExtensionTests): """Casting to and from ExtensionDtypes""" def test_astype_object_series(self, all_data): ser = pd.Series(all_data, name="A") result = ser.astype(object) assert isinstance(result._mgr.blocks[0], ObjectBlock) def test_astype_object_frame(self, all_data): df = pd.DataFrame({"A": all_data}) result = df.astype(object) blk = result._data.blocks[0] assert isinstance(blk, ObjectBlock), type(blk) # FIXME: these currently fail; dont leave commented-out # check that we can compare the dtypes # cmp = result.dtypes.equals(df.dtypes) # assert not cmp.any() def test_tolist(self, data): result = pd.Series(data).tolist() expected = list(data) assert result == expected def test_astype_str(self, data): result = pd.Series(data[:5]).astype(str) expected = pd.Series([str(x) for x in data[:5]], dtype=str) self.assert_series_equal(result, expected) def test_astype_string(self, data): # GH-33465 result = pd.Series(data[:5]).astype("string") expected = pd.Series([str(x) for x in data[:5]], dtype="string") self.assert_series_equal(result, expected) def test_to_numpy(self, data): expected = np.asarray(data) result = data.to_numpy() self.assert_equal(result, expected) result = pd.Series(data).to_numpy() self.assert_equal(result, expected) def test_astype_empty_dataframe(self, dtype): # https://github.com/pandas-dev/pandas/issues/33113 df = pd.DataFrame() result = df.astype(dtype) self.assert_frame_equal(result, df) @pytest.mark.parametrize("copy", [True, False]) def test_astype_own_type(self, data, copy): # ensure that astype returns the original object for equal dtype and copy=False # https://github.com/pandas-dev/pandas/issues/28488 result = data.astype(data.dtype, copy=copy) assert (result is data) is (not copy) self.assert_extension_array_equal(result, data)
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Series, date_range, offsets import pandas._testing as tm class TestDataFrameShift: def test_shift(self, datetime_frame, int_frame): # naive shift shiftedFrame = datetime_frame.shift(5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) shiftedFrame = datetime_frame.shift(-5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(-5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 unshifted = datetime_frame.shift(0) tm.assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) assert len(shiftedFrame) == len(datetime_frame) shiftedFrame2 = datetime_frame.shift(5, freq="B") tm.assert_frame_equal(shiftedFrame, shiftedFrame2) d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) tm.assert_series_equal( datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) # shift int frame int_shifted = int_frame.shift(1) # noqa # Shifting with PeriodIndex ps = tm.makePeriodFrame() shifted = ps.shift(1) unshifted = shifted.shift(-1) tm.assert_index_equal(shifted.index, ps.index) tm.assert_index_equal(unshifted.index, ps.index) tm.assert_numpy_array_equal( unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values ) shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, offsets.BDay()) tm.assert_frame_equal(shifted2, shifted3) tm.assert_frame_equal(ps, shifted2.shift(-1, "B")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): ps.shift(freq="D") # shift other axis # GH#6371 df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis=1) tm.assert_frame_equal(result, expected) # shift named axis df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis="columns") tm.assert_frame_equal(result, expected) def test_shift_bool(self): df = DataFrame({"high": [True, False], "low": [False, False]}) rs = df.shift(1) xp = DataFrame( np.array([[np.nan, np.nan], [True, False]], dtype=object), columns=["high", "low"], ) tm.assert_frame_equal(rs, xp) def test_shift_categorical(self): # GH#9416 s1 = pd.Series(["a", "b", "c"], dtype="category") s2 = pd.Series(["A", "B", "C"], dtype="category") df = DataFrame({"one": s1, "two": s2}) rs = df.shift(1) xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) tm.assert_frame_equal(rs, xp) def test_shift_fill_value(self): # GH#24128 df = DataFrame( [1, 2, 3, 4, 5], index=date_range("1/1/2000", periods=5, freq="H") ) exp = DataFrame( [0, 1, 2, 3, 4], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(1, fill_value=0) tm.assert_frame_equal(result, exp) exp = DataFrame( [0, 0, 1, 2, 3], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(2, fill_value=0) tm.assert_frame_equal(result, exp) def test_shift_empty(self): # Regression test for GH#8019 df = DataFrame({"foo": []}) rs = df.shift(-1) tm.assert_frame_equal(df, rs) def test_shift_duplicate_columns(self): # GH#9092; verify that position-based shifting works # in the presence of duplicate columns column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]] data = np.random.randn(20, 5) shifted = [] for columns in column_lists: df = pd.DataFrame(data.copy(), columns=columns) for s in range(5): df.iloc[:, s] = df.iloc[:, s].shift(s + 1) df.columns = range(5) shifted.append(df) # sanity check the base case nulls = shifted[0].isna().sum() tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) # check all answers are the same tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) def test_shift_axis1_multiple_blocks(self): # GH#35488 df1 = pd.DataFrame(np.random.randint(1000, size=(5, 3))) df2 = pd.DataFrame(np.random.randint(1000, size=(5, 2))) df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(2, axis=1) expected = df3.take([-1, -1, 0, 1, 2], axis=1) expected.iloc[:, :2] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) # Case with periods < 0 # rebuild df3 because `take` call above consolidated df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(-2, axis=1) expected = df3.take([2, 3, 4, -1, -1], axis=1) expected.iloc[:, -2:] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): # TODO: remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.tshift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.tshift(freq="M") # DatetimeIndex shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.tshift(1) expected = datetime_frame.tshift(1) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() def test_tshift_deprecated(self, datetime_frame): # GH#11631 with tm.assert_produces_warning(FutureWarning): datetime_frame.tshift() def test_period_index_frame_shift_with_freq(self): ps = tm.makePeriodFrame() shifted = ps.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, ps) shifted2 = ps.shift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.shift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) def test_datetime_frame_shift_with_freq(self, datetime_frame): shifted = datetime_frame.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.shift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.shift(1, freq="infer") expected = datetime_frame.shift(1, freq="infer") expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, inferred_ts) def test_period_index_frame_shift_with_freq_error(self): ps = tm.makePeriodFrame() msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.shift(freq="M") def test_datetime_frame_shift_with_freq_error(self, datetime_frame): no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.shift(freq="infer") def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) df = ser.to_frame() with tm.assert_produces_warning(FutureWarning): result = df.shift(1, fill_value=0) expected = pd.Series([pd.Timestamp(0), ser[0]]).to_frame() tm.assert_frame_equal(result, expected) # axis = 1 df2 = pd.DataFrame({"A": ser, "B": ser}) df2._consolidate_inplace() with tm.assert_produces_warning(FutureWarning): result = df2.shift(1, axis=1, fill_value=0) expected = pd.DataFrame( {"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]} ) tm.assert_frame_equal(result, expected)
rs2/pandas
pandas/tests/frame/methods/test_shift.py
pandas/tests/extension/base/casting.py
""" Pyperclip A cross-platform clipboard module for Python, with copy & paste functions for plain text. By Al Sweigart al@inventwithpython.com BSD License Usage: import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste() if not pyperclip.is_available(): print("Copy functionality unavailable!") On Windows, no additional modules are needed. On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli commands. (These commands should come with OS X.). On Linux, install xclip or xsel via package manager. For example, in Debian: sudo apt-get install xclip sudo apt-get install xsel Otherwise on Linux, you will need the PyQt5 modules installed. This module does not work with PyGObject yet. Cygwin is currently not supported. Security Note: This module runs programs with these names: - which - where - pbcopy - pbpaste - xclip - xsel - klipper - qdbus A malicious user could rename or add programs with these names, tricking Pyperclip into running them with whatever permissions the Python process has. """ __version__ = "1.7.0" import contextlib import ctypes from ctypes import c_size_t, c_wchar, c_wchar_p, get_errno, sizeof import os import platform import subprocess import time import warnings # `import PyQt4` sys.exit()s if DISPLAY is not in the environment. # Thus, we need to detect the presence of $DISPLAY manually # and not load PyQt4 if it is absent. HAS_DISPLAY = os.getenv("DISPLAY", False) EXCEPT_MSG = """ Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error """ ENCODING = "utf-8" # The "which" unix command finds where a command is. if platform.system() == "Windows": WHICH_CMD = "where" else: WHICH_CMD = "which" def _executable_exists(name): return ( subprocess.call( [WHICH_CMD, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) == 0 ) # Exceptions class PyperclipException(RuntimeError): pass class PyperclipWindowsException(PyperclipException): def __init__(self, message): message += f" ({ctypes.WinError()})" super().__init__(message) def _stringifyText(text) -> str: acceptedTypes = (str, int, float, bool) if not isinstance(text, acceptedTypes): raise PyperclipException( f"only str, int, float, and bool values " f"can be copied to the clipboard, not {type(text).__name__}" ) return str(text) def init_osx_pbcopy_clipboard(): def copy_osx_pbcopy(text): text = _stringifyText(text) # Converts non-str values to str. p = subprocess.Popen(["pbcopy", "w"], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_osx_pbcopy(): p = subprocess.Popen(["pbpaste", "r"], stdout=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() return stdout.decode(ENCODING) return copy_osx_pbcopy, paste_osx_pbcopy def init_osx_pyobjc_clipboard(): def copy_osx_pyobjc(text): """Copy string argument to clipboard""" text = _stringifyText(text) # Converts non-str values to str. newStr = Foundation.NSString.stringWithString_(text).nsstring() newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding) board = AppKit.NSPasteboard.generalPasteboard() board.declareTypes_owner_([AppKit.NSStringPboardType], None) board.setData_forType_(newData, AppKit.NSStringPboardType) def paste_osx_pyobjc(): """Returns contents of clipboard""" board = AppKit.NSPasteboard.generalPasteboard() content = board.stringForType_(AppKit.NSStringPboardType) return content return copy_osx_pyobjc, paste_osx_pyobjc def init_qt_clipboard(): global QApplication # $DISPLAY should exist # Try to import from qtpy, but if that fails try PyQt5 then PyQt4 try: from qtpy.QtWidgets import QApplication except ImportError: try: from PyQt5.QtWidgets import QApplication except ImportError: from PyQt4.QtGui import QApplication app = QApplication.instance() if app is None: app = QApplication([]) def copy_qt(text): text = _stringifyText(text) # Converts non-str values to str. cb = app.clipboard() cb.setText(text) def paste_qt() -> str: cb = app.clipboard() return str(cb.text()) return copy_qt, paste_qt def init_xclip_clipboard(): DEFAULT_SELECTION = "c" PRIMARY_SELECTION = "p" def copy_xclip(text, primary=False): text = _stringifyText(text) # Converts non-str values to str. selection = DEFAULT_SELECTION if primary: selection = PRIMARY_SELECTION p = subprocess.Popen( ["xclip", "-selection", selection], stdin=subprocess.PIPE, close_fds=True ) p.communicate(input=text.encode(ENCODING)) def paste_xclip(primary=False): selection = DEFAULT_SELECTION if primary: selection = PRIMARY_SELECTION p = subprocess.Popen( ["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, ) stdout, stderr = p.communicate() # Intentionally ignore extraneous output on stderr when clipboard is empty return stdout.decode(ENCODING) return copy_xclip, paste_xclip def init_xsel_clipboard(): DEFAULT_SELECTION = "-b" PRIMARY_SELECTION = "-p" def copy_xsel(text, primary=False): text = _stringifyText(text) # Converts non-str values to str. selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION p = subprocess.Popen( ["xsel", selection_flag, "-i"], stdin=subprocess.PIPE, close_fds=True ) p.communicate(input=text.encode(ENCODING)) def paste_xsel(primary=False): selection_flag = DEFAULT_SELECTION if primary: selection_flag = PRIMARY_SELECTION p = subprocess.Popen( ["xsel", selection_flag, "-o"], stdout=subprocess.PIPE, close_fds=True ) stdout, stderr = p.communicate() return stdout.decode(ENCODING) return copy_xsel, paste_xsel def init_klipper_clipboard(): def copy_klipper(text): text = _stringifyText(text) # Converts non-str values to str. p = subprocess.Popen( [ "qdbus", "org.kde.klipper", "/klipper", "setClipboardContents", text.encode(ENCODING), ], stdin=subprocess.PIPE, close_fds=True, ) p.communicate(input=None) def paste_klipper(): p = subprocess.Popen( ["qdbus", "org.kde.klipper", "/klipper", "getClipboardContents"], stdout=subprocess.PIPE, close_fds=True, ) stdout, stderr = p.communicate() # Workaround for https://bugs.kde.org/show_bug.cgi?id=342874 # TODO: https://github.com/asweigart/pyperclip/issues/43 clipboardContents = stdout.decode(ENCODING) # even if blank, Klipper will append a newline at the end assert len(clipboardContents) > 0 # make sure that newline is there assert clipboardContents.endswith("\n") if clipboardContents.endswith("\n"): clipboardContents = clipboardContents[:-1] return clipboardContents return copy_klipper, paste_klipper def init_dev_clipboard_clipboard(): def copy_dev_clipboard(text): text = _stringifyText(text) # Converts non-str values to str. if text == "": warnings.warn( "Pyperclip cannot copy a blank string to the clipboard on Cygwin." "This is effectively a no-op." ) if "\r" in text: warnings.warn("Pyperclip cannot handle \\r characters on Cygwin.") with open("/dev/clipboard", "wt") as fo: fo.write(text) def paste_dev_clipboard() -> str: with open("/dev/clipboard") as fo: content = fo.read() return content return copy_dev_clipboard, paste_dev_clipboard def init_no_clipboard(): class ClipboardUnavailable: def __call__(self, *args, **kwargs): raise PyperclipException(EXCEPT_MSG) def __bool__(self) -> bool: return False return ClipboardUnavailable(), ClipboardUnavailable() # Windows-related clipboard functions: class CheckedCall: def __init__(self, f): super().__setattr__("f", f) def __call__(self, *args): ret = self.f(*args) if not ret and get_errno(): raise PyperclipWindowsException("Error calling " + self.f.__name__) return ret def __setattr__(self, key, value): setattr(self.f, key, value) def init_windows_clipboard(): global HGLOBAL, LPVOID, DWORD, LPCSTR, INT global HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE from ctypes.wintypes import ( BOOL, DWORD, HANDLE, HGLOBAL, HINSTANCE, HMENU, HWND, INT, LPCSTR, LPVOID, UINT, ) windll = ctypes.windll msvcrt = ctypes.CDLL("msvcrt") safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA) safeCreateWindowExA.argtypes = [ DWORD, LPCSTR, LPCSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID, ] safeCreateWindowExA.restype = HWND safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow) safeDestroyWindow.argtypes = [HWND] safeDestroyWindow.restype = BOOL OpenClipboard = windll.user32.OpenClipboard OpenClipboard.argtypes = [HWND] OpenClipboard.restype = BOOL safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard) safeCloseClipboard.argtypes = [] safeCloseClipboard.restype = BOOL safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard) safeEmptyClipboard.argtypes = [] safeEmptyClipboard.restype = BOOL safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData) safeGetClipboardData.argtypes = [UINT] safeGetClipboardData.restype = HANDLE safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData) safeSetClipboardData.argtypes = [UINT, HANDLE] safeSetClipboardData.restype = HANDLE safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc) safeGlobalAlloc.argtypes = [UINT, c_size_t] safeGlobalAlloc.restype = HGLOBAL safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock) safeGlobalLock.argtypes = [HGLOBAL] safeGlobalLock.restype = LPVOID safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock) safeGlobalUnlock.argtypes = [HGLOBAL] safeGlobalUnlock.restype = BOOL wcslen = CheckedCall(msvcrt.wcslen) wcslen.argtypes = [c_wchar_p] wcslen.restype = UINT GMEM_MOVEABLE = 0x0002 CF_UNICODETEXT = 13 @contextlib.contextmanager def window(): """ Context that provides a valid Windows hwnd. """ # we really just need the hwnd, so setting "STATIC" # as predefined lpClass is just fine. hwnd = safeCreateWindowExA( 0, b"STATIC", None, 0, 0, 0, 0, 0, None, None, None, None ) try: yield hwnd finally: safeDestroyWindow(hwnd) @contextlib.contextmanager def clipboard(hwnd): """ Context manager that opens the clipboard and prevents other applications from modifying the clipboard content. """ # We may not get the clipboard handle immediately because # some other application is accessing it (?) # We try for at least 500ms to get the clipboard. t = time.time() + 0.5 success = False while time.time() < t: success = OpenClipboard(hwnd) if success: break time.sleep(0.01) if not success: raise PyperclipWindowsException("Error calling OpenClipboard") try: yield finally: safeCloseClipboard() def copy_windows(text): # This function is heavily based on # http://msdn.com/ms649016#_win32_Copying_Information_to_the_Clipboard text = _stringifyText(text) # Converts non-str values to str. with window() as hwnd: # http://msdn.com/ms649048 # If an application calls OpenClipboard with hwnd set to NULL, # EmptyClipboard sets the clipboard owner to NULL; # this causes SetClipboardData to fail. # => We need a valid hwnd to copy something. with clipboard(hwnd): safeEmptyClipboard() if text: # http://msdn.com/ms649051 # If the hMem parameter identifies a memory object, # the object must have been allocated using the # function with the GMEM_MOVEABLE flag. count = wcslen(text) + 1 handle = safeGlobalAlloc(GMEM_MOVEABLE, count * sizeof(c_wchar)) locked_handle = safeGlobalLock(handle) ctypes.memmove( c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar), ) safeGlobalUnlock(handle) safeSetClipboardData(CF_UNICODETEXT, handle) def paste_windows(): with clipboard(None): handle = safeGetClipboardData(CF_UNICODETEXT) if not handle: # GetClipboardData may return NULL with errno == NO_ERROR # if the clipboard is empty. # (Also, it may return a handle to an empty buffer, # but technically that's not empty) return "" return c_wchar_p(handle).value return copy_windows, paste_windows def init_wsl_clipboard(): def copy_wsl(text): text = _stringifyText(text) # Converts non-str values to str. p = subprocess.Popen(["clip.exe"], stdin=subprocess.PIPE, close_fds=True) p.communicate(input=text.encode(ENCODING)) def paste_wsl(): p = subprocess.Popen( ["powershell.exe", "-command", "Get-Clipboard"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, ) stdout, stderr = p.communicate() # WSL appends "\r\n" to the contents. return stdout[:-2].decode(ENCODING) return copy_wsl, paste_wsl # Automatic detection of clipboard mechanisms # and importing is done in determine_clipboard(): def determine_clipboard(): """ Determine the OS/platform and set the copy() and paste() functions accordingly. """ global Foundation, AppKit, qtpy, PyQt4, PyQt5 # Setup for the CYGWIN platform: if ( "cygwin" in platform.system().lower() ): # Cygwin has a variety of values returned by platform.system(), # such as 'CYGWIN_NT-6.1' # FIXME: pyperclip currently does not support Cygwin, # see https://github.com/asweigart/pyperclip/issues/55 if os.path.exists("/dev/clipboard"): warnings.warn( "Pyperclip's support for Cygwin is not perfect," "see https://github.com/asweigart/pyperclip/issues/55" ) return init_dev_clipboard_clipboard() # Setup for the WINDOWS platform: elif os.name == "nt" or platform.system() == "Windows": return init_windows_clipboard() if platform.system() == "Linux": with open("/proc/version") as f: if "Microsoft" in f.read(): return init_wsl_clipboard() # Setup for the MAC OS X platform: if os.name == "mac" or platform.system() == "Darwin": try: import AppKit import Foundation # check if pyobjc is installed except ImportError: return init_osx_pbcopy_clipboard() else: return init_osx_pyobjc_clipboard() # Setup for the LINUX platform: if HAS_DISPLAY: if _executable_exists("xsel"): return init_xsel_clipboard() if _executable_exists("xclip"): return init_xclip_clipboard() if _executable_exists("klipper") and _executable_exists("qdbus"): return init_klipper_clipboard() try: # qtpy is a small abstraction layer that lets you write applications # using a single api call to either PyQt or PySide. # https://pypi.python.org/project/QtPy import qtpy # check if qtpy is installed except ImportError: # If qtpy isn't installed, fall back on importing PyQt4. try: import PyQt5 # check if PyQt5 is installed except ImportError: try: import PyQt4 # check if PyQt4 is installed except ImportError: pass # We want to fail fast for all non-ImportError exceptions. else: return init_qt_clipboard() else: return init_qt_clipboard() else: return init_qt_clipboard() return init_no_clipboard() def set_clipboard(clipboard): """ Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how the copy() and paste() functions interact with the operating system to implement the copy/paste feature. The clipboard parameter must be one of: - pbcopy - pbobjc (default on Mac OS X) - qt - xclip - xsel - klipper - windows (default on Windows) - no (this is what is set when no clipboard mechanism can be found) """ global copy, paste clipboard_types = { "pbcopy": init_osx_pbcopy_clipboard, "pyobjc": init_osx_pyobjc_clipboard, "qt": init_qt_clipboard, # TODO - split this into 'qtpy', 'pyqt4', and 'pyqt5' "xclip": init_xclip_clipboard, "xsel": init_xsel_clipboard, "klipper": init_klipper_clipboard, "windows": init_windows_clipboard, "no": init_no_clipboard, } if clipboard not in clipboard_types: allowed_clipboard_types = [repr(_) for _ in clipboard_types.keys()] raise ValueError( f"Argument must be one of {', '.join(allowed_clipboard_types)}" ) # Sets pyperclip's copy() and paste() functions: copy, paste = clipboard_types[clipboard]() def lazy_load_stub_copy(text): """ A stub function for copy(), which will load the real copy() function when called so that the real copy() function is used for later calls. This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. """ global copy, paste copy, paste = determine_clipboard() return copy(text) def lazy_load_stub_paste(): """ A stub function for paste(), which will load the real paste() function when called so that the real paste() function is used for later calls. This allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. This could be a problem if it selects, say, the memory-heavy PyQt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. The lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. Or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. """ global copy, paste copy, paste = determine_clipboard() return paste() def is_available() -> bool: return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste # Initially, copy() and paste() are set to lazy loading wrappers which will # set `copy` and `paste` to real functions the first time they're used, unless # set_clipboard() or determine_clipboard() is called first. copy, paste = lazy_load_stub_copy, lazy_load_stub_paste __all__ = ["copy", "paste", "set_clipboard", "determine_clipboard"] # pandas aliases clipboard_get = paste clipboard_set = copy
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Series, date_range, offsets import pandas._testing as tm class TestDataFrameShift: def test_shift(self, datetime_frame, int_frame): # naive shift shiftedFrame = datetime_frame.shift(5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) shiftedFrame = datetime_frame.shift(-5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(-5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 unshifted = datetime_frame.shift(0) tm.assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) assert len(shiftedFrame) == len(datetime_frame) shiftedFrame2 = datetime_frame.shift(5, freq="B") tm.assert_frame_equal(shiftedFrame, shiftedFrame2) d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) tm.assert_series_equal( datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) # shift int frame int_shifted = int_frame.shift(1) # noqa # Shifting with PeriodIndex ps = tm.makePeriodFrame() shifted = ps.shift(1) unshifted = shifted.shift(-1) tm.assert_index_equal(shifted.index, ps.index) tm.assert_index_equal(unshifted.index, ps.index) tm.assert_numpy_array_equal( unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values ) shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, offsets.BDay()) tm.assert_frame_equal(shifted2, shifted3) tm.assert_frame_equal(ps, shifted2.shift(-1, "B")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): ps.shift(freq="D") # shift other axis # GH#6371 df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis=1) tm.assert_frame_equal(result, expected) # shift named axis df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis="columns") tm.assert_frame_equal(result, expected) def test_shift_bool(self): df = DataFrame({"high": [True, False], "low": [False, False]}) rs = df.shift(1) xp = DataFrame( np.array([[np.nan, np.nan], [True, False]], dtype=object), columns=["high", "low"], ) tm.assert_frame_equal(rs, xp) def test_shift_categorical(self): # GH#9416 s1 = pd.Series(["a", "b", "c"], dtype="category") s2 = pd.Series(["A", "B", "C"], dtype="category") df = DataFrame({"one": s1, "two": s2}) rs = df.shift(1) xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) tm.assert_frame_equal(rs, xp) def test_shift_fill_value(self): # GH#24128 df = DataFrame( [1, 2, 3, 4, 5], index=date_range("1/1/2000", periods=5, freq="H") ) exp = DataFrame( [0, 1, 2, 3, 4], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(1, fill_value=0) tm.assert_frame_equal(result, exp) exp = DataFrame( [0, 0, 1, 2, 3], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(2, fill_value=0) tm.assert_frame_equal(result, exp) def test_shift_empty(self): # Regression test for GH#8019 df = DataFrame({"foo": []}) rs = df.shift(-1) tm.assert_frame_equal(df, rs) def test_shift_duplicate_columns(self): # GH#9092; verify that position-based shifting works # in the presence of duplicate columns column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]] data = np.random.randn(20, 5) shifted = [] for columns in column_lists: df = pd.DataFrame(data.copy(), columns=columns) for s in range(5): df.iloc[:, s] = df.iloc[:, s].shift(s + 1) df.columns = range(5) shifted.append(df) # sanity check the base case nulls = shifted[0].isna().sum() tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) # check all answers are the same tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) def test_shift_axis1_multiple_blocks(self): # GH#35488 df1 = pd.DataFrame(np.random.randint(1000, size=(5, 3))) df2 = pd.DataFrame(np.random.randint(1000, size=(5, 2))) df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(2, axis=1) expected = df3.take([-1, -1, 0, 1, 2], axis=1) expected.iloc[:, :2] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) # Case with periods < 0 # rebuild df3 because `take` call above consolidated df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(-2, axis=1) expected = df3.take([2, 3, 4, -1, -1], axis=1) expected.iloc[:, -2:] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): # TODO: remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.tshift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.tshift(freq="M") # DatetimeIndex shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.tshift(1) expected = datetime_frame.tshift(1) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() def test_tshift_deprecated(self, datetime_frame): # GH#11631 with tm.assert_produces_warning(FutureWarning): datetime_frame.tshift() def test_period_index_frame_shift_with_freq(self): ps = tm.makePeriodFrame() shifted = ps.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, ps) shifted2 = ps.shift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.shift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) def test_datetime_frame_shift_with_freq(self, datetime_frame): shifted = datetime_frame.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.shift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.shift(1, freq="infer") expected = datetime_frame.shift(1, freq="infer") expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, inferred_ts) def test_period_index_frame_shift_with_freq_error(self): ps = tm.makePeriodFrame() msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.shift(freq="M") def test_datetime_frame_shift_with_freq_error(self, datetime_frame): no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.shift(freq="infer") def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) df = ser.to_frame() with tm.assert_produces_warning(FutureWarning): result = df.shift(1, fill_value=0) expected = pd.Series([pd.Timestamp(0), ser[0]]).to_frame() tm.assert_frame_equal(result, expected) # axis = 1 df2 = pd.DataFrame({"A": ser, "B": ser}) df2._consolidate_inplace() with tm.assert_produces_warning(FutureWarning): result = df2.shift(1, axis=1, fill_value=0) expected = pd.DataFrame( {"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]} ) tm.assert_frame_equal(result, expected)
rs2/pandas
pandas/tests/frame/methods/test_shift.py
pandas/io/clipboard/__init__.py
""" miscellaneous sorting / groupby utilities """ from collections import defaultdict from typing import ( TYPE_CHECKING, Callable, DefaultDict, Iterable, List, Optional, Tuple, Union, ) import numpy as np from pandas._libs import algos, hashtable, lib from pandas._libs.hashtable import unique_label_indices from pandas._typing import IndexKeyFunc from pandas.core.dtypes.common import ( ensure_int64, ensure_platform_int, is_extension_array_dtype, ) from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import isna import pandas.core.algorithms as algorithms from pandas.core.construction import extract_array if TYPE_CHECKING: from pandas.core.indexes.base import Index _INT64_MAX = np.iinfo(np.int64).max def get_indexer_indexer( target: "Index", level: Union[str, int, List[str], List[int]], ascending: bool, kind: str, na_position: str, sort_remaining: bool, key: IndexKeyFunc, ) -> Optional[np.array]: """ Helper method that return the indexer according to input parameters for the sort_index method of DataFrame and Series. Parameters ---------- target : Index level : int or level name or list of ints or list of level names ascending : bool or list of bools, default True kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort' na_position : {'first', 'last'}, default 'last' sort_remaining : bool, default True key : callable, optional Returns ------- Optional[ndarray] The indexer for the new index. """ target = ensure_key_mapped(target, key, levels=level) target = target._sort_levels_monotonic() if level is not None: _, indexer = target.sortlevel( level, ascending=ascending, sort_remaining=sort_remaining ) elif isinstance(target, ABCMultiIndex): indexer = lexsort_indexer( target._get_codes_for_sorting(), orders=ascending, na_position=na_position ) else: # Check monotonic-ness before sort an index (GH 11080) if (ascending and target.is_monotonic_increasing) or ( not ascending and target.is_monotonic_decreasing ): return None indexer = nargsort( target, kind=kind, ascending=ascending, na_position=na_position ) return indexer def get_group_index(labels, shape, sort: bool, xnull: bool): """ For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label combinations, *as long as* this space fits within int64 bounds; otherwise, though group indices identify unique combinations of labels, they cannot be deconstructed. - If `sort`, rank of returned ids preserve lexical ranks of labels. i.e. returned id's can be used to do lexical sort on labels; - If `xnull` nulls (-1 labels) are passed through. Parameters ---------- labels : sequence of arrays Integers identifying levels at each location shape : sequence of ints Number of unique levels at each location sort : bool If the ranks of returned ids should match lexical ranks of labels xnull : bool If true nulls are excluded. i.e. -1 values in the labels are passed through. Returns ------- An array of type int64 where two elements are equal if their corresponding labels are equal at all location. Notes ----- The length of `labels` and `shape` must be identical. """ def _int64_cut_off(shape) -> int: acc = 1 for i, mul in enumerate(shape): acc *= int(mul) if not acc < _INT64_MAX: return i return len(shape) def maybe_lift(lab, size): # promote nan values (assigned -1 label in lab array) # so that all output values are non-negative return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) labels = map(ensure_int64, labels) if not xnull: labels, shape = map(list, zip(*map(maybe_lift, labels, shape))) labels = list(labels) shape = list(shape) # Iteratively process all the labels in chunks sized so less # than _INT64_MAX unique int ids will be required for each chunk while True: # how many levels can be done without overflow: nlev = _int64_cut_off(shape) # compute flat ids for the first `nlev` levels stride = np.prod(shape[1:nlev], dtype="i8") out = stride * labels[0].astype("i8", subok=False, copy=False) for i in range(1, nlev): if shape[i] == 0: stride = 0 else: stride //= shape[i] out += labels[i] * stride if xnull: # exclude nulls mask = labels[0] == -1 for lab in labels[1:nlev]: mask |= lab == -1 out[mask] = -1 if nlev == len(shape): # all levels done! break # compress what has been done so far in order to avoid overflow # to retain lexical ranks, obs_ids should be sorted comp_ids, obs_ids = compress_group_index(out, sort=sort) labels = [comp_ids] + labels[nlev:] shape = [len(obs_ids)] + shape[nlev:] return out def get_compressed_ids(labels, sizes): """ Group_index is offsets into cartesian product of all possible labels. This space can be huge, so this function compresses it, by computing offsets (comp_ids) into the list of unique labels (obs_group_ids). Parameters ---------- labels : list of label arrays sizes : list of size of the levels Returns ------- tuple of (comp_ids, obs_group_ids) """ ids = get_group_index(labels, sizes, sort=True, xnull=False) return compress_group_index(ids, sort=True) def is_int64_overflow_possible(shape) -> bool: the_prod = 1 for x in shape: the_prod *= int(x) return the_prod >= _INT64_MAX def decons_group_index(comp_labels, shape): # reconstruct labels if is_int64_overflow_possible(shape): # at some point group indices are factorized, # and may not be deconstructed here! wrong path! raise ValueError("cannot deconstruct factorized group indices!") label_list = [] factor = 1 y = 0 x = comp_labels for i in reversed(range(len(shape))): labels = (x - y) % (factor * shape[i]) // factor np.putmask(labels, comp_labels < 0, -1) label_list.append(labels) y = labels * factor factor *= shape[i] return label_list[::-1] def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull: bool): """ Reconstruct labels from observed group ids. Parameters ---------- xnull : bool If nulls are excluded; i.e. -1 labels are passed through. """ if not xnull: lift = np.fromiter(((a == -1).any() for a in labels), dtype="i8") shape = np.asarray(shape, dtype="i8") + lift if not is_int64_overflow_possible(shape): # obs ids are deconstructable! take the fast route! out = decons_group_index(obs_ids, shape) return out if xnull or not lift.any() else [x - y for x, y in zip(out, lift)] i = unique_label_indices(comp_ids) i8copy = lambda a: a.astype("i8", subok=False, copy=True) return [i8copy(lab[i]) for lab in labels] def indexer_from_factorized(labels, shape, compress: bool = True): ids = get_group_index(labels, shape, sort=True, xnull=False) if not compress: ngroups = (ids.size and ids.max()) + 1 else: ids, obs = compress_group_index(ids, sort=True) ngroups = len(obs) return get_group_index_sorter(ids, ngroups) def lexsort_indexer( keys, orders=None, na_position: str = "last", key: Optional[Callable] = None ): """ Performs lexical sorting on a set of keys Parameters ---------- keys : sequence of arrays Sequence of ndarrays to be sorted by the indexer orders : boolean or list of booleans, optional Determines the sorting order for each element in keys. If a list, it must be the same length as keys. This determines whether the corresponding element in keys should be sorted in ascending (True) or descending (False) order. if bool, applied to all elements as above. if None, defaults to True. na_position : {'first', 'last'}, default 'last' Determines placement of NA elements in the sorted list ("last" or "first") key : Callable, optional Callable key function applied to every element in keys before sorting .. versionadded:: 1.0.0 """ from pandas.core.arrays import Categorical labels = [] shape = [] if isinstance(orders, bool): orders = [orders] * len(keys) elif orders is None: orders = [True] * len(keys) keys = [ensure_key_mapped(k, key) for k in keys] for k, order in zip(keys, orders): cat = Categorical(k, ordered=True) if na_position not in ["last", "first"]: raise ValueError(f"invalid na_position: {na_position}") n = len(cat.categories) codes = cat.codes.copy() mask = cat.codes == -1 if order: # ascending if na_position == "last": codes = np.where(mask, n, codes) elif na_position == "first": codes += 1 else: # not order means descending if na_position == "last": codes = np.where(mask, n, n - codes - 1) elif na_position == "first": codes = np.where(mask, 0, n - codes) if mask.any(): n += 1 shape.append(n) labels.append(codes) return indexer_from_factorized(labels, shape) def nargsort( items, kind: str = "quicksort", ascending: bool = True, na_position: str = "last", key: Optional[Callable] = None, ): """ Intended to be a drop-in replacement for np.argsort which handles NaNs. Adds ascending, na_position, and key parameters. (GH #6399, #5231, #27237) Parameters ---------- kind : str, default 'quicksort' ascending : bool, default True na_position : {'first', 'last'}, default 'last' key : Optional[Callable], default None """ if key is not None: items = ensure_key_mapped(items, key) return nargsort( items, kind=kind, ascending=ascending, na_position=na_position, key=None ) items = extract_array(items) mask = np.asarray(isna(items)) if is_extension_array_dtype(items): items = items._values_for_argsort() else: items = np.asanyarray(items) idx = np.arange(len(items)) non_nans = items[~mask] non_nan_idx = idx[~mask] nan_idx = np.nonzero(mask)[0] if not ascending: non_nans = non_nans[::-1] non_nan_idx = non_nan_idx[::-1] indexer = non_nan_idx[non_nans.argsort(kind=kind)] if not ascending: indexer = indexer[::-1] # Finally, place the NaNs at the end or the beginning according to # na_position if na_position == "last": indexer = np.concatenate([indexer, nan_idx]) elif na_position == "first": indexer = np.concatenate([nan_idx, indexer]) else: raise ValueError(f"invalid na_position: {na_position}") return indexer def nargminmax(values, method: str): """ Implementation of np.argmin/argmax but for ExtensionArray and which handles missing values. Parameters ---------- values : ExtensionArray method : {"argmax", "argmin"} Returns ------- int """ assert method in {"argmax", "argmin"} func = np.argmax if method == "argmax" else np.argmin mask = np.asarray(isna(values)) values = values._values_for_argsort() idx = np.arange(len(values)) non_nans = values[~mask] non_nan_idx = idx[~mask] return non_nan_idx[func(non_nans)] def ensure_key_mapped_multiindex(index, key: Callable, level=None): """ Returns a new MultiIndex in which key has been applied to all levels specified in level (or all levels if level is None). Used for key sorting for MultiIndex. Parameters ---------- index : MultiIndex Index to which to apply the key function on the specified levels. key : Callable Function that takes an Index and returns an Index of the same shape. This key is applied to each level separately. The name of the level can be used to distinguish different levels for application. level : list-like, int or str, default None Level or list of levels to apply the key function to. If None, key function is applied to all levels. Other levels are left unchanged. Returns ------- labels : MultiIndex Resulting MultiIndex with modified levels. """ from pandas.core.indexes.api import MultiIndex if level is not None: if isinstance(level, (str, int)): sort_levels = [level] else: sort_levels = level sort_levels = [index._get_level_number(lev) for lev in sort_levels] else: sort_levels = list(range(index.nlevels)) # satisfies mypy mapped = [ ensure_key_mapped(index._get_level_values(level), key) if level in sort_levels else index._get_level_values(level) for level in range(index.nlevels) ] labels = MultiIndex.from_arrays(mapped) return labels def ensure_key_mapped(values, key: Optional[Callable], levels=None): """ Applies a callable key function to the values function and checks that the resulting value has the same shape. Can be called on Index subclasses, Series, DataFrames, or ndarrays. Parameters ---------- values : Series, DataFrame, Index subclass, or ndarray key : Optional[Callable], key to be called on the values array levels : Optional[List], if values is a MultiIndex, list of levels to apply the key to. """ from pandas.core.indexes.api import Index # noqa:F811 if not key: return values if isinstance(values, ABCMultiIndex): return ensure_key_mapped_multiindex(values, key, level=levels) result = key(values.copy()) if len(result) != len(values): raise ValueError( "User-provided `key` function must not change the shape of the array." ) try: if isinstance( values, Index ): # convert to a new Index subclass, not necessarily the same result = Index(result) else: type_of_values = type(values) result = type_of_values(result) # try to revert to original type otherwise except TypeError: raise TypeError( f"User-provided `key` function returned an invalid type {type(result)} \ which could not be converted to {type(values)}." ) return result def get_flattened_list( comp_ids: np.ndarray, ngroups: int, levels: Iterable["Index"], labels: Iterable[np.ndarray], ) -> List[Tuple]: """Map compressed group id -> key tuple.""" comp_ids = comp_ids.astype(np.int64, copy=False) arrays: DefaultDict[int, List[int]] = defaultdict(list) for labs, level in zip(labels, levels): table = hashtable.Int64HashTable(ngroups) table.map(comp_ids, labs.astype(np.int64, copy=False)) for i in range(ngroups): arrays[i].append(level[table.get_item(i)]) return [tuple(array) for array in arrays.values()] def get_indexer_dict(label_list, keys): """ Returns ------- dict Labels mapped to indexers. """ shape = [len(x) for x in keys] group_index = get_group_index(label_list, shape, sort=True, xnull=True) ngroups = ( ((group_index.size and group_index.max()) + 1) if is_int64_overflow_possible(shape) else np.prod(shape, dtype="i8") ) sorter = get_group_index_sorter(group_index, ngroups) sorted_labels = [lab.take(sorter) for lab in label_list] group_index = group_index.take(sorter) return lib.indices_fast(sorter, group_index, keys, sorted_labels) # ---------------------------------------------------------------------- # sorting levels...cleverly? def get_group_index_sorter(group_index, ngroups: int): """ algos.groupsort_indexer implements `counting sort` and it is at least O(ngroups), where ngroups = prod(shape) shape = map(len, keys) that is, linear in the number of combinations (cartesian product) of unique values of groupby keys. This can be huge when doing multi-key groupby. np.argsort(kind='mergesort') is O(count x log(count)) where count is the length of the data-frame; Both algorithms are `stable` sort and that is necessary for correctness of groupby operations. e.g. consider: df.groupby(key)[col].transform('first') """ count = len(group_index) alpha = 0.0 # taking complexities literally; there may be beta = 1.0 # some room for fine-tuning these parameters do_groupsort = count > 0 and ((alpha + beta * ngroups) < (count * np.log(count))) if do_groupsort: sorter, _ = algos.groupsort_indexer(ensure_int64(group_index), ngroups) return ensure_platform_int(sorter) else: return group_index.argsort(kind="mergesort") def compress_group_index(group_index, sort: bool = True): """ Group_index is offsets into cartesian product of all possible labels. This space can be huge, so this function compresses it, by computing offsets (comp_ids) into the list of unique labels (obs_group_ids). """ size_hint = min(len(group_index), hashtable.SIZE_HINT_LIMIT) table = hashtable.Int64HashTable(size_hint) group_index = ensure_int64(group_index) # note, group labels come out ascending (ie, 1,2,3 etc) comp_ids, obs_group_ids = table.get_labels_groupby(group_index) if sort and len(obs_group_ids) > 0: obs_group_ids, comp_ids = _reorder_by_uniques(obs_group_ids, comp_ids) return comp_ids, obs_group_ids def _reorder_by_uniques(uniques, labels): # sorter is index where elements ought to go sorter = uniques.argsort() # reverse_indexer is where elements came from reverse_indexer = np.empty(len(sorter), dtype=np.int64) reverse_indexer.put(sorter, np.arange(len(sorter))) mask = labels < 0 # move labels to right locations (ie, unsort ascending labels) labels = algorithms.take_nd(reverse_indexer, labels, allow_fill=False) np.putmask(labels, mask, -1) # sort observed ids uniques = algorithms.take_nd(uniques, sorter, allow_fill=False) return uniques, labels
import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, Series, date_range, offsets import pandas._testing as tm class TestDataFrameShift: def test_shift(self, datetime_frame, int_frame): # naive shift shiftedFrame = datetime_frame.shift(5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) shiftedFrame = datetime_frame.shift(-5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(-5) tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 unshifted = datetime_frame.shift(0) tm.assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) assert len(shiftedFrame) == len(datetime_frame) shiftedFrame2 = datetime_frame.shift(5, freq="B") tm.assert_frame_equal(shiftedFrame, shiftedFrame2) d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) tm.assert_series_equal( datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) # shift int frame int_shifted = int_frame.shift(1) # noqa # Shifting with PeriodIndex ps = tm.makePeriodFrame() shifted = ps.shift(1) unshifted = shifted.shift(-1) tm.assert_index_equal(shifted.index, ps.index) tm.assert_index_equal(unshifted.index, ps.index) tm.assert_numpy_array_equal( unshifted.iloc[:, 0].dropna().values, ps.iloc[:-1, 0].values ) shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, offsets.BDay()) tm.assert_frame_equal(shifted2, shifted3) tm.assert_frame_equal(ps, shifted2.shift(-1, "B")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): ps.shift(freq="D") # shift other axis # GH#6371 df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis=1) tm.assert_frame_equal(result, expected) # shift named axis df = DataFrame(np.random.rand(10, 5)) expected = pd.concat( [DataFrame(np.nan, index=df.index, columns=[0]), df.iloc[:, 0:-1]], ignore_index=True, axis=1, ) result = df.shift(1, axis="columns") tm.assert_frame_equal(result, expected) def test_shift_bool(self): df = DataFrame({"high": [True, False], "low": [False, False]}) rs = df.shift(1) xp = DataFrame( np.array([[np.nan, np.nan], [True, False]], dtype=object), columns=["high", "low"], ) tm.assert_frame_equal(rs, xp) def test_shift_categorical(self): # GH#9416 s1 = pd.Series(["a", "b", "c"], dtype="category") s2 = pd.Series(["A", "B", "C"], dtype="category") df = DataFrame({"one": s1, "two": s2}) rs = df.shift(1) xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) tm.assert_frame_equal(rs, xp) def test_shift_fill_value(self): # GH#24128 df = DataFrame( [1, 2, 3, 4, 5], index=date_range("1/1/2000", periods=5, freq="H") ) exp = DataFrame( [0, 1, 2, 3, 4], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(1, fill_value=0) tm.assert_frame_equal(result, exp) exp = DataFrame( [0, 0, 1, 2, 3], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(2, fill_value=0) tm.assert_frame_equal(result, exp) def test_shift_empty(self): # Regression test for GH#8019 df = DataFrame({"foo": []}) rs = df.shift(-1) tm.assert_frame_equal(df, rs) def test_shift_duplicate_columns(self): # GH#9092; verify that position-based shifting works # in the presence of duplicate columns column_lists = [list(range(5)), [1] * 5, [1, 1, 2, 2, 1]] data = np.random.randn(20, 5) shifted = [] for columns in column_lists: df = pd.DataFrame(data.copy(), columns=columns) for s in range(5): df.iloc[:, s] = df.iloc[:, s].shift(s + 1) df.columns = range(5) shifted.append(df) # sanity check the base case nulls = shifted[0].isna().sum() tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) # check all answers are the same tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) def test_shift_axis1_multiple_blocks(self): # GH#35488 df1 = pd.DataFrame(np.random.randint(1000, size=(5, 3))) df2 = pd.DataFrame(np.random.randint(1000, size=(5, 2))) df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(2, axis=1) expected = df3.take([-1, -1, 0, 1, 2], axis=1) expected.iloc[:, :2] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) # Case with periods < 0 # rebuild df3 because `take` call above consolidated df3 = pd.concat([df1, df2], axis=1) assert len(df3._mgr.blocks) == 2 result = df3.shift(-2, axis=1) expected = df3.take([2, 3, 4, -1, -1], axis=1) expected.iloc[:, -2:] = np.nan expected.columns = df3.columns tm.assert_frame_equal(result, expected) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): # TODO: remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.tshift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.tshift(freq="M") # DatetimeIndex shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.tshift(1) expected = datetime_frame.tshift(1) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.tshift(-1) tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() def test_tshift_deprecated(self, datetime_frame): # GH#11631 with tm.assert_produces_warning(FutureWarning): datetime_frame.tshift() def test_period_index_frame_shift_with_freq(self): ps = tm.makePeriodFrame() shifted = ps.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, ps) shifted2 = ps.shift(freq="B") tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.shift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) def test_datetime_frame_shift_with_freq(self, datetime_frame): shifted = datetime_frame.shift(1, freq="infer") unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.shift(freq=datetime_frame.index.freq) tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, Index(np.asarray(datetime_frame.index)), columns=datetime_frame.columns, ) shifted = inferred_ts.shift(1, freq="infer") expected = datetime_frame.shift(1, freq="infer") expected.index = expected.index._with_freq(None) tm.assert_frame_equal(shifted, expected) unshifted = shifted.shift(-1, freq="infer") tm.assert_frame_equal(unshifted, inferred_ts) def test_period_index_frame_shift_with_freq_error(self): ps = tm.makePeriodFrame() msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): ps.shift(freq="M") def test_datetime_frame_shift_with_freq_error(self, datetime_frame): no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.shift(freq="infer") def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) df = ser.to_frame() with tm.assert_produces_warning(FutureWarning): result = df.shift(1, fill_value=0) expected = pd.Series([pd.Timestamp(0), ser[0]]).to_frame() tm.assert_frame_equal(result, expected) # axis = 1 df2 = pd.DataFrame({"A": ser, "B": ser}) df2._consolidate_inplace() with tm.assert_produces_warning(FutureWarning): result = df2.shift(1, axis=1, fill_value=0) expected = pd.DataFrame( {"A": [pd.Timestamp(0), pd.Timestamp(0)], "B": df2["A"]} ) tm.assert_frame_equal(result, expected)
rs2/pandas
pandas/tests/frame/methods/test_shift.py
pandas/core/sorting.py
"""Interfaces with TotalConnect sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities) -> None: """Set up TotalConnect device sensors based on a config entry.""" sensors = [] client_locations = hass.data[DOMAIN][entry.entry_id].locations for location_id, location in client_locations.items(): for zone_id, zone in location.zones.items(): sensors.append(TotalConnectBinarySensor(zone_id, location_id, zone)) async_add_entities(sensors, True) class TotalConnectBinarySensor(BinarySensorEntity): """Represent an TotalConnect zone.""" def __init__(self, zone_id, location_id, zone): """Initialize the TotalConnect status.""" self._zone_id = zone_id self._location_id = location_id self._zone = zone self._name = self._zone.description self._unique_id = f"{location_id} {zone_id}" self._is_on = None self._is_tampered = None self._is_low_battery = None @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the device.""" return self._name def update(self): """Return the state of the device.""" self._is_tampered = self._zone.is_tampered() self._is_low_battery = self._zone.is_low_battery() if self._zone.is_faulted() or self._zone.is_triggered(): self._is_on = True else: self._is_on = False @property def is_on(self): """Return true if the binary sensor is on.""" return self._is_on @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" if self._zone.is_type_security(): return DEVICE_CLASS_DOOR if self._zone.is_type_fire(): return DEVICE_CLASS_SMOKE if self._zone.is_type_carbon_monoxide(): return DEVICE_CLASS_GAS return None @property def device_state_attributes(self): """Return the state attributes.""" attributes = { "zone_id": self._zone_id, "location_id": self._location_id, "low_battery": self._is_low_battery, "tampered": self._is_tampered, } return attributes
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/totalconnect/binary_sensor.py
"""Device tracker for BMW Connected Drive vehicles.""" import logging from homeassistant.util import slugify from . import DOMAIN as BMW_DOMAIN _LOGGER = logging.getLogger(__name__) def setup_scanner(hass, config, see, discovery_info=None): """Set up the BMW tracker.""" accounts = hass.data[BMW_DOMAIN] _LOGGER.debug("Found BMW accounts: %s", ", ".join([a.name for a in accounts])) for account in accounts: for vehicle in account.account.vehicles: tracker = BMWDeviceTracker(see, vehicle) account.add_update_listener(tracker.update) tracker.update() return True class BMWDeviceTracker: """BMW Connected Drive device tracker.""" def __init__(self, see, vehicle): """Initialize the Tracker.""" self._see = see self.vehicle = vehicle def update(self) -> None: """Update the device info. Only update the state in Home Assistant if tracking in the car is enabled. """ dev_id = slugify(self.vehicle.name) if not self.vehicle.state.is_vehicle_tracking_enabled: _LOGGER.debug("Tracking is disabled for vehicle %s", dev_id) return _LOGGER.debug("Updating %s", dev_id) attrs = {"vin": self.vehicle.vin} self._see( dev_id=dev_id, host_name=self.vehicle.name, gps=self.vehicle.state.gps_position, attributes=attrs, icon="mdi:car", )
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/bmw_connected_drive/device_tracker.py
"""Support for HomematicIP Cloud binary sensor.""" import logging from typing import Any, Dict from homematicip.aio.device import ( AsyncAccelerationSensor, AsyncContactInterface, AsyncDevice, AsyncFullFlushContactInterface, AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, AsyncPluggableMainsFailureSurveillance, AsyncPresenceDetectorIndoor, AsyncRotaryHandleSensor, AsyncShutterContact, AsyncShutterContactMagnetic, AsyncSmokeDetector, AsyncTiltVibrationSensor, AsyncWaterSensor, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ) from homematicip.aio.group import AsyncSecurityGroup, AsyncSecurityZoneGroup from homematicip.base.enums import SmokeDetectorAlarmType, WindowState from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_LIGHT, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_MOVING, DEVICE_CLASS_OPENING, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP _LOGGER = logging.getLogger(__name__) ATTR_ACCELERATION_SENSOR_MODE = "acceleration_sensor_mode" ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION = "acceleration_sensor_neutral_position" ATTR_ACCELERATION_SENSOR_SENSITIVITY = "acceleration_sensor_sensitivity" ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE = "acceleration_sensor_trigger_angle" ATTR_INTRUSION_ALARM = "intrusion_alarm" ATTR_MOISTURE_DETECTED = "moisture_detected" ATTR_MOTION_DETECTED = "motion_detected" ATTR_POWER_MAINS_FAILURE = "power_mains_failure" ATTR_PRESENCE_DETECTED = "presence_detected" ATTR_SMOKE_DETECTOR_ALARM = "smoke_detector_alarm" ATTR_TODAY_SUNSHINE_DURATION = "today_sunshine_duration_in_minutes" ATTR_WATER_LEVEL_DETECTED = "water_level_detected" ATTR_WINDOW_STATE = "window_state" GROUP_ATTRIBUTES = { "moistureDetected": ATTR_MOISTURE_DETECTED, "motionDetected": ATTR_MOTION_DETECTED, "powerMainsFailure": ATTR_POWER_MAINS_FAILURE, "presenceDetected": ATTR_PRESENCE_DETECTED, "waterlevelDetected": ATTR_WATER_LEVEL_DETECTED, } SAM_DEVICE_ATTRIBUTES = { "accelerationSensorNeutralPosition": ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION, "accelerationSensorMode": ATTR_ACCELERATION_SENSOR_MODE, "accelerationSensorSensitivity": ATTR_ACCELERATION_SENSOR_SENSITIVITY, "accelerationSensorTriggerAngle": ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE, } async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP Cloud binary sensor from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.devices: if isinstance(device, AsyncAccelerationSensor): entities.append(HomematicipAccelerationSensor(hap, device)) if isinstance(device, AsyncTiltVibrationSensor): entities.append(HomematicipTiltVibrationSensor(hap, device)) if isinstance(device, (AsyncContactInterface, AsyncFullFlushContactInterface)): entities.append(HomematicipContactInterface(hap, device)) if isinstance( device, (AsyncShutterContact, AsyncShutterContactMagnetic), ): entities.append(HomematicipShutterContact(hap, device)) if isinstance(device, AsyncRotaryHandleSensor): entities.append(HomematicipShutterContact(hap, device, True)) if isinstance( device, ( AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, ), ): entities.append(HomematicipMotionDetector(hap, device)) if isinstance(device, AsyncPluggableMainsFailureSurveillance): entities.append( HomematicipPluggableMainsFailureSurveillanceSensor(hap, device) ) if isinstance(device, AsyncPresenceDetectorIndoor): entities.append(HomematicipPresenceDetector(hap, device)) if isinstance(device, AsyncSmokeDetector): entities.append(HomematicipSmokeDetector(hap, device)) if isinstance(device, AsyncWaterSensor): entities.append(HomematicipWaterDetector(hap, device)) if isinstance(device, (AsyncWeatherSensorPlus, AsyncWeatherSensorPro)): entities.append(HomematicipRainSensor(hap, device)) if isinstance( device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) ): entities.append(HomematicipStormSensor(hap, device)) entities.append(HomematicipSunshineSensor(hap, device)) if isinstance(device, AsyncDevice) and device.lowBat is not None: entities.append(HomematicipBatterySensor(hap, device)) for group in hap.home.groups: if isinstance(group, AsyncSecurityGroup): entities.append(HomematicipSecuritySensorGroup(hap, group)) elif isinstance(group, AsyncSecurityZoneGroup): entities.append(HomematicipSecurityZoneSensorGroup(hap, group)) if entities: async_add_entities(entities) class HomematicipBaseActionSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP base action sensor.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOVING @property def is_on(self) -> bool: """Return true if acceleration is detected.""" return self._device.accelerationSensorTriggered @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the acceleration sensor.""" state_attr = super().device_state_attributes for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value return state_attr class HomematicipAccelerationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP acceleration sensor.""" class HomematicipTiltVibrationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP tilt vibration sensor.""" class HomematicipContactInterface(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP contact interface.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_OPENING @property def is_on(self) -> bool: """Return true if the contact interface is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED class HomematicipShutterContact(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP shutter contact.""" def __init__( self, hap: HomematicipHAP, device, has_additional_state: bool = False ) -> None: """Initialize the shutter contact.""" super().__init__(hap, device) self.has_additional_state = has_additional_state @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_DOOR @property def is_on(self) -> bool: """Return true if the shutter contact is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the Shutter Contact.""" state_attr = super().device_state_attributes if self.has_additional_state: window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = window_state return state_attr class HomematicipMotionDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP motion detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOTION @property def is_on(self) -> bool: """Return true if motion is detected.""" return self._device.motionDetected class HomematicipPresenceDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP presence detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_PRESENCE @property def is_on(self) -> bool: """Return true if presence is detected.""" return self._device.presenceDetected class HomematicipSmokeDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP smoke detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SMOKE @property def is_on(self) -> bool: """Return true if smoke is detected.""" if self._device.smokeDetectorAlarmType: return ( self._device.smokeDetectorAlarmType == SmokeDetectorAlarmType.PRIMARY_ALARM ) return False class HomematicipWaterDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP water detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if moisture or waterlevel is detected.""" return self._device.moistureDetected or self._device.waterlevelDetected class HomematicipStormSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP storm sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize storm sensor.""" super().__init__(hap, device, "Storm") @property def icon(self) -> str: """Return the icon.""" return "mdi:weather-windy" if self.is_on else "mdi:pinwheel-outline" @property def is_on(self) -> bool: """Return true, if storm is detected.""" return self._device.storm class HomematicipRainSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP rain sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize rain sensor.""" super().__init__(hap, device, "Raining") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if it is raining.""" return self._device.raining class HomematicipSunshineSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP sunshine sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize sunshine sensor.""" super().__init__(hap, device, "Sunshine") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_LIGHT @property def is_on(self) -> bool: """Return true if sun is shining.""" return self._device.sunshine @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the illuminance sensor.""" state_attr = super().device_state_attributes today_sunshine_duration = getattr(self._device, "todaySunshineDuration", None) if today_sunshine_duration: state_attr[ATTR_TODAY_SUNSHINE_DURATION] = today_sunshine_duration return state_attr class HomematicipBatterySensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP low battery sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize battery sensor.""" super().__init__(hap, device, "Battery") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_BATTERY @property def is_on(self) -> bool: """Return true if battery is low.""" return self._device.lowBat class HomematicipPluggableMainsFailureSurveillanceSensor( HomematicipGenericEntity, BinarySensorEntity ): """Representation of the HomematicIP pluggable mains failure surveillance sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize pluggable mains failure surveillance sensor.""" super().__init__(hap, device) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_POWER @property def is_on(self) -> bool: """Return true if power mains fails.""" return not self._device.powerMainsFailure class HomematicipSecurityZoneSensorGroup(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP security zone sensor group.""" def __init__(self, hap: HomematicipHAP, device, post: str = "SecurityZone") -> None: """Initialize security zone group.""" device.modelType = f"HmIP-{post}" super().__init__(hap, device, post) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SAFETY @property def available(self) -> bool: """Security-Group available.""" # A security-group must be available, and should not be affected by # the individual availability of group members. return True @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security zone group.""" state_attr = super().device_state_attributes for attr, attr_key in GROUP_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = str(window_state) return state_attr @property def is_on(self) -> bool: """Return true if security issue detected.""" if ( self._device.motionDetected or self._device.presenceDetected or self._device.unreach or self._device.sabotage ): return True if ( self._device.windowState is not None and self._device.windowState != WindowState.CLOSED ): return True return False class HomematicipSecuritySensorGroup( HomematicipSecurityZoneSensorGroup, BinarySensorEntity ): """Representation of the HomematicIP security group.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize security group.""" super().__init__(hap, device, "Sensors") @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security group.""" state_attr = super().device_state_attributes smoke_detector_at = getattr(self._device, "smokeDetectorAlarmType", None) if smoke_detector_at: if smoke_detector_at == SmokeDetectorAlarmType.PRIMARY_ALARM: state_attr[ATTR_SMOKE_DETECTOR_ALARM] = str(smoke_detector_at) if smoke_detector_at == SmokeDetectorAlarmType.INTRUSION_ALARM: state_attr[ATTR_INTRUSION_ALARM] = str(smoke_detector_at) return state_attr @property def is_on(self) -> bool: """Return true if safety issue detected.""" parent_is_on = super().is_on if parent_is_on: return True if ( self._device.powerMainsFailure or self._device.moistureDetected or self._device.waterlevelDetected or self._device.lowBat or self._device.dutyCycle ): return True if ( self._device.smokeDetectorAlarmType is not None and self._device.smokeDetectorAlarmType != SmokeDetectorAlarmType.IDLE_OFF ): return True return False
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/homematicip_cloud/binary_sensor.py
"""Support for OVO Energy.""" from datetime import datetime, timedelta import logging from typing import Any, Dict import aiohttp import async_timeout from ovoenergy import OVODailyUsage from ovoenergy.ovoenergy import OVOEnergy from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the OVO Energy components.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up OVO Energy from a config entry.""" client = OVOEnergy() try: await client.authenticate(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception async def async_update_data() -> OVODailyUsage: """Fetch data from OVO Energy.""" now = datetime.utcnow() async with async_timeout.timeout(10): try: await client.authenticate( entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD] ) return await client.get_daily_usage(now.strftime("%Y-%m")) except aiohttp.ClientError as exception: _LOGGER.warning(exception) return None coordinator = DataUpdateCoordinator( hass, _LOGGER, # Name of the data. For logging purposes. name="sensor", update_method=async_update_data, # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(seconds=300), ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_CLIENT: client, DATA_COORDINATOR: coordinator, } # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload OVO Energy config entry.""" # Unload sensors await hass.config_entries.async_forward_entry_unload(entry, "sensor") del hass.data[DOMAIN][entry.entry_id] return True class OVOEnergyEntity(CoordinatorEntity): """Defines a base OVO Energy entity.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, key: str, name: str, icon: str, ) -> None: """Initialize the OVO Energy entity.""" super().__init__(coordinator) self._client = client self._key = key self._name = name self._icon = icon self._available = True @property def unique_id(self) -> str: """Return the unique ID for this sensor.""" return self._key @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self.coordinator.last_update_success and self._available class OVOEnergyDeviceEntity(OVOEnergyEntity): """Defines a OVO Energy device entity.""" @property def device_info(self) -> Dict[str, Any]: """Return device information about this OVO Energy instance.""" return { "identifiers": {(DOMAIN, self._client.account_id)}, "manufacturer": "OVO Energy", "name": self._client.account_id, "entry_type": "service", }
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/ovo_energy/__init__.py
"""Support for turning on and off Pi-hole system.""" import logging from hole.exceptions import HoleError import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv, entity_platform from . import PiHoleEntity from .const import ( DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN, SERVICE_DISABLE, SERVICE_DISABLE_ATTR_DURATION, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up the Pi-hole switch.""" name = entry.data[CONF_NAME] hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id] switches = [ PiHoleSwitch( hole_data[DATA_KEY_API], hole_data[DATA_KEY_COORDINATOR], name, entry.entry_id, ) ] async_add_entities(switches, True) # register service platform = entity_platform.current_platform.get() platform.async_register_entity_service( SERVICE_DISABLE, { vol.Required(SERVICE_DISABLE_ATTR_DURATION): vol.All( cv.time_period_str, cv.positive_timedelta ), }, "async_disable", ) class PiHoleSwitch(PiHoleEntity, SwitchEntity): """Representation of a Pi-hole switch.""" @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of the switch.""" return f"{self._server_unique_id}/Switch" @property def icon(self): """Icon to use in the frontend, if any.""" return "mdi:pi-hole" @property def is_on(self): """Return if the service is on.""" return self.api.data.get("status") == "enabled" async def async_turn_on(self, **kwargs): """Turn on the service.""" try: await self.api.enable() await self.async_update() except HoleError as err: _LOGGER.error("Unable to enable Pi-hole: %s", err) async def async_turn_off(self, **kwargs): """Turn off the service.""" await self.async_disable() async def async_disable(self, duration=None): """Disable the service for a given duration.""" duration_seconds = True # Disable infinitely by default if duration is not None: duration_seconds = duration.total_seconds() _LOGGER.debug( "Disabling Pi-hole '%s' (%s) for %d seconds", self.name, self.api.host, duration_seconds, ) try: await self.api.disable(duration_seconds) await self.async_update() except HoleError as err: _LOGGER.error("Unable to disable Pi-hole: %s", err)
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/pi_hole/switch.py
"""Support for Rova garbage calendar.""" from datetime import datetime, timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError from rova.rova import Rova import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, DEVICE_CLASS_TIMESTAMP, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle # Config for rova requests. CONF_ZIP_CODE = "zip_code" CONF_HOUSE_NUMBER = "house_number" CONF_HOUSE_NUMBER_SUFFIX = "house_number_suffix" UPDATE_DELAY = timedelta(hours=12) SCAN_INTERVAL = timedelta(hours=12) # Supported sensor types: # Key: [json_key, name, icon] SENSOR_TYPES = { "bio": ["gft", "Biowaste", "mdi:recycle"], "paper": ["papier", "Paper", "mdi:recycle"], "plastic": ["pmd", "PET", "mdi:recycle"], "residual": ["restafval", "Residual", "mdi:recycle"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ZIP_CODE): cv.string, vol.Required(CONF_HOUSE_NUMBER): cv.string, vol.Optional(CONF_HOUSE_NUMBER_SUFFIX, default=""): cv.string, vol.Optional(CONF_NAME, default="Rova"): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["bio"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Create the Rova data service and sensors.""" zip_code = config[CONF_ZIP_CODE] house_number = config[CONF_HOUSE_NUMBER] house_number_suffix = config[CONF_HOUSE_NUMBER_SUFFIX] platform_name = config[CONF_NAME] # Create new Rova object to retrieve data api = Rova(zip_code, house_number, house_number_suffix) try: if not api.is_rova_area(): _LOGGER.error("ROVA does not collect garbage in this area") return except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve details from ROVA API") return # Create rova data service which will retrieve and update the data. data_service = RovaData(api) # Create a new sensor for each garbage type. entities = [] for sensor_key in config[CONF_MONITORED_CONDITIONS]: sensor = RovaSensor(platform_name, sensor_key, data_service) entities.append(sensor) add_entities(entities, True) class RovaSensor(Entity): """Representation of a Rova sensor.""" def __init__(self, platform_name, sensor_key, data_service): """Initialize the sensor.""" self.sensor_key = sensor_key self.platform_name = platform_name self.data_service = data_service self._state = None self._json_key = SENSOR_TYPES[self.sensor_key][0] @property def name(self): """Return the name.""" return f"{self.platform_name}_{self.sensor_key}" @property def icon(self): """Return the sensor icon.""" return SENSOR_TYPES[self.sensor_key][2] @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Get the latest data from the sensor and update the state.""" self.data_service.update() pickup_date = self.data_service.data.get(self._json_key) if pickup_date is not None: self._state = pickup_date.isoformat() class RovaData: """Get and update the latest data from the Rova API.""" def __init__(self, api): """Initialize the data object.""" self.api = api self.data = {} @Throttle(UPDATE_DELAY) def update(self): """Update the data from the Rova API.""" try: items = self.api.get_calendar_items() except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve data, retry again later") return self.data = {} for item in items: date = datetime.strptime(item["Date"], "%Y-%m-%dT%H:%M:%S") code = item["GarbageTypeCode"].lower() if code not in self.data and date > datetime.now(): self.data[code] = date _LOGGER.debug("Updated Rova calendar: %s", self.data)
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/rova/sensor.py
"""Support for Recollect Waste curbside collection pickup.""" from datetime import timedelta import logging import recollect_waste import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) ATTR_PICKUP_TYPES = "pickup_types" ATTR_AREA_NAME = "area_name" CONF_PLACE_ID = "place_id" CONF_SERVICE_ID = "service_id" DEFAULT_NAME = "recollect_waste" ICON = "mdi:trash-can-outline" SCAN_INTERVAL = timedelta(days=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PLACE_ID): cv.string, vol.Required(CONF_SERVICE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Recollect Waste platform.""" client = recollect_waste.RecollectWasteClient( config[CONF_PLACE_ID], config[CONF_SERVICE_ID] ) # Ensure the client can connect to the API successfully # with given place_id and service_id. try: client.get_next_pickup() except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex) return add_entities([RecollectWasteSensor(config.get(CONF_NAME), client)], True) class RecollectWasteSensor(Entity): """Recollect Waste Sensor.""" def __init__(self, name, client): """Initialize the sensor.""" self._attributes = {} self._name = name self._state = None self.client = client @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self.client.place_id}{self.client.service_id}" @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @property def icon(self): """Icon to use in the frontend.""" return ICON def update(self): """Update device state.""" try: pickup_event = self.client.get_next_pickup() self._state = pickup_event.event_date self._attributes.update( { ATTR_PICKUP_TYPES: pickup_event.pickup_types, ATTR_AREA_NAME: pickup_event.area_name, } ) except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex)
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/recollect_waste/sensor.py
"""Constants for the Rollease Acmeda Automate integration.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "acmeda" ACMEDA_HUB_UPDATE = "acmeda_hub_update_{}" ACMEDA_ENTITY_REMOVE = "acmeda_entity_remove_{}"
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/acmeda/const.py
"""Allows the creation of a sensor that filters state property.""" from collections import Counter, deque from copy import copy from datetime import timedelta from functools import partial import logging from numbers import Number import statistics from typing import Optional import voluptuous as vol from homeassistant.components import history from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, CONF_ENTITY_ID, CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.util.decorator import Registry import homeassistant.util.dt as dt_util from . import DOMAIN, PLATFORMS _LOGGER = logging.getLogger(__name__) FILTER_NAME_RANGE = "range" FILTER_NAME_LOWPASS = "lowpass" FILTER_NAME_OUTLIER = "outlier" FILTER_NAME_THROTTLE = "throttle" FILTER_NAME_TIME_THROTTLE = "time_throttle" FILTER_NAME_TIME_SMA = "time_simple_moving_average" FILTERS = Registry() CONF_FILTERS = "filters" CONF_FILTER_NAME = "filter" CONF_FILTER_WINDOW_SIZE = "window_size" CONF_FILTER_PRECISION = "precision" CONF_FILTER_RADIUS = "radius" CONF_FILTER_TIME_CONSTANT = "time_constant" CONF_FILTER_LOWER_BOUND = "lower_bound" CONF_FILTER_UPPER_BOUND = "upper_bound" CONF_TIME_SMA_TYPE = "type" TIME_SMA_LAST = "last" WINDOW_SIZE_UNIT_NUMBER_EVENTS = 1 WINDOW_SIZE_UNIT_TIME = 2 DEFAULT_WINDOW_SIZE = 1 DEFAULT_PRECISION = 2 DEFAULT_FILTER_RADIUS = 2.0 DEFAULT_FILTER_TIME_CONSTANT = 10 NAME_TEMPLATE = "{} filter" ICON = "mdi:chart-line-variant" FILTER_SCHEMA = vol.Schema( {vol.Optional(CONF_FILTER_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int)} ) FILTER_OUTLIER_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_OUTLIER, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional(CONF_FILTER_RADIUS, default=DEFAULT_FILTER_RADIUS): vol.Coerce( float ), } ) FILTER_LOWPASS_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_LOWPASS, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional( CONF_FILTER_TIME_CONSTANT, default=DEFAULT_FILTER_TIME_CONSTANT ): vol.Coerce(int), } ) FILTER_RANGE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_RANGE, vol.Optional(CONF_FILTER_LOWER_BOUND): vol.Coerce(float), vol.Optional(CONF_FILTER_UPPER_BOUND): vol.Coerce(float), } ) FILTER_TIME_SMA_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_SMA, vol.Optional(CONF_TIME_SMA_TYPE, default=TIME_SMA_LAST): vol.In( [TIME_SMA_LAST] ), vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) FILTER_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_THROTTLE, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), } ) FILTER_TIME_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_THROTTLE, vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_FILTERS): vol.All( cv.ensure_list, [ vol.Any( FILTER_OUTLIER_SCHEMA, FILTER_LOWPASS_SCHEMA, FILTER_TIME_SMA_SCHEMA, FILTER_THROTTLE_SCHEMA, FILTER_TIME_THROTTLE_SCHEMA, FILTER_RANGE_SCHEMA, ) ], ), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template sensors.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) name = config.get(CONF_NAME) entity_id = config.get(CONF_ENTITY_ID) filters = [ FILTERS[_filter.pop(CONF_FILTER_NAME)](entity=entity_id, **_filter) for _filter in config[CONF_FILTERS] ] async_add_entities([SensorFilter(name, entity_id, filters)]) class SensorFilter(Entity): """Representation of a Filter Sensor.""" def __init__(self, name, entity_id, filters): """Initialize the sensor.""" self._name = name self._entity = entity_id self._unit_of_measurement = None self._state = None self._filters = filters self._icon = None @callback def _update_filter_sensor_state_event(self, event): """Handle device state changes.""" self._update_filter_sensor_state(event.data.get("new_state")) @callback def _update_filter_sensor_state(self, new_state, update_ha=True): """Process device state changes.""" if new_state is None or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]: return temp_state = new_state try: for filt in self._filters: filtered_state = filt.filter_state(copy(temp_state)) _LOGGER.debug( "%s(%s=%s) -> %s", filt.name, self._entity, temp_state.state, "skip" if filt.skip_processing else filtered_state.state, ) if filt.skip_processing: return temp_state = filtered_state except ValueError: _LOGGER.error("Could not convert state: %s to number", self._state) return self._state = temp_state.state if self._icon is None: self._icon = new_state.attributes.get(ATTR_ICON, ICON) if self._unit_of_measurement is None: self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT ) if update_ha: self.async_write_ha_state() async def async_added_to_hass(self): """Register callbacks.""" if "recorder" in self.hass.config.components: history_list = [] largest_window_items = 0 largest_window_time = timedelta(0) # Determine the largest window_size by type for filt in self._filters: if ( filt.window_unit == WINDOW_SIZE_UNIT_NUMBER_EVENTS and largest_window_items < filt.window_size ): largest_window_items = filt.window_size elif ( filt.window_unit == WINDOW_SIZE_UNIT_TIME and largest_window_time < filt.window_size ): largest_window_time = filt.window_size # Retrieve the largest window_size of each type if largest_window_items > 0: filter_history = await self.hass.async_add_job( partial( history.get_last_state_changes, self.hass, largest_window_items, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend(filter_history[self._entity]) if largest_window_time > timedelta(seconds=0): start = dt_util.utcnow() - largest_window_time filter_history = await self.hass.async_add_job( partial( history.state_changes_during_period, self.hass, start, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend( [ state for state in filter_history[self._entity] if state not in history_list ] ) # Sort the window states history_list = sorted(history_list, key=lambda s: s.last_updated) _LOGGER.debug( "Loading from history: %s", [(s.state, s.last_updated) for s in history_list], ) # Replay history through the filter chain for state in history_list: self._update_filter_sensor_state(state, False) self.async_on_remove( async_track_state_change_event( self.hass, [self._entity], self._update_filter_sensor_state_event ) ) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon @property def unit_of_measurement(self): """Return the unit_of_measurement of the device.""" return self._unit_of_measurement @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes of the sensor.""" state_attr = {ATTR_ENTITY_ID: self._entity} return state_attr class FilterState: """State abstraction for filter usage.""" def __init__(self, state): """Initialize with HA State object.""" self.timestamp = state.last_updated try: self.state = float(state.state) except ValueError: self.state = state.state def set_precision(self, precision): """Set precision of Number based states.""" if isinstance(self.state, Number): value = round(float(self.state), precision) self.state = int(value) if precision == 0 else value def __str__(self): """Return state as the string representation of FilterState.""" return str(self.state) def __repr__(self): """Return timestamp and state as the representation of FilterState.""" return f"{self.timestamp} : {self.state}" class Filter: """Filter skeleton.""" def __init__( self, name, window_size: int = 1, precision: Optional[int] = None, entity: Optional[str] = None, ): """Initialize common attributes. :param window_size: size of the sliding window that holds previous values :param precision: round filtered value to precision value :param entity: used for debugging only """ if isinstance(window_size, int): self.states = deque(maxlen=window_size) self.window_unit = WINDOW_SIZE_UNIT_NUMBER_EVENTS else: self.states = deque(maxlen=0) self.window_unit = WINDOW_SIZE_UNIT_TIME self.precision = precision self._name = name self._entity = entity self._skip_processing = False self._window_size = window_size self._store_raw = False self._only_numbers = True @property def window_size(self): """Return window size.""" return self._window_size @property def name(self): """Return filter name.""" return self._name @property def skip_processing(self): """Return whether the current filter_state should be skipped.""" return self._skip_processing def _filter_state(self, new_state): """Implement filter.""" raise NotImplementedError() def filter_state(self, new_state): """Implement a common interface for filters.""" fstate = FilterState(new_state) if self._only_numbers and not isinstance(fstate.state, Number): raise ValueError filtered = self._filter_state(fstate) filtered.set_precision(self.precision) if self._store_raw: self.states.append(copy(FilterState(new_state))) else: self.states.append(copy(filtered)) new_state.state = filtered.state return new_state @FILTERS.register(FILTER_NAME_RANGE) class RangeFilter(Filter): """Range filter. Determines if new state is in the range of upper_bound and lower_bound. If not inside, lower or upper bound is returned instead. """ def __init__( self, entity, precision: Optional[int] = DEFAULT_PRECISION, lower_bound: Optional[float] = None, upper_bound: Optional[float] = None, ): """Initialize Filter. :param upper_bound: band upper bound :param lower_bound: band lower bound """ super().__init__(FILTER_NAME_RANGE, precision=precision, entity=entity) self._lower_bound = lower_bound self._upper_bound = upper_bound self._stats_internal = Counter() def _filter_state(self, new_state): """Implement the range filter.""" if self._upper_bound is not None and new_state.state > self._upper_bound: self._stats_internal["erasures_up"] += 1 _LOGGER.debug( "Upper outlier nr. %s in %s: %s", self._stats_internal["erasures_up"], self._entity, new_state, ) new_state.state = self._upper_bound elif self._lower_bound is not None and new_state.state < self._lower_bound: self._stats_internal["erasures_low"] += 1 _LOGGER.debug( "Lower outlier nr. %s in %s: %s", self._stats_internal["erasures_low"], self._entity, new_state, ) new_state.state = self._lower_bound return new_state @FILTERS.register(FILTER_NAME_OUTLIER) class OutlierFilter(Filter): """BASIC outlier filter. Determines if new state is in a band around the median. """ def __init__(self, window_size, precision, entity, radius: float): """Initialize Filter. :param radius: band radius """ super().__init__(FILTER_NAME_OUTLIER, window_size, precision, entity) self._radius = radius self._stats_internal = Counter() self._store_raw = True def _filter_state(self, new_state): """Implement the outlier filter.""" median = statistics.median([s.state for s in self.states]) if self.states else 0 if ( len(self.states) == self.states.maxlen and abs(new_state.state - median) > self._radius ): self._stats_internal["erasures"] += 1 _LOGGER.debug( "Outlier nr. %s in %s: %s", self._stats_internal["erasures"], self._entity, new_state, ) new_state.state = median return new_state @FILTERS.register(FILTER_NAME_LOWPASS) class LowPassFilter(Filter): """BASIC Low Pass Filter.""" def __init__(self, window_size, precision, entity, time_constant: int): """Initialize Filter.""" super().__init__(FILTER_NAME_LOWPASS, window_size, precision, entity) self._time_constant = time_constant def _filter_state(self, new_state): """Implement the low pass filter.""" if not self.states: return new_state new_weight = 1.0 / self._time_constant prev_weight = 1.0 - new_weight new_state.state = ( prev_weight * self.states[-1].state + new_weight * new_state.state ) return new_state @FILTERS.register(FILTER_NAME_TIME_SMA) class TimeSMAFilter(Filter): """Simple Moving Average (SMA) Filter. The window_size is determined by time, and SMA is time weighted. """ def __init__( self, window_size, precision, entity, type ): # pylint: disable=redefined-builtin """Initialize Filter. :param type: type of algorithm used to connect discrete values """ super().__init__(FILTER_NAME_TIME_SMA, window_size, precision, entity) self._time_window = window_size self.last_leak = None self.queue = deque() def _leak(self, left_boundary): """Remove timeouted elements.""" while self.queue: if self.queue[0].timestamp + self._time_window <= left_boundary: self.last_leak = self.queue.popleft() else: return def _filter_state(self, new_state): """Implement the Simple Moving Average filter.""" self._leak(new_state.timestamp) self.queue.append(copy(new_state)) moving_sum = 0 start = new_state.timestamp - self._time_window prev_state = self.last_leak or self.queue[0] for state in self.queue: moving_sum += (state.timestamp - start).total_seconds() * prev_state.state start = state.timestamp prev_state = state new_state.state = moving_sum / self._time_window.total_seconds() return new_state @FILTERS.register(FILTER_NAME_THROTTLE) class ThrottleFilter(Filter): """Throttle Filter. One sample per window. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_THROTTLE, window_size, precision, entity) self._only_numbers = False def _filter_state(self, new_state): """Implement the throttle filter.""" if not self.states or len(self.states) == self.states.maxlen: self.states.clear() self._skip_processing = False else: self._skip_processing = True return new_state @FILTERS.register(FILTER_NAME_TIME_THROTTLE) class TimeThrottleFilter(Filter): """Time Throttle Filter. One sample per time period. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision, entity) self._time_window = window_size self._last_emitted_at = None self._only_numbers = False def _filter_state(self, new_state): """Implement the filter.""" window_start = new_state.timestamp - self._time_window if not self._last_emitted_at or self._last_emitted_at <= window_start: self._last_emitted_at = new_state.timestamp self._skip_processing = False else: self._skip_processing = True return new_state
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/filter/sensor.py
"""Support for Alexa skill service end point.""" import logging import voluptuous as vol from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_NAME from homeassistant.helpers import config_validation as cv, entityfilter from . import flash_briefings, intent, smart_home_http from .const import ( CONF_AUDIO, CONF_DESCRIPTION, CONF_DISPLAY_CATEGORIES, CONF_DISPLAY_URL, CONF_ENDPOINT, CONF_ENTITY_CONFIG, CONF_FILTER, CONF_LOCALE, CONF_PASSWORD, CONF_SUPPORTED_LOCALES, CONF_TEXT, CONF_TITLE, CONF_UID, DOMAIN, ) _LOGGER = logging.getLogger(__name__) CONF_FLASH_BRIEFINGS = "flash_briefings" CONF_SMART_HOME = "smart_home" DEFAULT_LOCALE = "en-US" ALEXA_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_DESCRIPTION): cv.string, vol.Optional(CONF_DISPLAY_CATEGORIES): cv.string, vol.Optional(CONF_NAME): cv.string, } ) SMART_HOME_SCHEMA = vol.Schema( { vol.Optional(CONF_ENDPOINT): cv.string, vol.Optional(CONF_CLIENT_ID): cv.string, vol.Optional(CONF_CLIENT_SECRET): cv.string, vol.Optional(CONF_LOCALE, default=DEFAULT_LOCALE): vol.In( CONF_SUPPORTED_LOCALES ), vol.Optional(CONF_FILTER, default={}): entityfilter.FILTER_SCHEMA, vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: { CONF_FLASH_BRIEFINGS: { vol.Required(CONF_PASSWORD): cv.string, cv.string: vol.All( cv.ensure_list, [ { vol.Optional(CONF_UID): cv.string, vol.Required(CONF_TITLE): cv.template, vol.Optional(CONF_AUDIO): cv.template, vol.Required(CONF_TEXT, default=""): cv.template, vol.Optional(CONF_DISPLAY_URL): cv.template, } ], ), }, # vol.Optional here would mean we couldn't distinguish between an empty # smart_home: and none at all. CONF_SMART_HOME: vol.Any(SMART_HOME_SCHEMA, None), } }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Activate the Alexa component.""" if DOMAIN not in config: return True config = config[DOMAIN] flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS) intent.async_setup(hass) if flash_briefings_config: flash_briefings.async_setup(hass, flash_briefings_config) try: smart_home_config = config[CONF_SMART_HOME] except KeyError: pass else: smart_home_config = smart_home_config or SMART_HOME_SCHEMA({}) await smart_home_http.async_setup(hass, smart_home_config) return True
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/alexa/__init__.py
"""Support for LCN lights.""" import pypck from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.const import CONF_ADDRESS from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_DIMMABLE, CONF_OUTPUT, CONF_TRANSITION, DATA_LCN, OUTPUT_PORTS, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN light platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) if config[CONF_OUTPUT] in OUTPUT_PORTS: device = LcnOutputLight(config, address_connection) else: # in RELAY_PORTS device = LcnRelayLight(config, address_connection) devices.append(device) async_add_entities(devices) class LcnOutputLight(LcnDevice, LightEntity): """Representation of a LCN light for output ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.OutputPort[config[CONF_OUTPUT]] self._transition = pypck.lcn_defs.time_to_ramp_value(config[CONF_TRANSITION]) self.dimmable = config[CONF_DIMMABLE] self._brightness = 255 self._is_on = None self._is_dimming_to_zero = False async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def supported_features(self): """Flag supported features.""" features = SUPPORT_TRANSITION if self.dimmable: features |= SUPPORT_BRIGHTNESS return features @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True self._is_dimming_to_zero = False if ATTR_BRIGHTNESS in kwargs: percent = int(kwargs[ATTR_BRIGHTNESS] / 255.0 * 100) else: percent = 100 if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self.address_connection.dim_output(self.output.value, percent, transition) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self._is_dimming_to_zero = bool(transition) self.address_connection.dim_output(self.output.value, 0, transition) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if ( not isinstance(input_obj, pypck.inputs.ModStatusOutput) or input_obj.get_output_id() != self.output.value ): return self._brightness = int(input_obj.get_percent() / 100.0 * 255) if self.brightness == 0: self._is_dimming_to_zero = False if not self._is_dimming_to_zero: self._is_on = self.brightness > 0 self.async_write_ha_state() class LcnRelayLight(LcnDevice, LightEntity): """Representation of a LCN light for relay ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.RelayPort[config[CONF_OUTPUT]] self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.ON self.address_connection.control_relays(states) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.OFF self.address_connection.control_relays(states) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusRelays): return self._is_on = input_obj.get_state(self.output.value) self.async_write_ha_state()
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/lcn/light.py
"""Support for AlarmDecoder devices.""" import asyncio from datetime import timedelta import logging from adext import AdExt from alarmdecoder.devices import SerialDevice, SocketDevice from alarmdecoder.util import NoDeviceError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF_PROTOCOL, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util from .const import ( CONF_DEVICE_BAUD, CONF_DEVICE_PATH, DATA_AD, DATA_REMOVE_STOP_LISTENER, DATA_REMOVE_UPDATE_LISTENER, DATA_RESTART, DOMAIN, PROTOCOL_SERIAL, PROTOCOL_SOCKET, SIGNAL_PANEL_MESSAGE, SIGNAL_REL_MESSAGE, SIGNAL_RFX_MESSAGE, SIGNAL_ZONE_FAULT, SIGNAL_ZONE_RESTORE, ) _LOGGER = logging.getLogger(__name__) PLATFORMS = ["alarm_control_panel", "sensor", "binary_sensor"] async def async_setup(hass, config): """Set up for the AlarmDecoder devices.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up AlarmDecoder config flow.""" undo_listener = entry.add_update_listener(_update_listener) ad_connection = entry.data protocol = ad_connection[CONF_PROTOCOL] def stop_alarmdecoder(event): """Handle the shutdown of AlarmDecoder.""" if not hass.data.get(DOMAIN): return _LOGGER.debug("Shutting down alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False controller.close() async def open_connection(now=None): """Open a connection to AlarmDecoder.""" try: await hass.async_add_executor_job(controller.open, baud) except NoDeviceError: _LOGGER.debug("Failed to connect. Retrying in 5 seconds") hass.helpers.event.async_track_point_in_time( open_connection, dt_util.utcnow() + timedelta(seconds=5) ) return _LOGGER.debug("Established a connection with the alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = True def handle_closed_connection(event): """Restart after unexpected loss of connection.""" if not hass.data[DOMAIN][entry.entry_id][DATA_RESTART]: return hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False _LOGGER.warning("AlarmDecoder unexpectedly lost connection") hass.add_job(open_connection) def handle_message(sender, message): """Handle message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_PANEL_MESSAGE, message) def handle_rfx_message(sender, message): """Handle RFX message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_RFX_MESSAGE, message) def zone_fault_callback(sender, zone): """Handle zone fault from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_FAULT, zone) def zone_restore_callback(sender, zone): """Handle zone restore from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_RESTORE, zone) def handle_rel_message(sender, message): """Handle relay or zone expander message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_REL_MESSAGE, message) baud = ad_connection.get(CONF_DEVICE_BAUD) if protocol == PROTOCOL_SOCKET: host = ad_connection[CONF_HOST] port = ad_connection[CONF_PORT] controller = AdExt(SocketDevice(interface=(host, port))) if protocol == PROTOCOL_SERIAL: path = ad_connection[CONF_DEVICE_PATH] controller = AdExt(SerialDevice(interface=path)) controller.on_message += handle_message controller.on_rfx_message += handle_rfx_message controller.on_zone_fault += zone_fault_callback controller.on_zone_restore += zone_restore_callback controller.on_close += handle_closed_connection controller.on_expander_message += handle_rel_message remove_stop_listener = hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_AD: controller, DATA_REMOVE_UPDATE_LISTENER: undo_listener, DATA_REMOVE_STOP_LISTENER: remove_stop_listener, DATA_RESTART: False, } await open_connection() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): """Unload a AlarmDecoder entry.""" hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_UPDATE_LISTENER]() hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_STOP_LISTENER]() await hass.async_add_executor_job(hass.data[DOMAIN][entry.entry_id][DATA_AD].close) if hass.data[DOMAIN][entry.entry_id]: hass.data[DOMAIN].pop(entry.entry_id) if not hass.data[DOMAIN]: hass.data.pop(DOMAIN) return True async def _update_listener(hass: HomeAssistantType, entry: ConfigEntry): """Handle options update.""" _LOGGER.debug("AlarmDecoder options updated: %s", entry.as_dict()["options"]) await hass.config_entries.async_reload(entry.entry_id)
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/alarmdecoder/__init__.py
"""Support for Plaato Airlock.""" import logging from aiohttp import web import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR from homeassistant.const import ( CONF_WEBHOOK_ID, HTTP_OK, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLUME_GALLONS, VOLUME_LITERS, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import DOMAIN _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ["webhook"] PLAATO_DEVICE_SENSORS = "sensors" PLAATO_DEVICE_ATTRS = "attrs" ATTR_DEVICE_ID = "device_id" ATTR_DEVICE_NAME = "device_name" ATTR_TEMP_UNIT = "temp_unit" ATTR_VOLUME_UNIT = "volume_unit" ATTR_BPM = "bpm" ATTR_TEMP = "temp" ATTR_SG = "sg" ATTR_OG = "og" ATTR_BUBBLES = "bubbles" ATTR_ABV = "abv" ATTR_CO2_VOLUME = "co2_volume" ATTR_BATCH_VOLUME = "batch_volume" SENSOR_UPDATE = f"{DOMAIN}_sensor_update" SENSOR_DATA_KEY = f"{DOMAIN}.{SENSOR}" WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_NAME): cv.string, vol.Required(ATTR_DEVICE_ID): cv.positive_int, vol.Required(ATTR_TEMP_UNIT): vol.Any(TEMP_CELSIUS, TEMP_FAHRENHEIT), vol.Required(ATTR_VOLUME_UNIT): vol.Any(VOLUME_LITERS, VOLUME_GALLONS), vol.Required(ATTR_BPM): cv.positive_int, vol.Required(ATTR_TEMP): vol.Coerce(float), vol.Required(ATTR_SG): vol.Coerce(float), vol.Required(ATTR_OG): vol.Coerce(float), vol.Required(ATTR_ABV): vol.Coerce(float), vol.Required(ATTR_CO2_VOLUME): vol.Coerce(float), vol.Required(ATTR_BATCH_VOLUME): vol.Coerce(float), vol.Required(ATTR_BUBBLES): cv.positive_int, }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, hass_config): """Set up the Plaato component.""" return True async def async_setup_entry(hass, entry): """Configure based on config entry.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} webhook_id = entry.data[CONF_WEBHOOK_ID] hass.components.webhook.async_register(DOMAIN, "Plaato", webhook_id, handle_webhook) hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, SENSOR)) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[SENSOR_DATA_KEY]() await hass.config_entries.async_forward_entry_unload(entry, SENSOR) return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Plaato.""" try: data = WEBHOOK_SCHEMA(await request.json()) except vol.MultipleInvalid as error: _LOGGER.warning("An error occurred when parsing webhook data <%s>", error) return device_id = _device_id(data) attrs = { ATTR_DEVICE_NAME: data.get(ATTR_DEVICE_NAME), ATTR_DEVICE_ID: data.get(ATTR_DEVICE_ID), ATTR_TEMP_UNIT: data.get(ATTR_TEMP_UNIT), ATTR_VOLUME_UNIT: data.get(ATTR_VOLUME_UNIT), } sensors = { ATTR_TEMP: data.get(ATTR_TEMP), ATTR_BPM: data.get(ATTR_BPM), ATTR_SG: data.get(ATTR_SG), ATTR_OG: data.get(ATTR_OG), ATTR_ABV: data.get(ATTR_ABV), ATTR_CO2_VOLUME: data.get(ATTR_CO2_VOLUME), ATTR_BATCH_VOLUME: data.get(ATTR_BATCH_VOLUME), ATTR_BUBBLES: data.get(ATTR_BUBBLES), } hass.data[DOMAIN][device_id] = { PLAATO_DEVICE_ATTRS: attrs, PLAATO_DEVICE_SENSORS: sensors, } async_dispatcher_send(hass, SENSOR_UPDATE, device_id) return web.Response(text=f"Saving status for {device_id}", status=HTTP_OK) def _device_id(data): """Return name of device sensor.""" return f"{data.get(ATTR_DEVICE_NAME)}_{data.get(ATTR_DEVICE_ID)}"
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/plaato/__init__.py
"""Support for the Pico TTS speech service.""" import logging import os import shutil import subprocess import tempfile import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider _LOGGER = logging.getLogger(__name__) SUPPORT_LANGUAGES = ["en-US", "en-GB", "de-DE", "es-ES", "fr-FR", "it-IT"] DEFAULT_LANG = "en-US" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)} ) def get_engine(hass, config, discovery_info=None): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG]) class PicoProvider(Provider): """The Pico TTS API provider.""" def __init__(self, lang): """Initialize Pico TTS provider.""" self._lang = lang self.name = "PicoTTS" @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS using pico2wave.""" with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpf: fname = tmpf.name cmd = ["pico2wave", "--wave", fname, "-l", language, message] subprocess.call(cmd) data = None try: with open(fname, "rb") as voice: data = voice.read() except OSError: _LOGGER.error("Error trying to read %s", fname) return (None, None) finally: os.remove(fname) if data: return ("wav", data) return (None, None)
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/picotts/tts.py
"""Support for Dominos Pizza ordering.""" from datetime import timedelta import logging from pizzapi import Address, Customer, Order from pizzapi.address import StoreException import voluptuous as vol from homeassistant.components import http from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) # The domain of your component. Should be equal to the name of your component. DOMAIN = "dominos" ENTITY_ID_FORMAT = DOMAIN + ".{}" ATTR_COUNTRY = "country_code" ATTR_FIRST_NAME = "first_name" ATTR_LAST_NAME = "last_name" ATTR_EMAIL = "email" ATTR_PHONE = "phone" ATTR_ADDRESS = "address" ATTR_ORDERS = "orders" ATTR_SHOW_MENU = "show_menu" ATTR_ORDER_ENTITY = "order_entity_id" ATTR_ORDER_NAME = "name" ATTR_ORDER_CODES = "codes" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) MIN_TIME_BETWEEN_STORE_UPDATES = timedelta(minutes=3330) _ORDERS_SCHEMA = vol.Schema( { vol.Required(ATTR_ORDER_NAME): cv.string, vol.Required(ATTR_ORDER_CODES): vol.All(cv.ensure_list, [cv.string]), } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(ATTR_COUNTRY): cv.string, vol.Required(ATTR_FIRST_NAME): cv.string, vol.Required(ATTR_LAST_NAME): cv.string, vol.Required(ATTR_EMAIL): cv.string, vol.Required(ATTR_PHONE): cv.string, vol.Required(ATTR_ADDRESS): cv.string, vol.Optional(ATTR_SHOW_MENU): cv.boolean, vol.Optional(ATTR_ORDERS, default=[]): vol.All( cv.ensure_list, [_ORDERS_SCHEMA] ), } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up is called when Home Assistant is loading our component.""" dominos = Dominos(hass, config) component = EntityComponent(_LOGGER, DOMAIN, hass) hass.data[DOMAIN] = {} entities = [] conf = config[DOMAIN] hass.services.register(DOMAIN, "order", dominos.handle_order) if conf.get(ATTR_SHOW_MENU): hass.http.register_view(DominosProductListView(dominos)) for order_info in conf.get(ATTR_ORDERS): order = DominosOrder(order_info, dominos) entities.append(order) if entities: component.add_entities(entities) # Return boolean to indicate that initialization was successfully. return True class Dominos: """Main Dominos service.""" def __init__(self, hass, config): """Set up main service.""" conf = config[DOMAIN] self.hass = hass self.customer = Customer( conf.get(ATTR_FIRST_NAME), conf.get(ATTR_LAST_NAME), conf.get(ATTR_EMAIL), conf.get(ATTR_PHONE), conf.get(ATTR_ADDRESS), ) self.address = Address( *self.customer.address.split(","), country=conf.get(ATTR_COUNTRY) ) self.country = conf.get(ATTR_COUNTRY) try: self.closest_store = self.address.closest_store() except StoreException: self.closest_store = None def handle_order(self, call): """Handle ordering pizza.""" entity_ids = call.data.get(ATTR_ORDER_ENTITY) target_orders = [ order for order in self.hass.data[DOMAIN]["entities"] if order.entity_id in entity_ids ] for order in target_orders: order.place() @Throttle(MIN_TIME_BETWEEN_STORE_UPDATES) def update_closest_store(self): """Update the shared closest store (if open).""" try: self.closest_store = self.address.closest_store() return True except StoreException: self.closest_store = None return False def get_menu(self): """Return the products from the closest stores menu.""" self.update_closest_store() if self.closest_store is None: _LOGGER.warning("Cannot get menu. Store may be closed") return [] menu = self.closest_store.get_menu() product_entries = [] for product in menu.products: item = {} if isinstance(product.menu_data["Variants"], list): variants = ", ".join(product.menu_data["Variants"]) else: variants = product.menu_data["Variants"] item["name"] = product.name item["variants"] = variants product_entries.append(item) return product_entries class DominosProductListView(http.HomeAssistantView): """View to retrieve product list content.""" url = "/api/dominos" name = "api:dominos" def __init__(self, dominos): """Initialize suite view.""" self.dominos = dominos @callback def get(self, request): """Retrieve if API is running.""" return self.json(self.dominos.get_menu()) class DominosOrder(Entity): """Represents a Dominos order entity.""" def __init__(self, order_info, dominos): """Set up the entity.""" self._name = order_info["name"] self._product_codes = order_info["codes"] self._orderable = False self.dominos = dominos @property def name(self): """Return the orders name.""" return self._name @property def product_codes(self): """Return the orders product codes.""" return self._product_codes @property def orderable(self): """Return the true if orderable.""" return self._orderable @property def state(self): """Return the state either closed, orderable or unorderable.""" if self.dominos.closest_store is None: return "closed" return "orderable" if self._orderable else "unorderable" @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the order state and refreshes the store.""" try: self.dominos.update_closest_store() except StoreException: self._orderable = False return try: order = self.order() order.pay_with() self._orderable = True except StoreException: self._orderable = False def order(self): """Create the order object.""" if self.dominos.closest_store is None: raise StoreException order = Order( self.dominos.closest_store, self.dominos.customer, self.dominos.address, self.dominos.country, ) for code in self._product_codes: order.add_item(code) return order def place(self): """Place the order.""" try: order = self.order() order.place() except StoreException: self._orderable = False _LOGGER.warning( "Attempted to order Dominos - Order invalid or store closed" )
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/dominos/__init__.py
"""Support for Vera switches.""" import logging from typing import Any, Callable, List, Optional import pyvera as veraApi from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, SwitchEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import Entity from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraSwitch(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ] ) class VeraSwitch(VeraDevice[veraApi.VeraSwitch], SwitchEntity): """Representation of a Vera Switch.""" def __init__( self, vera_device: veraApi.VeraSwitch, controller_data: ControllerData ): """Initialize the Vera device.""" self._state = False VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) def turn_on(self, **kwargs: Any) -> None: """Turn device on.""" self.vera_device.switch_on() self._state = True self.schedule_update_ha_state() def turn_off(self, **kwargs: Any) -> None: """Turn device off.""" self.vera_device.switch_off() self._state = False self.schedule_update_ha_state() @property def current_power_w(self) -> Optional[float]: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def is_on(self) -> bool: """Return true if device is on.""" return self._state def update(self) -> None: """Update device state.""" self._state = self.vera_device.is_switched_on()
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/vera/switch.py
"""Support for Genius Hub switch/outlet devices.""" from homeassistant.components.switch import DEVICE_CLASS_OUTLET, SwitchEntity from homeassistant.helpers.typing import ConfigType, HomeAssistantType from . import DOMAIN, GeniusZone ATTR_DURATION = "duration" GH_ON_OFF_ZONE = "on / off" async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Set up the Genius Hub switch entities.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] async_add_entities( [ GeniusSwitch(broker, z) for z in broker.client.zone_objs if z.data["type"] == GH_ON_OFF_ZONE ] ) class GeniusSwitch(GeniusZone, SwitchEntity): """Representation of a Genius Hub switch.""" @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_OUTLET @property def is_on(self) -> bool: """Return the current state of the on/off zone. The zone is considered 'on' if & only if it is override/on (e.g. timer/on is 'off'). """ return self._zone.data["mode"] == "override" and self._zone.data["setpoint"] async def async_turn_off(self, **kwargs) -> None: """Send the zone to Timer mode. The zone is deemed 'off' in this mode, although the plugs may actually be on. """ await self._zone.set_mode("timer") async def async_turn_on(self, **kwargs) -> None: """Set the zone to override/on ({'setpoint': true}) for x seconds.""" await self._zone.set_override(1, kwargs.get(ATTR_DURATION, 3600))
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/geniushub/switch.py
"""Provide configuration end points for Groups.""" from homeassistant.components.group import DOMAIN, GROUP_SCHEMA from homeassistant.config import GROUP_CONFIG_PATH from homeassistant.const import SERVICE_RELOAD import homeassistant.helpers.config_validation as cv from . import EditKeyBasedConfigView async def async_setup(hass): """Set up the Group config API.""" async def hook(action, config_key): """post_write_hook for Config View that reloads groups.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) hass.http.register_view( EditKeyBasedConfigView( "group", "config", GROUP_CONFIG_PATH, cv.slug, GROUP_SCHEMA, post_write_hook=hook, ) ) return True
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/config/group.py
"""Support for LCN climate control.""" import pypck from homeassistant.components.climate import ClimateEntity, const from homeassistant.const import ATTR_TEMPERATURE, CONF_ADDRESS, CONF_UNIT_OF_MEASUREMENT from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_LOCKABLE, CONF_MAX_TEMP, CONF_MIN_TEMP, CONF_SETPOINT, CONF_SOURCE, DATA_LCN, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN climate platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) devices.append(LcnClimate(config, address_connection)) async_add_entities(devices) class LcnClimate(LcnDevice, ClimateEntity): """Representation of a LCN climate device.""" def __init__(self, config, address_connection): """Initialize of a LCN climate device.""" super().__init__(config, address_connection) self.variable = pypck.lcn_defs.Var[config[CONF_SOURCE]] self.setpoint = pypck.lcn_defs.Var[config[CONF_SETPOINT]] self.unit = pypck.lcn_defs.VarUnit.parse(config[CONF_UNIT_OF_MEASUREMENT]) self.regulator_id = pypck.lcn_defs.Var.to_set_point_id(self.setpoint) self.is_lockable = config[CONF_LOCKABLE] self._max_temp = config[CONF_MAX_TEMP] self._min_temp = config[CONF_MIN_TEMP] self._current_temperature = None self._target_temperature = None self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.variable) await self.address_connection.activate_status_request_handler(self.setpoint) @property def supported_features(self): """Return the list of supported features.""" return const.SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self): """Return the unit of measurement.""" return self.unit.value @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._is_on: return const.HVAC_MODE_HEAT return const.HVAC_MODE_OFF @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ modes = [const.HVAC_MODE_HEAT] if self.is_lockable: modes.append(const.HVAC_MODE_OFF) return modes @property def max_temp(self): """Return the maximum temperature.""" return self._max_temp @property def min_temp(self): """Return the minimum temperature.""" return self._min_temp async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == const.HVAC_MODE_HEAT: self._is_on = True self.address_connection.lock_regulator(self.regulator_id, False) elif hvac_mode == const.HVAC_MODE_OFF: self._is_on = False self.address_connection.lock_regulator(self.regulator_id, True) self._target_temperature = None self.async_write_ha_state() async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._target_temperature = temperature self.address_connection.var_abs( self.setpoint, self._target_temperature, self.unit ) self.async_write_ha_state() def input_received(self, input_obj): """Set temperature value when LCN input object is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusVar): return if input_obj.get_var() == self.variable: self._current_temperature = input_obj.get_value().to_var_unit(self.unit) elif input_obj.get_var() == self.setpoint: self._is_on = not input_obj.get_value().is_locked_regulator() if self._is_on: self._target_temperature = input_obj.get_value().to_var_unit(self.unit) self.async_write_ha_state()
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/lcn/climate.py
"""Support for HomeMatic binary sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import ATTR_DISCOVER_DEVICES, ATTR_DISCOVERY_TYPE, DISCOVER_BATTERY from .entity import HMDevice _LOGGER = logging.getLogger(__name__) SENSOR_TYPES_CLASS = { "IPShutterContact": DEVICE_CLASS_OPENING, "IPShutterContactSabotage": DEVICE_CLASS_OPENING, "MaxShutterContact": DEVICE_CLASS_OPENING, "Motion": DEVICE_CLASS_MOTION, "MotionV2": DEVICE_CLASS_MOTION, "PresenceIP": DEVICE_CLASS_PRESENCE, "Remote": None, "RemoteMotion": None, "ShutterContact": DEVICE_CLASS_OPENING, "Smoke": DEVICE_CLASS_SMOKE, "SmokeV2": DEVICE_CLASS_SMOKE, "TiltSensor": None, "WeatherSensor": None, "IPContact": DEVICE_CLASS_OPENING, "MotionIPV2": DEVICE_CLASS_MOTION, "IPRemoteMotionV2": DEVICE_CLASS_MOTION, } def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the HomeMatic binary sensor platform.""" if discovery_info is None: return devices = [] for conf in discovery_info[ATTR_DISCOVER_DEVICES]: if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY: devices.append(HMBatterySensor(conf)) else: devices.append(HMBinarySensor(conf)) add_entities(devices, True) class HMBinarySensor(HMDevice, BinarySensorEntity): """Representation of a binary HomeMatic device.""" @property def is_on(self): """Return true if switch is on.""" if not self.available: return False return bool(self._hm_get_state()) @property def device_class(self): """Return the class of this sensor from DEVICE_CLASSES.""" # If state is MOTION (Only RemoteMotion working) if self._state == "MOTION": return DEVICE_CLASS_MOTION return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None}) class HMBatterySensor(HMDevice, BinarySensorEntity): """Representation of an HomeMatic low battery sensor.""" @property def device_class(self): """Return battery as a device class.""" return DEVICE_CLASS_BATTERY @property def is_on(self): """Return True if battery is low.""" return bool(self._hm_get_state()) def _init_data_struct(self): """Generate the data dictionary (self._data) from metadata.""" # Add state to data struct if self._state: self._data.update({self._state: None})
"""The tests for the Alexa component.""" # pylint: disable=protected-access import json import pytest from homeassistant.components import alexa from homeassistant.components.alexa import intent from homeassistant.core import callback from homeassistant.setup import async_setup_component SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000" APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe" REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000" AUTHORITY_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.ZODIAC" BUILTIN_AUTH_ID = "amzn1.er-authority.000000-d0ed-0000-ad00-000000d00ebe.TEST" # pylint: disable=invalid-name calls = [] NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3" @pytest.fixture def alexa_client(loop, hass, hass_client): """Initialize a Home Assistant server for testing this module.""" @callback def mock_service(call): calls.append(call) hass.services.async_register("test", "alexa", mock_service) assert loop.run_until_complete( async_setup_component( hass, alexa.DOMAIN, { # Key is here to verify we allow other keys in config too "homeassistant": {}, "alexa": {}, }, ) ) assert loop.run_until_complete( async_setup_component( hass, "intent_script", { "intent_script": { "WhereAreWeIntent": { "speech": { "type": "plain", "text": """ {%- if is_state("device_tracker.paulus", "home") and is_state("device_tracker.anne_therese", "home") -%} You are both home, you silly {%- else -%} Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }} {% endif %} """, } }, "GetZodiacHoroscopeIntent": { "speech": { "type": "plain", "text": "You told us your sign is {{ ZodiacSign }}.", } }, "AMAZON.PlaybackAction<object@MusicCreativeWork>": { "speech": { "type": "plain", "text": "Playing {{ object_byArtist_name }}.", } }, "CallServiceIntent": { "speech": { "type": "plain", "text": "Service called for {{ ZodiacSign }}", }, "card": { "type": "simple", "title": "Card title for {{ ZodiacSign }}", "content": "Card content: {{ ZodiacSign }}", }, "action": { "service": "test.alexa", "data_template": {"hello": "{{ ZodiacSign }}"}, "entity_id": "switch.test", }, }, APPLICATION_ID: { "speech": { "type": "plain", "text": "LaunchRequest has been received.", } }, } }, ) ) return loop.run_until_complete(hass_client()) def _intent_req(client, data=None): return client.post( intent.INTENTS_API_ENDPOINT, data=json.dumps(data or {}), headers={"content-type": "application/json"}, ) async def test_intent_launch_request(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "LaunchRequest has been received." async def test_intent_launch_request_not_configured(alexa_client): """Test the launch of a request.""" data = { "version": "1.0", "session": { "new": True, "sessionId": SESSION_ID, "application": { "applicationId": "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00000" }, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "LaunchRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "This intent is not yet configured within Home Assistant." async def test_intent_request_with_slots(alexa_client): """Test a request with slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is virgo." async def test_intent_request_with_slots_and_synonym_resolution(alexa_client): """Test a request with slots and a name synonym.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_NO_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is Virgo." async def test_intent_request_with_slots_and_multi_synonym_resolution(alexa_client): """Test a request with slots and multiple name synonyms.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": { "ZodiacSign": { "name": "ZodiacSign", "value": "V zodiac", "resolutions": { "resolutionsPerAuthority": [ { "authority": AUTHORITY_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Virgo"}}], }, { "authority": BUILTIN_AUTH_ID, "status": {"code": "ER_SUCCESS_MATCH"}, "values": [{"value": {"name": "Test"}}], }, ] }, } }, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is V zodiac." async def test_intent_request_with_slots_but_no_value(alexa_client): """Test a request with slots but no value.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "GetZodiacHoroscopeIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign"}}, }, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You told us your sign is ." async def test_intent_request_without_slots(hass, alexa_client): """Test a request without slots.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": {"name": "WhereAreWeIntent"}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Anne Therese is at unknown and Paulus is at unknown" hass.states.async_set("device_tracker.paulus", "home") hass.states.async_set("device_tracker.anne_therese", "home") req = await _intent_req(alexa_client, data) assert req.status == 200 json = await req.json() text = json.get("response", {}).get("outputSpeech", {}).get("text") assert text == "You are both home, you silly" async def test_intent_request_calling_service(alexa_client): """Test a request for calling a service.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": {}, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "IntentRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "intent": { "name": "CallServiceIntent", "slots": {"ZodiacSign": {"name": "ZodiacSign", "value": "virgo"}}, }, }, } call_count = len(calls) req = await _intent_req(alexa_client, data) assert req.status == 200 assert call_count + 1 == len(calls) call = calls[-1] assert call.domain == "test" assert call.service == "alexa" assert call.data.get("entity_id") == ["switch.test"] assert call.data.get("hello") == "virgo" data = await req.json() assert data["response"]["card"]["title"] == "Card title for virgo" assert data["response"]["card"]["content"] == "Card content: virgo" assert data["response"]["outputSpeech"]["type"] == "PlainText" assert data["response"]["outputSpeech"]["text"] == "Service called for virgo" async def test_intent_session_ended_request(alexa_client): """Test the request for ending the session.""" data = { "version": "1.0", "session": { "new": False, "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, "attributes": { "supportedHoroscopePeriods": { "daily": True, "weekly": False, "monthly": False, } }, "user": {"userId": "amzn1.account.AM3B00000000000000000000000"}, }, "request": { "type": "SessionEndedRequest", "requestId": REQUEST_ID, "timestamp": "2015-05-13T12:34:56Z", "reason": "USER_INITIATED", }, } req = await _intent_req(alexa_client, data) assert req.status == 200 text = await req.text() assert text == "" async def test_intent_from_built_in_intent_library(alexa_client): """Test intents from the Built-in Intent Library.""" data = { "request": { "intent": { "name": "AMAZON.PlaybackAction<object@MusicCreativeWork>", "slots": { "object.byArtist.name": { "name": "object.byArtist.name", "value": "the shins", }, "object.composer.name": {"name": "object.composer.name"}, "object.contentSource": {"name": "object.contentSource"}, "object.era": {"name": "object.era"}, "object.genre": {"name": "object.genre"}, "object.name": {"name": "object.name"}, "object.owner.name": {"name": "object.owner.name"}, "object.select": {"name": "object.select"}, "object.sort": {"name": "object.sort"}, "object.type": {"name": "object.type", "value": "music"}, }, }, "timestamp": "2016-12-14T23:23:37Z", "type": "IntentRequest", "requestId": REQUEST_ID, }, "session": { "sessionId": SESSION_ID, "application": {"applicationId": APPLICATION_ID}, }, } req = await _intent_req(alexa_client, data) assert req.status == 200 data = await req.json() text = data.get("response", {}).get("outputSpeech", {}).get("text") assert text == "Playing the shins."
tchellomello/home-assistant
tests/components/alexa/test_intent.py
homeassistant/components/homematic/binary_sensor.py