Search is not available for this dataset
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_restoring_devices
(hass)
Test restoring existing device_tracker entities if not detected on startup.
Test restoring existing device_tracker entities if not detected on startup.
async def test_restoring_devices(hass): """Test restoring existing device_tracker entities if not detected on startup.""" config_entry = MockConfigEntry( domain=mikrotik.DOMAIN, data=MOCK_DATA, options=MOCK_OPTIONS ) config_entry.add_to_hass(hass) registry = await entity_registry.async_get_registry(hass) registry.async_get_or_create( device_tracker.DOMAIN, mikrotik.DOMAIN, "00:00:00:00:00:01", suggested_object_id="device_1", config_entry=config_entry, ) registry.async_get_or_create( device_tracker.DOMAIN, mikrotik.DOMAIN, "00:00:00:00:00:02", suggested_object_id="device_2", config_entry=config_entry, ) await setup_mikrotik_entry(hass) # test device_2 which is not in wireless list is restored device_1 = hass.states.get("device_tracker.device_1") assert device_1 is not None assert device_1.state == "home" device_2 = hass.states.get("device_tracker.device_2") assert device_2 is not None assert device_2.state == "not_home"
[ "async", "def", "test_restoring_devices", "(", "hass", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "mikrotik", ".", "DOMAIN", ",", "data", "=", "MOCK_DATA", ",", "options", "=", "MOCK_OPTIONS", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "registry", ".", "async_get_or_create", "(", "device_tracker", ".", "DOMAIN", ",", "mikrotik", ".", "DOMAIN", ",", "\"00:00:00:00:00:01\"", ",", "suggested_object_id", "=", "\"device_1\"", ",", "config_entry", "=", "config_entry", ",", ")", "registry", ".", "async_get_or_create", "(", "device_tracker", ".", "DOMAIN", ",", "mikrotik", ".", "DOMAIN", ",", "\"00:00:00:00:00:02\"", ",", "suggested_object_id", "=", "\"device_2\"", ",", "config_entry", "=", "config_entry", ",", ")", "await", "setup_mikrotik_entry", "(", "hass", ")", "# test device_2 which is not in wireless list is restored", "device_1", "=", "hass", ".", "states", ".", "get", "(", "\"device_tracker.device_1\"", ")", "assert", "device_1", "is", "not", "None", "assert", "device_1", ".", "state", "==", "\"home\"", "device_2", "=", "hass", ".", "states", ".", "get", "(", "\"device_tracker.device_2\"", ")", "assert", "device_2", "is", "not", "None", "assert", "device_2", ".", "state", "==", "\"not_home\"" ]
[ 86, 0 ]
[ 117, 39 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Fibaro controller devices.
Set up the Fibaro controller devices.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Fibaro controller devices.""" if discovery_info is None: return add_entities( [FibaroSensor(device) for device in hass.data[FIBARO_DEVICES]["sensor"]], True )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "add_entities", "(", "[", "FibaroSensor", "(", "device", ")", "for", "device", "in", "hass", ".", "data", "[", "FIBARO_DEVICES", "]", "[", "\"sensor\"", "]", "]", ",", "True", ")" ]
[ 40, 0 ]
[ 47, 5 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.__init__
(self, fibaro_device)
Initialize the sensor.
Initialize the sensor.
def __init__(self, fibaro_device): """Initialize the sensor.""" self.current_value = None self.last_changed_time = None super().__init__(fibaro_device) self.entity_id = f"{DOMAIN}.{self.ha_id}" if fibaro_device.type in SENSOR_TYPES: self._unit = SENSOR_TYPES[fibaro_device.type][1] self._icon = SENSOR_TYPES[fibaro_device.type][2] self._device_class = SENSOR_TYPES[fibaro_device.type][3] else: self._unit = None self._icon = None self._device_class = None try: if not self._unit: if self.fibaro_device.properties.unit == "lux": self._unit = LIGHT_LUX elif self.fibaro_device.properties.unit == "C": self._unit = TEMP_CELSIUS elif self.fibaro_device.properties.unit == "F": self._unit = TEMP_FAHRENHEIT else: self._unit = self.fibaro_device.properties.unit except (KeyError, ValueError): pass
[ "def", "__init__", "(", "self", ",", "fibaro_device", ")", ":", "self", ".", "current_value", "=", "None", "self", ".", "last_changed_time", "=", "None", "super", "(", ")", ".", "__init__", "(", "fibaro_device", ")", "self", ".", "entity_id", "=", "f\"{DOMAIN}.{self.ha_id}\"", "if", "fibaro_device", ".", "type", "in", "SENSOR_TYPES", ":", "self", ".", "_unit", "=", "SENSOR_TYPES", "[", "fibaro_device", ".", "type", "]", "[", "1", "]", "self", ".", "_icon", "=", "SENSOR_TYPES", "[", "fibaro_device", ".", "type", "]", "[", "2", "]", "self", ".", "_device_class", "=", "SENSOR_TYPES", "[", "fibaro_device", ".", "type", "]", "[", "3", "]", "else", ":", "self", ".", "_unit", "=", "None", "self", ".", "_icon", "=", "None", "self", ".", "_device_class", "=", "None", "try", ":", "if", "not", "self", ".", "_unit", ":", "if", "self", ".", "fibaro_device", ".", "properties", ".", "unit", "==", "\"lux\"", ":", "self", ".", "_unit", "=", "LIGHT_LUX", "elif", "self", ".", "fibaro_device", ".", "properties", ".", "unit", "==", "\"C\"", ":", "self", ".", "_unit", "=", "TEMP_CELSIUS", "elif", "self", ".", "fibaro_device", ".", "properties", ".", "unit", "==", "\"F\"", ":", "self", ".", "_unit", "=", "TEMP_FAHRENHEIT", "else", ":", "self", ".", "_unit", "=", "self", ".", "fibaro_device", ".", "properties", ".", "unit", "except", "(", "KeyError", ",", "ValueError", ")", ":", "pass" ]
[ 53, 4 ]
[ 78, 16 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self.current_value
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "current_value" ]
[ 81, 4 ]
[ 83, 33 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.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): """Return the unit of measurement of this entity, if any.""" return self._unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit" ]
[ 86, 4 ]
[ 88, 25 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.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 self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 91, 4 ]
[ 93, 25 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.device_class
(self)
Return the device class of the sensor.
Return the device class of the sensor.
def device_class(self): """Return the device class of the sensor.""" return self._device_class
[ "def", "device_class", "(", "self", ")", ":", "return", "self", ".", "_device_class" ]
[ 96, 4 ]
[ 98, 33 ]
python
en
['en', 'en', 'en']
True
FibaroSensor.update
(self)
Update the state.
Update the state.
def update(self): """Update the state.""" try: self.current_value = float(self.fibaro_device.properties.value) except (KeyError, ValueError): pass
[ "def", "update", "(", "self", ")", ":", "try", ":", "self", ".", "current_value", "=", "float", "(", "self", ".", "fibaro_device", ".", "properties", ".", "value", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "pass" ]
[ 100, 4 ]
[ 105, 16 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the mysensors platform for binary sensors.
Set up the mysensors platform for binary sensors.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the mysensors platform for binary sensors.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsBinarySensor, async_add_entities=async_add_entities, )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "mysensors", ".", "setup_mysensors_platform", "(", "hass", ",", "DOMAIN", ",", "discovery_info", ",", "MySensorsBinarySensor", ",", "async_add_entities", "=", "async_add_entities", ",", ")" ]
[ 26, 0 ]
[ 34, 5 ]
python
en
['en', 'da', 'en']
True
MySensorsBinarySensor.is_on
(self)
Return True if the binary sensor is on.
Return True if the binary sensor is on.
def is_on(self): """Return True if the binary sensor is on.""" return self._values.get(self.value_type) == STATE_ON
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_values", ".", "get", "(", "self", ".", "value_type", ")", "==", "STATE_ON" ]
[ 41, 4 ]
[ 43, 60 ]
python
en
['en', 'fy', 'en']
True
MySensorsBinarySensor.device_class
(self)
Return the class of this sensor, from DEVICE_CLASSES.
Return the class of this sensor, from DEVICE_CLASSES.
def device_class(self): """Return the class of this sensor, from DEVICE_CLASSES.""" pres = self.gateway.const.Presentation device_class = SENSORS.get(pres(self.child_type).name) if device_class in DEVICE_CLASSES: return device_class return None
[ "def", "device_class", "(", "self", ")", ":", "pres", "=", "self", ".", "gateway", ".", "const", ".", "Presentation", "device_class", "=", "SENSORS", ".", "get", "(", "pres", "(", "self", ".", "child_type", ")", ".", "name", ")", "if", "device_class", "in", "DEVICE_CLASSES", ":", "return", "device_class", "return", "None" ]
[ 46, 4 ]
[ 52, 19 ]
python
en
['en', 'en', 'en']
True
test_bridge_import_flow
(hass)
Test a bridge entry gets created and set up during the import flow.
Test a bridge entry gets created and set up during the import flow.
async def test_bridge_import_flow(hass): """Test a bridge entry gets created and set up during the import flow.""" entry_mock_data = { CONF_HOST: "1.1.1.1", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch( "homeassistant.components.lutron_caseta.async_setup_entry", return_value=True, ) as mock_setup_entry, patch( "homeassistant.components.lutron_caseta.async_setup", return_value=True ), patch.object( Smartbridge, "create_tls" ) as create_tls: create_tls.return_value = MockBridge(can_connect=True) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == "create_entry" assert result["title"] == CasetaConfigFlow.ENTRY_DEFAULT_TITLE assert result["data"] == entry_mock_data await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_bridge_import_flow", "(", "hass", ")", ":", "entry_mock_data", "=", "{", "CONF_HOST", ":", "\"1.1.1.1\"", ",", "CONF_KEYFILE", ":", "\"\"", ",", "CONF_CERTFILE", ":", "\"\"", ",", "CONF_CA_CERTS", ":", "\"\"", ",", "}", "with", "patch", "(", "\"homeassistant.components.lutron_caseta.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ",", "patch", "(", "\"homeassistant.components.lutron_caseta.async_setup\"", ",", "return_value", "=", "True", ")", ",", "patch", ".", "object", "(", "Smartbridge", ",", "\"create_tls\"", ")", "as", "create_tls", ":", "create_tls", ".", "return_value", "=", "MockBridge", "(", "can_connect", "=", "True", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_mock_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "CasetaConfigFlow", ".", "ENTRY_DEFAULT_TITLE", "assert", "result", "[", "\"data\"", "]", "==", "entry_mock_data", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 41, 0 ]
[ 71, 48 ]
python
en
['en', 'en', 'en']
True
test_bridge_cannot_connect
(hass)
Test checking for connection and cannot_connect error.
Test checking for connection and cannot_connect error.
async def test_bridge_cannot_connect(hass): """Test checking for connection and cannot_connect error.""" entry_mock_data = { CONF_HOST: "not.a.valid.host", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch.object(Smartbridge, "create_tls") as create_tls: create_tls.return_value = MockBridge(can_connect=False) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == "form" assert result["step_id"] == STEP_IMPORT_FAILED assert result["errors"] == {"base": ERROR_CANNOT_CONNECT} result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == CasetaConfigFlow.ABORT_REASON_CANNOT_CONNECT
[ "async", "def", "test_bridge_cannot_connect", "(", "hass", ")", ":", "entry_mock_data", "=", "{", "CONF_HOST", ":", "\"not.a.valid.host\"", ",", "CONF_KEYFILE", ":", "\"\"", ",", "CONF_CERTFILE", ":", "\"\"", ",", "CONF_CA_CERTS", ":", "\"\"", ",", "}", "with", "patch", ".", "object", "(", "Smartbridge", ",", "\"create_tls\"", ")", "as", "create_tls", ":", "create_tls", ".", "return_value", "=", "MockBridge", "(", "can_connect", "=", "False", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_mock_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"step_id\"", "]", "==", "STEP_IMPORT_FAILED", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "ERROR_CANNOT_CONNECT", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "CasetaConfigFlow", ".", "ABORT_REASON_CANNOT_CONNECT" ]
[ 74, 0 ]
[ 100, 75 ]
python
en
['en', 'en', 'en']
True
test_bridge_cannot_connect_unknown_error
(hass)
Test checking for connection and encountering an unknown error.
Test checking for connection and encountering an unknown error.
async def test_bridge_cannot_connect_unknown_error(hass): """Test checking for connection and encountering an unknown error.""" entry_mock_data = { CONF_HOST: "", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch.object(Smartbridge, "create_tls") as create_tls: mock_bridge = MockBridge() mock_bridge.connect = AsyncMock(side_effect=Exception()) create_tls.return_value = mock_bridge result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == "form" assert result["step_id"] == STEP_IMPORT_FAILED assert result["errors"] == {"base": ERROR_CANNOT_CONNECT} result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == CasetaConfigFlow.ABORT_REASON_CANNOT_CONNECT
[ "async", "def", "test_bridge_cannot_connect_unknown_error", "(", "hass", ")", ":", "entry_mock_data", "=", "{", "CONF_HOST", ":", "\"\"", ",", "CONF_KEYFILE", ":", "\"\"", ",", "CONF_CERTFILE", ":", "\"\"", ",", "CONF_CA_CERTS", ":", "\"\"", ",", "}", "with", "patch", ".", "object", "(", "Smartbridge", ",", "\"create_tls\"", ")", "as", "create_tls", ":", "mock_bridge", "=", "MockBridge", "(", ")", "mock_bridge", ".", "connect", "=", "AsyncMock", "(", "side_effect", "=", "Exception", "(", ")", ")", "create_tls", ".", "return_value", "=", "mock_bridge", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_mock_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"step_id\"", "]", "==", "STEP_IMPORT_FAILED", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "ERROR_CANNOT_CONNECT", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "CasetaConfigFlow", ".", "ABORT_REASON_CANNOT_CONNECT" ]
[ 103, 0 ]
[ 130, 75 ]
python
en
['en', 'en', 'en']
True
test_duplicate_bridge_import
(hass)
Test that creating a bridge entry with a duplicate host errors.
Test that creating a bridge entry with a duplicate host errors.
async def test_duplicate_bridge_import(hass): """Test that creating a bridge entry with a duplicate host errors.""" entry_mock_data = { CONF_HOST: "1.1.1.1", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } mock_entry = MockConfigEntry(domain=DOMAIN, data=entry_mock_data) mock_entry.add_to_hass(hass) with patch( "homeassistant.components.lutron_caseta.async_setup_entry", return_value=True, ) as mock_setup_entry: # Mock entry added, try initializing flow with duplicate host result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=entry_mock_data, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == CasetaConfigFlow.ABORT_REASON_ALREADY_CONFIGURED assert len(mock_setup_entry.mock_calls) == 0
[ "async", "def", "test_duplicate_bridge_import", "(", "hass", ")", ":", "entry_mock_data", "=", "{", "CONF_HOST", ":", "\"1.1.1.1\"", ",", "CONF_KEYFILE", ":", "\"\"", ",", "CONF_CERTFILE", ":", "\"\"", ",", "CONF_CA_CERTS", ":", "\"\"", ",", "}", "mock_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "entry_mock_data", ")", "mock_entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", "(", "\"homeassistant.components.lutron_caseta.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "# Mock entry added, try initializing flow with duplicate host", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "entry_mock_data", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "CasetaConfigFlow", ".", "ABORT_REASON_ALREADY_CONFIGURED", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "0" ]
[ 133, 0 ]
[ 158, 48 ]
python
en
['en', 'en', 'en']
True
MockBridge.__init__
(self, can_connect=True)
Initialize MockBridge instance with configured mock connectivity.
Initialize MockBridge instance with configured mock connectivity.
def __init__(self, can_connect=True): """Initialize MockBridge instance with configured mock connectivity.""" self.can_connect = can_connect self.is_currently_connected = False
[ "def", "__init__", "(", "self", ",", "can_connect", "=", "True", ")", ":", "self", ".", "can_connect", "=", "can_connect", "self", ".", "is_currently_connected", "=", "False" ]
[ 22, 4 ]
[ 25, 43 ]
python
en
['en', 'zu', 'en']
True
MockBridge.connect
(self)
Connect the mock bridge.
Connect the mock bridge.
async def connect(self): """Connect the mock bridge.""" if self.can_connect: self.is_currently_connected = True
[ "async", "def", "connect", "(", "self", ")", ":", "if", "self", ".", "can_connect", ":", "self", ".", "is_currently_connected", "=", "True" ]
[ 27, 4 ]
[ 30, 46 ]
python
en
['en', 'fr', 'en']
True
MockBridge.is_connected
(self)
Return whether the mock bridge is connected.
Return whether the mock bridge is connected.
def is_connected(self): """Return whether the mock bridge is connected.""" return self.is_currently_connected
[ "def", "is_connected", "(", "self", ")", ":", "return", "self", ".", "is_currently_connected" ]
[ 32, 4 ]
[ 34, 42 ]
python
en
['en', 'en', 'en']
True
MockBridge.close
(self)
Close the mock bridge connection.
Close the mock bridge connection.
async def close(self): """Close the mock bridge connection.""" self.is_currently_connected = False
[ "async", "def", "close", "(", "self", ")", ":", "self", ".", "is_currently_connected", "=", "False" ]
[ 36, 4 ]
[ 38, 43 ]
python
en
['en', 'fr', 'en']
True
HDEntity.__init__
(self, coordinator, device_info, unique_id)
Initialize the entity.
Initialize the entity.
def __init__(self, coordinator, device_info, unique_id): """Initialize the entity.""" super().__init__(coordinator) self._unique_id = unique_id self._device_info = device_info
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "device_info", ",", "unique_id", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "_unique_id", "=", "unique_id", "self", ".", "_device_info", "=", "device_info" ]
[ 25, 4 ]
[ 29, 39 ]
python
en
['en', 'en', 'en']
True
HDEntity.unique_id
(self)
Return the unique id.
Return the unique id.
def unique_id(self): """Return the unique id.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 32, 4 ]
[ 34, 30 ]
python
en
['en', 'la', 'en']
True
HDEntity.device_info
(self)
Return the device_info of the device.
Return the device_info of the device.
def device_info(self): """Return the device_info of the device.""" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}" return { "identifiers": {(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, "connections": { (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, "name": self._device_info[DEVICE_NAME], "model": self._device_info[DEVICE_MODEL], "sw_version": sw_version, "manufacturer": MANUFACTURER, }
[ "def", "device_info", "(", "self", ")", ":", "firmware", "=", "self", ".", "_device_info", "[", "DEVICE_FIRMWARE", "]", "sw_version", "=", "f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\"", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_device_info", "[", "DEVICE_SERIAL_NUMBER", "]", ")", "}", ",", "\"connections\"", ":", "{", "(", "dr", ".", "CONNECTION_NETWORK_MAC", ",", "self", ".", "_device_info", "[", "DEVICE_MAC_ADDRESS", "]", ")", "}", ",", "\"name\"", ":", "self", ".", "_device_info", "[", "DEVICE_NAME", "]", ",", "\"model\"", ":", "self", ".", "_device_info", "[", "DEVICE_MODEL", "]", ",", "\"sw_version\"", ":", "sw_version", ",", "\"manufacturer\"", ":", "MANUFACTURER", ",", "}" ]
[ 37, 4 ]
[ 50, 9 ]
python
en
['en', 'en', 'en']
True
ShadeEntity.__init__
(self, coordinator, device_info, shade, shade_name)
Initialize the shade.
Initialize the shade.
def __init__(self, coordinator, device_info, shade, shade_name): """Initialize the shade.""" super().__init__(coordinator, device_info, shade.id) self._shade_name = shade_name self._shade = shade
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "device_info", ",", "shade", ",", "shade_name", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ",", "device_info", ",", "shade", ".", "id", ")", "self", ".", "_shade_name", "=", "shade_name", "self", ".", "_shade", "=", "shade" ]
[ 56, 4 ]
[ 60, 27 ]
python
en
['en', 'en', 'en']
True
ShadeEntity.device_info
(self)
Return the device_info of the device.
Return the device_info of the device.
def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._shade.id)}, "name": self._shade_name, "manufacturer": MANUFACTURER, "via_device": (DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), } if FIRMWARE_IN_SHADE not in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE_IN_SHADE] sw_version = f"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}" model = self._shade.raw_data[ATTR_TYPE] for shade in self._shade.shade_types: if shade.shade_type == model: model = shade.description break device_info["sw_version"] = sw_version device_info["model"] = model return device_info
[ "def", "device_info", "(", "self", ")", ":", "device_info", "=", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_shade", ".", "id", ")", "}", ",", "\"name\"", ":", "self", ".", "_shade_name", ",", "\"manufacturer\"", ":", "MANUFACTURER", ",", "\"via_device\"", ":", "(", "DOMAIN", ",", "self", ".", "_device_info", "[", "DEVICE_SERIAL_NUMBER", "]", ")", ",", "}", "if", "FIRMWARE_IN_SHADE", "not", "in", "self", ".", "_shade", ".", "raw_data", ":", "return", "device_info", "firmware", "=", "self", ".", "_shade", ".", "raw_data", "[", "FIRMWARE_IN_SHADE", "]", "sw_version", "=", "f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\"", "model", "=", "self", ".", "_shade", ".", "raw_data", "[", "ATTR_TYPE", "]", "for", "shade", "in", "self", ".", "_shade", ".", "shade_types", ":", "if", "shade", ".", "shade_type", "==", "model", ":", "model", "=", "shade", ".", "description", "break", "device_info", "[", "\"sw_version\"", "]", "=", "sw_version", "device_info", "[", "\"model\"", "]", "=", "model", "return", "device_info" ]
[ 63, 4 ]
[ 86, 26 ]
python
en
['en', 'en', 'en']
True
test_component_unload_config_entry
(hass, config_entry)
Test that loading and unloading of a config entry works.
Test that loading and unloading of a config entry works.
async def test_component_unload_config_entry(hass, config_entry): """Test that loading and unloading of a config entry works.""" config_entry.add_to_hass(hass) with patch( "aio_geojson_geonetnz_volcano.GeonetnzVolcanoFeedManager.update", new_callable=AsyncMock, ) as mock_feed_manager_update: # Load config entry. assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert mock_feed_manager_update.call_count == 1 assert hass.data[DOMAIN][FEED][config_entry.entry_id] is not None # Unload config entry. assert await hass.config_entries.async_unload(config_entry.entry_id) await hass.async_block_till_done() assert hass.data[DOMAIN][FEED].get(config_entry.entry_id) is None
[ "async", "def", "test_component_unload_config_entry", "(", "hass", ",", "config_entry", ")", ":", "config_entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", "(", "\"aio_geojson_geonetnz_volcano.GeonetnzVolcanoFeedManager.update\"", ",", "new_callable", "=", "AsyncMock", ",", ")", "as", "mock_feed_manager_update", ":", "# Load config entry.", "assert", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "config_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mock_feed_manager_update", ".", "call_count", "==", "1", "assert", "hass", ".", "data", "[", "DOMAIN", "]", "[", "FEED", "]", "[", "config_entry", ".", "entry_id", "]", "is", "not", "None", "# Unload config entry.", "assert", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "config_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "data", "[", "DOMAIN", "]", "[", "FEED", "]", ".", "get", "(", "config_entry", ".", "entry_id", ")", "is", "None" ]
[ 6, 0 ]
[ 21, 73 ]
python
en
['en', 'en', 'en']
True
test_valid_state
(hass, requests_mock)
Test for operational london_air sensor with proper attributes.
Test for operational london_air sensor with proper attributes.
async def test_valid_state(hass, requests_mock): """Test for operational london_air sensor with proper attributes.""" requests_mock.get(URL, text=load_fixture("london_air.json"), status_code=HTTP_OK) assert await async_setup_component(hass, "sensor", VALID_CONFIG) await hass.async_block_till_done() state = hass.states.get("sensor.merton") assert state is not None assert state.state == "Low" assert state.attributes["icon"] == "mdi:cloud-outline" assert state.attributes["updated"] == "2017-08-03 03:00:00" assert state.attributes["sites"] == 2 assert state.attributes["friendly_name"] == "Merton" sites = state.attributes["data"] assert sites is not None assert len(sites) == 2 assert sites[0]["site_code"] == "ME2" assert sites[0]["site_type"] == "Roadside" assert sites[0]["site_name"] == "Merton Road" assert sites[0]["pollutants_status"] == "Low" pollutants = sites[0]["pollutants"] assert pollutants is not None assert len(pollutants) == 1 assert pollutants[0]["code"] == "PM10" assert pollutants[0]["quality"] == "Low" assert int(pollutants[0]["index"]) == 2 assert pollutants[0]["summary"] == "PM10 is Low"
[ "async", "def", "test_valid_state", "(", "hass", ",", "requests_mock", ")", ":", "requests_mock", ".", "get", "(", "URL", ",", "text", "=", "load_fixture", "(", "\"london_air.json\"", ")", ",", "status_code", "=", "HTTP_OK", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "VALID_CONFIG", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.merton\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "==", "\"Low\"", "assert", "state", ".", "attributes", "[", "\"icon\"", "]", "==", "\"mdi:cloud-outline\"", "assert", "state", ".", "attributes", "[", "\"updated\"", "]", "==", "\"2017-08-03 03:00:00\"", "assert", "state", ".", "attributes", "[", "\"sites\"", "]", "==", "2", "assert", "state", ".", "attributes", "[", "\"friendly_name\"", "]", "==", "\"Merton\"", "sites", "=", "state", ".", "attributes", "[", "\"data\"", "]", "assert", "sites", "is", "not", "None", "assert", "len", "(", "sites", ")", "==", "2", "assert", "sites", "[", "0", "]", "[", "\"site_code\"", "]", "==", "\"ME2\"", "assert", "sites", "[", "0", "]", "[", "\"site_type\"", "]", "==", "\"Roadside\"", "assert", "sites", "[", "0", "]", "[", "\"site_name\"", "]", "==", "\"Merton Road\"", "assert", "sites", "[", "0", "]", "[", "\"pollutants_status\"", "]", "==", "\"Low\"", "pollutants", "=", "sites", "[", "0", "]", "[", "\"pollutants\"", "]", "assert", "pollutants", "is", "not", "None", "assert", "len", "(", "pollutants", ")", "==", "1", "assert", "pollutants", "[", "0", "]", "[", "\"code\"", "]", "==", "\"PM10\"", "assert", "pollutants", "[", "0", "]", "[", "\"quality\"", "]", "==", "\"Low\"", "assert", "int", "(", "pollutants", "[", "0", "]", "[", "\"index\"", "]", ")", "==", "2", "assert", "pollutants", "[", "0", "]", "[", "\"summary\"", "]", "==", "\"PM10 is Low\"" ]
[ 10, 0 ]
[ 38, 52 ]
python
en
['en', 'en', 'en']
True
test_api_failure
(hass, requests_mock)
Test for failure in the API.
Test for failure in the API.
async def test_api_failure(hass, requests_mock): """Test for failure in the API.""" requests_mock.get(URL, status_code=HTTP_SERVICE_UNAVAILABLE) assert await async_setup_component(hass, "sensor", VALID_CONFIG) await hass.async_block_till_done() state = hass.states.get("sensor.merton") assert state is not None assert state.attributes["updated"] is None assert state.attributes["sites"] == 0
[ "async", "def", "test_api_failure", "(", "hass", ",", "requests_mock", ")", ":", "requests_mock", ".", "get", "(", "URL", ",", "status_code", "=", "HTTP_SERVICE_UNAVAILABLE", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "VALID_CONFIG", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.merton\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "attributes", "[", "\"updated\"", "]", "is", "None", "assert", "state", ".", "attributes", "[", "\"sites\"", "]", "==", "0" ]
[ 41, 0 ]
[ 50, 41 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up a BleBox climate entity.
Set up a BleBox climate entity.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a BleBox climate entity.""" create_blebox_entities( hass, config_entry, async_add_entities, BleBoxClimateEntity, "climates" )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "create_blebox_entities", "(", "hass", ",", "config_entry", ",", "async_add_entities", ",", "BleBoxClimateEntity", ",", "\"climates\"", ")" ]
[ 16, 0 ]
[ 21, 5 ]
python
en
['en', 'hu', 'en']
True
BleBoxClimateEntity.supported_features
(self)
Return the supported climate features.
Return the supported climate features.
def supported_features(self): """Return the supported climate features.""" return SUPPORT_TARGET_TEMPERATURE
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_TARGET_TEMPERATURE" ]
[ 28, 4 ]
[ 30, 41 ]
python
en
['en', 'en', 'en']
True
BleBoxClimateEntity.hvac_mode
(self)
Return the desired HVAC mode.
Return the desired HVAC mode.
def hvac_mode(self): """Return the desired HVAC mode.""" if self._feature.is_on is None: return None return HVAC_MODE_HEAT if self._feature.is_on else HVAC_MODE_OFF
[ "def", "hvac_mode", "(", "self", ")", ":", "if", "self", ".", "_feature", ".", "is_on", "is", "None", ":", "return", "None", "return", "HVAC_MODE_HEAT", "if", "self", ".", "_feature", ".", "is_on", "else", "HVAC_MODE_OFF" ]
[ 33, 4 ]
[ 38, 71 ]
python
en
['en', 'no', 'en']
True
BleBoxClimateEntity.hvac_action
(self)
Return the actual current HVAC action.
Return the actual current HVAC action.
def hvac_action(self): """Return the actual current HVAC action.""" is_on = self._feature.is_on if not is_on: return None if is_on is None else CURRENT_HVAC_OFF # NOTE: In practice, there's no need to handle case when is_heating is None return CURRENT_HVAC_HEAT if self._feature.is_heating else CURRENT_HVAC_IDLE
[ "def", "hvac_action", "(", "self", ")", ":", "is_on", "=", "self", ".", "_feature", ".", "is_on", "if", "not", "is_on", ":", "return", "None", "if", "is_on", "is", "None", "else", "CURRENT_HVAC_OFF", "# NOTE: In practice, there's no need to handle case when is_heating is None", "return", "CURRENT_HVAC_HEAT", "if", "self", ".", "_feature", ".", "is_heating", "else", "CURRENT_HVAC_IDLE" ]
[ 41, 4 ]
[ 48, 83 ]
python
en
['en', 'en', 'en']
True
BleBoxClimateEntity.hvac_modes
(self)
Return a list of possible HVAC modes.
Return a list of possible HVAC modes.
def hvac_modes(self): """Return a list of possible HVAC modes.""" return [HVAC_MODE_OFF, HVAC_MODE_HEAT]
[ "def", "hvac_modes", "(", "self", ")", ":", "return", "[", "HVAC_MODE_OFF", ",", "HVAC_MODE_HEAT", "]" ]
[ 51, 4 ]
[ 53, 46 ]
python
en
['en', 'en', 'en']
True
BleBoxClimateEntity.temperature_unit
(self)
Return the temperature unit.
Return the temperature unit.
def temperature_unit(self): """Return the temperature unit.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 56, 4 ]
[ 58, 27 ]
python
en
['en', 'la', 'en']
True
BleBoxClimateEntity.max_temp
(self)
Return the maximum temperature supported.
Return the maximum temperature supported.
def max_temp(self): """Return the maximum temperature supported.""" return self._feature.max_temp
[ "def", "max_temp", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "max_temp" ]
[ 61, 4 ]
[ 63, 37 ]
python
en
['en', 'la', 'en']
True
BleBoxClimateEntity.min_temp
(self)
Return the maximum temperature supported.
Return the maximum temperature supported.
def min_temp(self): """Return the maximum temperature supported.""" return self._feature.min_temp
[ "def", "min_temp", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "min_temp" ]
[ 66, 4 ]
[ 68, 37 ]
python
en
['en', 'la', 'en']
True
BleBoxClimateEntity.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self._feature.current
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "current" ]
[ 71, 4 ]
[ 73, 36 ]
python
en
['en', 'la', 'en']
True
BleBoxClimateEntity.target_temperature
(self)
Return the desired thermostat temperature.
Return the desired thermostat temperature.
def target_temperature(self): """Return the desired thermostat temperature.""" return self._feature.desired
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "desired" ]
[ 76, 4 ]
[ 78, 36 ]
python
en
['en', 'en', 'en']
True
BleBoxClimateEntity.async_set_hvac_mode
(self, hvac_mode)
Set the climate entity mode.
Set the climate entity mode.
async def async_set_hvac_mode(self, hvac_mode): """Set the climate entity mode.""" if hvac_mode == HVAC_MODE_HEAT: await self._feature.async_on() return await self._feature.async_off()
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ")", ":", "if", "hvac_mode", "==", "HVAC_MODE_HEAT", ":", "await", "self", ".", "_feature", ".", "async_on", "(", ")", "return", "await", "self", ".", "_feature", ".", "async_off", "(", ")" ]
[ 80, 4 ]
[ 86, 39 ]
python
en
['en', 'en', 'en']
True
BleBoxClimateEntity.async_set_temperature
(self, **kwargs)
Set the thermostat temperature.
Set the thermostat temperature.
async def async_set_temperature(self, **kwargs): """Set the thermostat temperature.""" value = kwargs[ATTR_TEMPERATURE] await self._feature.async_set_temperature(value)
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "value", "=", "kwargs", "[", "ATTR_TEMPERATURE", "]", "await", "self", ".", "_feature", ".", "async_set_temperature", "(", "value", ")" ]
[ 88, 4 ]
[ 91, 56 ]
python
en
['en', 'la', 'en']
True
update_vocabulary
(vocab, file_name, is_dict=False)
Read text and return dictionary that encodes vocabulary
Read text and return dictionary that encodes vocabulary
def update_vocabulary(vocab, file_name, is_dict=False): """Read text and return dictionary that encodes vocabulary """ #vocab = Counter() with codecs.open(file_name, encoding='utf-8') as fobj: for i, line in enumerate(fobj): if is_dict: try: word, count = line.strip('\r\n ').split(' ') except: print('Failed reading vocabulary file at line {0}: {1}'.format(i, line)) sys.exit(1) vocab[word] += int(count) else: for word in line.strip('\r\n ').split(' '): if word: vocab[word] += 1 return vocab
[ "def", "update_vocabulary", "(", "vocab", ",", "file_name", ",", "is_dict", "=", "False", ")", ":", "#vocab = Counter()", "with", "codecs", ".", "open", "(", "file_name", ",", "encoding", "=", "'utf-8'", ")", "as", "fobj", ":", "for", "i", ",", "line", "in", "enumerate", "(", "fobj", ")", ":", "if", "is_dict", ":", "try", ":", "word", ",", "count", "=", "line", ".", "strip", "(", "'\\r\\n '", ")", ".", "split", "(", "' '", ")", "except", ":", "print", "(", "'Failed reading vocabulary file at line {0}: {1}'", ".", "format", "(", "i", ",", "line", ")", ")", "sys", ".", "exit", "(", "1", ")", "vocab", "[", "word", "]", "+=", "int", "(", "count", ")", "else", ":", "for", "word", "in", "line", ".", "strip", "(", "'\\r\\n '", ")", ".", "split", "(", "' '", ")", ":", "if", "word", ":", "vocab", "[", "word", "]", "+=", "1", "return", "vocab" ]
[ 25, 0 ]
[ 43, 16 ]
python
en
['en', 'en', 'en']
True
update_pair_statistics
(pair, changed, stats, indices)
Minimally update the indices and frequency of symbol pairs if we merge a pair of symbols, only pairs that overlap with occurrences of this pair are affected, and need to be updated.
Minimally update the indices and frequency of symbol pairs
def update_pair_statistics(pair, changed, stats, indices): """Minimally update the indices and frequency of symbol pairs if we merge a pair of symbols, only pairs that overlap with occurrences of this pair are affected, and need to be updated. """ stats[pair] = 0 indices[pair] = defaultdict(int) first, second = pair new_pair = first+second for j, word, old_word, freq in changed: # find all instances of pair, and update frequency/indices around it i = 0 while True: # find first symbol try: i = old_word.index(first, i) except ValueError: break # if first symbol is followed by second symbol, we've found an occurrence of pair (old_word[i:i+2]) if i < len(old_word)-1 and old_word[i+1] == second: # assuming a symbol sequence "A B C", if "B C" is merged, reduce the frequency of "A B" if i: prev = old_word[i-1:i+1] stats[prev] -= freq indices[prev][j] -= 1 if i < len(old_word)-2: # assuming a symbol sequence "A B C B", if "B C" is merged, reduce the frequency of "C B". # however, skip this if the sequence is A B C B C, because the frequency of "C B" will be reduced by the previous code block if old_word[i+2] != first or i >= len(old_word)-3 or old_word[i+3] != second: nex = old_word[i+1:i+3] stats[nex] -= freq indices[nex][j] -= 1 i += 2 else: i += 1 i = 0 while True: try: # find new pair i = word.index(new_pair, i) except ValueError: break # assuming a symbol sequence "A BC D", if "B C" is merged, increase the frequency of "A BC" if i: prev = word[i-1:i+1] stats[prev] += freq indices[prev][j] += 1 # assuming a symbol sequence "A BC B", if "B C" is merged, increase the frequency of "BC B" # however, if the sequence is A BC BC, skip this step because the count of "BC BC" will be incremented by the previous code block if i < len(word)-1 and word[i+1] != new_pair: nex = word[i:i+2] stats[nex] += freq indices[nex][j] += 1 i += 1
[ "def", "update_pair_statistics", "(", "pair", ",", "changed", ",", "stats", ",", "indices", ")", ":", "stats", "[", "pair", "]", "=", "0", "indices", "[", "pair", "]", "=", "defaultdict", "(", "int", ")", "first", ",", "second", "=", "pair", "new_pair", "=", "first", "+", "second", "for", "j", ",", "word", ",", "old_word", ",", "freq", "in", "changed", ":", "# find all instances of pair, and update frequency/indices around it", "i", "=", "0", "while", "True", ":", "# find first symbol", "try", ":", "i", "=", "old_word", ".", "index", "(", "first", ",", "i", ")", "except", "ValueError", ":", "break", "# if first symbol is followed by second symbol, we've found an occurrence of pair (old_word[i:i+2])", "if", "i", "<", "len", "(", "old_word", ")", "-", "1", "and", "old_word", "[", "i", "+", "1", "]", "==", "second", ":", "# assuming a symbol sequence \"A B C\", if \"B C\" is merged, reduce the frequency of \"A B\"", "if", "i", ":", "prev", "=", "old_word", "[", "i", "-", "1", ":", "i", "+", "1", "]", "stats", "[", "prev", "]", "-=", "freq", "indices", "[", "prev", "]", "[", "j", "]", "-=", "1", "if", "i", "<", "len", "(", "old_word", ")", "-", "2", ":", "# assuming a symbol sequence \"A B C B\", if \"B C\" is merged, reduce the frequency of \"C B\".", "# however, skip this if the sequence is A B C B C, because the frequency of \"C B\" will be reduced by the previous code block", "if", "old_word", "[", "i", "+", "2", "]", "!=", "first", "or", "i", ">=", "len", "(", "old_word", ")", "-", "3", "or", "old_word", "[", "i", "+", "3", "]", "!=", "second", ":", "nex", "=", "old_word", "[", "i", "+", "1", ":", "i", "+", "3", "]", "stats", "[", "nex", "]", "-=", "freq", "indices", "[", "nex", "]", "[", "j", "]", "-=", "1", "i", "+=", "2", "else", ":", "i", "+=", "1", "i", "=", "0", "while", "True", ":", "try", ":", "# find new pair", "i", "=", "word", ".", "index", "(", "new_pair", ",", "i", ")", "except", "ValueError", ":", "break", "# assuming a symbol sequence \"A BC D\", if \"B C\" is merged, increase the frequency of \"A BC\"", "if", "i", ":", "prev", "=", "word", "[", "i", "-", "1", ":", "i", "+", "1", "]", "stats", "[", "prev", "]", "+=", "freq", "indices", "[", "prev", "]", "[", "j", "]", "+=", "1", "# assuming a symbol sequence \"A BC B\", if \"B C\" is merged, increase the frequency of \"BC B\"", "# however, if the sequence is A BC BC, skip this step because the count of \"BC BC\" will be incremented by the previous code block", "if", "i", "<", "len", "(", "word", ")", "-", "1", "and", "word", "[", "i", "+", "1", "]", "!=", "new_pair", ":", "nex", "=", "word", "[", "i", ":", "i", "+", "2", "]", "stats", "[", "nex", "]", "+=", "freq", "indices", "[", "nex", "]", "[", "j", "]", "+=", "1", "i", "+=", "1" ]
[ 46, 0 ]
[ 102, 18 ]
python
en
['en', 'en', 'en']
True
get_pair_statistics
(vocab)
Count frequency of all symbol pairs, and create index
Count frequency of all symbol pairs, and create index
def get_pair_statistics(vocab): """Count frequency of all symbol pairs, and create index""" # data structure of pair frequencies stats = defaultdict(int) #index from pairs to words indices = defaultdict(lambda: defaultdict(int)) for i, (word, freq) in enumerate(vocab): prev_char = word[0] for char in word[1:]: stats[prev_char, char] += freq indices[prev_char, char][i] += 1 prev_char = char return stats, indices
[ "def", "get_pair_statistics", "(", "vocab", ")", ":", "# data structure of pair frequencies", "stats", "=", "defaultdict", "(", "int", ")", "#index from pairs to words", "indices", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "int", ")", ")", "for", "i", ",", "(", "word", ",", "freq", ")", "in", "enumerate", "(", "vocab", ")", ":", "prev_char", "=", "word", "[", "0", "]", "for", "char", "in", "word", "[", "1", ":", "]", ":", "stats", "[", "prev_char", ",", "char", "]", "+=", "freq", "indices", "[", "prev_char", ",", "char", "]", "[", "i", "]", "+=", "1", "prev_char", "=", "char", "return", "stats", ",", "indices" ]
[ 105, 0 ]
[ 121, 25 ]
python
en
['en', 'en', 'en']
True
replace_pair
(pair, vocab, indices)
Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB
Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB
def replace_pair(pair, vocab, indices): """Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB'""" first, second = pair pair_str = ''.join(pair) pair_str = pair_str.replace('\\','\\\\') changes = [] pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)') if sys.version_info < (3, 0): iterator = indices[pair].iteritems() else: iterator = indices[pair].items() for j, freq in iterator: if freq < 1: continue word, freq = vocab[j] new_word = ' '.join(word) new_word = pattern.sub(pair_str, new_word) new_word = tuple(new_word.split(' ')) vocab[j] = (new_word, freq) changes.append((j, new_word, word, freq)) return changes
[ "def", "replace_pair", "(", "pair", ",", "vocab", ",", "indices", ")", ":", "first", ",", "second", "=", "pair", "pair_str", "=", "''", ".", "join", "(", "pair", ")", "pair_str", "=", "pair_str", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "changes", "=", "[", "]", "pattern", "=", "re", ".", "compile", "(", "r'(?<!\\S)'", "+", "re", ".", "escape", "(", "first", "+", "' '", "+", "second", ")", "+", "r'(?!\\S)'", ")", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "iterator", "=", "indices", "[", "pair", "]", ".", "iteritems", "(", ")", "else", ":", "iterator", "=", "indices", "[", "pair", "]", ".", "items", "(", ")", "for", "j", ",", "freq", "in", "iterator", ":", "if", "freq", "<", "1", ":", "continue", "word", ",", "freq", "=", "vocab", "[", "j", "]", "new_word", "=", "' '", ".", "join", "(", "word", ")", "new_word", "=", "pattern", ".", "sub", "(", "pair_str", ",", "new_word", ")", "new_word", "=", "tuple", "(", "new_word", ".", "split", "(", "' '", ")", ")", "vocab", "[", "j", "]", "=", "(", "new_word", ",", "freq", ")", "changes", ".", "append", "(", "(", "j", ",", "new_word", ",", "word", ",", "freq", ")", ")", "return", "changes" ]
[ 124, 0 ]
[ 146, 18 ]
python
en
['en', 'en', 'en']
True
prune_stats
(stats, big_stats, threshold)
Prune statistics dict for efficiency of max() The frequency of a symbol pair never increases, so pruning is generally safe (until we the most frequent pair is less frequent than a pair we previously pruned) big_stats keeps full statistics for when we need to access pruned items
Prune statistics dict for efficiency of max()
def prune_stats(stats, big_stats, threshold): """Prune statistics dict for efficiency of max() The frequency of a symbol pair never increases, so pruning is generally safe (until we the most frequent pair is less frequent than a pair we previously pruned) big_stats keeps full statistics for when we need to access pruned items """ for item,freq in list(stats.items()): if freq < threshold: del stats[item] if freq < 0: big_stats[item] += freq else: big_stats[item] = freq
[ "def", "prune_stats", "(", "stats", ",", "big_stats", ",", "threshold", ")", ":", "for", "item", ",", "freq", "in", "list", "(", "stats", ".", "items", "(", ")", ")", ":", "if", "freq", "<", "threshold", ":", "del", "stats", "[", "item", "]", "if", "freq", "<", "0", ":", "big_stats", "[", "item", "]", "+=", "freq", "else", ":", "big_stats", "[", "item", "]", "=", "freq" ]
[ 148, 0 ]
[ 161, 38 ]
python
en
['en', 'en', 'en']
True
learn_bpe
(infile_names, outfile_name, num_symbols, min_frequency=2, verbose=False, is_dict=False, total_symbols=False)
Learn num_symbols BPE operations from vocabulary, and write to outfile.
Learn num_symbols BPE operations from vocabulary, and write to outfile.
def learn_bpe(infile_names, outfile_name, num_symbols, min_frequency=2, verbose=False, is_dict=False, total_symbols=False): """Learn num_symbols BPE operations from vocabulary, and write to outfile. """ sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer) sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer) #vocab = get_vocabulary(infile, is_dict) vocab = Counter() for f in infile_names: sys.stderr.write(f'Collecting vocab from {f}\n') vocab = update_vocabulary(vocab, f, is_dict) vocab = dict([(tuple(x[:-1])+(x[-1]+'</w>',) ,y) for (x,y) in vocab.items()]) sorted_vocab = sorted(vocab.items(), key=lambda x: x[1], reverse=True) stats, indices = get_pair_statistics(sorted_vocab) big_stats = copy.deepcopy(stats) if total_symbols: uniq_char_internal = set() uniq_char_final = set() for word in vocab: for char in word[:-1]: uniq_char_internal.add(char) uniq_char_final.add(word[-1]) sys.stderr.write('Number of word-internal characters: {0}\n'.format(len(uniq_char_internal))) sys.stderr.write('Number of word-final characters: {0}\n'.format(len(uniq_char_final))) sys.stderr.write('Reducing number of merge operations by {0}\n'.format(len(uniq_char_internal) + len(uniq_char_final))) num_symbols -= len(uniq_char_internal) + len(uniq_char_final) sys.stderr.write(f'Write vocab file to {outfile_name}') with codecs.open(outfile_name, 'w', encoding='utf-8') as outfile: # version 0.2 changes the handling of the end-of-word token ('</w>'); # version numbering allows bckward compatibility outfile.write('#version: 0.2\n') # threshold is inspired by Zipfian assumption, but should only affect speed threshold = max(stats.values()) / 10 for i in range(num_symbols): if stats: most_frequent = max(stats, key=lambda x: (stats[x], x)) # we probably missed the best pair because of pruning; go back to full statistics if not stats or (i and stats[most_frequent] < threshold): prune_stats(stats, big_stats, threshold) stats = copy.deepcopy(big_stats) most_frequent = max(stats, key=lambda x: (stats[x], x)) # threshold is inspired by Zipfian assumption, but should only affect speed threshold = stats[most_frequent] * i/(i+10000.0) prune_stats(stats, big_stats, threshold) if stats[most_frequent] < min_frequency: sys.stderr.write(f'no pair has frequency >= {min_frequency}. Stopping\n') break if verbose: sys.stderr.write('pair {0}: {1} {2} -> {1}{2} (frequency {3})\n'.format( i, most_frequent[0], most_frequent[1], stats[most_frequent])) outfile.write('{0} {1}\n'.format(*most_frequent)) changes = replace_pair(most_frequent, sorted_vocab, indices) update_pair_statistics(most_frequent, changes, stats, indices) stats[most_frequent] = 0 if not i % 100: prune_stats(stats, big_stats, threshold)
[ "def", "learn_bpe", "(", "infile_names", ",", "outfile_name", ",", "num_symbols", ",", "min_frequency", "=", "2", ",", "verbose", "=", "False", ",", "is_dict", "=", "False", ",", "total_symbols", "=", "False", ")", ":", "sys", ".", "stderr", "=", "codecs", ".", "getwriter", "(", "'UTF-8'", ")", "(", "sys", ".", "stderr", ".", "buffer", ")", "sys", ".", "stdout", "=", "codecs", ".", "getwriter", "(", "'UTF-8'", ")", "(", "sys", ".", "stdout", ".", "buffer", ")", "sys", ".", "stdin", "=", "codecs", ".", "getreader", "(", "'UTF-8'", ")", "(", "sys", ".", "stdin", ".", "buffer", ")", "#vocab = get_vocabulary(infile, is_dict)", "vocab", "=", "Counter", "(", ")", "for", "f", "in", "infile_names", ":", "sys", ".", "stderr", ".", "write", "(", "f'Collecting vocab from {f}\\n'", ")", "vocab", "=", "update_vocabulary", "(", "vocab", ",", "f", ",", "is_dict", ")", "vocab", "=", "dict", "(", "[", "(", "tuple", "(", "x", "[", ":", "-", "1", "]", ")", "+", "(", "x", "[", "-", "1", "]", "+", "'</w>'", ",", ")", ",", "y", ")", "for", "(", "x", ",", "y", ")", "in", "vocab", ".", "items", "(", ")", "]", ")", "sorted_vocab", "=", "sorted", "(", "vocab", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "stats", ",", "indices", "=", "get_pair_statistics", "(", "sorted_vocab", ")", "big_stats", "=", "copy", ".", "deepcopy", "(", "stats", ")", "if", "total_symbols", ":", "uniq_char_internal", "=", "set", "(", ")", "uniq_char_final", "=", "set", "(", ")", "for", "word", "in", "vocab", ":", "for", "char", "in", "word", "[", ":", "-", "1", "]", ":", "uniq_char_internal", ".", "add", "(", "char", ")", "uniq_char_final", ".", "add", "(", "word", "[", "-", "1", "]", ")", "sys", ".", "stderr", ".", "write", "(", "'Number of word-internal characters: {0}\\n'", ".", "format", "(", "len", "(", "uniq_char_internal", ")", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Number of word-final characters: {0}\\n'", ".", "format", "(", "len", "(", "uniq_char_final", ")", ")", ")", "sys", ".", "stderr", ".", "write", "(", "'Reducing number of merge operations by {0}\\n'", ".", "format", "(", "len", "(", "uniq_char_internal", ")", "+", "len", "(", "uniq_char_final", ")", ")", ")", "num_symbols", "-=", "len", "(", "uniq_char_internal", ")", "+", "len", "(", "uniq_char_final", ")", "sys", ".", "stderr", ".", "write", "(", "f'Write vocab file to {outfile_name}'", ")", "with", "codecs", ".", "open", "(", "outfile_name", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "outfile", ":", "# version 0.2 changes the handling of the end-of-word token ('</w>');", "# version numbering allows bckward compatibility", "outfile", ".", "write", "(", "'#version: 0.2\\n'", ")", "# threshold is inspired by Zipfian assumption, but should only affect speed", "threshold", "=", "max", "(", "stats", ".", "values", "(", ")", ")", "/", "10", "for", "i", "in", "range", "(", "num_symbols", ")", ":", "if", "stats", ":", "most_frequent", "=", "max", "(", "stats", ",", "key", "=", "lambda", "x", ":", "(", "stats", "[", "x", "]", ",", "x", ")", ")", "# we probably missed the best pair because of pruning; go back to full statistics", "if", "not", "stats", "or", "(", "i", "and", "stats", "[", "most_frequent", "]", "<", "threshold", ")", ":", "prune_stats", "(", "stats", ",", "big_stats", ",", "threshold", ")", "stats", "=", "copy", ".", "deepcopy", "(", "big_stats", ")", "most_frequent", "=", "max", "(", "stats", ",", "key", "=", "lambda", "x", ":", "(", "stats", "[", "x", "]", ",", "x", ")", ")", "# threshold is inspired by Zipfian assumption, but should only affect speed", "threshold", "=", "stats", "[", "most_frequent", "]", "*", "i", "/", "(", "i", "+", "10000.0", ")", "prune_stats", "(", "stats", ",", "big_stats", ",", "threshold", ")", "if", "stats", "[", "most_frequent", "]", "<", "min_frequency", ":", "sys", ".", "stderr", ".", "write", "(", "f'no pair has frequency >= {min_frequency}. Stopping\\n'", ")", "break", "if", "verbose", ":", "sys", ".", "stderr", ".", "write", "(", "'pair {0}: {1} {2} -> {1}{2} (frequency {3})\\n'", ".", "format", "(", "i", ",", "most_frequent", "[", "0", "]", ",", "most_frequent", "[", "1", "]", ",", "stats", "[", "most_frequent", "]", ")", ")", "outfile", ".", "write", "(", "'{0} {1}\\n'", ".", "format", "(", "*", "most_frequent", ")", ")", "changes", "=", "replace_pair", "(", "most_frequent", ",", "sorted_vocab", ",", "indices", ")", "update_pair_statistics", "(", "most_frequent", ",", "changes", ",", "stats", ",", "indices", ")", "stats", "[", "most_frequent", "]", "=", "0", "if", "not", "i", "%", "100", ":", "prune_stats", "(", "stats", ",", "big_stats", ",", "threshold", ")" ]
[ 164, 0 ]
[ 229, 56 ]
python
en
['en', 'en', 'en']
True
test_load_from_storage
(hass, hass_storage)
Test that entity map can be correctly loaded from cache.
Test that entity map can be correctly loaded from cache.
async def test_load_from_storage(hass, hass_storage): """Test that entity map can be correctly loaded from cache.""" hkid = "00:00:00:00:00:00" hass_storage["homekit_controller-entity-map"] = { "version": 1, "data": {"pairings": {hkid: {"c#": 1, "accessories": []}}}, } await setup_platform(hass) assert hkid in hass.data[ENTITY_MAP].storage_data
[ "async", "def", "test_load_from_storage", "(", "hass", ",", "hass_storage", ")", ":", "hkid", "=", "\"00:00:00:00:00:00\"", "hass_storage", "[", "\"homekit_controller-entity-map\"", "]", "=", "{", "\"version\"", ":", "1", ",", "\"data\"", ":", "{", "\"pairings\"", ":", "{", "hkid", ":", "{", "\"c#\"", ":", "1", ",", "\"accessories\"", ":", "[", "]", "}", "}", "}", ",", "}", "await", "setup_platform", "(", "hass", ")", "assert", "hkid", "in", "hass", ".", "data", "[", "ENTITY_MAP", "]", ".", "storage_data" ]
[ 15, 0 ]
[ 25, 53 ]
python
en
['en', 'en', 'en']
True
test_storage_is_removed
(hass, hass_storage)
Test entity map storage removal is idempotent.
Test entity map storage removal is idempotent.
async def test_storage_is_removed(hass, hass_storage): """Test entity map storage removal is idempotent.""" await setup_platform(hass) entity_map = hass.data[ENTITY_MAP] hkid = "00:00:00:00:00:01" entity_map.async_create_or_update_map(hkid, 1, []) assert hkid in entity_map.storage_data await flush_store(entity_map.store) assert hkid in hass_storage[ENTITY_MAP]["data"]["pairings"] entity_map.async_delete_map(hkid) assert hkid not in hass.data[ENTITY_MAP].storage_data await flush_store(entity_map.store) assert hass_storage[ENTITY_MAP]["data"]["pairings"] == {}
[ "async", "def", "test_storage_is_removed", "(", "hass", ",", "hass_storage", ")", ":", "await", "setup_platform", "(", "hass", ")", "entity_map", "=", "hass", ".", "data", "[", "ENTITY_MAP", "]", "hkid", "=", "\"00:00:00:00:00:01\"", "entity_map", ".", "async_create_or_update_map", "(", "hkid", ",", "1", ",", "[", "]", ")", "assert", "hkid", "in", "entity_map", ".", "storage_data", "await", "flush_store", "(", "entity_map", ".", "store", ")", "assert", "hkid", "in", "hass_storage", "[", "ENTITY_MAP", "]", "[", "\"data\"", "]", "[", "\"pairings\"", "]", "entity_map", ".", "async_delete_map", "(", "hkid", ")", "assert", "hkid", "not", "in", "hass", ".", "data", "[", "ENTITY_MAP", "]", ".", "storage_data", "await", "flush_store", "(", "entity_map", ".", "store", ")", "assert", "hass_storage", "[", "ENTITY_MAP", "]", "[", "\"data\"", "]", "[", "\"pairings\"", "]", "==", "{", "}" ]
[ 28, 0 ]
[ 44, 61 ]
python
en
['en', 'en', 'en']
True
test_storage_is_removed_idempotent
(hass)
Test entity map storage removal is idempotent.
Test entity map storage removal is idempotent.
async def test_storage_is_removed_idempotent(hass): """Test entity map storage removal is idempotent.""" await setup_platform(hass) entity_map = hass.data[ENTITY_MAP] hkid = "00:00:00:00:00:01" assert hkid not in entity_map.storage_data entity_map.async_delete_map(hkid) assert hkid not in entity_map.storage_data
[ "async", "def", "test_storage_is_removed_idempotent", "(", "hass", ")", ":", "await", "setup_platform", "(", "hass", ")", "entity_map", "=", "hass", ".", "data", "[", "ENTITY_MAP", "]", "hkid", "=", "\"00:00:00:00:00:01\"", "assert", "hkid", "not", "in", "entity_map", ".", "storage_data", "entity_map", ".", "async_delete_map", "(", "hkid", ")", "assert", "hkid", "not", "in", "entity_map", ".", "storage_data" ]
[ 47, 0 ]
[ 58, 46 ]
python
en
['en', 'en', 'en']
True
create_lightbulb_service
(accessory)
Define lightbulb characteristics.
Define lightbulb characteristics.
def create_lightbulb_service(accessory): """Define lightbulb characteristics.""" service = accessory.add_service(ServicesTypes.LIGHTBULB) on_char = service.add_char(CharacteristicsTypes.ON) on_char.value = 0
[ "def", "create_lightbulb_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "LIGHTBULB", ")", "on_char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "ON", ")", "on_char", ".", "value", "=", "0" ]
[ 61, 0 ]
[ 65, 21 ]
python
en
['en', 'bg', 'en']
True
test_storage_is_updated_on_add
(hass, hass_storage, utcnow)
Test entity map storage is cleaned up on adding an accessory.
Test entity map storage is cleaned up on adding an accessory.
async def test_storage_is_updated_on_add(hass, hass_storage, utcnow): """Test entity map storage is cleaned up on adding an accessory.""" await setup_test_component(hass, create_lightbulb_service) entity_map = hass.data[ENTITY_MAP] hkid = "00:00:00:00:00:00" # Is in memory store updated? assert hkid in entity_map.storage_data # Is saved out to store? await flush_store(entity_map.store) assert hkid in hass_storage[ENTITY_MAP]["data"]["pairings"]
[ "async", "def", "test_storage_is_updated_on_add", "(", "hass", ",", "hass_storage", ",", "utcnow", ")", ":", "await", "setup_test_component", "(", "hass", ",", "create_lightbulb_service", ")", "entity_map", "=", "hass", ".", "data", "[", "ENTITY_MAP", "]", "hkid", "=", "\"00:00:00:00:00:00\"", "# Is in memory store updated?", "assert", "hkid", "in", "entity_map", ".", "storage_data", "# Is saved out to store?", "await", "flush_store", "(", "entity_map", ".", "store", ")", "assert", "hkid", "in", "hass_storage", "[", "ENTITY_MAP", "]", "[", "\"data\"", "]", "[", "\"pairings\"", "]" ]
[ 68, 0 ]
[ 80, 63 ]
python
en
['en', 'en', 'en']
True
test_storage_is_removed_on_config_entry_removal
(hass, utcnow)
Test entity map storage is cleaned up on config entry removal.
Test entity map storage is cleaned up on config entry removal.
async def test_storage_is_removed_on_config_entry_removal(hass, utcnow): """Test entity map storage is cleaned up on config entry removal.""" await setup_test_component(hass, create_lightbulb_service) hkid = "00:00:00:00:00:00" pairing_data = {"AccessoryPairingID": hkid} entry = config_entries.ConfigEntry( 1, "homekit_controller", "TestData", pairing_data, "test", config_entries.CONN_CLASS_LOCAL_PUSH, system_options={}, ) assert hkid in hass.data[ENTITY_MAP].storage_data await async_remove_entry(hass, entry) assert hkid not in hass.data[ENTITY_MAP].storage_data
[ "async", "def", "test_storage_is_removed_on_config_entry_removal", "(", "hass", ",", "utcnow", ")", ":", "await", "setup_test_component", "(", "hass", ",", "create_lightbulb_service", ")", "hkid", "=", "\"00:00:00:00:00:00\"", "pairing_data", "=", "{", "\"AccessoryPairingID\"", ":", "hkid", "}", "entry", "=", "config_entries", ".", "ConfigEntry", "(", "1", ",", "\"homekit_controller\"", ",", "\"TestData\"", ",", "pairing_data", ",", "\"test\"", ",", "config_entries", ".", "CONN_CLASS_LOCAL_PUSH", ",", "system_options", "=", "{", "}", ",", ")", "assert", "hkid", "in", "hass", ".", "data", "[", "ENTITY_MAP", "]", ".", "storage_data", "await", "async_remove_entry", "(", "hass", ",", "entry", ")", "assert", "hkid", "not", "in", "hass", ".", "data", "[", "ENTITY_MAP", "]", ".", "storage_data" ]
[ 83, 0 ]
[ 105, 57 ]
python
en
['en', 'en', 'en']
True
test_form_source_user
(hass)
Test we get config flow setup form as a user.
Test we get config flow setup form as a user.
async def test_form_source_user(hass): """Test we get config flow setup form as a user.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} mock_powerwall = await _mock_powerwall_site_name(hass, "My site") with patch( "homeassistant.components.powerwall.config_flow.Powerwall", return_value=mock_powerwall, ), patch( "homeassistant.components.powerwall.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.powerwall.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_IP_ADDRESS: "1.2.3.4"}, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "My site" assert result2["data"] == {CONF_IP_ADDRESS: "1.2.3.4"} assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_form_source_user", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "}", "mock_powerwall", "=", "await", "_mock_powerwall_site_name", "(", "hass", ",", "\"My site\"", ")", "with", "patch", "(", "\"homeassistant.components.powerwall.config_flow.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ",", ")", ",", "patch", "(", "\"homeassistant.components.powerwall.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.powerwall.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result2", "[", "\"title\"", "]", "==", "\"My site\"", "assert", "result2", "[", "\"data\"", "]", "==", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 13, 0 ]
[ 43, 48 ]
python
en
['en', 'da', 'en']
True
test_form_source_import
(hass)
Test we setup the config entry via import.
Test we setup the config entry via import.
async def test_form_source_import(hass): """Test we setup the config entry via import.""" await setup.async_setup_component(hass, "persistent_notification", {}) mock_powerwall = await _mock_powerwall_site_name(hass, "Imported site") with patch( "homeassistant.components.powerwall.config_flow.Powerwall", return_value=mock_powerwall, ), patch( "homeassistant.components.powerwall.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.powerwall.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={CONF_IP_ADDRESS: "1.2.3.4"}, ) await hass.async_block_till_done() assert result["type"] == "create_entry" assert result["title"] == "Imported site" assert result["data"] == {CONF_IP_ADDRESS: "1.2.3.4"} assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_form_source_import", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "mock_powerwall", "=", "await", "_mock_powerwall_site_name", "(", "hass", ",", "\"Imported site\"", ")", "with", "patch", "(", "\"homeassistant.components.powerwall.config_flow.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ",", ")", ",", "patch", "(", "\"homeassistant.components.powerwall.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.powerwall.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ",", "data", "=", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result", "[", "\"title\"", "]", "==", "\"Imported site\"", "assert", "result", "[", "\"data\"", "]", "==", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 46, 0 ]
[ 71, 48 ]
python
en
['en', 'pt', 'en']
True
test_form_cannot_connect
(hass)
Test we handle cannot connect error.
Test we handle cannot connect error.
async def test_form_cannot_connect(hass): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) mock_powerwall = _mock_powerwall_side_effect(site_info=PowerwallUnreachableError) with patch( "homeassistant.components.powerwall.config_flow.Powerwall", return_value=mock_powerwall, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_IP_ADDRESS: "1.2.3.4"}, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_form_cannot_connect", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "mock_powerwall", "=", "_mock_powerwall_side_effect", "(", "site_info", "=", "PowerwallUnreachableError", ")", "with", "patch", "(", "\"homeassistant.components.powerwall.config_flow.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 74, 0 ]
[ 92, 58 ]
python
en
['en', 'en', 'en']
True
test_form_wrong_version
(hass)
Test we can handle wrong version error.
Test we can handle wrong version error.
async def test_form_wrong_version(hass): """Test we can handle wrong version error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) mock_powerwall = _mock_powerwall_side_effect( site_info=MissingAttributeError({}, "") ) with patch( "homeassistant.components.powerwall.config_flow.Powerwall", return_value=mock_powerwall, ): result3 = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_IP_ADDRESS: "1.2.3.4"}, ) assert result3["type"] == "form" assert result3["errors"] == {"base": "wrong_version"}
[ "async", "def", "test_form_wrong_version", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "mock_powerwall", "=", "_mock_powerwall_side_effect", "(", "site_info", "=", "MissingAttributeError", "(", "{", "}", ",", "\"\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.powerwall.config_flow.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ",", ")", ":", "result3", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "CONF_IP_ADDRESS", ":", "\"1.2.3.4\"", "}", ",", ")", "assert", "result3", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result3", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"wrong_version\"", "}" ]
[ 95, 0 ]
[ 115, 57 ]
python
en
['nl', 'en', 'en']
True
test_battery_icon
()
Test icon generator for battery sensor.
Test icon generator for battery sensor.
def test_battery_icon(): """Test icon generator for battery sensor.""" from homeassistant.helpers.icon import icon_for_battery_level assert icon_for_battery_level(None, True) == "mdi:battery-unknown" assert icon_for_battery_level(None, False) == "mdi:battery-unknown" assert icon_for_battery_level(5, True) == "mdi:battery-outline" assert icon_for_battery_level(5, False) == "mdi:battery-alert" assert icon_for_battery_level(100, True) == "mdi:battery-charging-100" assert icon_for_battery_level(100, False) == "mdi:battery" iconbase = "mdi:battery" for level in range(0, 100, 5): print( "Level: %d. icon: %s, charging: %s" % ( level, icon_for_battery_level(level, False), icon_for_battery_level(level, True), ) ) if level <= 10: postfix_charging = "-outline" elif level <= 30: postfix_charging = "-charging-20" elif level <= 50: postfix_charging = "-charging-40" elif level <= 70: postfix_charging = "-charging-60" elif level <= 90: postfix_charging = "-charging-80" else: postfix_charging = "-charging-100" if 5 < level < 95: postfix = "-{}".format(int(round(level / 10 - 0.01)) * 10) elif level <= 5: postfix = "-alert" else: postfix = "" assert iconbase + postfix == icon_for_battery_level(level, False) assert iconbase + postfix_charging == icon_for_battery_level(level, True)
[ "def", "test_battery_icon", "(", ")", ":", "from", "homeassistant", ".", "helpers", ".", "icon", "import", "icon_for_battery_level", "assert", "icon_for_battery_level", "(", "None", ",", "True", ")", "==", "\"mdi:battery-unknown\"", "assert", "icon_for_battery_level", "(", "None", ",", "False", ")", "==", "\"mdi:battery-unknown\"", "assert", "icon_for_battery_level", "(", "5", ",", "True", ")", "==", "\"mdi:battery-outline\"", "assert", "icon_for_battery_level", "(", "5", ",", "False", ")", "==", "\"mdi:battery-alert\"", "assert", "icon_for_battery_level", "(", "100", ",", "True", ")", "==", "\"mdi:battery-charging-100\"", "assert", "icon_for_battery_level", "(", "100", ",", "False", ")", "==", "\"mdi:battery\"", "iconbase", "=", "\"mdi:battery\"", "for", "level", "in", "range", "(", "0", ",", "100", ",", "5", ")", ":", "print", "(", "\"Level: %d. icon: %s, charging: %s\"", "%", "(", "level", ",", "icon_for_battery_level", "(", "level", ",", "False", ")", ",", "icon_for_battery_level", "(", "level", ",", "True", ")", ",", ")", ")", "if", "level", "<=", "10", ":", "postfix_charging", "=", "\"-outline\"", "elif", "level", "<=", "30", ":", "postfix_charging", "=", "\"-charging-20\"", "elif", "level", "<=", "50", ":", "postfix_charging", "=", "\"-charging-40\"", "elif", "level", "<=", "70", ":", "postfix_charging", "=", "\"-charging-60\"", "elif", "level", "<=", "90", ":", "postfix_charging", "=", "\"-charging-80\"", "else", ":", "postfix_charging", "=", "\"-charging-100\"", "if", "5", "<", "level", "<", "95", ":", "postfix", "=", "\"-{}\"", ".", "format", "(", "int", "(", "round", "(", "level", "/", "10", "-", "0.01", ")", ")", "*", "10", ")", "elif", "level", "<=", "5", ":", "postfix", "=", "\"-alert\"", "else", ":", "postfix", "=", "\"\"", "assert", "iconbase", "+", "postfix", "==", "icon_for_battery_level", "(", "level", ",", "False", ")", "assert", "iconbase", "+", "postfix_charging", "==", "icon_for_battery_level", "(", "level", ",", "True", ")" ]
[ 3, 0 ]
[ 45, 81 ]
python
en
['en', 'no', 'en']
True
test_signal_icon
()
Test icon generator for signal sensor.
Test icon generator for signal sensor.
def test_signal_icon(): """Test icon generator for signal sensor.""" from homeassistant.helpers.icon import icon_for_signal_level assert icon_for_signal_level(None) == "mdi:signal-cellular-outline" assert icon_for_signal_level(0) == "mdi:signal-cellular-outline" assert icon_for_signal_level(5) == "mdi:signal-cellular-1" assert icon_for_signal_level(40) == "mdi:signal-cellular-2" assert icon_for_signal_level(80) == "mdi:signal-cellular-3" assert icon_for_signal_level(100) == "mdi:signal-cellular-3"
[ "def", "test_signal_icon", "(", ")", ":", "from", "homeassistant", ".", "helpers", ".", "icon", "import", "icon_for_signal_level", "assert", "icon_for_signal_level", "(", "None", ")", "==", "\"mdi:signal-cellular-outline\"", "assert", "icon_for_signal_level", "(", "0", ")", "==", "\"mdi:signal-cellular-outline\"", "assert", "icon_for_signal_level", "(", "5", ")", "==", "\"mdi:signal-cellular-1\"", "assert", "icon_for_signal_level", "(", "40", ")", "==", "\"mdi:signal-cellular-2\"", "assert", "icon_for_signal_level", "(", "80", ")", "==", "\"mdi:signal-cellular-3\"", "assert", "icon_for_signal_level", "(", "100", ")", "==", "\"mdi:signal-cellular-3\"" ]
[ 48, 0 ]
[ 57, 64 ]
python
en
['en', 'ja', 'en']
True
test_platform_manually_configured
(hass)
Test that we do not discover anything or try to set up a gateway.
Test that we do not discover anything or try to set up a gateway.
async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a gateway.""" assert ( await async_setup_component( hass, SWITCH_DOMAIN, {"switch": {"platform": DECONZ_DOMAIN}} ) is True ) assert DECONZ_DOMAIN not in hass.data
[ "async", "def", "test_platform_manually_configured", "(", "hass", ")", ":", "assert", "(", "await", "async_setup_component", "(", "hass", ",", "SWITCH_DOMAIN", ",", "{", "\"switch\"", ":", "{", "\"platform\"", ":", "DECONZ_DOMAIN", "}", "}", ")", "is", "True", ")", "assert", "DECONZ_DOMAIN", "not", "in", "hass", ".", "data" ]
[ 67, 0 ]
[ 75, 41 ]
python
en
['en', 'en', 'en']
True
test_no_switches
(hass)
Test that no switch entities are created.
Test that no switch entities are created.
async def test_no_switches(hass): """Test that no switch entities are created.""" await setup_deconz_integration(hass) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_no_switches", "(", "hass", ")", ":", "await", "setup_deconz_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 78, 0 ]
[ 81, 44 ]
python
en
['en', 'en', 'en']
True
test_power_plugs
(hass)
Test that all supported switch entities are created.
Test that all supported switch entities are created.
async def test_power_plugs(hass): """Test that all supported switch entities are created.""" data = deepcopy(DECONZ_WEB_REQUEST) data["lights"] = deepcopy(POWER_PLUGS) config_entry = await setup_deconz_integration(hass, get_state_response=data) gateway = get_gateway_from_config_entry(hass, config_entry) assert len(hass.states.async_all()) == 4 assert hass.states.get("switch.on_off_switch").state == STATE_ON assert hass.states.get("switch.smart_plug").state == STATE_OFF assert hass.states.get("switch.on_off_relay").state == STATE_ON assert hass.states.get("switch.unsupported_switch") is None state_changed_event = { "t": "event", "e": "changed", "r": "lights", "id": "1", "state": {"on": False}, } gateway.api.event_handler(state_changed_event) assert hass.states.get("switch.on_off_switch").state == STATE_OFF # Verify service calls on_off_switch_device = gateway.api.lights["1"] # Service turn on power plug with patch.object( on_off_switch_device, "_request", return_value=True ) as set_callback: await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.on_off_switch"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with("put", "/lights/1/state", json={"on": True}) # Service turn off power plug with patch.object( on_off_switch_device, "_request", return_value=True ) as set_callback: await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.on_off_switch"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with("put", "/lights/1/state", json={"on": False}) await hass.config_entries.async_unload(config_entry.entry_id) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_power_plugs", "(", "hass", ")", ":", "data", "=", "deepcopy", "(", "DECONZ_WEB_REQUEST", ")", "data", "[", "\"lights\"", "]", "=", "deepcopy", "(", "POWER_PLUGS", ")", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ",", "get_state_response", "=", "data", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "4", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.on_off_switch\"", ")", ".", "state", "==", "STATE_ON", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.smart_plug\"", ")", ".", "state", "==", "STATE_OFF", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.on_off_relay\"", ")", ".", "state", "==", "STATE_ON", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.unsupported_switch\"", ")", "is", "None", "state_changed_event", "=", "{", "\"t\"", ":", "\"event\"", ",", "\"e\"", ":", "\"changed\"", ",", "\"r\"", ":", "\"lights\"", ",", "\"id\"", ":", "\"1\"", ",", "\"state\"", ":", "{", "\"on\"", ":", "False", "}", ",", "}", "gateway", ".", "api", ".", "event_handler", "(", "state_changed_event", ")", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.on_off_switch\"", ")", ".", "state", "==", "STATE_OFF", "# Verify service calls", "on_off_switch_device", "=", "gateway", ".", "api", ".", "lights", "[", "\"1\"", "]", "# Service turn on power plug", "with", "patch", ".", "object", "(", "on_off_switch_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "SWITCH_DOMAIN", ",", "SERVICE_TURN_ON", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.on_off_switch\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"on\"", ":", "True", "}", ")", "# Service turn off power plug", "with", "patch", ".", "object", "(", "on_off_switch_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "SWITCH_DOMAIN", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.on_off_switch\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"on\"", ":", "False", "}", ")", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "config_entry", ".", "entry_id", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 84, 0 ]
[ 142, 44 ]
python
en
['en', 'en', 'en']
True
test_sirens
(hass)
Test that siren entities are created.
Test that siren entities are created.
async def test_sirens(hass): """Test that siren entities are created.""" data = deepcopy(DECONZ_WEB_REQUEST) data["lights"] = deepcopy(SIRENS) config_entry = await setup_deconz_integration(hass, get_state_response=data) gateway = get_gateway_from_config_entry(hass, config_entry) assert len(hass.states.async_all()) == 2 assert hass.states.get("switch.warning_device").state == STATE_ON assert hass.states.get("switch.unsupported_switch") is None state_changed_event = { "t": "event", "e": "changed", "r": "lights", "id": "1", "state": {"alert": None}, } gateway.api.event_handler(state_changed_event) assert hass.states.get("switch.warning_device").state == STATE_OFF # Verify service calls warning_device_device = gateway.api.lights["1"] # Service turn on siren with patch.object( warning_device_device, "_request", return_value=True ) as set_callback: await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.warning_device"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with( "put", "/lights/1/state", json={"alert": "lselect"} ) # Service turn off siren with patch.object( warning_device_device, "_request", return_value=True ) as set_callback: await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.warning_device"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with( "put", "/lights/1/state", json={"alert": "none"} ) await hass.config_entries.async_unload(config_entry.entry_id) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_sirens", "(", "hass", ")", ":", "data", "=", "deepcopy", "(", "DECONZ_WEB_REQUEST", ")", "data", "[", "\"lights\"", "]", "=", "deepcopy", "(", "SIRENS", ")", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ",", "get_state_response", "=", "data", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.warning_device\"", ")", ".", "state", "==", "STATE_ON", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.unsupported_switch\"", ")", "is", "None", "state_changed_event", "=", "{", "\"t\"", ":", "\"event\"", ",", "\"e\"", ":", "\"changed\"", ",", "\"r\"", ":", "\"lights\"", ",", "\"id\"", ":", "\"1\"", ",", "\"state\"", ":", "{", "\"alert\"", ":", "None", "}", ",", "}", "gateway", ".", "api", ".", "event_handler", "(", "state_changed_event", ")", "assert", "hass", ".", "states", ".", "get", "(", "\"switch.warning_device\"", ")", ".", "state", "==", "STATE_OFF", "# Verify service calls", "warning_device_device", "=", "gateway", ".", "api", ".", "lights", "[", "\"1\"", "]", "# Service turn on siren", "with", "patch", ".", "object", "(", "warning_device_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "SWITCH_DOMAIN", ",", "SERVICE_TURN_ON", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.warning_device\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"alert\"", ":", "\"lselect\"", "}", ")", "# Service turn off siren", "with", "patch", ".", "object", "(", "warning_device_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "SWITCH_DOMAIN", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.warning_device\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"alert\"", ":", "\"none\"", "}", ")", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "config_entry", ".", "entry_id", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 145, 0 ]
[ 205, 44 ]
python
en
['en', 'en', 'en']
True
test_set_username
(hass)
Test we clear config if we set different username.
Test we clear config if we set different username.
async def test_set_username(hass): """Test we clear config if we set different username.""" prefs = CloudPreferences(hass) await prefs.async_initialize() assert prefs.google_enabled await prefs.async_update(google_enabled=False) assert not prefs.google_enabled await prefs.async_set_username("new-username") assert prefs.google_enabled
[ "async", "def", "test_set_username", "(", "hass", ")", ":", "prefs", "=", "CloudPreferences", "(", "hass", ")", "await", "prefs", ".", "async_initialize", "(", ")", "assert", "prefs", ".", "google_enabled", "await", "prefs", ".", "async_update", "(", "google_enabled", "=", "False", ")", "assert", "not", "prefs", ".", "google_enabled", "await", "prefs", ".", "async_set_username", "(", "\"new-username\"", ")", "assert", "prefs", ".", "google_enabled" ]
[ 7, 0 ]
[ 20, 31 ]
python
en
['nl', 'en', 'en']
True
test_set_username_migration
(hass)
Test we not clear config if we had no username.
Test we not clear config if we had no username.
async def test_set_username_migration(hass): """Test we not clear config if we had no username.""" prefs = CloudPreferences(hass) with patch.object(prefs, "_empty_config", return_value=prefs._empty_config(None)): await prefs.async_initialize() assert prefs.google_enabled await prefs.async_update(google_enabled=False) assert not prefs.google_enabled await prefs.async_set_username("new-username") assert not prefs.google_enabled
[ "async", "def", "test_set_username_migration", "(", "hass", ")", ":", "prefs", "=", "CloudPreferences", "(", "hass", ")", "with", "patch", ".", "object", "(", "prefs", ",", "\"_empty_config\"", ",", "return_value", "=", "prefs", ".", "_empty_config", "(", "None", ")", ")", ":", "await", "prefs", ".", "async_initialize", "(", ")", "assert", "prefs", ".", "google_enabled", "await", "prefs", ".", "async_update", "(", "google_enabled", "=", "False", ")", "assert", "not", "prefs", ".", "google_enabled", "await", "prefs", ".", "async_set_username", "(", "\"new-username\"", ")", "assert", "not", "prefs", ".", "google_enabled" ]
[ 23, 0 ]
[ 38, 35 ]
python
en
['en', 'en', 'en']
True
test_load_invalid_cloud_user
(hass, hass_storage)
Test loading cloud user with invalid storage.
Test loading cloud user with invalid storage.
async def test_load_invalid_cloud_user(hass, hass_storage): """Test loading cloud user with invalid storage.""" hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": "non-existing"}} prefs = CloudPreferences(hass) await prefs.async_initialize() cloud_user_id = await prefs.get_cloud_user() assert cloud_user_id != "non-existing" cloud_user = await hass.auth.async_get_user( hass_storage[STORAGE_KEY]["data"]["cloud_user"] ) assert cloud_user assert cloud_user.groups[0].id == GROUP_ID_ADMIN
[ "async", "def", "test_load_invalid_cloud_user", "(", "hass", ",", "hass_storage", ")", ":", "hass_storage", "[", "STORAGE_KEY", "]", "=", "{", "\"version\"", ":", "1", ",", "\"data\"", ":", "{", "\"cloud_user\"", ":", "\"non-existing\"", "}", "}", "prefs", "=", "CloudPreferences", "(", "hass", ")", "await", "prefs", ".", "async_initialize", "(", ")", "cloud_user_id", "=", "await", "prefs", ".", "get_cloud_user", "(", ")", "assert", "cloud_user_id", "!=", "\"non-existing\"", "cloud_user", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "hass_storage", "[", "STORAGE_KEY", "]", "[", "\"data\"", "]", "[", "\"cloud_user\"", "]", ")", "assert", "cloud_user", "assert", "cloud_user", ".", "groups", "[", "0", "]", ".", "id", "==", "GROUP_ID_ADMIN" ]
[ 41, 0 ]
[ 57, 52 ]
python
en
['en', 'en', 'en']
True
test_setup_remove_cloud_user
(hass, hass_storage)
Test creating and removing cloud user.
Test creating and removing cloud user.
async def test_setup_remove_cloud_user(hass, hass_storage): """Test creating and removing cloud user.""" hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": None}} prefs = CloudPreferences(hass) await prefs.async_initialize() await prefs.async_set_username("user1") cloud_user = await hass.auth.async_get_user(await prefs.get_cloud_user()) assert cloud_user assert cloud_user.groups[0].id == GROUP_ID_ADMIN await prefs.async_set_username("user2") cloud_user2 = await hass.auth.async_get_user(await prefs.get_cloud_user()) assert cloud_user2 assert cloud_user2.groups[0].id == GROUP_ID_ADMIN assert cloud_user2.id != cloud_user.id
[ "async", "def", "test_setup_remove_cloud_user", "(", "hass", ",", "hass_storage", ")", ":", "hass_storage", "[", "STORAGE_KEY", "]", "=", "{", "\"version\"", ":", "1", ",", "\"data\"", ":", "{", "\"cloud_user\"", ":", "None", "}", "}", "prefs", "=", "CloudPreferences", "(", "hass", ")", "await", "prefs", ".", "async_initialize", "(", ")", "await", "prefs", ".", "async_set_username", "(", "\"user1\"", ")", "cloud_user", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "await", "prefs", ".", "get_cloud_user", "(", ")", ")", "assert", "cloud_user", "assert", "cloud_user", ".", "groups", "[", "0", "]", ".", "id", "==", "GROUP_ID_ADMIN", "await", "prefs", ".", "async_set_username", "(", "\"user2\"", ")", "cloud_user2", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "await", "prefs", ".", "get_cloud_user", "(", ")", ")", "assert", "cloud_user2", "assert", "cloud_user2", ".", "groups", "[", "0", "]", ".", "id", "==", "GROUP_ID_ADMIN", "assert", "cloud_user2", ".", "id", "!=", "cloud_user", ".", "id" ]
[ 60, 0 ]
[ 79, 42 ]
python
en
['en', 'en', 'en']
True
test_outlet_set_state
(hass, hk_driver, events)
Test if Outlet accessory and HA are updated accordingly.
Test if Outlet accessory and HA are updated accordingly.
async def test_outlet_set_state(hass, hk_driver, events): """Test if Outlet accessory and HA are updated accordingly.""" entity_id = "switch.outlet_test" hass.states.async_set(entity_id, None) await hass.async_block_till_done() acc = Outlet(hass, hk_driver, "Outlet", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 7 # Outlet assert acc.char_on.value is False assert acc.char_outlet_in_use.value is True hass.states.async_set(entity_id, STATE_ON) await hass.async_block_till_done() assert acc.char_on.value is True hass.states.async_set(entity_id, STATE_OFF) await hass.async_block_till_done() assert acc.char_on.value is False # Set from HomeKit call_turn_on = async_mock_service(hass, "switch", "turn_on") call_turn_off = async_mock_service(hass, "switch", "turn_off") await hass.async_add_executor_job(acc.char_on.client_update_value, True) await hass.async_block_till_done() assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_on.client_update_value, False) await hass.async_block_till_done() assert call_turn_off assert call_turn_off[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None
[ "async", "def", "test_outlet_set_state", "(", "hass", ",", "hk_driver", ",", "events", ")", ":", "entity_id", "=", "\"switch.outlet_test\"", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "Outlet", "(", "hass", ",", "hk_driver", ",", "\"Outlet\"", ",", "entity_id", ",", "2", ",", "None", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "aid", "==", "2", "assert", "acc", ".", "category", "==", "7", "# Outlet", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "assert", "acc", ".", "char_outlet_in_use", ".", "value", "is", "True", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "True", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_OFF", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "# Set from HomeKit", "call_turn_on", "=", "async_mock_service", "(", "hass", ",", "\"switch\"", ",", "\"turn_on\"", ")", "call_turn_off", "=", "async_mock_service", "(", "hass", ",", "\"switch\"", ",", "\"turn_off\"", ")", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_turn_on", "assert", "call_turn_on", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "False", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_turn_off", "assert", "call_turn_off", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "2", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None" ]
[ 32, 0 ]
[ 72, 46 ]
python
en
['en', 'en', 'en']
True
test_switch_set_state
(hass, hk_driver, entity_id, attrs, events)
Test if accessory and HA are updated accordingly.
Test if accessory and HA are updated accordingly.
async def test_switch_set_state(hass, hk_driver, entity_id, attrs, events): """Test if accessory and HA are updated accordingly.""" domain = split_entity_id(entity_id)[0] hass.states.async_set(entity_id, None, attrs) await hass.async_block_till_done() acc = Switch(hass, hk_driver, "Switch", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 8 # Switch assert acc.activate_only is False assert acc.char_on.value is False hass.states.async_set(entity_id, STATE_ON, attrs) await hass.async_block_till_done() assert acc.char_on.value is True hass.states.async_set(entity_id, STATE_OFF, attrs) await hass.async_block_till_done() assert acc.char_on.value is False # Set from HomeKit call_turn_on = async_mock_service(hass, domain, "turn_on") call_turn_off = async_mock_service(hass, domain, "turn_off") await hass.async_add_executor_job(acc.char_on.client_update_value, True) await hass.async_block_till_done() assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_on.client_update_value, False) await hass.async_block_till_done() assert call_turn_off assert call_turn_off[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None
[ "async", "def", "test_switch_set_state", "(", "hass", ",", "hk_driver", ",", "entity_id", ",", "attrs", ",", "events", ")", ":", "domain", "=", "split_entity_id", "(", "entity_id", ")", "[", "0", "]", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ",", "attrs", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "Switch", "(", "hass", ",", "hk_driver", ",", "\"Switch\"", ",", "entity_id", ",", "2", ",", "None", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "aid", "==", "2", "assert", "acc", ".", "category", "==", "8", "# Switch", "assert", "acc", ".", "activate_only", "is", "False", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_ON", ",", "attrs", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "True", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_OFF", ",", "attrs", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "# Set from HomeKit", "call_turn_on", "=", "async_mock_service", "(", "hass", ",", "domain", ",", "\"turn_on\"", ")", "call_turn_off", "=", "async_mock_service", "(", "hass", ",", "domain", ",", "\"turn_off\"", ")", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_turn_on", "assert", "call_turn_on", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "False", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "call_turn_off", "assert", "call_turn_off", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "2", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None" ]
[ 85, 0 ]
[ 125, 46 ]
python
en
['en', 'en', 'en']
True
test_valve_set_state
(hass, hk_driver, events)
Test if Valve accessory and HA are updated accordingly.
Test if Valve accessory and HA are updated accordingly.
async def test_valve_set_state(hass, hk_driver, events): """Test if Valve accessory and HA are updated accordingly.""" entity_id = "switch.valve_test" hass.states.async_set(entity_id, None) await hass.async_block_till_done() acc = Valve(hass, hk_driver, "Valve", entity_id, 2, {CONF_TYPE: TYPE_FAUCET}) await acc.run_handler() await hass.async_block_till_done() assert acc.category == 29 # Faucet assert acc.char_valve_type.value == 3 # Water faucet acc = Valve(hass, hk_driver, "Valve", entity_id, 2, {CONF_TYPE: TYPE_SHOWER}) await acc.run_handler() await hass.async_block_till_done() assert acc.category == 30 # Shower assert acc.char_valve_type.value == 2 # Shower head acc = Valve(hass, hk_driver, "Valve", entity_id, 2, {CONF_TYPE: TYPE_SPRINKLER}) await acc.run_handler() await hass.async_block_till_done() assert acc.category == 28 # Sprinkler assert acc.char_valve_type.value == 1 # Irrigation acc = Valve(hass, hk_driver, "Valve", entity_id, 2, {CONF_TYPE: TYPE_VALVE}) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 29 # Faucet assert acc.char_active.value == 0 assert acc.char_in_use.value == 0 assert acc.char_valve_type.value == 0 # Generic Valve hass.states.async_set(entity_id, STATE_ON) await hass.async_block_till_done() assert acc.char_active.value == 1 assert acc.char_in_use.value == 1 hass.states.async_set(entity_id, STATE_OFF) await hass.async_block_till_done() assert acc.char_active.value == 0 assert acc.char_in_use.value == 0 # Set from HomeKit call_turn_on = async_mock_service(hass, "switch", "turn_on") call_turn_off = async_mock_service(hass, "switch", "turn_off") await hass.async_add_executor_job(acc.char_active.client_update_value, 1) await hass.async_block_till_done() assert acc.char_in_use.value == 1 assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_active.client_update_value, 0) await hass.async_block_till_done() assert acc.char_in_use.value == 0 assert call_turn_off assert call_turn_off[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None
[ "async", "def", "test_valve_set_state", "(", "hass", ",", "hk_driver", ",", "events", ")", ":", "entity_id", "=", "\"switch.valve_test\"", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "Valve", "(", "hass", ",", "hk_driver", ",", "\"Valve\"", ",", "entity_id", ",", "2", ",", "{", "CONF_TYPE", ":", "TYPE_FAUCET", "}", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "category", "==", "29", "# Faucet", "assert", "acc", ".", "char_valve_type", ".", "value", "==", "3", "# Water faucet", "acc", "=", "Valve", "(", "hass", ",", "hk_driver", ",", "\"Valve\"", ",", "entity_id", ",", "2", ",", "{", "CONF_TYPE", ":", "TYPE_SHOWER", "}", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "category", "==", "30", "# Shower", "assert", "acc", ".", "char_valve_type", ".", "value", "==", "2", "# Shower head", "acc", "=", "Valve", "(", "hass", ",", "hk_driver", ",", "\"Valve\"", ",", "entity_id", ",", "2", ",", "{", "CONF_TYPE", ":", "TYPE_SPRINKLER", "}", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "category", "==", "28", "# Sprinkler", "assert", "acc", ".", "char_valve_type", ".", "value", "==", "1", "# Irrigation", "acc", "=", "Valve", "(", "hass", ",", "hk_driver", ",", "\"Valve\"", ",", "entity_id", ",", "2", ",", "{", "CONF_TYPE", ":", "TYPE_VALVE", "}", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "aid", "==", "2", "assert", "acc", ".", "category", "==", "29", "# Faucet", "assert", "acc", ".", "char_active", ".", "value", "==", "0", "assert", "acc", ".", "char_in_use", ".", "value", "==", "0", "assert", "acc", ".", "char_valve_type", ".", "value", "==", "0", "# Generic Valve", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_active", ".", "value", "==", "1", "assert", "acc", ".", "char_in_use", ".", "value", "==", "1", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_OFF", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_active", ".", "value", "==", "0", "assert", "acc", ".", "char_in_use", ".", "value", "==", "0", "# Set from HomeKit", "call_turn_on", "=", "async_mock_service", "(", "hass", ",", "\"switch\"", ",", "\"turn_on\"", ")", "call_turn_off", "=", "async_mock_service", "(", "hass", ",", "\"switch\"", ",", "\"turn_off\"", ")", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_active", ".", "client_update_value", ",", "1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_in_use", ".", "value", "==", "1", "assert", "call_turn_on", "assert", "call_turn_on", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_active", ".", "client_update_value", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_in_use", ".", "value", "==", "0", "assert", "call_turn_off", "assert", "call_turn_off", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "2", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None" ]
[ 128, 0 ]
[ 192, 46 ]
python
en
['en', 'en', 'en']
True
test_vacuum_set_state
(hass, hk_driver, events)
Test if Vacuum accessory and HA are updated accordingly.
Test if Vacuum accessory and HA are updated accordingly.
async def test_vacuum_set_state(hass, hk_driver, events): """Test if Vacuum accessory and HA are updated accordingly.""" entity_id = "vacuum.roomba" hass.states.async_set(entity_id, None) await hass.async_block_till_done() acc = DockVacuum(hass, hk_driver, "DockVacuum", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 8 # Switch assert acc.char_on.value == 0 hass.states.async_set(entity_id, STATE_CLEANING) await hass.async_block_till_done() assert acc.char_on.value == 1 hass.states.async_set(entity_id, STATE_DOCKED) await hass.async_block_till_done() assert acc.char_on.value == 0 # Set from HomeKit call_start = async_mock_service(hass, VACUUM_DOMAIN, SERVICE_START) call_return_to_base = async_mock_service( hass, VACUUM_DOMAIN, SERVICE_RETURN_TO_BASE ) await hass.async_add_executor_job(acc.char_on.client_update_value, 1) await hass.async_block_till_done() assert acc.char_on.value == 1 assert call_start assert call_start[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_on.client_update_value, 0) await hass.async_block_till_done() assert acc.char_on.value == 0 assert call_return_to_base assert call_return_to_base[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None
[ "async", "def", "test_vacuum_set_state", "(", "hass", ",", "hk_driver", ",", "events", ")", ":", "entity_id", "=", "\"vacuum.roomba\"", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "DockVacuum", "(", "hass", ",", "hk_driver", ",", "\"DockVacuum\"", ",", "entity_id", ",", "2", ",", "None", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "aid", "==", "2", "assert", "acc", ".", "category", "==", "8", "# Switch", "assert", "acc", ".", "char_on", ".", "value", "==", "0", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_CLEANING", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "==", "1", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "STATE_DOCKED", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "==", "0", "# Set from HomeKit", "call_start", "=", "async_mock_service", "(", "hass", ",", "VACUUM_DOMAIN", ",", "SERVICE_START", ")", "call_return_to_base", "=", "async_mock_service", "(", "hass", ",", "VACUUM_DOMAIN", ",", "SERVICE_RETURN_TO_BASE", ")", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "==", "1", "assert", "call_start", "assert", "call_start", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "==", "0", "assert", "call_return_to_base", "assert", "call_return_to_base", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "2", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None" ]
[ 195, 0 ]
[ 238, 46 ]
python
en
['en', 'en', 'en']
True
test_reset_switch
(hass, hk_driver, events)
Test if switch accessory is reset correctly.
Test if switch accessory is reset correctly.
async def test_reset_switch(hass, hk_driver, events): """Test if switch accessory is reset correctly.""" domain = "scene" entity_id = "scene.test" hass.states.async_set(entity_id, None) await hass.async_block_till_done() acc = Switch(hass, hk_driver, "Switch", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.activate_only is True assert acc.char_on.value is False call_turn_on = async_mock_service(hass, domain, "turn_on") call_turn_off = async_mock_service(hass, domain, "turn_off") await hass.async_add_executor_job(acc.char_on.client_update_value, True) await hass.async_block_till_done() assert acc.char_on.value is True assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None future = dt_util.utcnow() + timedelta(seconds=1) async_fire_time_changed(hass, future) await hass.async_block_till_done() assert acc.char_on.value is False assert len(events) == 1 assert not call_turn_off await hass.async_add_executor_job(acc.char_on.client_update_value, False) await hass.async_block_till_done() assert acc.char_on.value is False assert len(events) == 1
[ "async", "def", "test_reset_switch", "(", "hass", ",", "hk_driver", ",", "events", ")", ":", "domain", "=", "\"scene\"", "entity_id", "=", "\"scene.test\"", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "Switch", "(", "hass", ",", "hk_driver", ",", "\"Switch\"", ",", "entity_id", ",", "2", ",", "None", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "activate_only", "is", "True", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "call_turn_on", "=", "async_mock_service", "(", "hass", ",", "domain", ",", "\"turn_on\"", ")", "call_turn_off", "=", "async_mock_service", "(", "hass", ",", "domain", ",", "\"turn_off\"", ")", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "True", "assert", "call_turn_on", "assert", "call_turn_on", "[", "0", "]", ".", "data", "[", "ATTR_ENTITY_ID", "]", "==", "entity_id", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "-", "1", "]", ".", "data", "[", "ATTR_VALUE", "]", "is", "None", "future", "=", "dt_util", ".", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "1", ")", "async_fire_time_changed", "(", "hass", ",", "future", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "assert", "len", "(", "events", ")", "==", "1", "assert", "not", "call_turn_off", "await", "hass", ".", "async_add_executor_job", "(", "acc", ".", "char_on", ".", "client_update_value", ",", "False", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "False", "assert", "len", "(", "events", ")", "==", "1" ]
[ 241, 0 ]
[ 276, 27 ]
python
en
['en', 'en', 'en']
True
test_reset_switch_reload
(hass, hk_driver, events)
Test reset switch after script reload.
Test reset switch after script reload.
async def test_reset_switch_reload(hass, hk_driver, events): """Test reset switch after script reload.""" entity_id = "script.test" hass.states.async_set(entity_id, None) await hass.async_block_till_done() acc = Switch(hass, hk_driver, "Switch", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.activate_only is False hass.states.async_set(entity_id, None) await hass.async_block_till_done() assert acc.char_on.value is False
[ "async", "def", "test_reset_switch_reload", "(", "hass", ",", "hk_driver", ",", "events", ")", ":", "entity_id", "=", "\"script.test\"", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "acc", "=", "Switch", "(", "hass", ",", "hk_driver", ",", "\"Switch\"", ",", "entity_id", ",", "2", ",", "None", ")", "await", "acc", ".", "run_handler", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "activate_only", "is", "False", "hass", ".", "states", ".", "async_set", "(", "entity_id", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "acc", ".", "char_on", ".", "value", "is", "False" ]
[ 279, 0 ]
[ 293, 37 ]
python
en
['en', 'en', 'en']
True
config_schema_validate
(withings_config)
Assert a schema config succeeds.
Assert a schema config succeeds.
def config_schema_validate(withings_config) -> dict: """Assert a schema config succeeds.""" hass_config = {const.DOMAIN: withings_config} return CONFIG_SCHEMA(hass_config)
[ "def", "config_schema_validate", "(", "withings_config", ")", "->", "dict", ":", "hass_config", "=", "{", "const", ".", "DOMAIN", ":", "withings_config", "}", "return", "CONFIG_SCHEMA", "(", "hass_config", ")" ]
[ 31, 0 ]
[ 35, 37 ]
python
en
['it', 'lb', 'en']
False
config_schema_assert_fail
(withings_config)
Assert a schema config will fail.
Assert a schema config will fail.
def config_schema_assert_fail(withings_config) -> None: """Assert a schema config will fail.""" try: config_schema_validate(withings_config) assert False, "This line should not have run." except vol.error.MultipleInvalid: assert True
[ "def", "config_schema_assert_fail", "(", "withings_config", ")", "->", "None", ":", "try", ":", "config_schema_validate", "(", "withings_config", ")", "assert", "False", ",", "\"This line should not have run.\"", "except", "vol", ".", "error", ".", "MultipleInvalid", ":", "assert", "True" ]
[ 38, 0 ]
[ 44, 19 ]
python
en
['en', 'lb', 'en']
True
test_config_schema_basic_config
()
Test schema.
Test schema.
def test_config_schema_basic_config() -> None: """Test schema.""" config_schema_validate( { CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret", const.CONF_USE_WEBHOOK: True, } )
[ "def", "test_config_schema_basic_config", "(", ")", "->", "None", ":", "config_schema_validate", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "const", ".", "CONF_USE_WEBHOOK", ":", "True", ",", "}", ")" ]
[ 47, 0 ]
[ 55, 5 ]
python
de
['de', 'de', 'it']
False
test_config_schema_client_id
()
Test schema.
Test schema.
def test_config_schema_client_id() -> None: """Test schema.""" config_schema_assert_fail({CONF_CLIENT_SECRET: "my_client_secret"}) config_schema_assert_fail( {CONF_CLIENT_SECRET: "my_client_secret", CONF_CLIENT_ID: ""} ) config_schema_validate( {CONF_CLIENT_SECRET: "my_client_secret", CONF_CLIENT_ID: "my_client_id"} )
[ "def", "test_config_schema_client_id", "(", ")", "->", "None", ":", "config_schema_assert_fail", "(", "{", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", "}", ")", "config_schema_assert_fail", "(", "{", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "CONF_CLIENT_ID", ":", "\"\"", "}", ")", "config_schema_validate", "(", "{", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "CONF_CLIENT_ID", ":", "\"my_client_id\"", "}", ")" ]
[ 58, 0 ]
[ 66, 5 ]
python
de
['de', 'de', 'it']
False
test_config_schema_client_secret
()
Test schema.
Test schema.
def test_config_schema_client_secret() -> None: """Test schema.""" config_schema_assert_fail({CONF_CLIENT_ID: "my_client_id"}) config_schema_assert_fail({CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: ""}) config_schema_validate( {CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret"} )
[ "def", "test_config_schema_client_secret", "(", ")", "->", "None", ":", "config_schema_assert_fail", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", "}", ")", "config_schema_assert_fail", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"\"", "}", ")", "config_schema_validate", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", "}", ")" ]
[ 69, 0 ]
[ 75, 5 ]
python
de
['de', 'de', 'it']
False
test_config_schema_use_webhook
()
Test schema.
Test schema.
def test_config_schema_use_webhook() -> None: """Test schema.""" config_schema_validate( {CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret"} ) config = config_schema_validate( { CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret", const.CONF_USE_WEBHOOK: True, } ) assert config[const.DOMAIN][const.CONF_USE_WEBHOOK] is True config = config_schema_validate( { CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret", const.CONF_USE_WEBHOOK: False, } ) assert config[const.DOMAIN][const.CONF_USE_WEBHOOK] is False config_schema_assert_fail( { CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret", const.CONF_USE_WEBHOOK: "A", } )
[ "def", "test_config_schema_use_webhook", "(", ")", "->", "None", ":", "config_schema_validate", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", "}", ")", "config", "=", "config_schema_validate", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "const", ".", "CONF_USE_WEBHOOK", ":", "True", ",", "}", ")", "assert", "config", "[", "const", ".", "DOMAIN", "]", "[", "const", ".", "CONF_USE_WEBHOOK", "]", "is", "True", "config", "=", "config_schema_validate", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "const", ".", "CONF_USE_WEBHOOK", ":", "False", ",", "}", ")", "assert", "config", "[", "const", ".", "DOMAIN", "]", "[", "const", ".", "CONF_USE_WEBHOOK", "]", "is", "False", "config_schema_assert_fail", "(", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "const", ".", "CONF_USE_WEBHOOK", ":", "\"A\"", ",", "}", ")" ]
[ 78, 0 ]
[ 105, 5 ]
python
de
['de', 'de', 'it']
False
test_async_setup_no_config
(hass: HomeAssistant)
Test method.
Test method.
async def test_async_setup_no_config(hass: HomeAssistant) -> None: """Test method.""" hass.async_create_task = MagicMock() await async_setup(hass, {}) hass.async_create_task.assert_not_called()
[ "async", "def", "test_async_setup_no_config", "(", "hass", ":", "HomeAssistant", ")", "->", "None", ":", "hass", ".", "async_create_task", "=", "MagicMock", "(", ")", "await", "async_setup", "(", "hass", ",", "{", "}", ")", "hass", ".", "async_create_task", ".", "assert_not_called", "(", ")" ]
[ 108, 0 ]
[ 114, 46 ]
python
en
['en', 'et', 'en']
False
test_auth_failure
( hass: HomeAssistant, component_factory: ComponentFactory, exception: Exception )
Test auth failure.
Test auth failure.
async def test_auth_failure( hass: HomeAssistant, component_factory: ComponentFactory, exception: Exception ) -> None: """Test auth failure.""" person0 = new_profile_config( "person0", 0, api_response_user_get_device=exception, api_response_measure_get_meas=exception, api_response_sleep_get_summary=exception, ) await component_factory.configure_component(profile_configs=(person0,)) assert not async_get_flow_for_user_id(hass, person0.user_id) await component_factory.setup_profile(person0.user_id) data_manager = get_data_manager_by_user_id(hass, person0.user_id) await data_manager.poll_data_update_coordinator.async_refresh() flows = async_get_flow_for_user_id(hass, person0.user_id) assert flows assert len(flows) == 1 flow = flows[0] assert flow["handler"] == const.DOMAIN assert flow["context"]["profile"] == person0.profile assert flow["context"]["userid"] == person0.user_id result = await hass.config_entries.flow.async_configure( flow["flow_id"], user_input={} ) assert result assert result["type"] == "external" assert result["handler"] == const.DOMAIN assert result["step_id"] == "auth" await component_factory.unload(person0)
[ "async", "def", "test_auth_failure", "(", "hass", ":", "HomeAssistant", ",", "component_factory", ":", "ComponentFactory", ",", "exception", ":", "Exception", ")", "->", "None", ":", "person0", "=", "new_profile_config", "(", "\"person0\"", ",", "0", ",", "api_response_user_get_device", "=", "exception", ",", "api_response_measure_get_meas", "=", "exception", ",", "api_response_sleep_get_summary", "=", "exception", ",", ")", "await", "component_factory", ".", "configure_component", "(", "profile_configs", "=", "(", "person0", ",", ")", ")", "assert", "not", "async_get_flow_for_user_id", "(", "hass", ",", "person0", ".", "user_id", ")", "await", "component_factory", ".", "setup_profile", "(", "person0", ".", "user_id", ")", "data_manager", "=", "get_data_manager_by_user_id", "(", "hass", ",", "person0", ".", "user_id", ")", "await", "data_manager", ".", "poll_data_update_coordinator", ".", "async_refresh", "(", ")", "flows", "=", "async_get_flow_for_user_id", "(", "hass", ",", "person0", ".", "user_id", ")", "assert", "flows", "assert", "len", "(", "flows", ")", "==", "1", "flow", "=", "flows", "[", "0", "]", "assert", "flow", "[", "\"handler\"", "]", "==", "const", ".", "DOMAIN", "assert", "flow", "[", "\"context\"", "]", "[", "\"profile\"", "]", "==", "person0", ".", "profile", "assert", "flow", "[", "\"context\"", "]", "[", "\"userid\"", "]", "==", "person0", ".", "user_id", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "flow", "[", "\"flow_id\"", "]", ",", "user_input", "=", "{", "}", ")", "assert", "result", "assert", "result", "[", "\"type\"", "]", "==", "\"external\"", "assert", "result", "[", "\"handler\"", "]", "==", "const", ".", "DOMAIN", "assert", "result", "[", "\"step_id\"", "]", "==", "\"auth\"", "await", "component_factory", ".", "unload", "(", "person0", ")" ]
[ 125, 0 ]
[ 161, 43 ]
python
en
['fr', 'gd', 'en']
False
test_set_config_unique_id
( hass: HomeAssistant, component_factory: ComponentFactory )
Test upgrading configs to use a unique id.
Test upgrading configs to use a unique id.
async def test_set_config_unique_id( hass: HomeAssistant, component_factory: ComponentFactory ) -> None: """Test upgrading configs to use a unique id.""" person0 = new_profile_config("person0", 0) await component_factory.configure_component(profile_configs=(person0,)) config_entry = MockConfigEntry( domain=DOMAIN, data={"token": {"userid": "my_user_id"}, "profile": person0.profile}, ) with patch("homeassistant.components.withings.async_get_data_manager") as mock: data_manager: DataManager = MagicMock(spec=DataManager) data_manager.poll_data_update_coordinator = MagicMock( spec=DataUpdateCoordinator ) data_manager.poll_data_update_coordinator.last_update_success = True mock.return_value = data_manager config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) assert config_entry.unique_id == "my_user_id"
[ "async", "def", "test_set_config_unique_id", "(", "hass", ":", "HomeAssistant", ",", "component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "person0", "=", "new_profile_config", "(", "\"person0\"", ",", "0", ")", "await", "component_factory", ".", "configure_component", "(", "profile_configs", "=", "(", "person0", ",", ")", ")", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "\"token\"", ":", "{", "\"userid\"", ":", "\"my_user_id\"", "}", ",", "\"profile\"", ":", "person0", ".", "profile", "}", ",", ")", "with", "patch", "(", "\"homeassistant.components.withings.async_get_data_manager\"", ")", "as", "mock", ":", "data_manager", ":", "DataManager", "=", "MagicMock", "(", "spec", "=", "DataManager", ")", "data_manager", ".", "poll_data_update_coordinator", "=", "MagicMock", "(", "spec", "=", "DataUpdateCoordinator", ")", "data_manager", ".", "poll_data_update_coordinator", ".", "last_update_success", "=", "True", "mock", ".", "return_value", "=", "data_manager", "config_entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "config_entry", ".", "entry_id", ")", "assert", "config_entry", ".", "unique_id", "==", "\"my_user_id\"" ]
[ 164, 0 ]
[ 187, 53 ]
python
en
['en', 'en', 'en']
True
test_set_convert_unique_id_to_string
(hass: HomeAssistant)
Test upgrading configs to use a unique id.
Test upgrading configs to use a unique id.
async def test_set_convert_unique_id_to_string(hass: HomeAssistant) -> None: """Test upgrading configs to use a unique id.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ "token": {"userid": 1234}, "auth_implementation": "withings", "profile": "person0", }, ) config_entry.add_to_hass(hass) hass_config = { HA_DOMAIN: { CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_METRIC, CONF_EXTERNAL_URL: "http://127.0.0.1:8080/", }, const.DOMAIN: { CONF_CLIENT_ID: "my_client_id", CONF_CLIENT_SECRET: "my_client_secret", const.CONF_USE_WEBHOOK: False, }, } with patch( "homeassistant.components.withings.common.ConfigEntryWithingsApi", spec=ConfigEntryWithingsApi, ): await async_process_ha_core_config(hass, hass_config.get(HA_DOMAIN)) assert await async_setup_component(hass, HA_DOMAIN, {}) assert await async_setup_component(hass, webhook.DOMAIN, hass_config) assert await async_setup_component(hass, const.DOMAIN, hass_config) await hass.async_block_till_done() assert config_entry.unique_id == "1234"
[ "async", "def", "test_set_convert_unique_id_to_string", "(", "hass", ":", "HomeAssistant", ")", "->", "None", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "\"token\"", ":", "{", "\"userid\"", ":", "1234", "}", ",", "\"auth_implementation\"", ":", "\"withings\"", ",", "\"profile\"", ":", "\"person0\"", ",", "}", ",", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "hass_config", "=", "{", "HA_DOMAIN", ":", "{", "CONF_UNIT_SYSTEM", ":", "CONF_UNIT_SYSTEM_METRIC", ",", "CONF_EXTERNAL_URL", ":", "\"http://127.0.0.1:8080/\"", ",", "}", ",", "const", ".", "DOMAIN", ":", "{", "CONF_CLIENT_ID", ":", "\"my_client_id\"", ",", "CONF_CLIENT_SECRET", ":", "\"my_client_secret\"", ",", "const", ".", "CONF_USE_WEBHOOK", ":", "False", ",", "}", ",", "}", "with", "patch", "(", "\"homeassistant.components.withings.common.ConfigEntryWithingsApi\"", ",", "spec", "=", "ConfigEntryWithingsApi", ",", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "hass_config", ".", "get", "(", "HA_DOMAIN", ")", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "HA_DOMAIN", ",", "{", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "webhook", ".", "DOMAIN", ",", "hass_config", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "const", ".", "DOMAIN", ",", "hass_config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "config_entry", ".", "unique_id", "==", "\"1234\"" ]
[ 190, 0 ]
[ 224, 47 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Add AccuWeather entities from a config_entry.
Add AccuWeather entities from a config_entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Add AccuWeather entities from a config_entry.""" name = config_entry.data[CONF_NAME] coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] sensors = [] for sensor in SENSOR_TYPES: sensors.append(AccuWeatherSensor(name, sensor, coordinator)) if coordinator.forecast: for sensor in FORECAST_SENSOR_TYPES: for day in FORECAST_DAYS: # Some air quality/allergy sensors are only available for certain # locations. if sensor in coordinator.data[ATTR_FORECAST][0]: sensors.append( AccuWeatherSensor(name, sensor, coordinator, forecast_day=day) ) async_add_entities(sensors, False)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "name", "=", "config_entry", ".", "data", "[", "CONF_NAME", "]", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "COORDINATOR", "]", "sensors", "=", "[", "]", "for", "sensor", "in", "SENSOR_TYPES", ":", "sensors", ".", "append", "(", "AccuWeatherSensor", "(", "name", ",", "sensor", ",", "coordinator", ")", ")", "if", "coordinator", ".", "forecast", ":", "for", "sensor", "in", "FORECAST_SENSOR_TYPES", ":", "for", "day", "in", "FORECAST_DAYS", ":", "# Some air quality/allergy sensors are only available for certain", "# locations.", "if", "sensor", "in", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "0", "]", ":", "sensors", ".", "append", "(", "AccuWeatherSensor", "(", "name", ",", "sensor", ",", "coordinator", ",", "forecast_day", "=", "day", ")", ")", "async_add_entities", "(", "sensors", ",", "False", ")" ]
[ 27, 0 ]
[ 47, 38 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.__init__
(self, name, kind, coordinator, forecast_day=None)
Initialize.
Initialize.
def __init__(self, name, kind, coordinator, forecast_day=None): """Initialize.""" super().__init__(coordinator) self._name = name self.kind = kind self._device_class = None self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION} self._unit_system = "Metric" if self.coordinator.is_metric else "Imperial" self.forecast_day = forecast_day
[ "def", "__init__", "(", "self", ",", "name", ",", "kind", ",", "coordinator", ",", "forecast_day", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "_name", "=", "name", "self", ".", "kind", "=", "kind", "self", ".", "_device_class", "=", "None", "self", ".", "_attrs", "=", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}", "self", ".", "_unit_system", "=", "\"Metric\"", "if", "self", ".", "coordinator", ".", "is_metric", "else", "\"Imperial\"", "self", ".", "forecast_day", "=", "forecast_day" ]
[ 53, 4 ]
[ 61, 40 ]
python
en
['en', 'en', 'it']
False
AccuWeatherSensor.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" if self.forecast_day is not None: return f"{self._name} {FORECAST_SENSOR_TYPES[self.kind][ATTR_LABEL]} {self.forecast_day}d" return f"{self._name} {SENSOR_TYPES[self.kind][ATTR_LABEL]}"
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "f\"{self._name} {FORECAST_SENSOR_TYPES[self.kind][ATTR_LABEL]} {self.forecast_day}d\"", "return", "f\"{self._name} {SENSOR_TYPES[self.kind][ATTR_LABEL]}\"" ]
[ 64, 4 ]
[ 68, 68 ]
python
en
['en', 'ig', 'en']
True
AccuWeatherSensor.unique_id
(self)
Return a unique_id for this entity.
Return a unique_id for this entity.
def unique_id(self): """Return a unique_id for this entity.""" if self.forecast_day is not None: return f"{self.coordinator.location_key}-{self.kind}-{self.forecast_day}".lower() return f"{self.coordinator.location_key}-{self.kind}".lower()
[ "def", "unique_id", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "f\"{self.coordinator.location_key}-{self.kind}-{self.forecast_day}\"", ".", "lower", "(", ")", "return", "f\"{self.coordinator.location_key}-{self.kind}\"", ".", "lower", "(", ")" ]
[ 71, 4 ]
[ 75, 69 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.device_info
(self)
Return the device info.
Return the device info.
def device_info(self): """Return the device info.""" return { "identifiers": {(DOMAIN, self.coordinator.location_key)}, "name": NAME, "manufacturer": MANUFACTURER, "entry_type": "service", }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "coordinator", ".", "location_key", ")", "}", ",", "\"name\"", ":", "NAME", ",", "\"manufacturer\"", ":", "MANUFACTURER", ",", "\"entry_type\"", ":", "\"service\"", ",", "}" ]
[ 78, 4 ]
[ 85, 9 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" if self.forecast_day is not None: if ( FORECAST_SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS] == DEVICE_CLASS_TEMPERATURE ): return self.coordinator.data[ATTR_FORECAST][self.forecast_day][ self.kind ]["Value"] if self.kind in ["WindGustDay", "WindGustNight"]: return self.coordinator.data[ATTR_FORECAST][self.forecast_day][ self.kind ]["Speed"]["Value"] if self.kind in ["Grass", "Mold", "Ragweed", "Tree", "UVIndex", "Ozone"]: return self.coordinator.data[ATTR_FORECAST][self.forecast_day][ self.kind ]["Value"] return self.coordinator.data[ATTR_FORECAST][self.forecast_day][self.kind] if self.kind == "Ceiling": return round(self.coordinator.data[self.kind][self._unit_system]["Value"]) if self.kind == "PressureTendency": return self.coordinator.data[self.kind]["LocalizedText"].lower() if SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS] == DEVICE_CLASS_TEMPERATURE: return self.coordinator.data[self.kind][self._unit_system]["Value"] if self.kind == "Precipitation": return self.coordinator.data["PrecipitationSummary"][self.kind][ self._unit_system ]["Value"] if self.kind == "WindGust": return self.coordinator.data[self.kind]["Speed"][self._unit_system]["Value"] return self.coordinator.data[self.kind]
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "if", "(", "FORECAST_SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_DEVICE_CLASS", "]", "==", "DEVICE_CLASS_TEMPERATURE", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "[", "\"Value\"", "]", "if", "self", ".", "kind", "in", "[", "\"WindGustDay\"", ",", "\"WindGustNight\"", "]", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "[", "\"Speed\"", "]", "[", "\"Value\"", "]", "if", "self", ".", "kind", "in", "[", "\"Grass\"", ",", "\"Mold\"", ",", "\"Ragweed\"", ",", "\"Tree\"", ",", "\"UVIndex\"", ",", "\"Ozone\"", "]", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "[", "\"Value\"", "]", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "if", "self", ".", "kind", "==", "\"Ceiling\"", ":", "return", "round", "(", "self", ".", "coordinator", ".", "data", "[", "self", ".", "kind", "]", "[", "self", ".", "_unit_system", "]", "[", "\"Value\"", "]", ")", "if", "self", ".", "kind", "==", "\"PressureTendency\"", ":", "return", "self", ".", "coordinator", ".", "data", "[", "self", ".", "kind", "]", "[", "\"LocalizedText\"", "]", ".", "lower", "(", ")", "if", "SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_DEVICE_CLASS", "]", "==", "DEVICE_CLASS_TEMPERATURE", ":", "return", "self", ".", "coordinator", ".", "data", "[", "self", ".", "kind", "]", "[", "self", ".", "_unit_system", "]", "[", "\"Value\"", "]", "if", "self", ".", "kind", "==", "\"Precipitation\"", ":", "return", "self", ".", "coordinator", ".", "data", "[", "\"PrecipitationSummary\"", "]", "[", "self", ".", "kind", "]", "[", "self", ".", "_unit_system", "]", "[", "\"Value\"", "]", "if", "self", ".", "kind", "==", "\"WindGust\"", ":", "return", "self", ".", "coordinator", ".", "data", "[", "self", ".", "kind", "]", "[", "\"Speed\"", "]", "[", "self", ".", "_unit_system", "]", "[", "\"Value\"", "]", "return", "self", ".", "coordinator", ".", "data", "[", "self", ".", "kind", "]" ]
[ 88, 4 ]
[ 119, 47 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.icon
(self)
Return the icon.
Return the icon.
def icon(self): """Return the icon.""" if self.forecast_day is not None: return FORECAST_SENSOR_TYPES[self.kind][ATTR_ICON] return SENSOR_TYPES[self.kind][ATTR_ICON]
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "FORECAST_SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_ICON", "]", "return", "SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_ICON", "]" ]
[ 122, 4 ]
[ 126, 49 ]
python
en
['en', 'sr', 'en']
True
AccuWeatherSensor.device_class
(self)
Return the device_class.
Return the device_class.
def device_class(self): """Return the device_class.""" if self.forecast_day is not None: return FORECAST_SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS] return SENSOR_TYPES[self.kind][ATTR_DEVICE_CLASS]
[ "def", "device_class", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "FORECAST_SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_DEVICE_CLASS", "]", "return", "SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "ATTR_DEVICE_CLASS", "]" ]
[ 129, 4 ]
[ 133, 57 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" if self.forecast_day is not None: return FORECAST_SENSOR_TYPES[self.kind][self._unit_system] return SENSOR_TYPES[self.kind][self._unit_system]
[ "def", "unit_of_measurement", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "FORECAST_SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "self", ".", "_unit_system", "]", "return", "SENSOR_TYPES", "[", "self", ".", "kind", "]", "[", "self", ".", "_unit_system", "]" ]
[ 136, 4 ]
[ 140, 57 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" if self.forecast_day is not None: if self.kind in ["WindGustDay", "WindGustNight"]: self._attrs["direction"] = self.coordinator.data[ATTR_FORECAST][ self.forecast_day ][self.kind]["Direction"]["English"] elif self.kind in ["Grass", "Mold", "Ragweed", "Tree", "UVIndex", "Ozone"]: self._attrs["level"] = self.coordinator.data[ATTR_FORECAST][ self.forecast_day ][self.kind]["Category"] return self._attrs if self.kind == "UVIndex": self._attrs["level"] = self.coordinator.data["UVIndexText"] elif self.kind == "Precipitation": self._attrs["type"] = self.coordinator.data["PrecipitationType"] return self._attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "if", "self", ".", "kind", "in", "[", "\"WindGustDay\"", ",", "\"WindGustNight\"", "]", ":", "self", ".", "_attrs", "[", "\"direction\"", "]", "=", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "[", "\"Direction\"", "]", "[", "\"English\"", "]", "elif", "self", ".", "kind", "in", "[", "\"Grass\"", ",", "\"Mold\"", ",", "\"Ragweed\"", ",", "\"Tree\"", ",", "\"UVIndex\"", ",", "\"Ozone\"", "]", ":", "self", ".", "_attrs", "[", "\"level\"", "]", "=", "self", ".", "coordinator", ".", "data", "[", "ATTR_FORECAST", "]", "[", "self", ".", "forecast_day", "]", "[", "self", ".", "kind", "]", "[", "\"Category\"", "]", "return", "self", ".", "_attrs", "if", "self", ".", "kind", "==", "\"UVIndex\"", ":", "self", ".", "_attrs", "[", "\"level\"", "]", "=", "self", ".", "coordinator", ".", "data", "[", "\"UVIndexText\"", "]", "elif", "self", ".", "kind", "==", "\"Precipitation\"", ":", "self", ".", "_attrs", "[", "\"type\"", "]", "=", "self", ".", "coordinator", ".", "data", "[", "\"PrecipitationType\"", "]", "return", "self", ".", "_attrs" ]
[ 143, 4 ]
[ 159, 26 ]
python
en
['en', 'en', 'en']
True
AccuWeatherSensor.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): """Return if the entity should be enabled when first added to the entity registry.""" return bool(self.kind not in OPTIONAL_SENSORS)
[ "def", "entity_registry_enabled_default", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "kind", "not", "in", "OPTIONAL_SENSORS", ")" ]
[ 162, 4 ]
[ 164, 54 ]
python
en
['en', 'en', 'en']
True
mock_device
()
Mock a Dynalite device.
Mock a Dynalite device.
def mock_device(): """Mock a Dynalite device.""" mock_dev = create_mock_device("cover", DynaliteTimeCoverWithTiltDevice) mock_dev.device_class = "blind" return mock_dev
[ "def", "mock_device", "(", ")", ":", "mock_dev", "=", "create_mock_device", "(", "\"cover\"", ",", "DynaliteTimeCoverWithTiltDevice", ")", "mock_dev", ".", "device_class", "=", "\"blind\"", "return", "mock_dev" ]
[ 17, 0 ]
[ 21, 19 ]
python
en
['ro', 'ht', 'en']
False
test_cover_setup
(hass, mock_device)
Test a successful setup.
Test a successful setup.
async def test_cover_setup(hass, mock_device): """Test a successful setup.""" await create_entity_from_device(hass, mock_device) entity_state = hass.states.get("cover.name") assert entity_state.attributes[ATTR_FRIENDLY_NAME] == mock_device.name assert ( entity_state.attributes["current_position"] == mock_device.current_cover_position ) assert ( entity_state.attributes["current_tilt_position"] == mock_device.current_cover_tilt_position ) assert entity_state.attributes[ATTR_DEVICE_CLASS] == mock_device.device_class await run_service_tests( hass, mock_device, "cover", [ {ATTR_SERVICE: "open_cover", ATTR_METHOD: "async_open_cover"}, {ATTR_SERVICE: "close_cover", ATTR_METHOD: "async_close_cover"}, {ATTR_SERVICE: "stop_cover", ATTR_METHOD: "async_stop_cover"}, { ATTR_SERVICE: "set_cover_position", ATTR_METHOD: "async_set_cover_position", ATTR_ARGS: {"position": 50}, }, {ATTR_SERVICE: "open_cover_tilt", ATTR_METHOD: "async_open_cover_tilt"}, {ATTR_SERVICE: "close_cover_tilt", ATTR_METHOD: "async_close_cover_tilt"}, {ATTR_SERVICE: "stop_cover_tilt", ATTR_METHOD: "async_stop_cover_tilt"}, { ATTR_SERVICE: "set_cover_tilt_position", ATTR_METHOD: "async_set_cover_tilt_position", ATTR_ARGS: {"tilt_position": 50}, }, ], )
[ "async", "def", "test_cover_setup", "(", "hass", ",", "mock_device", ")", ":", "await", "create_entity_from_device", "(", "hass", ",", "mock_device", ")", "entity_state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.name\"", ")", "assert", "entity_state", ".", "attributes", "[", "ATTR_FRIENDLY_NAME", "]", "==", "mock_device", ".", "name", "assert", "(", "entity_state", ".", "attributes", "[", "\"current_position\"", "]", "==", "mock_device", ".", "current_cover_position", ")", "assert", "(", "entity_state", ".", "attributes", "[", "\"current_tilt_position\"", "]", "==", "mock_device", ".", "current_cover_tilt_position", ")", "assert", "entity_state", ".", "attributes", "[", "ATTR_DEVICE_CLASS", "]", "==", "mock_device", ".", "device_class", "await", "run_service_tests", "(", "hass", ",", "mock_device", ",", "\"cover\"", ",", "[", "{", "ATTR_SERVICE", ":", "\"open_cover\"", ",", "ATTR_METHOD", ":", "\"async_open_cover\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"close_cover\"", ",", "ATTR_METHOD", ":", "\"async_close_cover\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"stop_cover\"", ",", "ATTR_METHOD", ":", "\"async_stop_cover\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"set_cover_position\"", ",", "ATTR_METHOD", ":", "\"async_set_cover_position\"", ",", "ATTR_ARGS", ":", "{", "\"position\"", ":", "50", "}", ",", "}", ",", "{", "ATTR_SERVICE", ":", "\"open_cover_tilt\"", ",", "ATTR_METHOD", ":", "\"async_open_cover_tilt\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"close_cover_tilt\"", ",", "ATTR_METHOD", ":", "\"async_close_cover_tilt\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"stop_cover_tilt\"", ",", "ATTR_METHOD", ":", "\"async_stop_cover_tilt\"", "}", ",", "{", "ATTR_SERVICE", ":", "\"set_cover_tilt_position\"", ",", "ATTR_METHOD", ":", "\"async_set_cover_tilt_position\"", ",", "ATTR_ARGS", ":", "{", "\"tilt_position\"", ":", "50", "}", ",", "}", ",", "]", ",", ")" ]
[ 24, 0 ]
[ 60, 5 ]
python
en
['en', 'co', 'en']
True
test_cover_without_tilt
(hass, mock_device)
Test a cover with no tilt.
Test a cover with no tilt.
async def test_cover_without_tilt(hass, mock_device): """Test a cover with no tilt.""" mock_device.has_tilt = False await create_entity_from_device(hass, mock_device) await hass.services.async_call( "cover", "open_cover_tilt", {"entity_id": "cover.name"}, blocking=True ) await hass.async_block_till_done() mock_device.async_open_cover_tilt.assert_not_called()
[ "async", "def", "test_cover_without_tilt", "(", "hass", ",", "mock_device", ")", ":", "mock_device", ".", "has_tilt", "=", "False", "await", "create_entity_from_device", "(", "hass", ",", "mock_device", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"open_cover_tilt\"", ",", "{", "\"entity_id\"", ":", "\"cover.name\"", "}", ",", "blocking", "=", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "mock_device", ".", "async_open_cover_tilt", ".", "assert_not_called", "(", ")" ]
[ 63, 0 ]
[ 71, 57 ]
python
en
['en', 'en', 'en']
True
check_cover_position
( hass, update_func, device, closing, opening, closed, expected )
Check that a given position behaves correctly.
Check that a given position behaves correctly.
async def check_cover_position( hass, update_func, device, closing, opening, closed, expected ): """Check that a given position behaves correctly.""" device.is_closing = closing device.is_opening = opening device.is_closed = closed update_func(device) await hass.async_block_till_done() entity_state = hass.states.get("cover.name") assert entity_state.state == expected
[ "async", "def", "check_cover_position", "(", "hass", ",", "update_func", ",", "device", ",", "closing", ",", "opening", ",", "closed", ",", "expected", ")", ":", "device", ".", "is_closing", "=", "closing", "device", ".", "is_opening", "=", "opening", "device", ".", "is_closed", "=", "closed", "update_func", "(", "device", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "entity_state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.name\"", ")", "assert", "entity_state", ".", "state", "==", "expected" ]
[ 74, 0 ]
[ 84, 41 ]
python
en
['en', 'en', 'en']
True
test_cover_positions
(hass, mock_device)
Test that the state updates in the various positions.
Test that the state updates in the various positions.
async def test_cover_positions(hass, mock_device): """Test that the state updates in the various positions.""" update_func = await create_entity_from_device(hass, mock_device) await check_cover_position( hass, update_func, mock_device, True, False, False, "closing" ) await check_cover_position( hass, update_func, mock_device, False, True, False, "opening" ) await check_cover_position( hass, update_func, mock_device, False, False, True, "closed" ) await check_cover_position( hass, update_func, mock_device, False, False, False, "open" )
[ "async", "def", "test_cover_positions", "(", "hass", ",", "mock_device", ")", ":", "update_func", "=", "await", "create_entity_from_device", "(", "hass", ",", "mock_device", ")", "await", "check_cover_position", "(", "hass", ",", "update_func", ",", "mock_device", ",", "True", ",", "False", ",", "False", ",", "\"closing\"", ")", "await", "check_cover_position", "(", "hass", ",", "update_func", ",", "mock_device", ",", "False", ",", "True", ",", "False", ",", "\"opening\"", ")", "await", "check_cover_position", "(", "hass", ",", "update_func", ",", "mock_device", ",", "False", ",", "False", ",", "True", ",", "\"closed\"", ")", "await", "check_cover_position", "(", "hass", ",", "update_func", ",", "mock_device", ",", "False", ",", "False", ",", "False", ",", "\"open\"", ")" ]
[ 87, 0 ]
[ 101, 5 ]
python
en
['en', 'en', 'en']
True
BatchTuner.is_valid
(self, search_space)
Check the search space is valid: only contains 'choice' type Parameters ---------- search_space : dict Returns ------- None or list If valid, return candidate values; else return None.
Check the search space is valid: only contains 'choice' type
def is_valid(self, search_space): """ Check the search space is valid: only contains 'choice' type Parameters ---------- search_space : dict Returns ------- None or list If valid, return candidate values; else return None. """ if not len(search_space) == 1: raise RuntimeError('BatchTuner only supprt one combined-paramreters key.') for param in search_space: param_type = search_space[param][TYPE] if not param_type == CHOICE: raise RuntimeError('BatchTuner only supprt \ one combined-paramreters type is choice.') if isinstance(search_space[param][VALUE], list): return search_space[param][VALUE] raise RuntimeError('The combined-paramreters \ value in BatchTuner is not a list.') return None
[ "def", "is_valid", "(", "self", ",", "search_space", ")", ":", "if", "not", "len", "(", "search_space", ")", "==", "1", ":", "raise", "RuntimeError", "(", "'BatchTuner only supprt one combined-paramreters key.'", ")", "for", "param", "in", "search_space", ":", "param_type", "=", "search_space", "[", "param", "]", "[", "TYPE", "]", "if", "not", "param_type", "==", "CHOICE", ":", "raise", "RuntimeError", "(", "'BatchTuner only supprt \\\n one combined-paramreters type is choice.'", ")", "if", "isinstance", "(", "search_space", "[", "param", "]", "[", "VALUE", "]", ",", "list", ")", ":", "return", "search_space", "[", "param", "]", "[", "VALUE", "]", "raise", "RuntimeError", "(", "'The combined-paramreters \\\n value in BatchTuner is not a list.'", ")", "return", "None" ]
[ 41, 4 ]
[ 68, 19 ]
python
en
['en', 'error', 'th']
False
BatchTuner.update_search_space
(self, search_space)
Update the search space Parameters ---------- search_space : dict
Update the search space
def update_search_space(self, search_space): """Update the search space Parameters ---------- search_space : dict """ self._values = self.is_valid(search_space)
[ "def", "update_search_space", "(", "self", ",", "search_space", ")", ":", "self", ".", "_values", "=", "self", ".", "is_valid", "(", "search_space", ")" ]
[ 70, 4 ]
[ 77, 50 ]
python
en
['en', 'en', 'en']
True
BatchTuner.generate_parameters
(self, parameter_id, **kwargs)
Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- dict A candidate parameter group.
Returns a dict of trial (hyper-)parameters, as a serializable object.
def generate_parameters(self, parameter_id, **kwargs): """Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- dict A candidate parameter group. """ self._count += 1 if self._count > len(self._values) - 1: raise nni.NoMoreTrialError('no more parameters now.') return self._values[self._count]
[ "def", "generate_parameters", "(", "self", ",", "parameter_id", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_count", "+=", "1", "if", "self", ".", "_count", ">", "len", "(", "self", ".", "_values", ")", "-", "1", ":", "raise", "nni", ".", "NoMoreTrialError", "(", "'no more parameters now.'", ")", "return", "self", ".", "_values", "[", "self", ".", "_count", "]" ]
[ 79, 4 ]
[ 94, 40 ]
python
en
['en', 'en', 'en']
True