identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_singleton
(mock_hass)
Test singleton with function.
Test singleton with function.
def test_singleton(mock_hass): """Test singleton with function.""" @singleton.singleton("test_key") def something(hass): return object() result1 = something(mock_hass) result2 = something(mock_hass) assert result1 is result2 assert "test_key" in mock_hass.data assert mock_hass.data["test_key"] is result1
[ "def", "test_singleton", "(", "mock_hass", ")", ":", "@", "singleton", ".", "singleton", "(", "\"test_key\"", ")", "def", "something", "(", "hass", ")", ":", "return", "object", "(", ")", "result1", "=", "something", "(", "mock_hass", ")", "result2", "=", "something", "(", "mock_hass", ")", "assert", "result1", "is", "result2", "assert", "\"test_key\"", "in", "mock_hass", ".", "data", "assert", "mock_hass", ".", "data", "[", "\"test_key\"", "]", "is", "result1" ]
[ 28, 0 ]
[ 39, 48 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the RPi cover platform.
Set up the RPi cover platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the RPi cover platform.""" setup_reload_service(hass, DOMAIN, PLATFORMS) relay_time = config.get(CONF_RELAY_TIME) state_pull_mode = config.get(CONF_STATE_PULL_MODE) invert_state = config.get(CONF_INVERT_STATE) invert_relay = config.get(CONF_INVERT_RELAY) covers = [] covers_conf = config.get(CONF_COVERS) for cover in covers_conf: covers.append( RPiGPIOCover( cover[CONF_NAME], cover[CONF_RELAY_PIN], cover[CONF_STATE_PIN], state_pull_mode, relay_time, invert_state, invert_relay, ) ) add_entities(covers)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "setup_reload_service", "(", "hass", ",", "DOMAIN", ",", "PLATFORMS", ")", "relay_time", "=", "config", ".", "get", "(", "CONF_RELAY_TIME", ")", "state_pull_mode", "=", "config", ".", "get", "(", "CONF_STATE_PULL_MODE", ")", "invert_state", "=", "config", ".", "get", "(", "CONF_INVERT_STATE", ")", "invert_relay", "=", "config", ".", "get", "(", "CONF_INVERT_RELAY", ")", "covers", "=", "[", "]", "covers_conf", "=", "config", ".", "get", "(", "CONF_COVERS", ")", "for", "cover", "in", "covers_conf", ":", "covers", ".", "append", "(", "RPiGPIOCover", "(", "cover", "[", "CONF_NAME", "]", ",", "cover", "[", "CONF_RELAY_PIN", "]", ",", "cover", "[", "CONF_STATE_PIN", "]", ",", "state_pull_mode", ",", "relay_time", ",", "invert_state", ",", "invert_relay", ",", ")", ")", "add_entities", "(", "covers", ")" ]
[ 49, 0 ]
[ 73, 24 ]
python
en
['en', 'da', 'en']
True
RPiGPIOCover.__init__
( self, name, relay_pin, state_pin, state_pull_mode, relay_time, invert_state, invert_relay, )
Initialize the cover.
Initialize the cover.
def __init__( self, name, relay_pin, state_pin, state_pull_mode, relay_time, invert_state, invert_relay, ): """Initialize the cover.""" self._name = name self._state = False self._relay_pin = relay_pin self._state_pin = state_pin self._state_pull_mode = state_pull_mode self._relay_time = relay_time self._invert_state = invert_state self._invert_relay = invert_relay rpi_gpio.setup_output(self._relay_pin) rpi_gpio.setup_input(self._state_pin, self._state_pull_mode) rpi_gpio.write_output(self._relay_pin, 0 if self._invert_relay else 1)
[ "def", "__init__", "(", "self", ",", "name", ",", "relay_pin", ",", "state_pin", ",", "state_pull_mode", ",", "relay_time", ",", "invert_state", ",", "invert_relay", ",", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_state", "=", "False", "self", ".", "_relay_pin", "=", "relay_pin", "self", ".", "_state_pin", "=", "state_pin", "self", ".", "_state_pull_mode", "=", "state_pull_mode", "self", ".", "_relay_time", "=", "relay_time", "self", ".", "_invert_state", "=", "invert_state", "self", ".", "_invert_relay", "=", "invert_relay", "rpi_gpio", ".", "setup_output", "(", "self", ".", "_relay_pin", ")", "rpi_gpio", ".", "setup_input", "(", "self", ".", "_state_pin", ",", "self", ".", "_state_pull_mode", ")", "rpi_gpio", ".", "write_output", "(", "self", ".", "_relay_pin", ",", "0", "if", "self", ".", "_invert_relay", "else", "1", ")" ]
[ 79, 4 ]
[ 100, 78 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover.name
(self)
Return the name of the cover if any.
Return the name of the cover if any.
def name(self): """Return the name of the cover if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 103, 4 ]
[ 105, 25 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover.update
(self)
Update the state of the cover.
Update the state of the cover.
def update(self): """Update the state of the cover.""" self._state = rpi_gpio.read_input(self._state_pin)
[ "def", "update", "(", "self", ")", ":", "self", ".", "_state", "=", "rpi_gpio", ".", "read_input", "(", "self", ".", "_state_pin", ")" ]
[ 107, 4 ]
[ 109, 58 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover.is_closed
(self)
Return true if cover is closed.
Return true if cover is closed.
def is_closed(self): """Return true if cover is closed.""" return self._state != self._invert_state
[ "def", "is_closed", "(", "self", ")", ":", "return", "self", ".", "_state", "!=", "self", ".", "_invert_state" ]
[ 112, 4 ]
[ 114, 48 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover._trigger
(self)
Trigger the cover.
Trigger the cover.
def _trigger(self): """Trigger the cover.""" rpi_gpio.write_output(self._relay_pin, 1 if self._invert_relay else 0) sleep(self._relay_time) rpi_gpio.write_output(self._relay_pin, 0 if self._invert_relay else 1)
[ "def", "_trigger", "(", "self", ")", ":", "rpi_gpio", ".", "write_output", "(", "self", ".", "_relay_pin", ",", "1", "if", "self", ".", "_invert_relay", "else", "0", ")", "sleep", "(", "self", ".", "_relay_time", ")", "rpi_gpio", ".", "write_output", "(", "self", ".", "_relay_pin", ",", "0", "if", "self", ".", "_invert_relay", "else", "1", ")" ]
[ 116, 4 ]
[ 120, 78 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover.close_cover
(self, **kwargs)
Close the cover.
Close the cover.
def close_cover(self, **kwargs): """Close the cover.""" if not self.is_closed: self._trigger()
[ "def", "close_cover", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_closed", ":", "self", ".", "_trigger", "(", ")" ]
[ 122, 4 ]
[ 125, 27 ]
python
en
['en', 'en', 'en']
True
RPiGPIOCover.open_cover
(self, **kwargs)
Open the cover.
Open the cover.
def open_cover(self, **kwargs): """Open the cover.""" if self.is_closed: self._trigger()
[ "def", "open_cover", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "is_closed", ":", "self", ".", "_trigger", "(", ")" ]
[ 127, 4 ]
[ 130, 27 ]
python
en
['en', 'en', 'en']
True
convert_slow_tokenizer
(transformer_tokenizer)
Utilities to convert a slow tokenizer instance in a fast tokenizer instance. Args: transformer_tokenizer (:class:`~transformers.tokenization_utils_base.PreTrainedTokenizer`): Instance of a slow tokenizer to convert in the backend tokenizer for :class:`~transformers.tokenization_utils_base.PreTrainedTokenizerFast`. Return: A instance of :class:`~tokenizers.Tokenizer` to be used as the backend tokenizer of a :class:`~transformers.tokenization_utils_base.PreTrainedTokenizerFast`
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
def convert_slow_tokenizer(transformer_tokenizer) -> Tokenizer: """ Utilities to convert a slow tokenizer instance in a fast tokenizer instance. Args: transformer_tokenizer (:class:`~transformers.tokenization_utils_base.PreTrainedTokenizer`): Instance of a slow tokenizer to convert in the backend tokenizer for :class:`~transformers.tokenization_utils_base.PreTrainedTokenizerFast`. Return: A instance of :class:`~tokenizers.Tokenizer` to be used as the backend tokenizer of a :class:`~transformers.tokenization_utils_base.PreTrainedTokenizerFast` """ tokenizer_class_name = transformer_tokenizer.__class__.__name__ if tokenizer_class_name not in SLOW_TO_FAST_CONVERTERS: raise ValueError( f"An instance of tokenizer class {tokenizer_class_name} cannot be converted in a Fast tokenizer instance. " f"No converter was found. Currently available slow->fast convertors: {list(SLOW_TO_FAST_CONVERTERS.keys())}" ) converter_class = SLOW_TO_FAST_CONVERTERS[tokenizer_class_name] return converter_class(transformer_tokenizer).converted()
[ "def", "convert_slow_tokenizer", "(", "transformer_tokenizer", ")", "->", "Tokenizer", ":", "tokenizer_class_name", "=", "transformer_tokenizer", ".", "__class__", ".", "__name__", "if", "tokenizer_class_name", "not", "in", "SLOW_TO_FAST_CONVERTERS", ":", "raise", "ValueError", "(", "f\"An instance of tokenizer class {tokenizer_class_name} cannot be converted in a Fast tokenizer instance. \"", "f\"No converter was found. Currently available slow->fast convertors: {list(SLOW_TO_FAST_CONVERTERS.keys())}\"", ")", "converter_class", "=", "SLOW_TO_FAST_CONVERTERS", "[", "tokenizer_class_name", "]", "return", "converter_class", "(", "transformer_tokenizer", ")", ".", "converted", "(", ")" ]
[ 683, 0 ]
[ 707, 61 ]
python
en
['en', 'error', 'th']
False
entity_sources
(hass: HomeAssistant)
Get the entity sources.
Get the entity sources.
def entity_sources(hass: HomeAssistant) -> Dict[str, Dict[str, str]]: """Get the entity sources.""" return hass.data.get(DATA_ENTITY_SOURCE, {})
[ "def", "entity_sources", "(", "hass", ":", "HomeAssistant", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "return", "hass", ".", "data", ".", "get", "(", "DATA_ENTITY_SOURCE", ",", "{", "}", ")" ]
[ 44, 0 ]
[ 46, 48 ]
python
en
['en', 'en', 'en']
True
generate_entity_id
( entity_id_format: str, name: Optional[str], current_ids: Optional[List[str]] = None, hass: Optional[HomeAssistant] = None, )
Generate a unique entity ID based on given entity IDs or used IDs.
Generate a unique entity ID based on given entity IDs or used IDs.
def generate_entity_id( entity_id_format: str, name: Optional[str], current_ids: Optional[List[str]] = None, hass: Optional[HomeAssistant] = None, ) -> str: """Generate a unique entity ID based on given entity IDs or used IDs.""" return async_generate_entity_id(entity_id_format, name, current_ids, hass)
[ "def", "generate_entity_id", "(", "entity_id_format", ":", "str", ",", "name", ":", "Optional", "[", "str", "]", ",", "current_ids", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "hass", ":", "Optional", "[", "HomeAssistant", "]", "=", "None", ",", ")", "->", "str", ":", "return", "async_generate_entity_id", "(", "entity_id_format", ",", "name", ",", "current_ids", ",", "hass", ")" ]
[ 49, 0 ]
[ 56, 78 ]
python
en
['en', 'en', 'en']
True
async_generate_entity_id
( entity_id_format: str, name: Optional[str], current_ids: Optional[Iterable[str]] = None, hass: Optional[HomeAssistant] = None, )
Generate a unique entity ID based on given entity IDs or used IDs.
Generate a unique entity ID based on given entity IDs or used IDs.
def async_generate_entity_id( entity_id_format: str, name: Optional[str], current_ids: Optional[Iterable[str]] = None, hass: Optional[HomeAssistant] = None, ) -> str: """Generate a unique entity ID based on given entity IDs or used IDs.""" name = (name or DEVICE_DEFAULT_NAME).lower() preferred_string = entity_id_format.format(slugify(name)) if current_ids is not None: return ensure_unique_string(preferred_string, current_ids) if hass is None: raise ValueError("Missing required parameter current_ids or hass") test_string = preferred_string tries = 1 while not hass.states.async_available(test_string): tries += 1 test_string = f"{preferred_string}_{tries}" return test_string
[ "def", "async_generate_entity_id", "(", "entity_id_format", ":", "str", ",", "name", ":", "Optional", "[", "str", "]", ",", "current_ids", ":", "Optional", "[", "Iterable", "[", "str", "]", "]", "=", "None", ",", "hass", ":", "Optional", "[", "HomeAssistant", "]", "=", "None", ",", ")", "->", "str", ":", "name", "=", "(", "name", "or", "DEVICE_DEFAULT_NAME", ")", ".", "lower", "(", ")", "preferred_string", "=", "entity_id_format", ".", "format", "(", "slugify", "(", "name", ")", ")", "if", "current_ids", "is", "not", "None", ":", "return", "ensure_unique_string", "(", "preferred_string", ",", "current_ids", ")", "if", "hass", "is", "None", ":", "raise", "ValueError", "(", "\"Missing required parameter current_ids or hass\"", ")", "test_string", "=", "preferred_string", "tries", "=", "1", "while", "not", "hass", ".", "states", ".", "async_available", "(", "test_string", ")", ":", "tries", "+=", "1", "test_string", "=", "f\"{preferred_string}_{tries}\"", "return", "test_string" ]
[ 60, 0 ]
[ 83, 22 ]
python
en
['en', 'en', 'en']
True
Entity.should_poll
(self)
Return True if entity has to be polled for state. False if entity pushes its state to HA.
Return True if entity has to be polled for state.
def should_poll(self) -> bool: """Return True if entity has to be polled for state. False if entity pushes its state to HA. """ return True
[ "def", "should_poll", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 126, 4 ]
[ 131, 19 ]
python
en
['en', 'en', 'en']
True
Entity.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self) -> Optional[str]: """Return a unique ID.""" return None
[ "def", "unique_id", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 134, 4 ]
[ 136, 19 ]
python
ca
['fr', 'ca', 'en']
False
Entity.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self) -> Optional[str]: """Return the name of the entity.""" return None
[ "def", "name", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 139, 4 ]
[ 141, 19 ]
python
en
['en', 'en', 'en']
True
Entity.state
(self)
Return the state of the entity.
Return the state of the entity.
def state(self) -> StateType: """Return the state of the entity.""" return STATE_UNKNOWN
[ "def", "state", "(", "self", ")", "->", "StateType", ":", "return", "STATE_UNKNOWN" ]
[ 144, 4 ]
[ 146, 28 ]
python
en
['en', 'en', 'en']
True
Entity.capability_attributes
(self)
Return the capability attributes. Attributes that explain the capabilities of an entity. Implemented by component base class. Convention for attribute names is lowercase snake_case.
Return the capability attributes.
def capability_attributes(self) -> Optional[Dict[str, Any]]: """Return the capability attributes. Attributes that explain the capabilities of an entity. Implemented by component base class. Convention for attribute names is lowercase snake_case. """ return None
[ "def", "capability_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "None" ]
[ 149, 4 ]
[ 157, 19 ]
python
en
['en', 'en', 'en']
True
Entity.state_attributes
(self)
Return the state attributes. Implemented by component base class. Convention for attribute names is lowercase snake_case.
Return the state attributes.
def state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes. Implemented by component base class. Convention for attribute names is lowercase snake_case. """ return None
[ "def", "state_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "None" ]
[ 160, 4 ]
[ 166, 19 ]
python
en
['en', 'en', 'en']
True
Entity.device_state_attributes
(self)
Return device specific state attributes. Implemented by platform classes. Convention for attribute names is lowercase snake_case.
Return device specific state attributes.
def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return device specific state attributes. Implemented by platform classes. Convention for attribute names is lowercase snake_case. """ return None
[ "def", "device_state_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "None" ]
[ 169, 4 ]
[ 175, 19 ]
python
en
['fr', 'en', 'en']
True
Entity.device_info
(self)
Return device specific attributes. Implemented by platform classes.
Return device specific attributes.
def device_info(self) -> Optional[Dict[str, Any]]: """Return device specific attributes. Implemented by platform classes. """ return None
[ "def", "device_info", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "None" ]
[ 178, 4 ]
[ 183, 19 ]
python
en
['fr', 'it', 'en']
False
Entity.device_class
(self)
Return the class of this device, from component DEVICE_CLASSES.
Return the class of this device, from component DEVICE_CLASSES.
def device_class(self) -> Optional[str]: """Return the class of this device, from component DEVICE_CLASSES.""" return None
[ "def", "device_class", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 186, 4 ]
[ 188, 19 ]
python
en
['en', 'en', 'en']
True
Entity.unit_of_measurement
(self)
Return the unit of measurement of this entity, if any.
Return the unit of measurement of this entity, if any.
def unit_of_measurement(self) -> Optional[str]: """Return the unit of measurement of this entity, if any.""" return None
[ "def", "unit_of_measurement", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 191, 4 ]
[ 193, 19 ]
python
en
['en', 'en', 'en']
True
Entity.icon
(self)
Return the icon to use in the frontend, if any.
Return the icon to use in the frontend, if any.
def icon(self) -> Optional[str]: """Return the icon to use in the frontend, if any.""" return None
[ "def", "icon", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 196, 4 ]
[ 198, 19 ]
python
en
['en', 'en', 'en']
True
Entity.entity_picture
(self)
Return the entity picture to use in the frontend, if any.
Return the entity picture to use in the frontend, if any.
def entity_picture(self) -> Optional[str]: """Return the entity picture to use in the frontend, if any.""" return None
[ "def", "entity_picture", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "None" ]
[ 201, 4 ]
[ 203, 19 ]
python
en
['en', 'en', 'en']
True
Entity.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" return True
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 206, 4 ]
[ 208, 19 ]
python
en
['en', 'en', 'en']
True
Entity.assumed_state
(self)
Return True if unable to access real state of the entity.
Return True if unable to access real state of the entity.
def assumed_state(self) -> bool: """Return True if unable to access real state of the entity.""" return False
[ "def", "assumed_state", "(", "self", ")", "->", "bool", ":", "return", "False" ]
[ 211, 4 ]
[ 213, 20 ]
python
en
['en', 'en', 'en']
True
Entity.force_update
(self)
Return True if state updates should be forced. If True, a state change will be triggered anytime the state property is updated, not just when the value changes.
Return True if state updates should be forced.
def force_update(self) -> bool: """Return True if state updates should be forced. If True, a state change will be triggered anytime the state property is updated, not just when the value changes. """ return False
[ "def", "force_update", "(", "self", ")", "->", "bool", ":", "return", "False" ]
[ 216, 4 ]
[ 222, 20 ]
python
en
['en', 'en', 'en']
True
Entity.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> Optional[int]: """Flag supported features.""" return None
[ "def", "supported_features", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "return", "None" ]
[ 225, 4 ]
[ 227, 19 ]
python
en
['da', 'en', 'en']
True
Entity.context_recent_time
(self)
Time that a context is considered recent.
Time that a context is considered recent.
def context_recent_time(self) -> timedelta: """Time that a context is considered recent.""" return timedelta(seconds=5)
[ "def", "context_recent_time", "(", "self", ")", "->", "timedelta", ":", "return", "timedelta", "(", "seconds", "=", "5", ")" ]
[ 230, 4 ]
[ 232, 35 ]
python
en
['en', 'en', 'en']
True
Entity.entity_registry_enabled_default
(self)
Return if the entity should be enabled when first added to the entity registry.
Return if the entity should be enabled when first added to the entity registry.
def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return True
[ "def", "entity_registry_enabled_default", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 235, 4 ]
[ 237, 19 ]
python
en
['en', 'en', 'en']
True
Entity.enabled
(self)
Return if the entity is enabled in the entity registry. If an entity is not part of the registry, it cannot be disabled and will therefore always be enabled.
Return if the entity is enabled in the entity registry.
def enabled(self) -> bool: """Return if the entity is enabled in the entity registry. If an entity is not part of the registry, it cannot be disabled and will therefore always be enabled. """ return self.registry_entry is None or not self.registry_entry.disabled
[ "def", "enabled", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "registry_entry", "is", "None", "or", "not", "self", ".", "registry_entry", ".", "disabled" ]
[ 245, 4 ]
[ 251, 78 ]
python
en
['en', 'en', 'en']
True
Entity.async_set_context
(self, context: Context)
Set the context the entity currently operates under.
Set the context the entity currently operates under.
def async_set_context(self, context: Context) -> None: """Set the context the entity currently operates under.""" self._context = context self._context_set = dt_util.utcnow()
[ "def", "async_set_context", "(", "self", ",", "context", ":", "Context", ")", "->", "None", ":", "self", ".", "_context", "=", "context", "self", ".", "_context_set", "=", "dt_util", ".", "utcnow", "(", ")" ]
[ 254, 4 ]
[ 257, 44 ]
python
en
['en', 'en', 'en']
True
Entity.async_update_ha_state
(self, force_refresh: bool = False)
Update Home Assistant with current state of entity. If force_refresh == True will update entity before setting state. This method must be run in the event loop.
Update Home Assistant with current state of entity.
async def async_update_ha_state(self, force_refresh: bool = False) -> None: """Update Home Assistant with current state of entity. If force_refresh == True will update entity before setting state. This method must be run in the event loop. """ if self.hass is None: raise RuntimeError(f"Attribute hass is None for {self}") if self.entity_id is None: raise NoEntitySpecifiedError( f"No entity id specified for entity {self.name}" ) # update entity data if force_refresh: try: await self.async_device_update() except Exception: # pylint: disable=broad-except _LOGGER.exception("Update for %s fails", self.entity_id) return self._async_write_ha_state()
[ "async", "def", "async_update_ha_state", "(", "self", ",", "force_refresh", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "self", ".", "hass", "is", "None", ":", "raise", "RuntimeError", "(", "f\"Attribute hass is None for {self}\"", ")", "if", "self", ".", "entity_id", "is", "None", ":", "raise", "NoEntitySpecifiedError", "(", "f\"No entity id specified for entity {self.name}\"", ")", "# update entity data", "if", "force_refresh", ":", "try", ":", "await", "self", ".", "async_device_update", "(", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Update for %s fails\"", ",", "self", ".", "entity_id", ")", "return", "self", ".", "_async_write_ha_state", "(", ")" ]
[ 259, 4 ]
[ 282, 36 ]
python
en
['en', 'en', 'en']
True
Entity.async_write_ha_state
(self)
Write the state to the state machine.
Write the state to the state machine.
def async_write_ha_state(self) -> None: """Write the state to the state machine.""" if self.hass is None: raise RuntimeError(f"Attribute hass is None for {self}") if self.entity_id is None: raise NoEntitySpecifiedError( f"No entity id specified for entity {self.name}" ) self._async_write_ha_state()
[ "def", "async_write_ha_state", "(", "self", ")", "->", "None", ":", "if", "self", ".", "hass", "is", "None", ":", "raise", "RuntimeError", "(", "f\"Attribute hass is None for {self}\"", ")", "if", "self", ".", "entity_id", "is", "None", ":", "raise", "NoEntitySpecifiedError", "(", "f\"No entity id specified for entity {self.name}\"", ")", "self", ".", "_async_write_ha_state", "(", ")" ]
[ 285, 4 ]
[ 295, 36 ]
python
en
['en', 'en', 'en']
True
Entity._async_write_ha_state
(self)
Write the state to the state machine.
Write the state to the state machine.
def _async_write_ha_state(self) -> None: """Write the state to the state machine.""" if self.registry_entry and self.registry_entry.disabled_by: if not self._disabled_reported: self._disabled_reported = True assert self.platform is not None _LOGGER.warning( "Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration", self.entity_id, self.platform.platform_name, ) return start = timer() attr = self.capability_attributes attr = dict(attr) if attr else {} if not self.available: state = STATE_UNAVAILABLE else: sstate = self.state state = STATE_UNKNOWN if sstate is None else str(sstate) attr.update(self.state_attributes or {}) attr.update(self.device_state_attributes or {}) unit_of_measurement = self.unit_of_measurement if unit_of_measurement is not None: attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement entry = self.registry_entry # pylint: disable=consider-using-ternary name = (entry and entry.name) or self.name if name is not None: attr[ATTR_FRIENDLY_NAME] = name icon = (entry and entry.icon) or self.icon if icon is not None: attr[ATTR_ICON] = icon entity_picture = self.entity_picture if entity_picture is not None: attr[ATTR_ENTITY_PICTURE] = entity_picture assumed_state = self.assumed_state if assumed_state: attr[ATTR_ASSUMED_STATE] = assumed_state supported_features = self.supported_features if supported_features is not None: attr[ATTR_SUPPORTED_FEATURES] = supported_features device_class = self.device_class if device_class is not None: attr[ATTR_DEVICE_CLASS] = str(device_class) end = timer() if end - start > 0.4 and not self._slow_reported: self._slow_reported = True extra = "" if "custom_components" in type(self).__module__: extra = "Please report it to the custom component author." else: extra = ( "Please create a bug report at " "https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue" ) if self.platform: extra += ( f"+label%3A%22integration%3A+{self.platform.platform_name}%22" ) _LOGGER.warning( "Updating state for %s (%s) took %.3f seconds. %s", self.entity_id, type(self), end - start, extra, ) # Overwrite properties that have been set in the config file. assert self.hass is not None if DATA_CUSTOMIZE in self.hass.data: attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id)) # Convert temperature if we detect one try: unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT) units = self.hass.config.units if ( unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and unit_of_measure != units.temperature_unit ): prec = len(state) - state.index(".") - 1 if "." in state else 0 temp = units.temperature(float(state), unit_of_measure) state = str(round(temp) if prec == 0 else round(temp, prec)) attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit except ValueError: # Could not convert state to float pass if ( self._context_set is not None and dt_util.utcnow() - self._context_set > self.context_recent_time ): self._context = None self._context_set = None self.hass.states.async_set( self.entity_id, state, attr, self.force_update, self._context )
[ "def", "_async_write_ha_state", "(", "self", ")", "->", "None", ":", "if", "self", ".", "registry_entry", "and", "self", ".", "registry_entry", ".", "disabled_by", ":", "if", "not", "self", ".", "_disabled_reported", ":", "self", ".", "_disabled_reported", "=", "True", "assert", "self", ".", "platform", "is", "not", "None", "_LOGGER", ".", "warning", "(", "\"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration\"", ",", "self", ".", "entity_id", ",", "self", ".", "platform", ".", "platform_name", ",", ")", "return", "start", "=", "timer", "(", ")", "attr", "=", "self", ".", "capability_attributes", "attr", "=", "dict", "(", "attr", ")", "if", "attr", "else", "{", "}", "if", "not", "self", ".", "available", ":", "state", "=", "STATE_UNAVAILABLE", "else", ":", "sstate", "=", "self", ".", "state", "state", "=", "STATE_UNKNOWN", "if", "sstate", "is", "None", "else", "str", "(", "sstate", ")", "attr", ".", "update", "(", "self", ".", "state_attributes", "or", "{", "}", ")", "attr", ".", "update", "(", "self", ".", "device_state_attributes", "or", "{", "}", ")", "unit_of_measurement", "=", "self", ".", "unit_of_measurement", "if", "unit_of_measurement", "is", "not", "None", ":", "attr", "[", "ATTR_UNIT_OF_MEASUREMENT", "]", "=", "unit_of_measurement", "entry", "=", "self", ".", "registry_entry", "# pylint: disable=consider-using-ternary", "name", "=", "(", "entry", "and", "entry", ".", "name", ")", "or", "self", ".", "name", "if", "name", "is", "not", "None", ":", "attr", "[", "ATTR_FRIENDLY_NAME", "]", "=", "name", "icon", "=", "(", "entry", "and", "entry", ".", "icon", ")", "or", "self", ".", "icon", "if", "icon", "is", "not", "None", ":", "attr", "[", "ATTR_ICON", "]", "=", "icon", "entity_picture", "=", "self", ".", "entity_picture", "if", "entity_picture", "is", "not", "None", ":", "attr", "[", "ATTR_ENTITY_PICTURE", "]", "=", "entity_picture", "assumed_state", "=", "self", ".", "assumed_state", "if", "assumed_state", ":", "attr", "[", "ATTR_ASSUMED_STATE", "]", "=", "assumed_state", "supported_features", "=", "self", ".", "supported_features", "if", "supported_features", "is", "not", "None", ":", "attr", "[", "ATTR_SUPPORTED_FEATURES", "]", "=", "supported_features", "device_class", "=", "self", ".", "device_class", "if", "device_class", "is", "not", "None", ":", "attr", "[", "ATTR_DEVICE_CLASS", "]", "=", "str", "(", "device_class", ")", "end", "=", "timer", "(", ")", "if", "end", "-", "start", ">", "0.4", "and", "not", "self", ".", "_slow_reported", ":", "self", ".", "_slow_reported", "=", "True", "extra", "=", "\"\"", "if", "\"custom_components\"", "in", "type", "(", "self", ")", ".", "__module__", ":", "extra", "=", "\"Please report it to the custom component author.\"", "else", ":", "extra", "=", "(", "\"Please create a bug report at \"", "\"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue\"", ")", "if", "self", ".", "platform", ":", "extra", "+=", "(", "f\"+label%3A%22integration%3A+{self.platform.platform_name}%22\"", ")", "_LOGGER", ".", "warning", "(", "\"Updating state for %s (%s) took %.3f seconds. %s\"", ",", "self", ".", "entity_id", ",", "type", "(", "self", ")", ",", "end", "-", "start", ",", "extra", ",", ")", "# Overwrite properties that have been set in the config file.", "assert", "self", ".", "hass", "is", "not", "None", "if", "DATA_CUSTOMIZE", "in", "self", ".", "hass", ".", "data", ":", "attr", ".", "update", "(", "self", ".", "hass", ".", "data", "[", "DATA_CUSTOMIZE", "]", ".", "get", "(", "self", ".", "entity_id", ")", ")", "# Convert temperature if we detect one", "try", ":", "unit_of_measure", "=", "attr", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "units", "=", "self", ".", "hass", ".", "config", ".", "units", "if", "(", "unit_of_measure", "in", "(", "TEMP_CELSIUS", ",", "TEMP_FAHRENHEIT", ")", "and", "unit_of_measure", "!=", "units", ".", "temperature_unit", ")", ":", "prec", "=", "len", "(", "state", ")", "-", "state", ".", "index", "(", "\".\"", ")", "-", "1", "if", "\".\"", "in", "state", "else", "0", "temp", "=", "units", ".", "temperature", "(", "float", "(", "state", ")", ",", "unit_of_measure", ")", "state", "=", "str", "(", "round", "(", "temp", ")", "if", "prec", "==", "0", "else", "round", "(", "temp", ",", "prec", ")", ")", "attr", "[", "ATTR_UNIT_OF_MEASUREMENT", "]", "=", "units", ".", "temperature_unit", "except", "ValueError", ":", "# Could not convert state to float", "pass", "if", "(", "self", ".", "_context_set", "is", "not", "None", "and", "dt_util", ".", "utcnow", "(", ")", "-", "self", ".", "_context_set", ">", "self", ".", "context_recent_time", ")", ":", "self", ".", "_context", "=", "None", "self", ".", "_context_set", "=", "None", "self", ".", "hass", ".", "states", ".", "async_set", "(", "self", ".", "entity_id", ",", "state", ",", "attr", ",", "self", ".", "force_update", ",", "self", ".", "_context", ")" ]
[ 298, 4 ]
[ 409, 9 ]
python
en
['en', 'en', 'en']
True
Entity.schedule_update_ha_state
(self, force_refresh: bool = False)
Schedule an update ha state change task. Scheduling the update avoids executor deadlocks. Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed.
Schedule an update ha state change task.
def schedule_update_ha_state(self, force_refresh: bool = False) -> None: """Schedule an update ha state change task. Scheduling the update avoids executor deadlocks. Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed. """ assert self.hass is not None self.hass.add_job(self.async_update_ha_state(force_refresh))
[ "def", "schedule_update_ha_state", "(", "self", ",", "force_refresh", ":", "bool", "=", "False", ")", "->", "None", ":", "assert", "self", ".", "hass", "is", "not", "None", "self", ".", "hass", ".", "add_job", "(", "self", ".", "async_update_ha_state", "(", "force_refresh", ")", ")" ]
[ 411, 4 ]
[ 422, 68 ]
python
en
['br', 'en', 'en']
True
Entity.async_schedule_update_ha_state
(self, force_refresh: bool = False)
Schedule an update ha state change task. This method must be run in the event loop. Scheduling the update avoids executor deadlocks. Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed.
Schedule an update ha state change task.
def async_schedule_update_ha_state(self, force_refresh: bool = False) -> None: """Schedule an update ha state change task. This method must be run in the event loop. Scheduling the update avoids executor deadlocks. Entity state and attributes are read when the update ha state change task is executed. If state is changed more than once before the ha state change task has been executed, the intermediate state transitions will be missed. """ if force_refresh: assert self.hass is not None self.hass.async_create_task(self.async_update_ha_state(force_refresh)) else: self.async_write_ha_state()
[ "def", "async_schedule_update_ha_state", "(", "self", ",", "force_refresh", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "force_refresh", ":", "assert", "self", ".", "hass", "is", "not", "None", "self", ".", "hass", ".", "async_create_task", "(", "self", ".", "async_update_ha_state", "(", "force_refresh", ")", ")", "else", ":", "self", ".", "async_write_ha_state", "(", ")" ]
[ 425, 4 ]
[ 440, 39 ]
python
en
['br', 'en', 'en']
True
Entity.async_device_update
(self, warning: bool = True)
Process 'update' or 'async_update' from entity. This method is a coroutine.
Process 'update' or 'async_update' from entity.
async def async_device_update(self, warning: bool = True) -> None: """Process 'update' or 'async_update' from entity. This method is a coroutine. """ if self._update_staged: return self._update_staged = True # Process update sequential if self.parallel_updates: await self.parallel_updates.acquire() try: # pylint: disable=no-member if hasattr(self, "async_update"): task = self.hass.async_create_task(self.async_update()) # type: ignore elif hasattr(self, "update"): task = self.hass.async_add_executor_job(self.update) # type: ignore else: return if not warning: await task return finished, _ = await asyncio.wait([task], timeout=SLOW_UPDATE_WARNING) for done in finished: exc = done.exception() if exc: raise exc return _LOGGER.warning( "Update of %s is taking over %s seconds", self.entity_id, SLOW_UPDATE_WARNING, ) await task finally: self._update_staged = False if self.parallel_updates: self.parallel_updates.release()
[ "async", "def", "async_device_update", "(", "self", ",", "warning", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "self", ".", "_update_staged", ":", "return", "self", ".", "_update_staged", "=", "True", "# Process update sequential", "if", "self", ".", "parallel_updates", ":", "await", "self", ".", "parallel_updates", ".", "acquire", "(", ")", "try", ":", "# pylint: disable=no-member", "if", "hasattr", "(", "self", ",", "\"async_update\"", ")", ":", "task", "=", "self", ".", "hass", ".", "async_create_task", "(", "self", ".", "async_update", "(", ")", ")", "# type: ignore", "elif", "hasattr", "(", "self", ",", "\"update\"", ")", ":", "task", "=", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "update", ")", "# type: ignore", "else", ":", "return", "if", "not", "warning", ":", "await", "task", "return", "finished", ",", "_", "=", "await", "asyncio", ".", "wait", "(", "[", "task", "]", ",", "timeout", "=", "SLOW_UPDATE_WARNING", ")", "for", "done", "in", "finished", ":", "exc", "=", "done", ".", "exception", "(", ")", "if", "exc", ":", "raise", "exc", "return", "_LOGGER", ".", "warning", "(", "\"Update of %s is taking over %s seconds\"", ",", "self", ".", "entity_id", ",", "SLOW_UPDATE_WARNING", ",", ")", "await", "task", "finally", ":", "self", ".", "_update_staged", "=", "False", "if", "self", ".", "parallel_updates", ":", "self", ".", "parallel_updates", ".", "release", "(", ")" ]
[ 442, 4 ]
[ 485, 47 ]
python
en
['en', 'en', 'en']
True
Entity.async_on_remove
(self, func: CALLBACK_TYPE)
Add a function to call when entity removed.
Add a function to call when entity removed.
def async_on_remove(self, func: CALLBACK_TYPE) -> None: """Add a function to call when entity removed.""" if self._on_remove is None: self._on_remove = [] self._on_remove.append(func)
[ "def", "async_on_remove", "(", "self", ",", "func", ":", "CALLBACK_TYPE", ")", "->", "None", ":", "if", "self", ".", "_on_remove", "is", "None", ":", "self", ".", "_on_remove", "=", "[", "]", "self", ".", "_on_remove", ".", "append", "(", "func", ")" ]
[ 488, 4 ]
[ 492, 36 ]
python
en
['en', 'en', 'en']
True
Entity.async_removed_from_registry
(self)
Run when entity has been removed from entity registry. To be extended by integrations.
Run when entity has been removed from entity registry.
async def async_removed_from_registry(self) -> None: """Run when entity has been removed from entity registry. To be extended by integrations. """
[ "async", "def", "async_removed_from_registry", "(", "self", ")", "->", "None", ":" ]
[ 494, 4 ]
[ 498, 11 ]
python
en
['en', 'en', 'en']
True
Entity.add_to_platform_start
( self, hass: HomeAssistant, platform: EntityPlatform, parallel_updates: Optional[asyncio.Semaphore], )
Start adding an entity to a platform.
Start adding an entity to a platform.
def add_to_platform_start( self, hass: HomeAssistant, platform: EntityPlatform, parallel_updates: Optional[asyncio.Semaphore], ) -> None: """Start adding an entity to a platform.""" if self._added: raise HomeAssistantError( f"Entity {self.entity_id} cannot be added a second time to an entity platform" ) self.hass = hass self.platform = platform self.parallel_updates = parallel_updates self._added = True
[ "def", "add_to_platform_start", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "platform", ":", "EntityPlatform", ",", "parallel_updates", ":", "Optional", "[", "asyncio", ".", "Semaphore", "]", ",", ")", "->", "None", ":", "if", "self", ".", "_added", ":", "raise", "HomeAssistantError", "(", "f\"Entity {self.entity_id} cannot be added a second time to an entity platform\"", ")", "self", ".", "hass", "=", "hass", "self", ".", "platform", "=", "platform", "self", ".", "parallel_updates", "=", "parallel_updates", "self", ".", "_added", "=", "True" ]
[ 501, 4 ]
[ 516, 26 ]
python
en
['en', 'lb', 'en']
True
Entity.add_to_platform_abort
(self)
Abort adding an entity to a platform.
Abort adding an entity to a platform.
def add_to_platform_abort(self) -> None: """Abort adding an entity to a platform.""" self.hass = None self.platform = None self.parallel_updates = None self._added = False
[ "def", "add_to_platform_abort", "(", "self", ")", "->", "None", ":", "self", ".", "hass", "=", "None", "self", ".", "platform", "=", "None", "self", ".", "parallel_updates", "=", "None", "self", ".", "_added", "=", "False" ]
[ 519, 4 ]
[ 524, 27 ]
python
en
['en', 'cy', 'en']
True
Entity.add_to_platform_finish
(self)
Finish adding an entity to a platform.
Finish adding an entity to a platform.
async def add_to_platform_finish(self) -> None: """Finish adding an entity to a platform.""" await self.async_internal_added_to_hass() await self.async_added_to_hass() self.async_write_ha_state()
[ "async", "def", "add_to_platform_finish", "(", "self", ")", "->", "None", ":", "await", "self", ".", "async_internal_added_to_hass", "(", ")", "await", "self", ".", "async_added_to_hass", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 526, 4 ]
[ 530, 35 ]
python
en
['en', 'en', 'en']
True
Entity.async_remove
(self)
Remove entity from Home Assistant.
Remove entity from Home Assistant.
async def async_remove(self) -> None: """Remove entity from Home Assistant.""" assert self.hass is not None if self.platform and not self._added: raise HomeAssistantError( f"Entity {self.entity_id} async_remove called twice" ) self._added = False if self._on_remove is not None: while self._on_remove: self._on_remove.pop()() await self.async_internal_will_remove_from_hass() await self.async_will_remove_from_hass() self.hass.states.async_remove(self.entity_id, context=self._context)
[ "async", "def", "async_remove", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "hass", "is", "not", "None", "if", "self", ".", "platform", "and", "not", "self", ".", "_added", ":", "raise", "HomeAssistantError", "(", "f\"Entity {self.entity_id} async_remove called twice\"", ")", "self", ".", "_added", "=", "False", "if", "self", ".", "_on_remove", "is", "not", "None", ":", "while", "self", ".", "_on_remove", ":", "self", ".", "_on_remove", ".", "pop", "(", ")", "(", ")", "await", "self", ".", "async_internal_will_remove_from_hass", "(", ")", "await", "self", ".", "async_will_remove_from_hass", "(", ")", "self", ".", "hass", ".", "states", ".", "async_remove", "(", "self", ".", "entity_id", ",", "context", "=", "self", ".", "_context", ")" ]
[ 532, 4 ]
[ 550, 76 ]
python
en
['en', 'en', 'en']
True
Entity.async_added_to_hass
(self)
Run when entity about to be added to hass. To be extended by integrations.
Run when entity about to be added to hass.
async def async_added_to_hass(self) -> None: """Run when entity about to be added to hass. To be extended by integrations. """
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":" ]
[ 552, 4 ]
[ 556, 11 ]
python
en
['en', 'en', 'en']
True
Entity.async_will_remove_from_hass
(self)
Run when entity will be removed from hass. To be extended by integrations.
Run when entity will be removed from hass.
async def async_will_remove_from_hass(self) -> None: """Run when entity will be removed from hass. To be extended by integrations. """
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", "->", "None", ":" ]
[ 558, 4 ]
[ 562, 11 ]
python
en
['en', 'en', 'en']
True
Entity.async_internal_added_to_hass
(self)
Run when entity about to be added to hass. Not to be extended by integrations.
Run when entity about to be added to hass.
async def async_internal_added_to_hass(self) -> None: """Run when entity about to be added to hass. Not to be extended by integrations. """ assert self.hass is not None if self.platform: info = {"domain": self.platform.platform_name} if self.platform.config_entry: info["source"] = SOURCE_CONFIG_ENTRY info["config_entry"] = self.platform.config_entry.entry_id else: info["source"] = SOURCE_PLATFORM_CONFIG self.hass.data.setdefault(DATA_ENTITY_SOURCE, {})[self.entity_id] = info if self.registry_entry is not None: # This is an assert as it should never happen, but helps in tests assert ( not self.registry_entry.disabled_by ), f"Entity {self.entity_id} is being added while it's disabled" self.async_on_remove( async_track_entity_registry_updated_event( self.hass, self.entity_id, self._async_registry_updated ) )
[ "async", "def", "async_internal_added_to_hass", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "hass", "is", "not", "None", "if", "self", ".", "platform", ":", "info", "=", "{", "\"domain\"", ":", "self", ".", "platform", ".", "platform_name", "}", "if", "self", ".", "platform", ".", "config_entry", ":", "info", "[", "\"source\"", "]", "=", "SOURCE_CONFIG_ENTRY", "info", "[", "\"config_entry\"", "]", "=", "self", ".", "platform", ".", "config_entry", ".", "entry_id", "else", ":", "info", "[", "\"source\"", "]", "=", "SOURCE_PLATFORM_CONFIG", "self", ".", "hass", ".", "data", ".", "setdefault", "(", "DATA_ENTITY_SOURCE", ",", "{", "}", ")", "[", "self", ".", "entity_id", "]", "=", "info", "if", "self", ".", "registry_entry", "is", "not", "None", ":", "# This is an assert as it should never happen, but helps in tests", "assert", "(", "not", "self", ".", "registry_entry", ".", "disabled_by", ")", ",", "f\"Entity {self.entity_id} is being added while it's disabled\"", "self", ".", "async_on_remove", "(", "async_track_entity_registry_updated_event", "(", "self", ".", "hass", ",", "self", ".", "entity_id", ",", "self", ".", "_async_registry_updated", ")", ")" ]
[ 564, 4 ]
[ 592, 13 ]
python
en
['en', 'en', 'en']
True
Entity.async_internal_will_remove_from_hass
(self)
Run when entity will be removed from hass. Not to be extended by integrations.
Run when entity will be removed from hass.
async def async_internal_will_remove_from_hass(self) -> None: """Run when entity will be removed from hass. Not to be extended by integrations. """ if self.platform: assert self.hass is not None self.hass.data[DATA_ENTITY_SOURCE].pop(self.entity_id)
[ "async", "def", "async_internal_will_remove_from_hass", "(", "self", ")", "->", "None", ":", "if", "self", ".", "platform", ":", "assert", "self", ".", "hass", "is", "not", "None", "self", ".", "hass", ".", "data", "[", "DATA_ENTITY_SOURCE", "]", ".", "pop", "(", "self", ".", "entity_id", ")" ]
[ 594, 4 ]
[ 601, 66 ]
python
en
['en', 'en', 'en']
True
Entity._async_registry_updated
(self, event: Event)
Handle entity registry update.
Handle entity registry update.
async def _async_registry_updated(self, event: Event) -> None: """Handle entity registry update.""" data = event.data if data["action"] == "remove": await self.async_removed_from_registry() await self.async_remove() if data["action"] != "update": return assert self.hass is not None ent_reg = await self.hass.helpers.entity_registry.async_get_registry() old = self.registry_entry self.registry_entry = ent_reg.async_get(data["entity_id"]) assert self.registry_entry is not None if self.registry_entry.disabled_by is not None: await self.async_remove() return assert old is not None if self.registry_entry.entity_id == old.entity_id: self.async_write_ha_state() return await self.async_remove() assert self.platform is not None self.entity_id = self.registry_entry.entity_id await self.platform.async_add_entities([self])
[ "async", "def", "_async_registry_updated", "(", "self", ",", "event", ":", "Event", ")", "->", "None", ":", "data", "=", "event", ".", "data", "if", "data", "[", "\"action\"", "]", "==", "\"remove\"", ":", "await", "self", ".", "async_removed_from_registry", "(", ")", "await", "self", ".", "async_remove", "(", ")", "if", "data", "[", "\"action\"", "]", "!=", "\"update\"", ":", "return", "assert", "self", ".", "hass", "is", "not", "None", "ent_reg", "=", "await", "self", ".", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "old", "=", "self", ".", "registry_entry", "self", ".", "registry_entry", "=", "ent_reg", ".", "async_get", "(", "data", "[", "\"entity_id\"", "]", ")", "assert", "self", ".", "registry_entry", "is", "not", "None", "if", "self", ".", "registry_entry", ".", "disabled_by", "is", "not", "None", ":", "await", "self", ".", "async_remove", "(", ")", "return", "assert", "old", "is", "not", "None", "if", "self", ".", "registry_entry", ".", "entity_id", "==", "old", ".", "entity_id", ":", "self", ".", "async_write_ha_state", "(", ")", "return", "await", "self", ".", "async_remove", "(", ")", "assert", "self", ".", "platform", "is", "not", "None", "self", ".", "entity_id", "=", "self", ".", "registry_entry", ".", "entity_id", "await", "self", ".", "platform", ".", "async_add_entities", "(", "[", "self", "]", ")" ]
[ 603, 4 ]
[ 632, 54 ]
python
en
['en', 'af', 'en']
True
Entity.__eq__
(self, other: Any)
Return the comparison.
Return the comparison.
def __eq__(self, other: Any) -> bool: """Return the comparison.""" if not isinstance(other, self.__class__): return False # Can only decide equality if both have a unique id if self.unique_id is None or other.unique_id is None: return False # Ensure they belong to the same platform if self.platform is not None or other.platform is not None: if self.platform is None or other.platform is None: return False if self.platform.platform != other.platform.platform: return False return self.unique_id == other.unique_id
[ "def", "__eq__", "(", "self", ",", "other", ":", "Any", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "False", "# Can only decide equality if both have a unique id", "if", "self", ".", "unique_id", "is", "None", "or", "other", ".", "unique_id", "is", "None", ":", "return", "False", "# Ensure they belong to the same platform", "if", "self", ".", "platform", "is", "not", "None", "or", "other", ".", "platform", "is", "not", "None", ":", "if", "self", ".", "platform", "is", "None", "or", "other", ".", "platform", "is", "None", ":", "return", "False", "if", "self", ".", "platform", ".", "platform", "!=", "other", ".", "platform", ".", "platform", ":", "return", "False", "return", "self", ".", "unique_id", "==", "other", ".", "unique_id" ]
[ 634, 4 ]
[ 651, 48 ]
python
en
['en', 'it', 'en']
True
Entity.__repr__
(self)
Return the representation.
Return the representation.
def __repr__(self) -> str: """Return the representation.""" return f"<Entity {self.name}: {self.state}>"
[ "def", "__repr__", "(", "self", ")", "->", "str", ":", "return", "f\"<Entity {self.name}: {self.state}>\"" ]
[ 653, 4 ]
[ 655, 52 ]
python
en
['en', 'id', 'en']
True
Entity.async_request_call
(self, coro: Awaitable)
Process request batched.
Process request batched.
async def async_request_call(self, coro: Awaitable) -> None: """Process request batched.""" if self.parallel_updates: await self.parallel_updates.acquire() try: await coro finally: if self.parallel_updates: self.parallel_updates.release()
[ "async", "def", "async_request_call", "(", "self", ",", "coro", ":", "Awaitable", ")", "->", "None", ":", "if", "self", ".", "parallel_updates", ":", "await", "self", ".", "parallel_updates", ".", "acquire", "(", ")", "try", ":", "await", "coro", "finally", ":", "if", "self", ".", "parallel_updates", ":", "self", ".", "parallel_updates", ".", "release", "(", ")" ]
[ 657, 4 ]
[ 666, 47 ]
python
en
['en', 'fr', 'en']
True
ToggleEntity.state
(self)
Return the state.
Return the state.
def state(self) -> str: """Return the state.""" return STATE_ON if self.is_on else STATE_OFF
[ "def", "state", "(", "self", ")", "->", "str", ":", "return", "STATE_ON", "if", "self", ".", "is_on", "else", "STATE_OFF" ]
[ 673, 4 ]
[ 675, 52 ]
python
en
['en', 'en', 'en']
True
ToggleEntity.is_on
(self)
Return True if entity is on.
Return True if entity is on.
def is_on(self) -> bool: """Return True if entity is on.""" raise NotImplementedError()
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", ")" ]
[ 678, 4 ]
[ 680, 35 ]
python
en
['en', 'cy', 'en']
True
ToggleEntity.turn_on
(self, **kwargs: Any)
Turn the entity on.
Turn the entity on.
def turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" raise NotImplementedError()
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "raise", "NotImplementedError", "(", ")" ]
[ 682, 4 ]
[ 684, 35 ]
python
en
['en', 'en', 'en']
True
ToggleEntity.async_turn_on
(self, **kwargs: Any)
Turn the entity on.
Turn the entity on.
async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" assert self.hass is not None await self.hass.async_add_executor_job(ft.partial(self.turn_on, **kwargs))
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "assert", "self", ".", "hass", "is", "not", "None", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "ft", ".", "partial", "(", "self", ".", "turn_on", ",", "*", "*", "kwargs", ")", ")" ]
[ 686, 4 ]
[ 689, 82 ]
python
en
['en', 'en', 'en']
True
ToggleEntity.turn_off
(self, **kwargs: Any)
Turn the entity off.
Turn the entity off.
def turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" raise NotImplementedError()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "raise", "NotImplementedError", "(", ")" ]
[ 691, 4 ]
[ 693, 35 ]
python
en
['en', 'en', 'en']
True
ToggleEntity.async_turn_off
(self, **kwargs: Any)
Turn the entity off.
Turn the entity off.
async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" assert self.hass is not None await self.hass.async_add_executor_job(ft.partial(self.turn_off, **kwargs))
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "assert", "self", ".", "hass", "is", "not", "None", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "ft", ".", "partial", "(", "self", ".", "turn_off", ",", "*", "*", "kwargs", ")", ")" ]
[ 695, 4 ]
[ 698, 83 ]
python
en
['en', 'en', 'en']
True
ToggleEntity.toggle
(self, **kwargs: Any)
Toggle the entity.
Toggle the entity.
def toggle(self, **kwargs: Any) -> None: """Toggle the entity.""" if self.is_on: self.turn_off(**kwargs) else: self.turn_on(**kwargs)
[ "def", "toggle", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "is_on", ":", "self", ".", "turn_off", "(", "*", "*", "kwargs", ")", "else", ":", "self", ".", "turn_on", "(", "*", "*", "kwargs", ")" ]
[ 700, 4 ]
[ 705, 34 ]
python
en
['en', 'sm', 'en']
True
ToggleEntity.async_toggle
(self, **kwargs: Any)
Toggle the entity.
Toggle the entity.
async def async_toggle(self, **kwargs: Any) -> None: """Toggle the entity.""" if self.is_on: await self.async_turn_off(**kwargs) else: await self.async_turn_on(**kwargs)
[ "async", "def", "async_toggle", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "is_on", ":", "await", "self", ".", "async_turn_off", "(", "*", "*", "kwargs", ")", "else", ":", "await", "self", ".", "async_turn_on", "(", "*", "*", "kwargs", ")" ]
[ 707, 4 ]
[ 712, 46 ]
python
en
['en', 'sm', 'en']
True
main
()
Main Function
Main Function
def main(): '''Main Function''' parser = argparse.ArgumentParser(description='translate.py') parser.add_argument('-model', required=True, help='Path to model weight file') parser.add_argument('-data_pkl', required=True, help='Pickle file with both instances and vocabulary.') parser.add_argument('-output', default='pred.txt', help="""Path to output the predictions (each line will be the decoded sequence""") parser.add_argument('-beam_size', type=int, default=5) parser.add_argument('-max_seq_len', type=int, default=100) parser.add_argument('-no_cuda', action='store_true') # TODO: Translate bpe encoded files #parser.add_argument('-src', required=True, # help='Source sequence to decode (one line per sequence)') #parser.add_argument('-vocab', required=True, # help='Source sequence to decode (one line per sequence)') # TODO: Batch translation #parser.add_argument('-batch_size', type=int, default=30, # help='Batch size') #parser.add_argument('-n_best', type=int, default=1, # help="""If verbose is set, will output the n_best # decoded sentences""") opt = parser.parse_args() opt.cuda = not opt.no_cuda data = pickle.load(open(opt.data_pkl, 'rb')) SRC, TRG = data['vocab']['src'], data['vocab']['trg'] opt.src_pad_idx = SRC.vocab.stoi[Constants.PAD_WORD] opt.trg_pad_idx = TRG.vocab.stoi[Constants.PAD_WORD] opt.trg_bos_idx = TRG.vocab.stoi[Constants.BOS_WORD] opt.trg_eos_idx = TRG.vocab.stoi[Constants.EOS_WORD] test_loader = Dataset(examples=data['test'], fields={'src': SRC, 'trg': TRG}) device = torch.device('cuda' if opt.cuda else 'cpu') translator = Translator( model=load_model(opt, device), beam_size=opt.beam_size, max_seq_len=opt.max_seq_len, src_pad_idx=opt.src_pad_idx, trg_pad_idx=opt.trg_pad_idx, trg_bos_idx=opt.trg_bos_idx, trg_eos_idx=opt.trg_eos_idx).to(device) unk_idx = SRC.vocab.stoi[SRC.unk_token] with open(opt.output, 'w') as f: for example in tqdm(test_loader, mininterval=2, desc=' - (Test)', leave=False): #print(' '.join(example.src)) src_seq = [SRC.vocab.stoi.get(word, unk_idx) for word in example.src] pred_seq = translator.translate_sentence(torch.LongTensor([src_seq]).to(device)) pred_line = ' '.join(TRG.vocab.itos[idx] for idx in pred_seq) pred_line = pred_line.replace(Constants.BOS_WORD, '').replace(Constants.EOS_WORD, '') #print(pred_line) f.write(pred_line.strip() + '\n') print('[Info] Finished.')
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'translate.py'", ")", "parser", ".", "add_argument", "(", "'-model'", ",", "required", "=", "True", ",", "help", "=", "'Path to model weight file'", ")", "parser", ".", "add_argument", "(", "'-data_pkl'", ",", "required", "=", "True", ",", "help", "=", "'Pickle file with both instances and vocabulary.'", ")", "parser", ".", "add_argument", "(", "'-output'", ",", "default", "=", "'pred.txt'", ",", "help", "=", "\"\"\"Path to output the predictions (each line will\n be the decoded sequence\"\"\"", ")", "parser", ".", "add_argument", "(", "'-beam_size'", ",", "type", "=", "int", ",", "default", "=", "5", ")", "parser", ".", "add_argument", "(", "'-max_seq_len'", ",", "type", "=", "int", ",", "default", "=", "100", ")", "parser", ".", "add_argument", "(", "'-no_cuda'", ",", "action", "=", "'store_true'", ")", "# TODO: Translate bpe encoded files ", "#parser.add_argument('-src', required=True,", "# help='Source sequence to decode (one line per sequence)')", "#parser.add_argument('-vocab', required=True,", "# help='Source sequence to decode (one line per sequence)')", "# TODO: Batch translation", "#parser.add_argument('-batch_size', type=int, default=30,", "# help='Batch size')", "#parser.add_argument('-n_best', type=int, default=1,", "# help=\"\"\"If verbose is set, will output the n_best", "# decoded sentences\"\"\")", "opt", "=", "parser", ".", "parse_args", "(", ")", "opt", ".", "cuda", "=", "not", "opt", ".", "no_cuda", "data", "=", "pickle", ".", "load", "(", "open", "(", "opt", ".", "data_pkl", ",", "'rb'", ")", ")", "SRC", ",", "TRG", "=", "data", "[", "'vocab'", "]", "[", "'src'", "]", ",", "data", "[", "'vocab'", "]", "[", "'trg'", "]", "opt", ".", "src_pad_idx", "=", "SRC", ".", "vocab", ".", "stoi", "[", "Constants", ".", "PAD_WORD", "]", "opt", ".", "trg_pad_idx", "=", "TRG", ".", "vocab", ".", "stoi", "[", "Constants", ".", "PAD_WORD", "]", "opt", ".", "trg_bos_idx", "=", "TRG", ".", "vocab", ".", "stoi", "[", "Constants", ".", "BOS_WORD", "]", "opt", ".", "trg_eos_idx", "=", "TRG", ".", "vocab", ".", "stoi", "[", "Constants", ".", "EOS_WORD", "]", "test_loader", "=", "Dataset", "(", "examples", "=", "data", "[", "'test'", "]", ",", "fields", "=", "{", "'src'", ":", "SRC", ",", "'trg'", ":", "TRG", "}", ")", "device", "=", "torch", ".", "device", "(", "'cuda'", "if", "opt", ".", "cuda", "else", "'cpu'", ")", "translator", "=", "Translator", "(", "model", "=", "load_model", "(", "opt", ",", "device", ")", ",", "beam_size", "=", "opt", ".", "beam_size", ",", "max_seq_len", "=", "opt", ".", "max_seq_len", ",", "src_pad_idx", "=", "opt", ".", "src_pad_idx", ",", "trg_pad_idx", "=", "opt", ".", "trg_pad_idx", ",", "trg_bos_idx", "=", "opt", ".", "trg_bos_idx", ",", "trg_eos_idx", "=", "opt", ".", "trg_eos_idx", ")", ".", "to", "(", "device", ")", "unk_idx", "=", "SRC", ".", "vocab", ".", "stoi", "[", "SRC", ".", "unk_token", "]", "with", "open", "(", "opt", ".", "output", ",", "'w'", ")", "as", "f", ":", "for", "example", "in", "tqdm", "(", "test_loader", ",", "mininterval", "=", "2", ",", "desc", "=", "' - (Test)'", ",", "leave", "=", "False", ")", ":", "#print(' '.join(example.src))", "src_seq", "=", "[", "SRC", ".", "vocab", ".", "stoi", ".", "get", "(", "word", ",", "unk_idx", ")", "for", "word", "in", "example", ".", "src", "]", "pred_seq", "=", "translator", ".", "translate_sentence", "(", "torch", ".", "LongTensor", "(", "[", "src_seq", "]", ")", ".", "to", "(", "device", ")", ")", "pred_line", "=", "' '", ".", "join", "(", "TRG", ".", "vocab", ".", "itos", "[", "idx", "]", "for", "idx", "in", "pred_seq", ")", "pred_line", "=", "pred_line", ".", "replace", "(", "Constants", ".", "BOS_WORD", ",", "''", ")", ".", "replace", "(", "Constants", ".", "EOS_WORD", ",", "''", ")", "#print(pred_line)", "f", ".", "write", "(", "pred_line", ".", "strip", "(", ")", "+", "'\\n'", ")", "print", "(", "'[Info] Finished.'", ")" ]
[ 41, 0 ]
[ 102, 29 ]
python
en
['en', 'ja', 'en']
False
test_manually_configured_platform
(hass)
Test that we do not set up an access point.
Test that we do not set up an access point.
async def test_manually_configured_platform(hass): """Test that we do not set up an access point.""" assert await async_setup_component( hass, SWITCH_DOMAIN, {SWITCH_DOMAIN: {"platform": HMIPC_DOMAIN}} ) assert not hass.data.get(HMIPC_DOMAIN)
[ "async", "def", "test_manually_configured_platform", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "SWITCH_DOMAIN", ",", "{", "SWITCH_DOMAIN", ":", "{", "\"platform\"", ":", "HMIPC_DOMAIN", "}", "}", ")", "assert", "not", "hass", ".", "data", ".", "get", "(", "HMIPC_DOMAIN", ")" ]
[ 16, 0 ]
[ 21, 42 ]
python
en
['en', 'en', 'en']
True
test_hmip_switch
(hass, default_mock_hap_factory)
Test HomematicipSwitch.
Test HomematicipSwitch.
async def test_hmip_switch(hass, default_mock_hap_factory): """Test HomematicipSwitch.""" entity_id = "switch.schrank" entity_name = "Schrank" device_model = "HMIP-PS" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=[entity_name] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_ON service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", True) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON
[ "async", "def", "test_hmip_switch", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.schrank\"", "entity_name", "=", "\"Schrank\"", "device_model", "=", "\"HMIP-PS\"", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_devices", "=", "[", "entity_name", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON" ]
[ 24, 0 ]
[ 58, 37 ]
python
en
['en', 'en', 'en']
False
test_hmip_switch_input
(hass, default_mock_hap_factory)
Test HomematicipSwitch.
Test HomematicipSwitch.
async def test_hmip_switch_input(hass, default_mock_hap_factory): """Test HomematicipSwitch.""" entity_id = "switch.wohnzimmer_beleuchtung" entity_name = "Wohnzimmer Beleuchtung" device_model = "HmIP-FSI16" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=[entity_name] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_ON service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", True) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON
[ "async", "def", "test_hmip_switch_input", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.wohnzimmer_beleuchtung\"", "entity_name", "=", "\"Wohnzimmer Beleuchtung\"", "device_model", "=", "\"HmIP-FSI16\"", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_devices", "=", "[", "entity_name", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON" ]
[ 61, 0 ]
[ 95, 37 ]
python
en
['en', 'en', 'en']
False
test_hmip_switch_measuring
(hass, default_mock_hap_factory)
Test HomematicipSwitchMeasuring.
Test HomematicipSwitchMeasuring.
async def test_hmip_switch_measuring(hass, default_mock_hap_factory): """Test HomematicipSwitchMeasuring.""" entity_id = "switch.pc" entity_name = "Pc" device_model = "HMIP-PSM" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=[entity_name] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_ON service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", True) await async_manipulate_test_data(hass, hmip_device, "currentPowerConsumption", 50) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON assert ha_state.attributes[ATTR_CURRENT_POWER_W] == 50 assert ha_state.attributes[ATTR_TODAY_ENERGY_KWH] == 36 await async_manipulate_test_data(hass, hmip_device, "energyCounter", None) ha_state = hass.states.get(entity_id) assert not ha_state.attributes.get(ATTR_TODAY_ENERGY_KWH)
[ "async", "def", "test_hmip_switch_measuring", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.pc\"", "entity_name", "=", "\"Pc\"", "device_model", "=", "\"HMIP-PSM\"", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_devices", "=", "[", "entity_name", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"currentPowerConsumption\"", ",", "50", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "assert", "ha_state", ".", "attributes", "[", "ATTR_CURRENT_POWER_W", "]", "==", "50", "assert", "ha_state", ".", "attributes", "[", "ATTR_TODAY_ENERGY_KWH", "]", "==", "36", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"energyCounter\"", ",", "None", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "not", "ha_state", ".", "attributes", ".", "get", "(", "ATTR_TODAY_ENERGY_KWH", ")" ]
[ 98, 0 ]
[ 139, 61 ]
python
en
['en', 'en', 'en']
False
test_hmip_group_switch
(hass, default_mock_hap_factory)
Test HomematicipGroupSwitch.
Test HomematicipGroupSwitch.
async def test_hmip_group_switch(hass, default_mock_hap_factory): """Test HomematicipGroupSwitch.""" entity_id = "switch.strom_group" entity_name = "Strom Group" device_model = None mock_hap = await default_mock_hap_factory.async_get_mock_hap(test_groups=["Strom"]) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_ON service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == () await async_manipulate_test_data(hass, hmip_device, "on", True) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON assert not ha_state.attributes.get(ATTR_GROUP_MEMBER_UNREACHABLE) await async_manipulate_test_data(hass, hmip_device, "unreach", True) ha_state = hass.states.get(entity_id) assert ha_state.attributes[ATTR_GROUP_MEMBER_UNREACHABLE]
[ "async", "def", "test_hmip_group_switch", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.strom_group\"", "entity_name", "=", "\"Strom Group\"", "device_model", "=", "None", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_groups", "=", "[", "\"Strom\"", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "assert", "not", "ha_state", ".", "attributes", ".", "get", "(", "ATTR_GROUP_MEMBER_UNREACHABLE", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"unreach\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "attributes", "[", "ATTR_GROUP_MEMBER_UNREACHABLE", "]" ]
[ 142, 0 ]
[ 179, 61 ]
python
en
['en', 'en', 'en']
False
test_hmip_multi_switch
(hass, default_mock_hap_factory)
Test HomematicipMultiSwitch.
Test HomematicipMultiSwitch.
async def test_hmip_multi_switch(hass, default_mock_hap_factory): """Test HomematicipMultiSwitch.""" entity_id = "switch.jalousien_1_kizi_2_schlazi_channel1" entity_name = "Jalousien - 1 KiZi, 2 SchlaZi Channel1" device_model = "HmIP-PCBS2" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=[ "Jalousien - 1 KiZi, 2 SchlaZi", "Multi IO Box", "Heizungsaktor", "ioBroker", ] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_OFF service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == (1,) await async_manipulate_test_data(hass, hmip_device, "on", True) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == (1,) await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF
[ "async", "def", "test_hmip_multi_switch", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.jalousien_1_kizi_2_schlazi_channel1\"", "entity_name", "=", "\"Jalousien - 1 KiZi, 2 SchlaZi Channel1\"", "device_model", "=", "\"HmIP-PCBS2\"", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_devices", "=", "[", "\"Jalousien - 1 KiZi, 2 SchlaZi\"", ",", "\"Multi IO Box\"", ",", "\"Heizungsaktor\"", ",", "\"ioBroker\"", ",", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", "1", ",", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", "1", ",", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF" ]
[ 182, 0 ]
[ 221, 38 ]
python
en
['en', 'en', 'en']
False
test_hmip_wired_multi_switch
(hass, default_mock_hap_factory)
Test HomematicipMultiSwitch.
Test HomematicipMultiSwitch.
async def test_hmip_wired_multi_switch(hass, default_mock_hap_factory): """Test HomematicipMultiSwitch.""" entity_id = "switch.fernseher_wohnzimmer" entity_name = "Fernseher (Wohnzimmer)" device_model = "HmIPW-DRS8" mock_hap = await default_mock_hap_factory.async_get_mock_hap( test_devices=[ "Wired Schaltaktor – 8-fach", ] ) ha_state, hmip_device = get_and_check_entity_basics( hass, mock_hap, entity_id, entity_name, device_model ) assert ha_state.state == STATE_ON service_call_counter = len(hmip_device.mock_calls) await hass.services.async_call( "switch", "turn_off", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 1 assert hmip_device.mock_calls[-1][0] == "turn_off" assert hmip_device.mock_calls[-1][1] == (1,) await async_manipulate_test_data(hass, hmip_device, "on", False) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_OFF await hass.services.async_call( "switch", "turn_on", {"entity_id": entity_id}, blocking=True ) assert len(hmip_device.mock_calls) == service_call_counter + 3 assert hmip_device.mock_calls[-1][0] == "turn_on" assert hmip_device.mock_calls[-1][1] == (1,) await async_manipulate_test_data(hass, hmip_device, "on", True) ha_state = hass.states.get(entity_id) assert ha_state.state == STATE_ON
[ "async", "def", "test_hmip_wired_multi_switch", "(", "hass", ",", "default_mock_hap_factory", ")", ":", "entity_id", "=", "\"switch.fernseher_wohnzimmer\"", "entity_name", "=", "\"Fernseher (Wohnzimmer)\"", "device_model", "=", "\"HmIPW-DRS8\"", "mock_hap", "=", "await", "default_mock_hap_factory", ".", "async_get_mock_hap", "(", "test_devices", "=", "[", "\"Wired Schaltaktor – 8-fach\",", "", "]", ")", "ha_state", ",", "hmip_device", "=", "get_and_check_entity_basics", "(", "hass", ",", "mock_hap", ",", "entity_id", ",", "entity_name", ",", "device_model", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON", "service_call_counter", "=", "len", "(", "hmip_device", ".", "mock_calls", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "1", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_off\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", "1", ",", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "False", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "\"switch\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "hmip_device", ".", "mock_calls", ")", "==", "service_call_counter", "+", "3", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "0", "]", "==", "\"turn_on\"", "assert", "hmip_device", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "==", "(", "1", ",", ")", "await", "async_manipulate_test_data", "(", "hass", ",", "hmip_device", ",", "\"on\"", ",", "True", ")", "ha_state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "ha_state", ".", "state", "==", "STATE_ON" ]
[ 224, 0 ]
[ 260, 37 ]
python
en
['en', 'en', 'en']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Waze travel time sensor platform.
Set up the Waze travel time sensor platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Waze travel time sensor platform.""" destination = config.get(CONF_DESTINATION) name = config.get(CONF_NAME) origin = config.get(CONF_ORIGIN) region = config.get(CONF_REGION) incl_filter = config.get(CONF_INCL_FILTER) excl_filter = config.get(CONF_EXCL_FILTER) realtime = config.get(CONF_REALTIME) vehicle_type = config.get(CONF_VEHICLE_TYPE) avoid_toll_roads = config.get(CONF_AVOID_TOLL_ROADS) avoid_subscription_roads = config.get(CONF_AVOID_SUBSCRIPTION_ROADS) avoid_ferries = config.get(CONF_AVOID_FERRIES) units = config.get(CONF_UNITS, hass.config.units.name) data = WazeTravelTimeData( None, None, region, incl_filter, excl_filter, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries, ) sensor = WazeTravelTime(name, origin, destination, data) add_entities([sensor]) # Wait until start event is sent to load this component. hass.bus.listen_once(EVENT_HOMEASSISTANT_START, lambda _: sensor.update())
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "destination", "=", "config", ".", "get", "(", "CONF_DESTINATION", ")", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "origin", "=", "config", ".", "get", "(", "CONF_ORIGIN", ")", "region", "=", "config", ".", "get", "(", "CONF_REGION", ")", "incl_filter", "=", "config", ".", "get", "(", "CONF_INCL_FILTER", ")", "excl_filter", "=", "config", ".", "get", "(", "CONF_EXCL_FILTER", ")", "realtime", "=", "config", ".", "get", "(", "CONF_REALTIME", ")", "vehicle_type", "=", "config", ".", "get", "(", "CONF_VEHICLE_TYPE", ")", "avoid_toll_roads", "=", "config", ".", "get", "(", "CONF_AVOID_TOLL_ROADS", ")", "avoid_subscription_roads", "=", "config", ".", "get", "(", "CONF_AVOID_SUBSCRIPTION_ROADS", ")", "avoid_ferries", "=", "config", ".", "get", "(", "CONF_AVOID_FERRIES", ")", "units", "=", "config", ".", "get", "(", "CONF_UNITS", ",", "hass", ".", "config", ".", "units", ".", "name", ")", "data", "=", "WazeTravelTimeData", "(", "None", ",", "None", ",", "region", ",", "incl_filter", ",", "excl_filter", ",", "realtime", ",", "units", ",", "vehicle_type", ",", "avoid_toll_roads", ",", "avoid_subscription_roads", ",", "avoid_ferries", ",", ")", "sensor", "=", "WazeTravelTime", "(", "name", ",", "origin", ",", "destination", ",", "data", ")", "add_entities", "(", "[", "sensor", "]", ")", "# Wait until start event is sent to load this component.", "hass", ".", "bus", ".", "listen_once", "(", "EVENT_HOMEASSISTANT_START", ",", "lambda", "_", ":", "sensor", ".", "update", "(", ")", ")" ]
[ 85, 0 ]
[ 119, 78 ]
python
en
['en', 'pt', 'en']
True
_get_location_from_attributes
(state)
Get the lat/long string from an states attributes.
Get the lat/long string from an states attributes.
def _get_location_from_attributes(state): """Get the lat/long string from an states attributes.""" attr = state.attributes return "{},{}".format(attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE))
[ "def", "_get_location_from_attributes", "(", "state", ")", ":", "attr", "=", "state", ".", "attributes", "return", "\"{},{}\"", ".", "format", "(", "attr", ".", "get", "(", "ATTR_LATITUDE", ")", ",", "attr", ".", "get", "(", "ATTR_LONGITUDE", ")", ")" ]
[ 122, 0 ]
[ 125, 76 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime.__init__
(self, name, origin, destination, waze_data)
Initialize the Waze travel time sensor.
Initialize the Waze travel time sensor.
def __init__(self, name, origin, destination, waze_data): """Initialize the Waze travel time sensor.""" self._name = name self._waze_data = waze_data self._state = None self._origin_entity_id = None self._destination_entity_id = None # Attempt to find entity_id without finding address with period. pattern = "(?<![a-zA-Z0-9 ])[a-z_]+[.][a-zA-Z0-9_]+" if re.fullmatch(pattern, origin): _LOGGER.debug("Found origin source entity %s", origin) self._origin_entity_id = origin else: self._waze_data.origin = origin if re.fullmatch(pattern, destination): _LOGGER.debug("Found destination source entity %s", destination) self._destination_entity_id = destination else: self._waze_data.destination = destination
[ "def", "__init__", "(", "self", ",", "name", ",", "origin", ",", "destination", ",", "waze_data", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_waze_data", "=", "waze_data", "self", ".", "_state", "=", "None", "self", ".", "_origin_entity_id", "=", "None", "self", ".", "_destination_entity_id", "=", "None", "# Attempt to find entity_id without finding address with period.", "pattern", "=", "\"(?<![a-zA-Z0-9 ])[a-z_]+[.][a-zA-Z0-9_]+\"", "if", "re", ".", "fullmatch", "(", "pattern", ",", "origin", ")", ":", "_LOGGER", ".", "debug", "(", "\"Found origin source entity %s\"", ",", "origin", ")", "self", ".", "_origin_entity_id", "=", "origin", "else", ":", "self", ".", "_waze_data", ".", "origin", "=", "origin", "if", "re", ".", "fullmatch", "(", "pattern", ",", "destination", ")", ":", "_LOGGER", ".", "debug", "(", "\"Found destination source entity %s\"", ",", "destination", ")", "self", ".", "_destination_entity_id", "=", "destination", "else", ":", "self", ".", "_waze_data", ".", "destination", "=", "destination" ]
[ 131, 4 ]
[ 152, 53 ]
python
en
['en', 'pt', 'en']
True
WazeTravelTime.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 155, 4 ]
[ 157, 25 ]
python
en
['en', 'mi', 'en']
True
WazeTravelTime.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" if self._waze_data.duration is not None: return round(self._waze_data.duration) return None
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "_waze_data", ".", "duration", "is", "not", "None", ":", "return", "round", "(", "self", ".", "_waze_data", ".", "duration", ")", "return", "None" ]
[ 160, 4 ]
[ 165, 19 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return TIME_MINUTES
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TIME_MINUTES" ]
[ 168, 4 ]
[ 170, 27 ]
python
en
['en', 'la', 'en']
True
WazeTravelTime.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" return ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 173, 4 ]
[ 175, 19 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime.device_state_attributes
(self)
Return the state attributes of the last update.
Return the state attributes of the last update.
def device_state_attributes(self): """Return the state attributes of the last update.""" if self._waze_data.duration is None: return None res = {ATTR_ATTRIBUTION: ATTRIBUTION} res[ATTR_DURATION] = self._waze_data.duration res[ATTR_DISTANCE] = self._waze_data.distance res[ATTR_ROUTE] = self._waze_data.route res[ATTR_ORIGIN] = self._waze_data.origin res[ATTR_DESTINATION] = self._waze_data.destination return res
[ "def", "device_state_attributes", "(", "self", ")", ":", "if", "self", ".", "_waze_data", ".", "duration", "is", "None", ":", "return", "None", "res", "=", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}", "res", "[", "ATTR_DURATION", "]", "=", "self", ".", "_waze_data", ".", "duration", "res", "[", "ATTR_DISTANCE", "]", "=", "self", ".", "_waze_data", ".", "distance", "res", "[", "ATTR_ROUTE", "]", "=", "self", ".", "_waze_data", ".", "route", "res", "[", "ATTR_ORIGIN", "]", "=", "self", ".", "_waze_data", ".", "origin", "res", "[", "ATTR_DESTINATION", "]", "=", "self", ".", "_waze_data", ".", "destination", "return", "res" ]
[ 178, 4 ]
[ 189, 18 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime._get_location_from_entity
(self, entity_id)
Get the location from the entity_id.
Get the location from the entity_id.
def _get_location_from_entity(self, entity_id): """Get the location from the entity_id.""" state = self.hass.states.get(entity_id) if state is None: _LOGGER.error("Unable to find entity %s", entity_id) return None # Check if the entity has location attributes. if location.has_location(state): _LOGGER.debug("Getting %s location", entity_id) return _get_location_from_attributes(state) # Check if device is inside a zone. zone_state = self.hass.states.get(f"zone.{state.state}") if location.has_location(zone_state): _LOGGER.debug( "%s is in %s, getting zone location", entity_id, zone_state.entity_id ) return _get_location_from_attributes(zone_state) # If zone was not found in state then use the state as the location. if entity_id.startswith("sensor."): return state.state # When everything fails just return nothing. return None
[ "def", "_get_location_from_entity", "(", "self", ",", "entity_id", ")", ":", "state", "=", "self", ".", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "if", "state", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Unable to find entity %s\"", ",", "entity_id", ")", "return", "None", "# Check if the entity has location attributes.", "if", "location", ".", "has_location", "(", "state", ")", ":", "_LOGGER", ".", "debug", "(", "\"Getting %s location\"", ",", "entity_id", ")", "return", "_get_location_from_attributes", "(", "state", ")", "# Check if device is inside a zone.", "zone_state", "=", "self", ".", "hass", ".", "states", ".", "get", "(", "f\"zone.{state.state}\"", ")", "if", "location", ".", "has_location", "(", "zone_state", ")", ":", "_LOGGER", ".", "debug", "(", "\"%s is in %s, getting zone location\"", ",", "entity_id", ",", "zone_state", ".", "entity_id", ")", "return", "_get_location_from_attributes", "(", "zone_state", ")", "# If zone was not found in state then use the state as the location.", "if", "entity_id", ".", "startswith", "(", "\"sensor.\"", ")", ":", "return", "state", ".", "state", "# When everything fails just return nothing.", "return", "None" ]
[ 191, 4 ]
[ 217, 19 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime._resolve_zone
(self, friendly_name)
Get a lat/long from a zones friendly_name.
Get a lat/long from a zones friendly_name.
def _resolve_zone(self, friendly_name): """Get a lat/long from a zones friendly_name.""" states = self.hass.states.all() for state in states: if state.domain == "zone" and state.name == friendly_name: return _get_location_from_attributes(state) return friendly_name
[ "def", "_resolve_zone", "(", "self", ",", "friendly_name", ")", ":", "states", "=", "self", ".", "hass", ".", "states", ".", "all", "(", ")", "for", "state", "in", "states", ":", "if", "state", ".", "domain", "==", "\"zone\"", "and", "state", ".", "name", "==", "friendly_name", ":", "return", "_get_location_from_attributes", "(", "state", ")", "return", "friendly_name" ]
[ 219, 4 ]
[ 226, 28 ]
python
en
['en', 'en', 'en']
True
WazeTravelTime.update
(self)
Fetch new state data for the sensor.
Fetch new state data for the sensor.
def update(self): """Fetch new state data for the sensor.""" _LOGGER.debug("Fetching Route for %s", self._name) # Get origin latitude and longitude from entity_id. if self._origin_entity_id is not None: self._waze_data.origin = self._get_location_from_entity( self._origin_entity_id ) # Get destination latitude and longitude from entity_id. if self._destination_entity_id is not None: self._waze_data.destination = self._get_location_from_entity( self._destination_entity_id ) # Get origin from zone name. self._waze_data.origin = self._resolve_zone(self._waze_data.origin) # Get destination from zone name. self._waze_data.destination = self._resolve_zone(self._waze_data.destination) self._waze_data.update()
[ "def", "update", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Fetching Route for %s\"", ",", "self", ".", "_name", ")", "# Get origin latitude and longitude from entity_id.", "if", "self", ".", "_origin_entity_id", "is", "not", "None", ":", "self", ".", "_waze_data", ".", "origin", "=", "self", ".", "_get_location_from_entity", "(", "self", ".", "_origin_entity_id", ")", "# Get destination latitude and longitude from entity_id.", "if", "self", ".", "_destination_entity_id", "is", "not", "None", ":", "self", ".", "_waze_data", ".", "destination", "=", "self", ".", "_get_location_from_entity", "(", "self", ".", "_destination_entity_id", ")", "# Get origin from zone name.", "self", ".", "_waze_data", ".", "origin", "=", "self", ".", "_resolve_zone", "(", "self", ".", "_waze_data", ".", "origin", ")", "# Get destination from zone name.", "self", ".", "_waze_data", ".", "destination", "=", "self", ".", "_resolve_zone", "(", "self", ".", "_waze_data", ".", "destination", ")", "self", ".", "_waze_data", ".", "update", "(", ")" ]
[ 228, 4 ]
[ 249, 32 ]
python
en
['en', 'en', 'en']
True
WazeTravelTimeData.__init__
( self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries, )
Set up WazeRouteCalculator.
Set up WazeRouteCalculator.
def __init__( self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries, ): """Set up WazeRouteCalculator.""" self._calc = WazeRouteCalculator self.origin = origin self.destination = destination self.region = region self.include = include self.exclude = exclude self.realtime = realtime self.units = units self.duration = None self.distance = None self.route = None self.avoid_toll_roads = avoid_toll_roads self.avoid_subscription_roads = avoid_subscription_roads self.avoid_ferries = avoid_ferries # Currently WazeRouteCalc only supports PRIVATE, TAXI, MOTORCYCLE. if vehicle_type.upper() == "CAR": # Empty means PRIVATE for waze which translates to car. self.vehicle_type = "" else: self.vehicle_type = vehicle_type.upper()
[ "def", "__init__", "(", "self", ",", "origin", ",", "destination", ",", "region", ",", "include", ",", "exclude", ",", "realtime", ",", "units", ",", "vehicle_type", ",", "avoid_toll_roads", ",", "avoid_subscription_roads", ",", "avoid_ferries", ",", ")", ":", "self", ".", "_calc", "=", "WazeRouteCalculator", "self", ".", "origin", "=", "origin", "self", ".", "destination", "=", "destination", "self", ".", "region", "=", "region", "self", ".", "include", "=", "include", "self", ".", "exclude", "=", "exclude", "self", ".", "realtime", "=", "realtime", "self", ".", "units", "=", "units", "self", ".", "duration", "=", "None", "self", ".", "distance", "=", "None", "self", ".", "route", "=", "None", "self", ".", "avoid_toll_roads", "=", "avoid_toll_roads", "self", ".", "avoid_subscription_roads", "=", "avoid_subscription_roads", "self", ".", "avoid_ferries", "=", "avoid_ferries", "# Currently WazeRouteCalc only supports PRIVATE, TAXI, MOTORCYCLE.", "if", "vehicle_type", ".", "upper", "(", ")", "==", "\"CAR\"", ":", "# Empty means PRIVATE for waze which translates to car.", "self", ".", "vehicle_type", "=", "\"\"", "else", ":", "self", ".", "vehicle_type", "=", "vehicle_type", ".", "upper", "(", ")" ]
[ 255, 4 ]
[ 292, 52 ]
python
en
['en', 'ny', 'it']
False
WazeTravelTimeData.update
(self)
Update WazeRouteCalculator Sensor.
Update WazeRouteCalculator Sensor.
def update(self): """Update WazeRouteCalculator Sensor.""" if self.origin is not None and self.destination is not None: try: params = self._calc.WazeRouteCalculator( self.origin, self.destination, self.region, self.vehicle_type, self.avoid_toll_roads, self.avoid_subscription_roads, self.avoid_ferries, ) routes = params.calc_all_routes_info(real_time=self.realtime) if self.include is not None: routes = { k: v for k, v in routes.items() if self.include.lower() in k.lower() } if self.exclude is not None: routes = { k: v for k, v in routes.items() if self.exclude.lower() not in k.lower() } route = list(routes)[0] self.duration, distance = routes[route] if self.units == CONF_UNIT_SYSTEM_IMPERIAL: # Convert to miles. self.distance = distance / 1.609 else: self.distance = distance self.route = route except self._calc.WRCError as exp: _LOGGER.warning("Error on retrieving data: %s", exp) return except KeyError: _LOGGER.error("Error retrieving data from server") return
[ "def", "update", "(", "self", ")", ":", "if", "self", ".", "origin", "is", "not", "None", "and", "self", ".", "destination", "is", "not", "None", ":", "try", ":", "params", "=", "self", ".", "_calc", ".", "WazeRouteCalculator", "(", "self", ".", "origin", ",", "self", ".", "destination", ",", "self", ".", "region", ",", "self", ".", "vehicle_type", ",", "self", ".", "avoid_toll_roads", ",", "self", ".", "avoid_subscription_roads", ",", "self", ".", "avoid_ferries", ",", ")", "routes", "=", "params", ".", "calc_all_routes_info", "(", "real_time", "=", "self", ".", "realtime", ")", "if", "self", ".", "include", "is", "not", "None", ":", "routes", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "routes", ".", "items", "(", ")", "if", "self", ".", "include", ".", "lower", "(", ")", "in", "k", ".", "lower", "(", ")", "}", "if", "self", ".", "exclude", "is", "not", "None", ":", "routes", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "routes", ".", "items", "(", ")", "if", "self", ".", "exclude", ".", "lower", "(", ")", "not", "in", "k", ".", "lower", "(", ")", "}", "route", "=", "list", "(", "routes", ")", "[", "0", "]", "self", ".", "duration", ",", "distance", "=", "routes", "[", "route", "]", "if", "self", ".", "units", "==", "CONF_UNIT_SYSTEM_IMPERIAL", ":", "# Convert to miles.", "self", ".", "distance", "=", "distance", "/", "1.609", "else", ":", "self", ".", "distance", "=", "distance", "self", ".", "route", "=", "route", "except", "self", ".", "_calc", ".", "WRCError", "as", "exp", ":", "_LOGGER", ".", "warning", "(", "\"Error on retrieving data: %s\"", ",", "exp", ")", "return", "except", "KeyError", ":", "_LOGGER", ".", "error", "(", "\"Error retrieving data from server\"", ")", "return" ]
[ 294, 4 ]
[ 339, 22 ]
python
en
['en', 'eu', 'it']
False
test_setup_loads_platforms
(hass)
Test the loading of the platforms.
Test the loading of the platforms.
async def test_setup_loads_platforms(hass): """Test the loading of the platforms.""" component_setup = Mock(return_value=True) platform_setup = Mock(return_value=None) mock_integration(hass, MockModule("test_component", setup=component_setup)) # mock the dependencies mock_integration(hass, MockModule("mod2", dependencies=["test_component"])) mock_entity_platform(hass, "test_domain.mod2", MockPlatform(platform_setup)) component = EntityComponent(_LOGGER, DOMAIN, hass) assert not component_setup.called assert not platform_setup.called component.setup({DOMAIN: {"platform": "mod2"}}) await hass.async_block_till_done() assert component_setup.called assert platform_setup.called
[ "async", "def", "test_setup_loads_platforms", "(", "hass", ")", ":", "component_setup", "=", "Mock", "(", "return_value", "=", "True", ")", "platform_setup", "=", "Mock", "(", "return_value", "=", "None", ")", "mock_integration", "(", "hass", ",", "MockModule", "(", "\"test_component\"", ",", "setup", "=", "component_setup", ")", ")", "# mock the dependencies", "mock_integration", "(", "hass", ",", "MockModule", "(", "\"mod2\"", ",", "dependencies", "=", "[", "\"test_component\"", "]", ")", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.mod2\"", ",", "MockPlatform", "(", "platform_setup", ")", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "assert", "not", "component_setup", ".", "called", "assert", "not", "platform_setup", ".", "called", "component", ".", "setup", "(", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"mod2\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "component_setup", ".", "called", "assert", "platform_setup", ".", "called" ]
[ 32, 0 ]
[ 51, 32 ]
python
en
['en', 'en', 'en']
True
test_setup_recovers_when_setup_raises
(hass)
Test the setup if exceptions are happening.
Test the setup if exceptions are happening.
async def test_setup_recovers_when_setup_raises(hass): """Test the setup if exceptions are happening.""" platform1_setup = Mock(side_effect=Exception("Broken")) platform2_setup = Mock(return_value=None) mock_entity_platform(hass, "test_domain.mod1", MockPlatform(platform1_setup)) mock_entity_platform(hass, "test_domain.mod2", MockPlatform(platform2_setup)) component = EntityComponent(_LOGGER, DOMAIN, hass) assert not platform1_setup.called assert not platform2_setup.called component.setup( OrderedDict( [ (DOMAIN, {"platform": "mod1"}), (f"{DOMAIN} 2", {"platform": "non_exist"}), (f"{DOMAIN} 3", {"platform": "mod2"}), ] ) ) await hass.async_block_till_done() assert platform1_setup.called assert platform2_setup.called
[ "async", "def", "test_setup_recovers_when_setup_raises", "(", "hass", ")", ":", "platform1_setup", "=", "Mock", "(", "side_effect", "=", "Exception", "(", "\"Broken\"", ")", ")", "platform2_setup", "=", "Mock", "(", "return_value", "=", "None", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.mod1\"", ",", "MockPlatform", "(", "platform1_setup", ")", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.mod2\"", ",", "MockPlatform", "(", "platform2_setup", ")", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "assert", "not", "platform1_setup", ".", "called", "assert", "not", "platform2_setup", ".", "called", "component", ".", "setup", "(", "OrderedDict", "(", "[", "(", "DOMAIN", ",", "{", "\"platform\"", ":", "\"mod1\"", "}", ")", ",", "(", "f\"{DOMAIN} 2\"", ",", "{", "\"platform\"", ":", "\"non_exist\"", "}", ")", ",", "(", "f\"{DOMAIN} 3\"", ",", "{", "\"platform\"", ":", "\"mod2\"", "}", ")", ",", "]", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "platform1_setup", ".", "called", "assert", "platform2_setup", ".", "called" ]
[ 54, 0 ]
[ 79, 33 ]
python
en
['en', 'en', 'en']
True
test_setup_does_discovery
(mock_setup_component, mock_setup, hass)
Test setup for discovery.
Test setup for discovery.
async def test_setup_does_discovery(mock_setup_component, mock_setup, hass): """Test setup for discovery.""" component = EntityComponent(_LOGGER, DOMAIN, hass) component.setup({}) discovery.load_platform( hass, DOMAIN, "platform_test", {"msg": "discovery_info"}, {DOMAIN: {}} ) await hass.async_block_till_done() assert mock_setup.called assert ("platform_test", {}, {"msg": "discovery_info"}) == mock_setup.call_args[0]
[ "async", "def", "test_setup_does_discovery", "(", "mock_setup_component", ",", "mock_setup", ",", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "component", ".", "setup", "(", "{", "}", ")", "discovery", ".", "load_platform", "(", "hass", ",", "DOMAIN", ",", "\"platform_test\"", ",", "{", "\"msg\"", ":", "\"discovery_info\"", "}", ",", "{", "DOMAIN", ":", "{", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mock_setup", ".", "called", "assert", "(", "\"platform_test\"", ",", "{", "}", ",", "{", "\"msg\"", ":", "\"discovery_info\"", "}", ")", "==", "mock_setup", ".", "call_args", "[", "0", "]" ]
[ 86, 0 ]
[ 99, 86 ]
python
en
['en', 'en', 'en']
True
test_set_scan_interval_via_config
(mock_track, hass)
Test the setting of the scan interval via configuration.
Test the setting of the scan interval via configuration.
async def test_set_scan_interval_via_config(mock_track, hass): """Test the setting of the scan interval via configuration.""" def platform_setup(hass, config, add_entities, discovery_info=None): """Test the platform setup.""" add_entities([MockEntity(should_poll=True)]) mock_entity_platform(hass, "test_domain.platform", MockPlatform(platform_setup)) component = EntityComponent(_LOGGER, DOMAIN, hass) component.setup( {DOMAIN: {"platform": "platform", "scan_interval": timedelta(seconds=30)}} ) await hass.async_block_till_done() assert mock_track.called assert timedelta(seconds=30) == mock_track.call_args[0][2]
[ "async", "def", "test_set_scan_interval_via_config", "(", "mock_track", ",", "hass", ")", ":", "def", "platform_setup", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "\"\"\"Test the platform setup.\"\"\"", "add_entities", "(", "[", "MockEntity", "(", "should_poll", "=", "True", ")", "]", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.platform\"", ",", "MockPlatform", "(", "platform_setup", ")", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "component", ".", "setup", "(", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"platform\"", ",", "\"scan_interval\"", ":", "timedelta", "(", "seconds", "=", "30", ")", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mock_track", ".", "called", "assert", "timedelta", "(", "seconds", "=", "30", ")", "==", "mock_track", ".", "call_args", "[", "0", "]", "[", "2", "]" ]
[ 103, 0 ]
[ 120, 62 ]
python
en
['en', 'en', 'en']
True
test_set_entity_namespace_via_config
(hass)
Test setting an entity namespace.
Test setting an entity namespace.
async def test_set_entity_namespace_via_config(hass): """Test setting an entity namespace.""" def platform_setup(hass, config, add_entities, discovery_info=None): """Test the platform setup.""" add_entities([MockEntity(name="beer"), MockEntity(name=None)]) platform = MockPlatform(platform_setup) mock_entity_platform(hass, "test_domain.platform", platform) component = EntityComponent(_LOGGER, DOMAIN, hass) component.setup({DOMAIN: {"platform": "platform", "entity_namespace": "yummy"}}) await hass.async_block_till_done() assert sorted(hass.states.async_entity_ids()) == [ "test_domain.yummy_beer", "test_domain.yummy_unnamed_device", ]
[ "async", "def", "test_set_entity_namespace_via_config", "(", "hass", ")", ":", "def", "platform_setup", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "\"\"\"Test the platform setup.\"\"\"", "add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"beer\"", ")", ",", "MockEntity", "(", "name", "=", "None", ")", "]", ")", "platform", "=", "MockPlatform", "(", "platform_setup", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.platform\"", ",", "platform", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "component", ".", "setup", "(", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"platform\"", ",", "\"entity_namespace\"", ":", "\"yummy\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "sorted", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "==", "[", "\"test_domain.yummy_beer\"", ",", "\"test_domain.yummy_unnamed_device\"", ",", "]" ]
[ 123, 0 ]
[ 143, 5 ]
python
en
['en', 'en', 'en']
True
test_extract_from_service_available_device
(hass)
Test the extraction of entity from service and device is available.
Test the extraction of entity from service and device is available.
async def test_extract_from_service_available_device(hass): """Test the extraction of entity from service and device is available.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [ MockEntity(name="test_1"), MockEntity(name="test_2", available=False), MockEntity(name="test_3"), MockEntity(name="test_4", available=False), ] ) call_1 = ha.ServiceCall("test", "service", data={"entity_id": ENTITY_MATCH_ALL}) assert ["test_domain.test_1", "test_domain.test_3"] == sorted( ent.entity_id for ent in (await component.async_extract_from_service(call_1)) ) call_2 = ha.ServiceCall( "test", "service", data={"entity_id": ["test_domain.test_3", "test_domain.test_4"]}, ) assert ["test_domain.test_3"] == sorted( ent.entity_id for ent in (await component.async_extract_from_service(call_2)) )
[ "async", "def", "test_extract_from_service_available_device", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"test_1\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_2\"", ",", "available", "=", "False", ")", ",", "MockEntity", "(", "name", "=", "\"test_3\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_4\"", ",", "available", "=", "False", ")", ",", "]", ")", "call_1", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "data", "=", "{", "\"entity_id\"", ":", "ENTITY_MATCH_ALL", "}", ")", "assert", "[", "\"test_domain.test_1\"", ",", "\"test_domain.test_3\"", "]", "==", "sorted", "(", "ent", ".", "entity_id", "for", "ent", "in", "(", "await", "component", ".", "async_extract_from_service", "(", "call_1", ")", ")", ")", "call_2", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "data", "=", "{", "\"entity_id\"", ":", "[", "\"test_domain.test_3\"", ",", "\"test_domain.test_4\"", "]", "}", ",", ")", "assert", "[", "\"test_domain.test_3\"", "]", "==", "sorted", "(", "ent", ".", "entity_id", "for", "ent", "in", "(", "await", "component", ".", "async_extract_from_service", "(", "call_2", ")", ")", ")" ]
[ 146, 0 ]
[ 172, 5 ]
python
en
['en', 'en', 'en']
True
test_platform_not_ready
(hass, legacy_patchable_time)
Test that we retry when platform not ready.
Test that we retry when platform not ready.
async def test_platform_not_ready(hass, legacy_patchable_time): """Test that we retry when platform not ready.""" platform1_setup = Mock(side_effect=[PlatformNotReady, PlatformNotReady, None]) mock_integration(hass, MockModule("mod1")) mock_entity_platform(hass, "test_domain.mod1", MockPlatform(platform1_setup)) component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_setup({DOMAIN: {"platform": "mod1"}}) await hass.async_block_till_done() assert len(platform1_setup.mock_calls) == 1 assert "test_domain.mod1" not in hass.config.components utcnow = dt_util.utcnow() with patch("homeassistant.util.dt.utcnow", return_value=utcnow): # Should not trigger attempt 2 async_fire_time_changed(hass, utcnow + timedelta(seconds=29)) await hass.async_block_till_done() assert len(platform1_setup.mock_calls) == 1 # Should trigger attempt 2 async_fire_time_changed(hass, utcnow + timedelta(seconds=30)) await hass.async_block_till_done() assert len(platform1_setup.mock_calls) == 2 assert "test_domain.mod1" not in hass.config.components # This should not trigger attempt 3 async_fire_time_changed(hass, utcnow + timedelta(seconds=59)) await hass.async_block_till_done() assert len(platform1_setup.mock_calls) == 2 # Trigger attempt 3, which succeeds async_fire_time_changed(hass, utcnow + timedelta(seconds=60)) await hass.async_block_till_done() assert len(platform1_setup.mock_calls) == 3 assert "test_domain.mod1" in hass.config.components
[ "async", "def", "test_platform_not_ready", "(", "hass", ",", "legacy_patchable_time", ")", ":", "platform1_setup", "=", "Mock", "(", "side_effect", "=", "[", "PlatformNotReady", ",", "PlatformNotReady", ",", "None", "]", ")", "mock_integration", "(", "hass", ",", "MockModule", "(", "\"mod1\"", ")", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.mod1\"", ",", "MockPlatform", "(", "platform1_setup", ")", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_setup", "(", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"mod1\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "platform1_setup", ".", "mock_calls", ")", "==", "1", "assert", "\"test_domain.mod1\"", "not", "in", "hass", ".", "config", ".", "components", "utcnow", "=", "dt_util", ".", "utcnow", "(", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "utcnow", ")", ":", "# Should not trigger attempt 2", "async_fire_time_changed", "(", "hass", ",", "utcnow", "+", "timedelta", "(", "seconds", "=", "29", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "platform1_setup", ".", "mock_calls", ")", "==", "1", "# Should trigger attempt 2", "async_fire_time_changed", "(", "hass", ",", "utcnow", "+", "timedelta", "(", "seconds", "=", "30", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "platform1_setup", ".", "mock_calls", ")", "==", "2", "assert", "\"test_domain.mod1\"", "not", "in", "hass", ".", "config", ".", "components", "# This should not trigger attempt 3", "async_fire_time_changed", "(", "hass", ",", "utcnow", "+", "timedelta", "(", "seconds", "=", "59", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "platform1_setup", ".", "mock_calls", ")", "==", "2", "# Trigger attempt 3, which succeeds", "async_fire_time_changed", "(", "hass", ",", "utcnow", "+", "timedelta", "(", "seconds", "=", "60", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "platform1_setup", ".", "mock_calls", ")", "==", "3", "assert", "\"test_domain.mod1\"", "in", "hass", ".", "config", ".", "components" ]
[ 175, 0 ]
[ 211, 59 ]
python
en
['en', 'en', 'en']
True
test_extract_from_service_fails_if_no_entity_id
(hass)
Test the extraction of everything from service.
Test the extraction of everything from service.
async def test_extract_from_service_fails_if_no_entity_id(hass): """Test the extraction of everything from service.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [MockEntity(name="test_1"), MockEntity(name="test_2")] ) assert ( await component.async_extract_from_service(ha.ServiceCall("test", "service")) == [] ) assert ( await component.async_extract_from_service( ha.ServiceCall("test", "service", {"entity_id": ENTITY_MATCH_NONE}) ) == [] ) assert ( await component.async_extract_from_service( ha.ServiceCall("test", "service", {"area_id": ENTITY_MATCH_NONE}) ) == [] )
[ "async", "def", "test_extract_from_service_fails_if_no_entity_id", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"test_1\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_2\"", ")", "]", ")", "assert", "(", "await", "component", ".", "async_extract_from_service", "(", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ")", ")", "==", "[", "]", ")", "assert", "(", "await", "component", ".", "async_extract_from_service", "(", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "{", "\"entity_id\"", ":", "ENTITY_MATCH_NONE", "}", ")", ")", "==", "[", "]", ")", "assert", "(", "await", "component", ".", "async_extract_from_service", "(", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "{", "\"area_id\"", ":", "ENTITY_MATCH_NONE", "}", ")", ")", "==", "[", "]", ")" ]
[ 214, 0 ]
[ 236, 5 ]
python
en
['en', 'en', 'en']
True
test_extract_from_service_filter_out_non_existing_entities
(hass)
Test the extraction of non existing entities from service.
Test the extraction of non existing entities from service.
async def test_extract_from_service_filter_out_non_existing_entities(hass): """Test the extraction of non existing entities from service.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [MockEntity(name="test_1"), MockEntity(name="test_2")] ) call = ha.ServiceCall( "test", "service", {"entity_id": ["test_domain.test_2", "test_domain.non_exist"]}, ) assert ["test_domain.test_2"] == [ ent.entity_id for ent in await component.async_extract_from_service(call) ]
[ "async", "def", "test_extract_from_service_filter_out_non_existing_entities", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"test_1\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_2\"", ")", "]", ")", "call", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "{", "\"entity_id\"", ":", "[", "\"test_domain.test_2\"", ",", "\"test_domain.non_exist\"", "]", "}", ",", ")", "assert", "[", "\"test_domain.test_2\"", "]", "==", "[", "ent", ".", "entity_id", "for", "ent", "in", "await", "component", ".", "async_extract_from_service", "(", "call", ")", "]" ]
[ 239, 0 ]
[ 254, 5 ]
python
en
['en', 'en', 'en']
True
test_extract_from_service_no_group_expand
(hass)
Test not expanding a group.
Test not expanding a group.
async def test_extract_from_service_no_group_expand(hass): """Test not expanding a group.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities([MockEntity(entity_id="group.test_group")]) call = ha.ServiceCall("test", "service", {"entity_id": ["group.test_group"]}) extracted = await component.async_extract_from_service(call, expand_group=False) assert len(extracted) == 1 assert extracted[0].entity_id == "group.test_group"
[ "async", "def", "test_extract_from_service_no_group_expand", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "entity_id", "=", "\"group.test_group\"", ")", "]", ")", "call", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ",", "{", "\"entity_id\"", ":", "[", "\"group.test_group\"", "]", "}", ")", "extracted", "=", "await", "component", ".", "async_extract_from_service", "(", "call", ",", "expand_group", "=", "False", ")", "assert", "len", "(", "extracted", ")", "==", "1", "assert", "extracted", "[", "0", "]", ".", "entity_id", "==", "\"group.test_group\"" ]
[ 257, 0 ]
[ 266, 55 ]
python
en
['en', 'en', 'en']
True
test_setup_dependencies_platform
(hass)
Test we setup the dependencies of a platform. We're explicitly testing that we process dependencies even if a component with the same name has already been loaded.
Test we setup the dependencies of a platform.
async def test_setup_dependencies_platform(hass): """Test we setup the dependencies of a platform. We're explicitly testing that we process dependencies even if a component with the same name has already been loaded. """ mock_integration( hass, MockModule("test_component", dependencies=["test_component2"]) ) mock_integration(hass, MockModule("test_component2")) mock_entity_platform(hass, "test_domain.test_component", MockPlatform()) component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_setup({DOMAIN: {"platform": "test_component"}}) await hass.async_block_till_done() assert "test_component" in hass.config.components assert "test_component2" in hass.config.components assert "test_domain.test_component" in hass.config.components
[ "async", "def", "test_setup_dependencies_platform", "(", "hass", ")", ":", "mock_integration", "(", "hass", ",", "MockModule", "(", "\"test_component\"", ",", "dependencies", "=", "[", "\"test_component2\"", "]", ")", ")", "mock_integration", "(", "hass", ",", "MockModule", "(", "\"test_component2\"", ")", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.test_component\"", ",", "MockPlatform", "(", ")", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_setup", "(", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"test_component\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"test_component\"", "in", "hass", ".", "config", ".", "components", "assert", "\"test_component2\"", "in", "hass", ".", "config", ".", "components", "assert", "\"test_domain.test_component\"", "in", "hass", ".", "config", ".", "components" ]
[ 269, 0 ]
[ 287, 65 ]
python
en
['en', 'da', 'en']
True
test_setup_entry
(hass)
Test setup entry calls async_setup_entry on platform.
Test setup entry calls async_setup_entry on platform.
async def test_setup_entry(hass): """Test setup entry calls async_setup_entry on platform.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", MockPlatform( async_setup_entry=mock_setup_entry, scan_interval=timedelta(seconds=5) ), ) component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="entry_domain") assert await component.async_setup_entry(entry) assert len(mock_setup_entry.mock_calls) == 1 p_hass, p_entry, _ = mock_setup_entry.mock_calls[0][1] assert p_hass is hass assert p_entry is entry assert component._platforms[entry.entry_id].scan_interval == timedelta(seconds=5)
[ "async", "def", "test_setup_entry", "(", "hass", ")", ":", "mock_setup_entry", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.entry_domain\"", ",", "MockPlatform", "(", "async_setup_entry", "=", "mock_setup_entry", ",", "scan_interval", "=", "timedelta", "(", "seconds", "=", "5", ")", ")", ",", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "\"entry_domain\"", ")", "assert", "await", "component", ".", "async_setup_entry", "(", "entry", ")", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1", "p_hass", ",", "p_entry", ",", "_", "=", "mock_setup_entry", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "assert", "p_hass", "is", "hass", "assert", "p_entry", "is", "entry", "assert", "component", ".", "_platforms", "[", "entry", ".", "entry_id", "]", ".", "scan_interval", "==", "timedelta", "(", "seconds", "=", "5", ")" ]
[ 290, 0 ]
[ 310, 85 ]
python
en
['en', 'da', 'en']
True
test_setup_entry_platform_not_exist
(hass)
Test setup entry fails if platform does not exist.
Test setup entry fails if platform does not exist.
async def test_setup_entry_platform_not_exist(hass): """Test setup entry fails if platform does not exist.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="non_existing") assert (await component.async_setup_entry(entry)) is False
[ "async", "def", "test_setup_entry_platform_not_exist", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "\"non_existing\"", ")", "assert", "(", "await", "component", ".", "async_setup_entry", "(", "entry", ")", ")", "is", "False" ]
[ 313, 0 ]
[ 318, 62 ]
python
en
['en', 'da', 'en']
True
test_setup_entry_fails_duplicate
(hass)
Test we don't allow setting up a config entry twice.
Test we don't allow setting up a config entry twice.
async def test_setup_entry_fails_duplicate(hass): """Test we don't allow setting up a config entry twice.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", MockPlatform(async_setup_entry=mock_setup_entry), ) component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="entry_domain") assert await component.async_setup_entry(entry) with pytest.raises(ValueError): await component.async_setup_entry(entry)
[ "async", "def", "test_setup_entry_fails_duplicate", "(", "hass", ")", ":", "mock_setup_entry", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.entry_domain\"", ",", "MockPlatform", "(", "async_setup_entry", "=", "mock_setup_entry", ")", ",", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "\"entry_domain\"", ")", "assert", "await", "component", ".", "async_setup_entry", "(", "entry", ")", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "await", "component", ".", "async_setup_entry", "(", "entry", ")" ]
[ 321, 0 ]
[ 336, 48 ]
python
en
['en', 'en', 'en']
True
test_unload_entry_resets_platform
(hass)
Test unloading an entry removes all entities.
Test unloading an entry removes all entities.
async def test_unload_entry_resets_platform(hass): """Test unloading an entry removes all entities.""" mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", MockPlatform(async_setup_entry=mock_setup_entry), ) component = EntityComponent(_LOGGER, DOMAIN, hass) entry = MockConfigEntry(domain="entry_domain") assert await component.async_setup_entry(entry) assert len(mock_setup_entry.mock_calls) == 1 add_entities = mock_setup_entry.mock_calls[0][1][2] add_entities([MockEntity()]) await hass.async_block_till_done() assert len(hass.states.async_entity_ids()) == 1 assert await component.async_unload_entry(entry) assert len(hass.states.async_entity_ids()) == 0
[ "async", "def", "test_unload_entry_resets_platform", "(", "hass", ")", ":", "mock_setup_entry", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_entity_platform", "(", "hass", ",", "\"test_domain.entry_domain\"", ",", "MockPlatform", "(", "async_setup_entry", "=", "mock_setup_entry", ")", ",", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "entry", "=", "MockConfigEntry", "(", "domain", "=", "\"entry_domain\"", ")", "assert", "await", "component", ".", "async_setup_entry", "(", "entry", ")", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1", "add_entities", "=", "mock_setup_entry", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "[", "2", "]", "add_entities", "(", "[", "MockEntity", "(", ")", "]", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "==", "1", "assert", "await", "component", ".", "async_unload_entry", "(", "entry", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "==", "0" ]
[ 339, 0 ]
[ 360, 51 ]
python
en
['en', 'en', 'en']
True
test_update_entity
(hass)
Test that we can update an entity with the helper.
Test that we can update an entity with the helper.
async def test_update_entity(hass): """Test that we can update an entity with the helper.""" component = EntityComponent(_LOGGER, DOMAIN, hass) entity = MockEntity() entity.async_write_ha_state = Mock() entity.async_update_ha_state = AsyncMock(return_value=None) await component.async_add_entities([entity]) # Called as part of async_add_entities assert len(entity.async_write_ha_state.mock_calls) == 1 await hass.helpers.entity_component.async_update_entity(entity.entity_id) assert len(entity.async_update_ha_state.mock_calls) == 1 assert entity.async_update_ha_state.mock_calls[-1][1][0] is True
[ "async", "def", "test_update_entity", "(", "hass", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "entity", "=", "MockEntity", "(", ")", "entity", ".", "async_write_ha_state", "=", "Mock", "(", ")", "entity", ".", "async_update_ha_state", "=", "AsyncMock", "(", "return_value", "=", "None", ")", "await", "component", ".", "async_add_entities", "(", "[", "entity", "]", ")", "# Called as part of async_add_entities", "assert", "len", "(", "entity", ".", "async_write_ha_state", ".", "mock_calls", ")", "==", "1", "await", "hass", ".", "helpers", ".", "entity_component", ".", "async_update_entity", "(", "entity", ".", "entity_id", ")", "assert", "len", "(", "entity", ".", "async_update_ha_state", ".", "mock_calls", ")", "==", "1", "assert", "entity", ".", "async_update_ha_state", ".", "mock_calls", "[", "-", "1", "]", "[", "1", "]", "[", "0", "]", "is", "True" ]
[ 372, 0 ]
[ 386, 68 ]
python
en
['en', 'en', 'en']
True
test_set_service_race
(hass)
Test race condition on setting service.
Test race condition on setting service.
async def test_set_service_race(hass): """Test race condition on setting service.""" exception = False def async_loop_exception_handler(_, _2) -> None: """Handle all exception inside the core loop.""" nonlocal exception exception = True hass.loop.set_exception_handler(async_loop_exception_handler) await async_setup_component(hass, "group", {}) component = EntityComponent(_LOGGER, DOMAIN, hass) for _ in range(2): hass.async_create_task(component.async_add_entities([MockEntity()])) await hass.async_block_till_done() assert not exception
[ "async", "def", "test_set_service_race", "(", "hass", ")", ":", "exception", "=", "False", "def", "async_loop_exception_handler", "(", "_", ",", "_2", ")", "->", "None", ":", "\"\"\"Handle all exception inside the core loop.\"\"\"", "nonlocal", "exception", "exception", "=", "True", "hass", ".", "loop", ".", "set_exception_handler", "(", "async_loop_exception_handler", ")", "await", "async_setup_component", "(", "hass", ",", "\"group\"", ",", "{", "}", ")", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "for", "_", "in", "range", "(", "2", ")", ":", "hass", ".", "async_create_task", "(", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", ")", "]", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "exception" ]
[ 389, 0 ]
[ 407, 24 ]
python
en
['en', 'en', 'en']
True
test_extract_all_omit_entity_id
(hass, caplog)
Test extract all with None and *.
Test extract all with None and *.
async def test_extract_all_omit_entity_id(hass, caplog): """Test extract all with None and *.""" component = EntityComponent(_LOGGER, DOMAIN, hass) await component.async_add_entities( [MockEntity(name="test_1"), MockEntity(name="test_2")] ) call = ha.ServiceCall("test", "service") assert [] == sorted( ent.entity_id for ent in await component.async_extract_from_service(call) )
[ "async", "def", "test_extract_all_omit_entity_id", "(", "hass", ",", "caplog", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_add_entities", "(", "[", "MockEntity", "(", "name", "=", "\"test_1\"", ")", ",", "MockEntity", "(", "name", "=", "\"test_2\"", ")", "]", ")", "call", "=", "ha", ".", "ServiceCall", "(", "\"test\"", ",", "\"service\"", ")", "assert", "[", "]", "==", "sorted", "(", "ent", ".", "entity_id", "for", "ent", "in", "await", "component", ".", "async_extract_from_service", "(", "call", ")", ")" ]
[ 410, 0 ]
[ 421, 5 ]
python
en
['en', 'en', 'en']
True