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_sending_non_templated_notification
(hass, mock_notifier)
Test notifications.
Test notifications.
async def test_sending_non_templated_notification(hass, mock_notifier): """Test notifications.""" assert await async_setup_component(hass, alert.DOMAIN, TEST_CONFIG) hass.states.async_set(TEST_ENTITY, STATE_ON) await hass.async_block_till_done() assert len(mock_notifier) == 1 last_event = mock_notifier[-1] assert last_event.data[notify.ATTR_MESSAGE] == NAME
[ "async", "def", "test_sending_non_templated_notification", "(", "hass", ",", "mock_notifier", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "TEST_CONFIG", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_notifier", ")", "==", "1", "last_event", "=", "mock_notifier", "[", "-", "1", "]", "assert", "last_event", ".", "data", "[", "notify", ".", "ATTR_MESSAGE", "]", "==", "NAME" ]
[ 226, 0 ]
[ 234, 55 ]
python
en
['en', 'en', 'en']
False
test_sending_templated_notification
(hass, mock_notifier)
Test templated notification.
Test templated notification.
async def test_sending_templated_notification(hass, mock_notifier): """Test templated notification.""" config = deepcopy(TEST_CONFIG) config[alert.DOMAIN][NAME][alert.CONF_ALERT_MESSAGE] = TEMPLATE assert await async_setup_component(hass, alert.DOMAIN, config) hass.states.async_set(TEST_ENTITY, STATE_ON) await hass.async_block_till_done() assert len(mock_notifier) == 1 last_event = mock_notifier[-1] assert last_event.data[notify.ATTR_MESSAGE] == TEST_ENTITY
[ "async", "def", "test_sending_templated_notification", "(", "hass", ",", "mock_notifier", ")", ":", "config", "=", "deepcopy", "(", "TEST_CONFIG", ")", "config", "[", "alert", ".", "DOMAIN", "]", "[", "NAME", "]", "[", "alert", ".", "CONF_ALERT_MESSAGE", "]", "=", "TEMPLATE", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "config", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_notifier", ")", "==", "1", "last_event", "=", "mock_notifier", "[", "-", "1", "]", "assert", "last_event", ".", "data", "[", "notify", ".", "ATTR_MESSAGE", "]", "==", "TEST_ENTITY" ]
[ 237, 0 ]
[ 247, 62 ]
python
en
['en', 'en', 'en']
True
test_sending_templated_done_notification
(hass, mock_notifier)
Test templated notification.
Test templated notification.
async def test_sending_templated_done_notification(hass, mock_notifier): """Test templated notification.""" config = deepcopy(TEST_CONFIG) config[alert.DOMAIN][NAME][alert.CONF_DONE_MESSAGE] = TEMPLATE assert await async_setup_component(hass, alert.DOMAIN, config) hass.states.async_set(TEST_ENTITY, STATE_ON) await hass.async_block_till_done() hass.states.async_set(TEST_ENTITY, STATE_OFF) await hass.async_block_till_done() assert len(mock_notifier) == 2 last_event = mock_notifier[-1] assert last_event.data[notify.ATTR_MESSAGE] == TEST_ENTITY
[ "async", "def", "test_sending_templated_done_notification", "(", "hass", ",", "mock_notifier", ")", ":", "config", "=", "deepcopy", "(", "TEST_CONFIG", ")", "config", "[", "alert", ".", "DOMAIN", "]", "[", "NAME", "]", "[", "alert", ".", "CONF_DONE_MESSAGE", "]", "=", "TEMPLATE", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "config", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_OFF", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_notifier", ")", "==", "2", "last_event", "=", "mock_notifier", "[", "-", "1", "]", "assert", "last_event", ".", "data", "[", "notify", ".", "ATTR_MESSAGE", "]", "==", "TEST_ENTITY" ]
[ 250, 0 ]
[ 262, 62 ]
python
en
['en', 'en', 'en']
True
test_sending_titled_notification
(hass, mock_notifier)
Test notifications.
Test notifications.
async def test_sending_titled_notification(hass, mock_notifier): """Test notifications.""" config = deepcopy(TEST_CONFIG) config[alert.DOMAIN][NAME][alert.CONF_TITLE] = TITLE assert await async_setup_component(hass, alert.DOMAIN, config) hass.states.async_set(TEST_ENTITY, STATE_ON) await hass.async_block_till_done() assert len(mock_notifier) == 1 last_event = mock_notifier[-1] assert last_event.data[notify.ATTR_TITLE] == TEST_TITLE
[ "async", "def", "test_sending_titled_notification", "(", "hass", ",", "mock_notifier", ")", ":", "config", "=", "deepcopy", "(", "TEST_CONFIG", ")", "config", "[", "alert", ".", "DOMAIN", "]", "[", "NAME", "]", "[", "alert", ".", "CONF_TITLE", "]", "=", "TITLE", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "config", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_notifier", ")", "==", "1", "last_event", "=", "mock_notifier", "[", "-", "1", "]", "assert", "last_event", ".", "data", "[", "notify", ".", "ATTR_TITLE", "]", "==", "TEST_TITLE" ]
[ 265, 0 ]
[ 275, 59 ]
python
en
['en', 'en', 'en']
False
test_sending_data_notification
(hass, mock_notifier)
Test notifications.
Test notifications.
async def test_sending_data_notification(hass, mock_notifier): """Test notifications.""" config = deepcopy(TEST_CONFIG) config[alert.DOMAIN][NAME][alert.CONF_DATA] = TEST_DATA assert await async_setup_component(hass, alert.DOMAIN, config) hass.states.async_set(TEST_ENTITY, STATE_ON) await hass.async_block_till_done() assert len(mock_notifier) == 1 last_event = mock_notifier[-1] assert last_event.data[notify.ATTR_DATA] == TEST_DATA
[ "async", "def", "test_sending_data_notification", "(", "hass", ",", "mock_notifier", ")", ":", "config", "=", "deepcopy", "(", "TEST_CONFIG", ")", "config", "[", "alert", ".", "DOMAIN", "]", "[", "NAME", "]", "[", "alert", ".", "CONF_DATA", "]", "=", "TEST_DATA", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "config", ")", "hass", ".", "states", ".", "async_set", "(", "TEST_ENTITY", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_notifier", ")", "==", "1", "last_event", "=", "mock_notifier", "[", "-", "1", "]", "assert", "last_event", ".", "data", "[", "notify", ".", "ATTR_DATA", "]", "==", "TEST_DATA" ]
[ 278, 0 ]
[ 288, 57 ]
python
en
['en', 'en', 'en']
False
test_skipfirst
(hass)
Test skipping first notification.
Test skipping first notification.
async def test_skipfirst(hass): """Test skipping first notification.""" config = deepcopy(TEST_CONFIG) config[alert.DOMAIN][NAME][alert.CONF_SKIP_FIRST] = True events = [] @callback def record_event(event): """Add recorded event to set.""" events.append(event) hass.services.async_register(notify.DOMAIN, NOTIFIER, record_event) assert await async_setup_component(hass, alert.DOMAIN, config) assert len(events) == 0 hass.states.async_set("sensor.test", STATE_ON) await hass.async_block_till_done() assert len(events) == 0
[ "async", "def", "test_skipfirst", "(", "hass", ")", ":", "config", "=", "deepcopy", "(", "TEST_CONFIG", ")", "config", "[", "alert", ".", "DOMAIN", "]", "[", "NAME", "]", "[", "alert", ".", "CONF_SKIP_FIRST", "]", "=", "True", "events", "=", "[", "]", "@", "callback", "def", "record_event", "(", "event", ")", ":", "\"\"\"Add recorded event to set.\"\"\"", "events", ".", "append", "(", "event", ")", "hass", ".", "services", ".", "async_register", "(", "notify", ".", "DOMAIN", ",", "NOTIFIER", ",", "record_event", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "alert", ".", "DOMAIN", ",", "config", ")", "assert", "len", "(", "events", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "\"sensor.test\"", ",", "STATE_ON", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "events", ")", "==", "0" ]
[ 291, 0 ]
[ 309, 27 ]
python
en
['sv', 'en', 'en']
True
test_noack
(hass)
Test no ack feature.
Test no ack feature.
async def test_noack(hass): """Test no ack feature.""" entity = alert.Alert(hass, *TEST_NOACK) hass.async_add_job(entity.begin_alerting) await hass.async_block_till_done()
[ "async", "def", "test_noack", "(", "hass", ")", ":", "entity", "=", "alert", ".", "Alert", "(", "hass", ",", "*", "TEST_NOACK", ")", "hass", ".", "async_add_job", "(", "entity", ".", "begin_alerting", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 312, 0 ]
[ 316, 38 ]
python
en
['pt', 'en', 'en']
True
test_done_message_state_tracker_reset_on_cancel
(hass)
Test that the done message is reset when canceled.
Test that the done message is reset when canceled.
async def test_done_message_state_tracker_reset_on_cancel(hass): """Test that the done message is reset when canceled.""" entity = alert.Alert(hass, *TEST_NOACK) entity._cancel = lambda *args: None assert entity._send_done_message is False entity._send_done_message = True hass.async_add_job(entity.end_alerting) await hass.async_block_till_done() assert entity._send_done_message is False
[ "async", "def", "test_done_message_state_tracker_reset_on_cancel", "(", "hass", ")", ":", "entity", "=", "alert", ".", "Alert", "(", "hass", ",", "*", "TEST_NOACK", ")", "entity", ".", "_cancel", "=", "lambda", "*", "args", ":", "None", "assert", "entity", ".", "_send_done_message", "is", "False", "entity", ".", "_send_done_message", "=", "True", "hass", ".", "async_add_job", "(", "entity", ".", "end_alerting", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "entity", ".", "_send_done_message", "is", "False" ]
[ 319, 0 ]
[ 327, 45 ]
python
en
['en', 'en', 'en']
True
ResourceInfo.get_static_info
()
Get static resource information about local environment. Returns: Tuple[int, list]: (total cpu number, [cpu usage per core])
Get static resource information about local environment.
def get_static_info() -> dict: """ Get static resource information about local environment. Returns: Tuple[int, list]: (total cpu number, [cpu usage per core]) """ static_info = {} static_info["cpu"] = psutil.cpu_count() memory = psutil.virtual_memory() static_info["total_memory"] = round(float(memory.total) / (1024 ** 2), 2) static_info["memory"] = round(float(memory.free) / (1024 ** 2), 2) gpu_static_command = "nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits" try: return_str = Subprocess.run(command=gpu_static_command) gpus_info = return_str.split(os.linesep) static_info["gpu"] = len(gpus_info) - 1 # (int) logical number static_info["gpu_name"] = [] static_info["gpu_memory"] = [] for info in gpus_info: name, total_memory = info.split(", ") static_info["gpu_name"].append(name) static_info["gpu_memory"].append(total_memory) except Exception: static_info["gpu"] = 0 return static_info
[ "def", "get_static_info", "(", ")", "->", "dict", ":", "static_info", "=", "{", "}", "static_info", "[", "\"cpu\"", "]", "=", "psutil", ".", "cpu_count", "(", ")", "memory", "=", "psutil", ".", "virtual_memory", "(", ")", "static_info", "[", "\"total_memory\"", "]", "=", "round", "(", "float", "(", "memory", ".", "total", ")", "/", "(", "1024", "**", "2", ")", ",", "2", ")", "static_info", "[", "\"memory\"", "]", "=", "round", "(", "float", "(", "memory", ".", "free", ")", "/", "(", "1024", "**", "2", ")", ",", "2", ")", "gpu_static_command", "=", "\"nvidia-smi --query-gpu=name,memory.total --format=csv,noheader,nounits\"", "try", ":", "return_str", "=", "Subprocess", ".", "run", "(", "command", "=", "gpu_static_command", ")", "gpus_info", "=", "return_str", ".", "split", "(", "os", ".", "linesep", ")", "static_info", "[", "\"gpu\"", "]", "=", "len", "(", "gpus_info", ")", "-", "1", "# (int) logical number", "static_info", "[", "\"gpu_name\"", "]", "=", "[", "]", "static_info", "[", "\"gpu_memory\"", "]", "=", "[", "]", "for", "info", "in", "gpus_info", ":", "name", ",", "total_memory", "=", "info", ".", "split", "(", "\", \"", ")", "static_info", "[", "\"gpu_name\"", "]", ".", "append", "(", "name", ")", "static_info", "[", "\"gpu_memory\"", "]", ".", "append", "(", "total_memory", ")", "except", "Exception", ":", "static_info", "[", "\"gpu\"", "]", "=", "0", "return", "static_info" ]
[ 20, 4 ]
[ 47, 26 ]
python
en
['en', 'en', 'en']
True
ResourceInfo.get_dynamic_info
(interval: int = None)
Get dynamic resource information about local environment. Returns: Tuple[float]: (total memory, free memory, used memory, memory usage)
Get dynamic resource information about local environment.
def get_dynamic_info(interval: int = None) -> dict: """ Get dynamic resource information about local environment. Returns: Tuple[float]: (total memory, free memory, used memory, memory usage) """ dynamic_info = {} dynamic_info["cpu_usage_per_core"] = psutil.cpu_percent(interval=interval, percpu=True) memory = psutil.virtual_memory() dynamic_info["memory_usage"] = memory.percent / 100 gpu_dynamic_command = "nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits" dynamic_info["gpu_memory_usage"] = [] try: return_str = Subprocess.run(command=gpu_dynamic_command) memory_usage_per_gpu = return_str.split("\n") for single_usage in memory_usage_per_gpu: dynamic_info["gpu_memory_usage"].append(float(single_usage)) except Exception: pass return dynamic_info
[ "def", "get_dynamic_info", "(", "interval", ":", "int", "=", "None", ")", "->", "dict", ":", "dynamic_info", "=", "{", "}", "dynamic_info", "[", "\"cpu_usage_per_core\"", "]", "=", "psutil", ".", "cpu_percent", "(", "interval", "=", "interval", ",", "percpu", "=", "True", ")", "memory", "=", "psutil", ".", "virtual_memory", "(", ")", "dynamic_info", "[", "\"memory_usage\"", "]", "=", "memory", ".", "percent", "/", "100", "gpu_dynamic_command", "=", "\"nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits\"", "dynamic_info", "[", "\"gpu_memory_usage\"", "]", "=", "[", "]", "try", ":", "return_str", "=", "Subprocess", ".", "run", "(", "command", "=", "gpu_dynamic_command", ")", "memory_usage_per_gpu", "=", "return_str", ".", "split", "(", "\"\\n\"", ")", "for", "single_usage", "in", "memory_usage_per_gpu", ":", "dynamic_info", "[", "\"gpu_memory_usage\"", "]", ".", "append", "(", "float", "(", "single_usage", ")", ")", "except", "Exception", ":", "pass", "return", "dynamic_info" ]
[ 50, 4 ]
[ 72, 27 ]
python
en
['en', 'en', 'en']
True
test_websocket_api
(hass, generic_data, hass_ws_client)
Test the ozw websocket api.
Test the ozw websocket api.
async def test_websocket_api(hass, generic_data, hass_ws_client): """Test the ozw websocket api.""" await setup_ozw(hass, fixture=generic_data) client = await hass_ws_client(hass) # Test instance list await client.send_json({ID: 4, TYPE: "ozw/get_instances"}) msg = await client.receive_json() assert len(msg["result"]) == 1 result = msg["result"][0] assert result[OZW_INSTANCE] == 1 assert result["Status"] == "driverAllNodesQueried" assert result["OpenZWave_Version"] == "1.6.1008" # Test network status await client.send_json({ID: 5, TYPE: "ozw/network_status"}) msg = await client.receive_json() result = msg["result"] assert result["Status"] == "driverAllNodesQueried" assert result[OZW_INSTANCE] == 1 # Test node status await client.send_json({ID: 6, TYPE: "ozw/node_status", NODE_ID: 32}) msg = await client.receive_json() result = msg["result"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 32 assert result[ATTR_NODE_QUERY_STAGE] == "Complete" assert result[ATTR_IS_ZWAVE_PLUS] assert result[ATTR_IS_AWAKE] assert not result[ATTR_IS_FAILED] assert result[ATTR_NODE_BAUD_RATE] == 100000 assert result[ATTR_IS_BEAMING] assert not result[ATTR_IS_FLIRS] assert result[ATTR_IS_ROUTING] assert not result[ATTR_IS_SECURITYV1] assert result[ATTR_NODE_BASIC_STRING] == "Routing Slave" assert result[ATTR_NODE_GENERIC_STRING] == "Binary Switch" assert result[ATTR_NODE_SPECIFIC_STRING] == "Binary Power Switch" assert result[ATTR_NEIGHBORS] == [1, 33, 36, 37, 39] await client.send_json({ID: 7, TYPE: "ozw/node_status", NODE_ID: 999}) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test node statistics await client.send_json({ID: 8, TYPE: "ozw/node_statistics", NODE_ID: 39}) msg = await client.receive_json() result = msg["result"] assert result[OZW_INSTANCE] == 1 assert result[NODE_ID] == 39 assert result["send_count"] == 57 assert result["sent_failed"] == 0 assert result["retries"] == 1 assert result["last_request_rtt"] == 26 assert result["last_response_rtt"] == 38 assert result["average_request_rtt"] == 29 assert result["average_response_rtt"] == 37 assert result["received_packets"] == 3594 assert result["received_dup_packets"] == 12 assert result["received_unsolicited"] == 3546 # Test node metadata await client.send_json({ID: 9, TYPE: "ozw/node_metadata", NODE_ID: 39}) msg = await client.receive_json() result = msg["result"] assert result["metadata"]["ProductPic"] == "images/aeotec/zwa002.png" await client.send_json({ID: 10, TYPE: "ozw/node_metadata", NODE_ID: 999}) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test network statistics await client.send_json({ID: 11, TYPE: "ozw/network_statistics"}) msg = await client.receive_json() result = msg["result"] assert result["readCnt"] == 92220 assert result[OZW_INSTANCE] == 1 assert result["node_count"] == 5 # Test get nodes await client.send_json({ID: 12, TYPE: "ozw/get_nodes"}) msg = await client.receive_json() result = msg["result"] assert len(result) == 5 assert result[2][ATTR_IS_AWAKE] assert not result[1][ATTR_IS_FAILED] # Test get config parameters await client.send_json({ID: 13, TYPE: "ozw/get_config_parameters", NODE_ID: 39}) msg = await client.receive_json() result = msg["result"] assert len(result) == 8 for config_param in result: assert config_param["type"] in ( ValueType.LIST.value, ValueType.BOOL.value, ValueType.INT.value, ValueType.BYTE.value, ValueType.SHORT.value, ValueType.BITSET.value, ) # Test set config parameter config_param = result[0] print(config_param) current_val = config_param[ATTR_VALUE] new_val = next( option[0] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[0] != current_val ) new_label = next( option[1] for option in config_param[SCHEMA][0][ATTR_OPTIONS] if option[1] != current_val and option[0] != new_val ) await client.send_json( { ID: 14, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_val, } ) msg = await client.receive_json() assert msg["success"] await client.send_json( { ID: 15, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: new_label, } ) msg = await client.receive_json() assert msg["success"] # Test OZW Instance not found error await client.send_json( {ID: 16, TYPE: "ozw/get_config_parameters", OZW_INSTANCE: 999, NODE_ID: 1} ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test OZW Node not found error await client.send_json( { ID: 18, TYPE: "ozw/set_config_parameter", NODE_ID: 999, PARAMETER: 0, VALUE: "test", } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test parameter not found await client.send_json( { ID: 19, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: 45, VALUE: "test", } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test list value not found await client.send_json( { ID: 20, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: config_param[ATTR_CONFIG_PARAMETER], VALUE: "test", } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND # Test value type invalid await client.send_json( { ID: 21, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: 3, VALUE: 0, } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_SUPPORTED # Test invalid bitset format await client.send_json( { ID: 22, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: 3, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True, ATTR_LABEL: "test"}, } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_INVALID_FORMAT # Test valid bitset format passes validation await client.send_json( { ID: 23, TYPE: "ozw/set_config_parameter", NODE_ID: 39, PARAMETER: 10000, VALUE: {ATTR_POSITION: 1, ATTR_VALUE: True}, } ) msg = await client.receive_json() result = msg["error"] assert result["code"] == ERR_NOT_FOUND
[ "async", "def", "test_websocket_api", "(", "hass", ",", "generic_data", ",", "hass_ws_client", ")", ":", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "generic_data", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "# Test instance list", "await", "client", ".", "send_json", "(", "{", "ID", ":", "4", ",", "TYPE", ":", "\"ozw/get_instances\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "len", "(", "msg", "[", "\"result\"", "]", ")", "==", "1", "result", "=", "msg", "[", "\"result\"", "]", "[", "0", "]", "assert", "result", "[", "OZW_INSTANCE", "]", "==", "1", "assert", "result", "[", "\"Status\"", "]", "==", "\"driverAllNodesQueried\"", "assert", "result", "[", "\"OpenZWave_Version\"", "]", "==", "\"1.6.1008\"", "# Test network status", "await", "client", ".", "send_json", "(", "{", "ID", ":", "5", ",", "TYPE", ":", "\"ozw/network_status\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "\"Status\"", "]", "==", "\"driverAllNodesQueried\"", "assert", "result", "[", "OZW_INSTANCE", "]", "==", "1", "# Test node status", "await", "client", ".", "send_json", "(", "{", "ID", ":", "6", ",", "TYPE", ":", "\"ozw/node_status\"", ",", "NODE_ID", ":", "32", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "OZW_INSTANCE", "]", "==", "1", "assert", "result", "[", "NODE_ID", "]", "==", "32", "assert", "result", "[", "ATTR_NODE_QUERY_STAGE", "]", "==", "\"Complete\"", "assert", "result", "[", "ATTR_IS_ZWAVE_PLUS", "]", "assert", "result", "[", "ATTR_IS_AWAKE", "]", "assert", "not", "result", "[", "ATTR_IS_FAILED", "]", "assert", "result", "[", "ATTR_NODE_BAUD_RATE", "]", "==", "100000", "assert", "result", "[", "ATTR_IS_BEAMING", "]", "assert", "not", "result", "[", "ATTR_IS_FLIRS", "]", "assert", "result", "[", "ATTR_IS_ROUTING", "]", "assert", "not", "result", "[", "ATTR_IS_SECURITYV1", "]", "assert", "result", "[", "ATTR_NODE_BASIC_STRING", "]", "==", "\"Routing Slave\"", "assert", "result", "[", "ATTR_NODE_GENERIC_STRING", "]", "==", "\"Binary Switch\"", "assert", "result", "[", "ATTR_NODE_SPECIFIC_STRING", "]", "==", "\"Binary Power Switch\"", "assert", "result", "[", "ATTR_NEIGHBORS", "]", "==", "[", "1", ",", "33", ",", "36", ",", "37", ",", "39", "]", "await", "client", ".", "send_json", "(", "{", "ID", ":", "7", ",", "TYPE", ":", "\"ozw/node_status\"", ",", "NODE_ID", ":", "999", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test node statistics", "await", "client", ".", "send_json", "(", "{", "ID", ":", "8", ",", "TYPE", ":", "\"ozw/node_statistics\"", ",", "NODE_ID", ":", "39", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "OZW_INSTANCE", "]", "==", "1", "assert", "result", "[", "NODE_ID", "]", "==", "39", "assert", "result", "[", "\"send_count\"", "]", "==", "57", "assert", "result", "[", "\"sent_failed\"", "]", "==", "0", "assert", "result", "[", "\"retries\"", "]", "==", "1", "assert", "result", "[", "\"last_request_rtt\"", "]", "==", "26", "assert", "result", "[", "\"last_response_rtt\"", "]", "==", "38", "assert", "result", "[", "\"average_request_rtt\"", "]", "==", "29", "assert", "result", "[", "\"average_response_rtt\"", "]", "==", "37", "assert", "result", "[", "\"received_packets\"", "]", "==", "3594", "assert", "result", "[", "\"received_dup_packets\"", "]", "==", "12", "assert", "result", "[", "\"received_unsolicited\"", "]", "==", "3546", "# Test node metadata", "await", "client", ".", "send_json", "(", "{", "ID", ":", "9", ",", "TYPE", ":", "\"ozw/node_metadata\"", ",", "NODE_ID", ":", "39", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "\"metadata\"", "]", "[", "\"ProductPic\"", "]", "==", "\"images/aeotec/zwa002.png\"", "await", "client", ".", "send_json", "(", "{", "ID", ":", "10", ",", "TYPE", ":", "\"ozw/node_metadata\"", ",", "NODE_ID", ":", "999", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test network statistics", "await", "client", ".", "send_json", "(", "{", "ID", ":", "11", ",", "TYPE", ":", "\"ozw/network_statistics\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "result", "[", "\"readCnt\"", "]", "==", "92220", "assert", "result", "[", "OZW_INSTANCE", "]", "==", "1", "assert", "result", "[", "\"node_count\"", "]", "==", "5", "# Test get nodes", "await", "client", ".", "send_json", "(", "{", "ID", ":", "12", ",", "TYPE", ":", "\"ozw/get_nodes\"", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "result", ")", "==", "5", "assert", "result", "[", "2", "]", "[", "ATTR_IS_AWAKE", "]", "assert", "not", "result", "[", "1", "]", "[", "ATTR_IS_FAILED", "]", "# Test get config parameters", "await", "client", ".", "send_json", "(", "{", "ID", ":", "13", ",", "TYPE", ":", "\"ozw/get_config_parameters\"", ",", "NODE_ID", ":", "39", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "result", ")", "==", "8", "for", "config_param", "in", "result", ":", "assert", "config_param", "[", "\"type\"", "]", "in", "(", "ValueType", ".", "LIST", ".", "value", ",", "ValueType", ".", "BOOL", ".", "value", ",", "ValueType", ".", "INT", ".", "value", ",", "ValueType", ".", "BYTE", ".", "value", ",", "ValueType", ".", "SHORT", ".", "value", ",", "ValueType", ".", "BITSET", ".", "value", ",", ")", "# Test set config parameter", "config_param", "=", "result", "[", "0", "]", "print", "(", "config_param", ")", "current_val", "=", "config_param", "[", "ATTR_VALUE", "]", "new_val", "=", "next", "(", "option", "[", "0", "]", "for", "option", "in", "config_param", "[", "SCHEMA", "]", "[", "0", "]", "[", "ATTR_OPTIONS", "]", "if", "option", "[", "0", "]", "!=", "current_val", ")", "new_label", "=", "next", "(", "option", "[", "1", "]", "for", "option", "in", "config_param", "[", "SCHEMA", "]", "[", "0", "]", "[", "ATTR_OPTIONS", "]", "if", "option", "[", "1", "]", "!=", "current_val", "and", "option", "[", "0", "]", "!=", "new_val", ")", "await", "client", ".", "send_json", "(", "{", "ID", ":", "14", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "config_param", "[", "ATTR_CONFIG_PARAMETER", "]", ",", "VALUE", ":", "new_val", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "ID", ":", "15", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "config_param", "[", "ATTR_CONFIG_PARAMETER", "]", ",", "VALUE", ":", "new_label", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"success\"", "]", "# Test OZW Instance not found error", "await", "client", ".", "send_json", "(", "{", "ID", ":", "16", ",", "TYPE", ":", "\"ozw/get_config_parameters\"", ",", "OZW_INSTANCE", ":", "999", ",", "NODE_ID", ":", "1", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test OZW Node not found error", "await", "client", ".", "send_json", "(", "{", "ID", ":", "18", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "999", ",", "PARAMETER", ":", "0", ",", "VALUE", ":", "\"test\"", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test parameter not found", "await", "client", ".", "send_json", "(", "{", "ID", ":", "19", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "45", ",", "VALUE", ":", "\"test\"", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test list value not found", "await", "client", ".", "send_json", "(", "{", "ID", ":", "20", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "config_param", "[", "ATTR_CONFIG_PARAMETER", "]", ",", "VALUE", ":", "\"test\"", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND", "# Test value type invalid", "await", "client", ".", "send_json", "(", "{", "ID", ":", "21", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "3", ",", "VALUE", ":", "0", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_SUPPORTED", "# Test invalid bitset format", "await", "client", ".", "send_json", "(", "{", "ID", ":", "22", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "3", ",", "VALUE", ":", "{", "ATTR_POSITION", ":", "1", ",", "ATTR_VALUE", ":", "True", ",", "ATTR_LABEL", ":", "\"test\"", "}", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_INVALID_FORMAT", "# Test valid bitset format passes validation", "await", "client", ".", "send_json", "(", "{", "ID", ":", "23", ",", "TYPE", ":", "\"ozw/set_config_parameter\"", ",", "NODE_ID", ":", "39", ",", "PARAMETER", ":", "10000", ",", "VALUE", ":", "{", "ATTR_POSITION", ":", "1", ",", "ATTR_VALUE", ":", "True", "}", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"error\"", "]", "assert", "result", "[", "\"code\"", "]", "==", "ERR_NOT_FOUND" ]
[ 45, 0 ]
[ 280, 42 ]
python
en
['en', 'hu', 'it']
False
test_ws_locks
(hass, lock_data, hass_ws_client)
Test lock websocket apis.
Test lock websocket apis.
async def test_ws_locks(hass, lock_data, hass_ws_client): """Test lock websocket apis.""" await setup_ozw(hass, fixture=lock_data) client = await hass_ws_client(hass) await client.send_json( { ID: 1, TYPE: "ozw/get_code_slots", NODE_ID: 10, } ) msg = await client.receive_json() assert msg["success"] await client.send_json( { ID: 2, TYPE: "ozw/set_usercode", NODE_ID: 10, ATTR_CODE_SLOT: 1, ATTR_USERCODE: "1234", } ) msg = await client.receive_json() assert msg["success"] await client.send_json( { ID: 3, TYPE: "ozw/clear_usercode", NODE_ID: 10, ATTR_CODE_SLOT: 1, } ) msg = await client.receive_json() assert msg["success"]
[ "async", "def", "test_ws_locks", "(", "hass", ",", "lock_data", ",", "hass_ws_client", ")", ":", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "lock_data", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "ID", ":", "1", ",", "TYPE", ":", "\"ozw/get_code_slots\"", ",", "NODE_ID", ":", "10", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "ID", ":", "2", ",", "TYPE", ":", "\"ozw/set_usercode\"", ",", "NODE_ID", ":", "10", ",", "ATTR_CODE_SLOT", ":", "1", ",", "ATTR_USERCODE", ":", "\"1234\"", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "ID", ":", "3", ",", "TYPE", ":", "\"ozw/clear_usercode\"", ",", "NODE_ID", ":", "10", ",", "ATTR_CODE_SLOT", ":", "1", ",", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"success\"", "]" ]
[ 283, 0 ]
[ 319, 25 ]
python
en
['en', 'fy', 'en']
True
test_refresh_node
(hass, generic_data, sent_messages, hass_ws_client)
Test the ozw refresh node api.
Test the ozw refresh node api.
async def test_refresh_node(hass, generic_data, sent_messages, hass_ws_client): """Test the ozw refresh node api.""" receive_message = await setup_ozw(hass, fixture=generic_data) client = await hass_ws_client(hass) # Send the refresh_node_info command await client.send_json({ID: 9, TYPE: "ozw/refresh_node_info", NODE_ID: 39}) msg = await client.receive_json() assert len(sent_messages) == 1 assert msg["success"] # Receive a mock status update from OZW message = MQTTMessage( topic="OpenZWave/1/node/39/", payload={"NodeID": 39, "NodeQueryStage": "initializing"}, ) message.encode() receive_message(message) # Verify we got expected data on the websocket msg = await client.receive_json() result = msg["event"] assert result["type"] == "node_updated" assert result["node_query_stage"] == "initializing" # Send another mock status update from OZW message = MQTTMessage( topic="OpenZWave/1/node/39/", payload={"NodeID": 39, "NodeQueryStage": "versions"}, ) message.encode() receive_message(message) # Send a mock status update for a different node message = MQTTMessage( topic="OpenZWave/1/node/35/", payload={"NodeID": 35, "NodeQueryStage": "fake_shouldnt_be_received"}, ) message.encode() receive_message(message) # Verify we received the message for node 39 but not for node 35 msg = await client.receive_json() result = msg["event"] assert result["type"] == "node_updated" assert result["node_query_stage"] == "versions"
[ "async", "def", "test_refresh_node", "(", "hass", ",", "generic_data", ",", "sent_messages", ",", "hass_ws_client", ")", ":", "receive_message", "=", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "generic_data", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "# Send the refresh_node_info command", "await", "client", ".", "send_json", "(", "{", "ID", ":", "9", ",", "TYPE", ":", "\"ozw/refresh_node_info\"", ",", "NODE_ID", ":", "39", "}", ")", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "len", "(", "sent_messages", ")", "==", "1", "assert", "msg", "[", "\"success\"", "]", "# Receive a mock status update from OZW", "message", "=", "MQTTMessage", "(", "topic", "=", "\"OpenZWave/1/node/39/\"", ",", "payload", "=", "{", "\"NodeID\"", ":", "39", ",", "\"NodeQueryStage\"", ":", "\"initializing\"", "}", ",", ")", "message", ".", "encode", "(", ")", "receive_message", "(", "message", ")", "# Verify we got expected data on the websocket", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"event\"", "]", "assert", "result", "[", "\"type\"", "]", "==", "\"node_updated\"", "assert", "result", "[", "\"node_query_stage\"", "]", "==", "\"initializing\"", "# Send another mock status update from OZW", "message", "=", "MQTTMessage", "(", "topic", "=", "\"OpenZWave/1/node/39/\"", ",", "payload", "=", "{", "\"NodeID\"", ":", "39", ",", "\"NodeQueryStage\"", ":", "\"versions\"", "}", ",", ")", "message", ".", "encode", "(", ")", "receive_message", "(", "message", ")", "# Send a mock status update for a different node", "message", "=", "MQTTMessage", "(", "topic", "=", "\"OpenZWave/1/node/35/\"", ",", "payload", "=", "{", "\"NodeID\"", ":", "35", ",", "\"NodeQueryStage\"", ":", "\"fake_shouldnt_be_received\"", "}", ",", ")", "message", ".", "encode", "(", ")", "receive_message", "(", "message", ")", "# Verify we received the message for node 39 but not for node 35", "msg", "=", "await", "client", ".", "receive_json", "(", ")", "result", "=", "msg", "[", "\"event\"", "]", "assert", "result", "[", "\"type\"", "]", "==", "\"node_updated\"", "assert", "result", "[", "\"node_query_stage\"", "]", "==", "\"versions\"" ]
[ 322, 0 ]
[ 368, 51 ]
python
en
['en', 'pt', 'en']
True
test_refresh_node_unsubscribe
(hass, generic_data, hass_ws_client)
Test unsubscribing the ozw refresh node api.
Test unsubscribing the ozw refresh node api.
async def test_refresh_node_unsubscribe(hass, generic_data, hass_ws_client): """Test unsubscribing the ozw refresh node api.""" await setup_ozw(hass, fixture=generic_data) client = await hass_ws_client(hass) with patch("openzwavemqtt.OZWOptions.listen") as mock_listen: # Send the refresh_node_info command await client.send_json({ID: 9, TYPE: "ozw/refresh_node_info", NODE_ID: 39}) await client.receive_json() # Send the unsubscribe command await client.send_json({ID: 10, TYPE: "unsubscribe_events", "subscription": 9}) await client.receive_json() assert mock_listen.return_value.called
[ "async", "def", "test_refresh_node_unsubscribe", "(", "hass", ",", "generic_data", ",", "hass_ws_client", ")", ":", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "generic_data", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "with", "patch", "(", "\"openzwavemqtt.OZWOptions.listen\"", ")", "as", "mock_listen", ":", "# Send the refresh_node_info command", "await", "client", ".", "send_json", "(", "{", "ID", ":", "9", ",", "TYPE", ":", "\"ozw/refresh_node_info\"", ",", "NODE_ID", ":", "39", "}", ")", "await", "client", ".", "receive_json", "(", ")", "# Send the unsubscribe command", "await", "client", ".", "send_json", "(", "{", "ID", ":", "10", ",", "TYPE", ":", "\"unsubscribe_events\"", ",", "\"subscription\"", ":", "9", "}", ")", "await", "client", ".", "receive_json", "(", ")", "assert", "mock_listen", ".", "return_value", ".", "called" ]
[ 371, 0 ]
[ 385, 46 ]
python
en
['en', 'en', 'en']
True
mock_bridge_fixture
()
Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.
Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.
def mock_bridge_fixture() -> Generator[None, Any, None]: """Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.""" queue = Queue() async def mock_queue(): """Mock asyncio's Queue.""" await queue.put(MockSwitcherV2Device()) return await queue.get() mock_bridge = AsyncMock() patchers = [ patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.start", new=mock_bridge, ), patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.stop", new=mock_bridge, ), patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.queue", get=mock_queue, ), patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.running", return_value=True, ), ] for patcher in patchers: patcher.start() yield for patcher in patchers: patcher.stop()
[ "def", "mock_bridge_fixture", "(", ")", "->", "Generator", "[", "None", ",", "Any", ",", "None", "]", ":", "queue", "=", "Queue", "(", ")", "async", "def", "mock_queue", "(", ")", ":", "\"\"\"Mock asyncio's Queue.\"\"\"", "await", "queue", ".", "put", "(", "MockSwitcherV2Device", "(", ")", ")", "return", "await", "queue", ".", "get", "(", ")", "mock_bridge", "=", "AsyncMock", "(", ")", "patchers", "=", "[", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.start\"", ",", "new", "=", "mock_bridge", ",", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.stop\"", ",", "new", "=", "mock_bridge", ",", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.queue\"", ",", "get", "=", "mock_queue", ",", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.running\"", ",", "return_value", "=", "True", ",", ")", ",", "]", "for", "patcher", "in", "patchers", ":", "patcher", ".", "start", "(", ")", "yield", "for", "patcher", "in", "patchers", ":", "patcher", ".", "stop", "(", ")" ]
[ 94, 0 ]
[ 130, 22 ]
python
en
['en', 'sr', 'en']
True
mock_failed_bridge_fixture
()
Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.
Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.
def mock_failed_bridge_fixture() -> Generator[None, Any, None]: """Fixture for mocking aioswitcher.bridge.SwitcherV2Bridge.""" async def mock_queue(): """Mock asyncio's Queue.""" raise RuntimeError patchers = [ patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.start", return_value=None, ), patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.stop", return_value=None, ), patch( "homeassistant.components.switcher_kis.SwitcherV2Bridge.queue", get=mock_queue, ), ] for patcher in patchers: patcher.start() yield for patcher in patchers: patcher.stop()
[ "def", "mock_failed_bridge_fixture", "(", ")", "->", "Generator", "[", "None", ",", "Any", ",", "None", "]", ":", "async", "def", "mock_queue", "(", ")", ":", "\"\"\"Mock asyncio's Queue.\"\"\"", "raise", "RuntimeError", "patchers", "=", "[", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.start\"", ",", "return_value", "=", "None", ",", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.stop\"", ",", "return_value", "=", "None", ",", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Bridge.queue\"", ",", "get", "=", "mock_queue", ",", ")", ",", "]", "for", "patcher", "in", "patchers", ":", "patcher", ".", "start", "(", ")", "yield", "for", "patcher", "in", "patchers", ":", "patcher", ".", "stop", "(", ")" ]
[ 134, 0 ]
[ 162, 22 ]
python
en
['en', 'sr', 'en']
True
mock_api_fixture
()
Fixture for mocking aioswitcher.api.SwitcherV2Api.
Fixture for mocking aioswitcher.api.SwitcherV2Api.
def mock_api_fixture() -> Generator[AsyncMock, Any, None]: """Fixture for mocking aioswitcher.api.SwitcherV2Api.""" mock_api = AsyncMock() patchers = [ patch( "homeassistant.components.switcher_kis.SwitcherV2Api.connect", new=mock_api ), patch( "homeassistant.components.switcher_kis.SwitcherV2Api.disconnect", new=mock_api, ), ] for patcher in patchers: patcher.start() yield for patcher in patchers: patcher.stop()
[ "def", "mock_api_fixture", "(", ")", "->", "Generator", "[", "AsyncMock", ",", "Any", ",", "None", "]", ":", "mock_api", "=", "AsyncMock", "(", ")", "patchers", "=", "[", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Api.connect\"", ",", "new", "=", "mock_api", ")", ",", "patch", "(", "\"homeassistant.components.switcher_kis.SwitcherV2Api.disconnect\"", ",", "new", "=", "mock_api", ",", ")", ",", "]", "for", "patcher", "in", "patchers", ":", "patcher", ".", "start", "(", ")", "yield", "for", "patcher", "in", "patchers", ":", "patcher", ".", "stop", "(", ")" ]
[ 166, 0 ]
[ 186, 22 ]
python
en
['en', 'pl', 'en']
True
entropy
(x)
Calculate entropy of a pre-softmax logit Tensor
Calculate entropy of a pre-softmax logit Tensor
def entropy(x): """Calculate entropy of a pre-softmax logit Tensor""" exp_x = torch.exp(x) A = torch.sum(exp_x, dim=1) # sum of exp(x_i) B = torch.sum(x * exp_x, dim=1) # sum of x_i * exp(x_i) return torch.log(A) - B / A
[ "def", "entropy", "(", "x", ")", ":", "exp_x", "=", "torch", ".", "exp", "(", "x", ")", "A", "=", "torch", ".", "sum", "(", "exp_x", ",", "dim", "=", "1", ")", "# sum of exp(x_i)", "B", "=", "torch", ".", "sum", "(", "x", "*", "exp_x", ",", "dim", "=", "1", ")", "# sum of x_i * exp(x_i)", "return", "torch", ".", "log", "(", "A", ")", "-", "B", "/", "A" ]
[ 15, 0 ]
[ 20, 31 ]
python
en
['en', 'en', 'en']
True
SuperNetBuilder.__call__
(self, in_chs, model_block_args)
Build the blocks Args: in_chs: Number of input-channels passed to first block model_block_args: A list of lists, outer list defines stages, inner list contains strings defining block configuration(s) Return: List of block stacks (each stack wrapped in nn.Sequential)
Build the blocks Args: in_chs: Number of input-channels passed to first block model_block_args: A list of lists, outer list defines stages, inner list contains strings defining block configuration(s) Return: List of block stacks (each stack wrapped in nn.Sequential)
def __call__(self, in_chs, model_block_args): """ Build the blocks Args: in_chs: Number of input-channels passed to first block model_block_args: A list of lists, outer list defines stages, inner list contains strings defining block configuration(s) Return: List of block stacks (each stack wrapped in nn.Sequential) """ if self.verbose: logging.info('Building model trunk with %d stages...' % len(model_block_args)) self.in_chs = in_chs total_block_count = sum([len(x) for x in model_block_args]) total_block_idx = 0 current_stride = 2 current_dilation = 1 feature_idx = 0 stages = [] # outer list of block_args defines the stacks ('stages' by some conventions) for stage_idx, stage_block_args in enumerate(model_block_args): last_stack = stage_idx == (len(model_block_args) - 1) if self.verbose: self.logger.info('Stack: {}'.format(stage_idx)) assert isinstance(stage_block_args, list) # blocks = [] # each stack (stage) contains a list of block arguments for block_idx, block_args in enumerate(stage_block_args): last_block = block_idx == (len(stage_block_args) - 1) if self.verbose: self.logger.info(' Block: {}'.format(block_idx)) # Sort out stride, dilation, and feature extraction details assert block_args['stride'] in (1, 2) if block_idx >= 1: # only the first block in any stack can have a stride > 1 block_args['stride'] = 1 next_dilation = current_dilation if block_args['stride'] > 1: next_output_stride = current_stride * block_args['stride'] if next_output_stride > self.output_stride: next_dilation = current_dilation * block_args['stride'] block_args['stride'] = 1 else: current_stride = next_output_stride block_args['dilation'] = current_dilation if next_dilation != current_dilation: current_dilation = next_dilation if stage_idx==0 or stage_idx==6: self.choice_num = 1 else: self.choice_num = len(self.choices) if self.dil_conv: self.choice_num += 2 choice_blocks = [] block_args_copy = deepcopy(block_args) if self.choice_num == 1: # create the block block = self._make_block(block_args, 0, total_block_idx, total_block_count) choice_blocks.append(block) else: for choice_idx, choice in enumerate(self.choices): # create the block block_args = deepcopy(block_args_copy) block_args = modify_block_args(block_args, choice[0], choice[1]) block = self._make_block(block_args, choice_idx, total_block_idx, total_block_count) choice_blocks.append(block) if self.dil_conv: block_args = deepcopy(block_args_copy) block_args = modify_block_args(block_args, 3, 0) block = self._make_block(block_args, self.choice_num - 2, total_block_idx, total_block_count, resunit=self.resunit, dil_conv=self.dil_conv) choice_blocks.append(block) block_args = deepcopy(block_args_copy) block_args = modify_block_args(block_args, 5, 0) block = self._make_block(block_args, self.choice_num - 1, total_block_idx, total_block_count, resunit=self.resunit, dil_conv=self.dil_conv) choice_blocks.append(block) if self.resunit: block = get_Bottleneck(block.conv_pw.in_channels, block.conv_pwl.out_channels, block.conv_dw.stride[0]) choice_blocks.append(block) choice_block = mutables.LayerChoice(choice_blocks) stages.append(choice_block) # create the block # block = self._make_block(block_args, total_block_idx, total_block_count) total_block_idx += 1 # incr global block idx (across all stacks) # stages.append(blocks) return stages
[ "def", "__call__", "(", "self", ",", "in_chs", ",", "model_block_args", ")", ":", "if", "self", ".", "verbose", ":", "logging", ".", "info", "(", "'Building model trunk with %d stages...'", "%", "len", "(", "model_block_args", ")", ")", "self", ".", "in_chs", "=", "in_chs", "total_block_count", "=", "sum", "(", "[", "len", "(", "x", ")", "for", "x", "in", "model_block_args", "]", ")", "total_block_idx", "=", "0", "current_stride", "=", "2", "current_dilation", "=", "1", "feature_idx", "=", "0", "stages", "=", "[", "]", "# outer list of block_args defines the stacks ('stages' by some conventions)", "for", "stage_idx", ",", "stage_block_args", "in", "enumerate", "(", "model_block_args", ")", ":", "last_stack", "=", "stage_idx", "==", "(", "len", "(", "model_block_args", ")", "-", "1", ")", "if", "self", ".", "verbose", ":", "self", ".", "logger", ".", "info", "(", "'Stack: {}'", ".", "format", "(", "stage_idx", ")", ")", "assert", "isinstance", "(", "stage_block_args", ",", "list", ")", "# blocks = []", "# each stack (stage) contains a list of block arguments", "for", "block_idx", ",", "block_args", "in", "enumerate", "(", "stage_block_args", ")", ":", "last_block", "=", "block_idx", "==", "(", "len", "(", "stage_block_args", ")", "-", "1", ")", "if", "self", ".", "verbose", ":", "self", ".", "logger", ".", "info", "(", "' Block: {}'", ".", "format", "(", "block_idx", ")", ")", "# Sort out stride, dilation, and feature extraction details", "assert", "block_args", "[", "'stride'", "]", "in", "(", "1", ",", "2", ")", "if", "block_idx", ">=", "1", ":", "# only the first block in any stack can have a stride > 1", "block_args", "[", "'stride'", "]", "=", "1", "next_dilation", "=", "current_dilation", "if", "block_args", "[", "'stride'", "]", ">", "1", ":", "next_output_stride", "=", "current_stride", "*", "block_args", "[", "'stride'", "]", "if", "next_output_stride", ">", "self", ".", "output_stride", ":", "next_dilation", "=", "current_dilation", "*", "block_args", "[", "'stride'", "]", "block_args", "[", "'stride'", "]", "=", "1", "else", ":", "current_stride", "=", "next_output_stride", "block_args", "[", "'dilation'", "]", "=", "current_dilation", "if", "next_dilation", "!=", "current_dilation", ":", "current_dilation", "=", "next_dilation", "if", "stage_idx", "==", "0", "or", "stage_idx", "==", "6", ":", "self", ".", "choice_num", "=", "1", "else", ":", "self", ".", "choice_num", "=", "len", "(", "self", ".", "choices", ")", "if", "self", ".", "dil_conv", ":", "self", ".", "choice_num", "+=", "2", "choice_blocks", "=", "[", "]", "block_args_copy", "=", "deepcopy", "(", "block_args", ")", "if", "self", ".", "choice_num", "==", "1", ":", "# create the block", "block", "=", "self", ".", "_make_block", "(", "block_args", ",", "0", ",", "total_block_idx", ",", "total_block_count", ")", "choice_blocks", ".", "append", "(", "block", ")", "else", ":", "for", "choice_idx", ",", "choice", "in", "enumerate", "(", "self", ".", "choices", ")", ":", "# create the block", "block_args", "=", "deepcopy", "(", "block_args_copy", ")", "block_args", "=", "modify_block_args", "(", "block_args", ",", "choice", "[", "0", "]", ",", "choice", "[", "1", "]", ")", "block", "=", "self", ".", "_make_block", "(", "block_args", ",", "choice_idx", ",", "total_block_idx", ",", "total_block_count", ")", "choice_blocks", ".", "append", "(", "block", ")", "if", "self", ".", "dil_conv", ":", "block_args", "=", "deepcopy", "(", "block_args_copy", ")", "block_args", "=", "modify_block_args", "(", "block_args", ",", "3", ",", "0", ")", "block", "=", "self", ".", "_make_block", "(", "block_args", ",", "self", ".", "choice_num", "-", "2", ",", "total_block_idx", ",", "total_block_count", ",", "resunit", "=", "self", ".", "resunit", ",", "dil_conv", "=", "self", ".", "dil_conv", ")", "choice_blocks", ".", "append", "(", "block", ")", "block_args", "=", "deepcopy", "(", "block_args_copy", ")", "block_args", "=", "modify_block_args", "(", "block_args", ",", "5", ",", "0", ")", "block", "=", "self", ".", "_make_block", "(", "block_args", ",", "self", ".", "choice_num", "-", "1", ",", "total_block_idx", ",", "total_block_count", ",", "resunit", "=", "self", ".", "resunit", ",", "dil_conv", "=", "self", ".", "dil_conv", ")", "choice_blocks", ".", "append", "(", "block", ")", "if", "self", ".", "resunit", ":", "block", "=", "get_Bottleneck", "(", "block", ".", "conv_pw", ".", "in_channels", ",", "block", ".", "conv_pwl", ".", "out_channels", ",", "block", ".", "conv_dw", ".", "stride", "[", "0", "]", ")", "choice_blocks", ".", "append", "(", "block", ")", "choice_block", "=", "mutables", ".", "LayerChoice", "(", "choice_blocks", ")", "stages", ".", "append", "(", "choice_block", ")", "# create the block", "# block = self._make_block(block_args, total_block_idx, total_block_count)", "total_block_idx", "+=", "1", "# incr global block idx (across all stacks)", "# stages.append(blocks)", "return", "stages" ]
[ 115, 4 ]
[ 213, 21 ]
python
en
['en', 'la', 'en']
True
async_setup
(hass, config)
Set up the Unify Circuit component.
Set up the Unify Circuit component.
async def async_setup(hass, config): """Set up the Unify Circuit component.""" webhooks = config[DOMAIN][CONF_WEBHOOK] for webhook_conf in webhooks: hass.async_create_task( discovery.async_load_platform(hass, "notify", DOMAIN, webhook_conf, config) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "webhooks", "=", "config", "[", "DOMAIN", "]", "[", "CONF_WEBHOOK", "]", "for", "webhook_conf", "in", "webhooks", ":", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "\"notify\"", ",", "DOMAIN", ",", "webhook_conf", ",", "config", ")", ")", "return", "True" ]
[ 23, 0 ]
[ 32, 15 ]
python
en
['en', 'en', 'en']
True
merge_versions
(old: OurVersionJSON, new: OurVersionJSON)
Copies already-known hashes from version.json to avoid having to re-fetch.
Copies already-known hashes from version.json to avoid having to re-fetch.
def merge_versions(old: OurVersionJSON, new: OurVersionJSON) -> OurVersionJSON: """Copies already-known hashes from version.json to avoid having to re-fetch.""" def _merge_version(system_name: str, release_type_name: str, release_channel_name: str, release: Dict[str, str]) -> Dict[str, str]: old_system = old.get(system_name, {}) old_release_type = old_system.get(release_type_name, {}) old_release = old_release_type.get(release_channel_name, {}) if not "sha256" in old_release: logging.info("%s/%s/%s: not copying sha256 since it's missing", system_name, release_type_name, release_channel_name) return release if not all(old_release.get(k, None) == release[k] for k in ['name', 'version', 'url']): logging.info("%s/%s/%s: not copying sha256 due to mismatch", system_name, release_type_name, release_channel_name) return release release["sha256"] = old_release["sha256"] return release return iter_version(new, _merge_version)
[ "def", "merge_versions", "(", "old", ":", "OurVersionJSON", ",", "new", ":", "OurVersionJSON", ")", "->", "OurVersionJSON", ":", "def", "_merge_version", "(", "system_name", ":", "str", ",", "release_type_name", ":", "str", ",", "release_channel_name", ":", "str", ",", "release", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "old_system", "=", "old", ".", "get", "(", "system_name", ",", "{", "}", ")", "old_release_type", "=", "old_system", ".", "get", "(", "release_type_name", ",", "{", "}", ")", "old_release", "=", "old_release_type", ".", "get", "(", "release_channel_name", ",", "{", "}", ")", "if", "not", "\"sha256\"", "in", "old_release", ":", "logging", ".", "info", "(", "\"%s/%s/%s: not copying sha256 since it's missing\"", ",", "system_name", ",", "release_type_name", ",", "release_channel_name", ")", "return", "release", "if", "not", "all", "(", "old_release", ".", "get", "(", "k", ",", "None", ")", "==", "release", "[", "k", "]", "for", "k", "in", "[", "'name'", ",", "'version'", ",", "'url'", "]", ")", ":", "logging", ".", "info", "(", "\"%s/%s/%s: not copying sha256 due to mismatch\"", ",", "system_name", ",", "release_type_name", ",", "release_channel_name", ")", "return", "release", "release", "[", "\"sha256\"", "]", "=", "old_release", "[", "\"sha256\"", "]", "return", "release", "return", "iter_version", "(", "new", ",", "_merge_version", ")" ]
[ 112, 0 ]
[ 126, 44 ]
python
en
['en', 'en', 'en']
True
fill_in_hash
(versions: OurVersionJSON)
Fill in sha256 hashes for anything missing them.
Fill in sha256 hashes for anything missing them.
def fill_in_hash(versions: OurVersionJSON) -> OurVersionJSON: """Fill in sha256 hashes for anything missing them.""" urls_to_hash = {} def _fill_in_hash(system_name: str, release_type_name: str, release_channel_name: str, release: Dict[str, str]) -> Dict[str, str]: if "sha256" in release: logging.info("%s/%s/%s: skipping fetch, sha256 already present", system_name, release_type_name, release_channel_name) return release url = release["url"] if url in urls_to_hash: logging.info("%s/%s/%s: found url %s in cache", system_name, release_type_name, release_channel_name, url) release["sha256"] = urls_to_hash[url] return release logging.info("%s/%s/%s: fetching %s", system_name, release_type_name, release_channel_name, url) if release["needsAuth"]: if not FLAGS.username or not FLAGS.token: raise Exception("fetching %s/%s/%s from %s requires --username and --token" % (system_name, release_type_name, release_channel_name, url)) url += f"?username={FLAGS.username}&token={FLAGS.token}" release["sha256"] = nix_prefetch_url(release["name"], url) urls_to_hash[url] = release["sha256"] return release return iter_version(versions, _fill_in_hash)
[ "def", "fill_in_hash", "(", "versions", ":", "OurVersionJSON", ")", "->", "OurVersionJSON", ":", "urls_to_hash", "=", "{", "}", "def", "_fill_in_hash", "(", "system_name", ":", "str", ",", "release_type_name", ":", "str", ",", "release_channel_name", ":", "str", ",", "release", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "if", "\"sha256\"", "in", "release", ":", "logging", ".", "info", "(", "\"%s/%s/%s: skipping fetch, sha256 already present\"", ",", "system_name", ",", "release_type_name", ",", "release_channel_name", ")", "return", "release", "url", "=", "release", "[", "\"url\"", "]", "if", "url", "in", "urls_to_hash", ":", "logging", ".", "info", "(", "\"%s/%s/%s: found url %s in cache\"", ",", "system_name", ",", "release_type_name", ",", "release_channel_name", ",", "url", ")", "release", "[", "\"sha256\"", "]", "=", "urls_to_hash", "[", "url", "]", "return", "release", "logging", ".", "info", "(", "\"%s/%s/%s: fetching %s\"", ",", "system_name", ",", "release_type_name", ",", "release_channel_name", ",", "url", ")", "if", "release", "[", "\"needsAuth\"", "]", ":", "if", "not", "FLAGS", ".", "username", "or", "not", "FLAGS", ".", "token", ":", "raise", "Exception", "(", "\"fetching %s/%s/%s from %s requires --username and --token\"", "%", "(", "system_name", ",", "release_type_name", ",", "release_channel_name", ",", "url", ")", ")", "url", "+=", "f\"?username={FLAGS.username}&token={FLAGS.token}\"", "release", "[", "\"sha256\"", "]", "=", "nix_prefetch_url", "(", "release", "[", "\"name\"", "]", ",", "url", ")", "urls_to_hash", "[", "url", "]", "=", "release", "[", "\"sha256\"", "]", "return", "release", "return", "iter_version", "(", "versions", ",", "_fill_in_hash", ")" ]
[ 136, 0 ]
[ 156, 48 ]
python
en
['en', 'en', 'en']
True
create_thermostat_service
(accessory)
Define thermostat characteristics.
Define thermostat characteristics.
def create_thermostat_service(accessory): """Define thermostat characteristics.""" service = accessory.add_service(ServicesTypes.THERMOSTAT) char = service.add_char(CharacteristicsTypes.HEATING_COOLING_TARGET) char.value = 0 char = service.add_char(CharacteristicsTypes.HEATING_COOLING_CURRENT) char.value = 0 char = service.add_char(CharacteristicsTypes.TEMPERATURE_TARGET) char.minValue = 7 char.maxValue = 35 char.value = 0 char = service.add_char(CharacteristicsTypes.TEMPERATURE_CURRENT) char.value = 0 char = service.add_char(CharacteristicsTypes.RELATIVE_HUMIDITY_TARGET) char.value = 0 char = service.add_char(CharacteristicsTypes.RELATIVE_HUMIDITY_CURRENT) char.value = 0
[ "def", "create_thermostat_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "THERMOSTAT", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HEATING_COOLING_TARGET", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HEATING_COOLING_CURRENT", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TEMPERATURE_TARGET", ")", "char", ".", "minValue", "=", "7", "char", ".", "maxValue", "=", "35", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TEMPERATURE_CURRENT", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "RELATIVE_HUMIDITY_TARGET", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "RELATIVE_HUMIDITY_CURRENT", ")", "char", ".", "value", "=", "0" ]
[ 34, 0 ]
[ 56, 18 ]
python
en
['en', 'mt', 'en']
True
create_thermostat_service_min_max
(accessory)
Define thermostat characteristics.
Define thermostat characteristics.
def create_thermostat_service_min_max(accessory): """Define thermostat characteristics.""" service = accessory.add_service(ServicesTypes.THERMOSTAT) char = service.add_char(CharacteristicsTypes.HEATING_COOLING_TARGET) char.value = 0 char.minValue = 0 char.maxValue = 1
[ "def", "create_thermostat_service_min_max", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "THERMOSTAT", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HEATING_COOLING_TARGET", ")", "char", ".", "value", "=", "0", "char", ".", "minValue", "=", "0", "char", ".", "maxValue", "=", "1" ]
[ 59, 0 ]
[ 65, 21 ]
python
en
['en', 'mt', 'en']
True
test_climate_respect_supported_op_modes_1
(hass, utcnow)
Test that climate respects minValue/maxValue hints.
Test that climate respects minValue/maxValue hints.
async def test_climate_respect_supported_op_modes_1(hass, utcnow): """Test that climate respects minValue/maxValue hints.""" helper = await setup_test_component(hass, create_thermostat_service_min_max) state = await helper.poll_and_get_state() assert state.attributes["hvac_modes"] == ["off", "heat"]
[ "async", "def", "test_climate_respect_supported_op_modes_1", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service_min_max", ")", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"hvac_modes\"", "]", "==", "[", "\"off\"", ",", "\"heat\"", "]" ]
[ 68, 0 ]
[ 72, 60 ]
python
en
['en', 'en', 'en']
True
create_thermostat_service_valid_vals
(accessory)
Define thermostat characteristics.
Define thermostat characteristics.
def create_thermostat_service_valid_vals(accessory): """Define thermostat characteristics.""" service = accessory.add_service(ServicesTypes.THERMOSTAT) char = service.add_char(CharacteristicsTypes.HEATING_COOLING_TARGET) char.value = 0 char.valid_values = [0, 1, 2]
[ "def", "create_thermostat_service_valid_vals", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "THERMOSTAT", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HEATING_COOLING_TARGET", ")", "char", ".", "value", "=", "0", "char", ".", "valid_values", "=", "[", "0", ",", "1", ",", "2", "]" ]
[ 75, 0 ]
[ 80, 33 ]
python
en
['en', 'mt', 'en']
True
test_climate_respect_supported_op_modes_2
(hass, utcnow)
Test that climate respects validValue hints.
Test that climate respects validValue hints.
async def test_climate_respect_supported_op_modes_2(hass, utcnow): """Test that climate respects validValue hints.""" helper = await setup_test_component(hass, create_thermostat_service_valid_vals) state = await helper.poll_and_get_state() assert state.attributes["hvac_modes"] == ["off", "heat", "cool"]
[ "async", "def", "test_climate_respect_supported_op_modes_2", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service_valid_vals", ")", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"hvac_modes\"", "]", "==", "[", "\"off\"", ",", "\"heat\"", ",", "\"cool\"", "]" ]
[ 83, 0 ]
[ 87, 68 ]
python
en
['en', 'en', 'en']
True
test_climate_change_thermostat_state
(hass, utcnow)
Test that we can turn a HomeKit thermostat on and off again.
Test that we can turn a HomeKit thermostat on and off again.
async def test_climate_change_thermostat_state(hass, utcnow): """Test that we can turn a HomeKit thermostat on and off again.""" helper = await setup_test_component(hass, create_thermostat_service) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_HEAT}, blocking=True, ) assert helper.characteristics[HEATING_COOLING_TARGET].value == 1 await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_COOL}, blocking=True, ) assert helper.characteristics[HEATING_COOLING_TARGET].value == 2 await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_HEAT_COOL}, blocking=True, ) assert helper.characteristics[HEATING_COOLING_TARGET].value == 3 await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_OFF}, blocking=True, ) assert helper.characteristics[HEATING_COOLING_TARGET].value == 0
[ "async", "def", "test_climate_change_thermostat_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_HEAT", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "==", "1", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_COOL", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "==", "2", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_HEAT_COOL", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "==", "3", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_OFF", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "==", "0" ]
[ 90, 0 ]
[ 125, 68 ]
python
en
['en', 'en', 'en']
True
test_climate_change_thermostat_temperature
(hass, utcnow)
Test that we can turn a HomeKit thermostat on and off again.
Test that we can turn a HomeKit thermostat on and off again.
async def test_climate_change_thermostat_temperature(hass, utcnow): """Test that we can turn a HomeKit thermostat on and off again.""" helper = await setup_test_component(hass, create_thermostat_service) await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, {"entity_id": "climate.testdevice", "temperature": 21}, blocking=True, ) assert helper.characteristics[TEMPERATURE_TARGET].value == 21 await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, {"entity_id": "climate.testdevice", "temperature": 25}, blocking=True, ) assert helper.characteristics[TEMPERATURE_TARGET].value == 25
[ "async", "def", "test_climate_change_thermostat_temperature", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_TEMPERATURE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"temperature\"", ":", "21", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "==", "21", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_TEMPERATURE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"temperature\"", ":", "25", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "==", "25" ]
[ 128, 0 ]
[ 146, 65 ]
python
en
['en', 'en', 'en']
True
test_climate_change_thermostat_humidity
(hass, utcnow)
Test that we can turn a HomeKit thermostat on and off again.
Test that we can turn a HomeKit thermostat on and off again.
async def test_climate_change_thermostat_humidity(hass, utcnow): """Test that we can turn a HomeKit thermostat on and off again.""" helper = await setup_test_component(hass, create_thermostat_service) await hass.services.async_call( DOMAIN, SERVICE_SET_HUMIDITY, {"entity_id": "climate.testdevice", "humidity": 50}, blocking=True, ) assert helper.characteristics[HUMIDITY_TARGET].value == 50 await hass.services.async_call( DOMAIN, SERVICE_SET_HUMIDITY, {"entity_id": "climate.testdevice", "humidity": 45}, blocking=True, ) assert helper.characteristics[HUMIDITY_TARGET].value == 45
[ "async", "def", "test_climate_change_thermostat_humidity", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HUMIDITY", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"humidity\"", ":", "50", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HUMIDITY_TARGET", "]", ".", "value", "==", "50", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HUMIDITY", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"humidity\"", ":", "45", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "HUMIDITY_TARGET", "]", ".", "value", "==", "45" ]
[ 149, 0 ]
[ 167, 62 ]
python
en
['en', 'en', 'en']
True
test_climate_read_thermostat_state
(hass, utcnow)
Test that we can read the state of a HomeKit thermostat accessory.
Test that we can read the state of a HomeKit thermostat accessory.
async def test_climate_read_thermostat_state(hass, utcnow): """Test that we can read the state of a HomeKit thermostat accessory.""" helper = await setup_test_component(hass, create_thermostat_service) # Simulate that heating is on helper.characteristics[TEMPERATURE_CURRENT].value = 19 helper.characteristics[TEMPERATURE_TARGET].value = 21 helper.characteristics[HEATING_COOLING_CURRENT].value = 1 helper.characteristics[HEATING_COOLING_TARGET].value = 1 helper.characteristics[HUMIDITY_CURRENT].value = 50 helper.characteristics[HUMIDITY_TARGET].value = 45 state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_HEAT assert state.attributes["current_temperature"] == 19 assert state.attributes["current_humidity"] == 50 assert state.attributes["min_temp"] == 7 assert state.attributes["max_temp"] == 35 # Simulate that cooling is on helper.characteristics[TEMPERATURE_CURRENT].value = 21 helper.characteristics[TEMPERATURE_TARGET].value = 19 helper.characteristics[HEATING_COOLING_CURRENT].value = 2 helper.characteristics[HEATING_COOLING_TARGET].value = 2 helper.characteristics[HUMIDITY_CURRENT].value = 45 helper.characteristics[HUMIDITY_TARGET].value = 45 state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_COOL assert state.attributes["current_temperature"] == 21 assert state.attributes["current_humidity"] == 45 # Simulate that we are in heat/cool mode helper.characteristics[TEMPERATURE_CURRENT].value = 21 helper.characteristics[TEMPERATURE_TARGET].value = 21 helper.characteristics[HEATING_COOLING_CURRENT].value = 0 helper.characteristics[HEATING_COOLING_TARGET].value = 3 state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_HEAT_COOL
[ "async", "def", "test_climate_read_thermostat_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service", ")", "# Simulate that heating is on", "helper", ".", "characteristics", "[", "TEMPERATURE_CURRENT", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "HEATING_COOLING_CURRENT", "]", ".", "value", "=", "1", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "=", "1", "helper", ".", "characteristics", "[", "HUMIDITY_CURRENT", "]", ".", "value", "=", "50", "helper", ".", "characteristics", "[", "HUMIDITY_TARGET", "]", ".", "value", "=", "45", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "state", ".", "attributes", "[", "\"current_temperature\"", "]", "==", "19", "assert", "state", ".", "attributes", "[", "\"current_humidity\"", "]", "==", "50", "assert", "state", ".", "attributes", "[", "\"min_temp\"", "]", "==", "7", "assert", "state", ".", "attributes", "[", "\"max_temp\"", "]", "==", "35", "# Simulate that cooling is on", "helper", ".", "characteristics", "[", "TEMPERATURE_CURRENT", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "HEATING_COOLING_CURRENT", "]", ".", "value", "=", "2", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "=", "2", "helper", ".", "characteristics", "[", "HUMIDITY_CURRENT", "]", ".", "value", "=", "45", "helper", ".", "characteristics", "[", "HUMIDITY_TARGET", "]", ".", "value", "=", "45", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_COOL", "assert", "state", ".", "attributes", "[", "\"current_temperature\"", "]", "==", "21", "assert", "state", ".", "attributes", "[", "\"current_humidity\"", "]", "==", "45", "# Simulate that we are in heat/cool mode", "helper", ".", "characteristics", "[", "TEMPERATURE_CURRENT", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "HEATING_COOLING_CURRENT", "]", ".", "value", "=", "0", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "=", "3", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_HEAT_COOL" ]
[ 170, 0 ]
[ 209, 45 ]
python
en
['en', 'en', 'en']
True
test_hvac_mode_vs_hvac_action
(hass, utcnow)
Check that we haven't conflated hvac_mode and hvac_action.
Check that we haven't conflated hvac_mode and hvac_action.
async def test_hvac_mode_vs_hvac_action(hass, utcnow): """Check that we haven't conflated hvac_mode and hvac_action.""" helper = await setup_test_component(hass, create_thermostat_service) # Simulate that current temperature is above target temp # Heating might be on, but hvac_action currently 'off' helper.characteristics[TEMPERATURE_CURRENT].value = 22 helper.characteristics[TEMPERATURE_TARGET].value = 21 helper.characteristics[HEATING_COOLING_CURRENT].value = 0 helper.characteristics[HEATING_COOLING_TARGET].value = 1 helper.characteristics[HUMIDITY_CURRENT].value = 50 helper.characteristics[HUMIDITY_TARGET].value = 45 state = await helper.poll_and_get_state() assert state.state == "heat" assert state.attributes["hvac_action"] == "idle" # Simulate that current temperature is below target temp # Heating might be on and hvac_action currently 'heat' helper.characteristics[TEMPERATURE_CURRENT].value = 19 helper.characteristics[HEATING_COOLING_CURRENT].value = 1 state = await helper.poll_and_get_state() assert state.state == "heat" assert state.attributes["hvac_action"] == "heating"
[ "async", "def", "test_hvac_mode_vs_hvac_action", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_thermostat_service", ")", "# Simulate that current temperature is above target temp", "# Heating might be on, but hvac_action currently 'off'", "helper", ".", "characteristics", "[", "TEMPERATURE_CURRENT", "]", ".", "value", "=", "22", "helper", ".", "characteristics", "[", "TEMPERATURE_TARGET", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "HEATING_COOLING_CURRENT", "]", ".", "value", "=", "0", "helper", ".", "characteristics", "[", "HEATING_COOLING_TARGET", "]", ".", "value", "=", "1", "helper", ".", "characteristics", "[", "HUMIDITY_CURRENT", "]", ".", "value", "=", "50", "helper", ".", "characteristics", "[", "HUMIDITY_TARGET", "]", ".", "value", "=", "45", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"heat\"", "assert", "state", ".", "attributes", "[", "\"hvac_action\"", "]", "==", "\"idle\"", "# Simulate that current temperature is below target temp", "# Heating might be on and hvac_action currently 'heat'", "helper", ".", "characteristics", "[", "TEMPERATURE_CURRENT", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "HEATING_COOLING_CURRENT", "]", ".", "value", "=", "1", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"heat\"", "assert", "state", ".", "attributes", "[", "\"hvac_action\"", "]", "==", "\"heating\"" ]
[ 212, 0 ]
[ 236, 55 ]
python
en
['en', 'en', 'en']
True
create_heater_cooler_service
(accessory)
Define thermostat characteristics.
Define thermostat characteristics.
def create_heater_cooler_service(accessory): """Define thermostat characteristics.""" service = accessory.add_service(ServicesTypes.HEATER_COOLER) char = service.add_char(CharacteristicsTypes.TARGET_HEATER_COOLER_STATE) char.value = 0 char = service.add_char(CharacteristicsTypes.CURRENT_HEATER_COOLER_STATE) char.value = 0 char = service.add_char(CharacteristicsTypes.ACTIVE) char.value = 1 char = service.add_char(CharacteristicsTypes.TEMPERATURE_COOLING_THRESHOLD) char.minValue = 7 char.maxValue = 35 char.value = 0 char = service.add_char(CharacteristicsTypes.TEMPERATURE_HEATING_THRESHOLD) char.minValue = 7 char.maxValue = 35 char.value = 0 char = service.add_char(CharacteristicsTypes.TEMPERATURE_CURRENT) char.value = 0 char = service.add_char(CharacteristicsTypes.SWING_MODE) char.value = 0
[ "def", "create_heater_cooler_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "HEATER_COOLER", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TARGET_HEATER_COOLER_STATE", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "CURRENT_HEATER_COOLER_STATE", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "ACTIVE", ")", "char", ".", "value", "=", "1", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TEMPERATURE_COOLING_THRESHOLD", ")", "char", ".", "minValue", "=", "7", "char", ".", "maxValue", "=", "35", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TEMPERATURE_HEATING_THRESHOLD", ")", "char", ".", "minValue", "=", "7", "char", ".", "maxValue", "=", "35", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TEMPERATURE_CURRENT", ")", "char", ".", "value", "=", "0", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "SWING_MODE", ")", "char", ".", "value", "=", "0" ]
[ 248, 0 ]
[ 275, 18 ]
python
en
['en', 'mt', 'en']
True
create_heater_cooler_service_min_max
(accessory)
Define thermostat characteristics.
Define thermostat characteristics.
def create_heater_cooler_service_min_max(accessory): """Define thermostat characteristics.""" service = accessory.add_service(ServicesTypes.HEATER_COOLER) char = service.add_char(CharacteristicsTypes.TARGET_HEATER_COOLER_STATE) char.value = 1 char.minValue = 1 char.maxValue = 2
[ "def", "create_heater_cooler_service_min_max", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "HEATER_COOLER", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TARGET_HEATER_COOLER_STATE", ")", "char", ".", "value", "=", "1", "char", ".", "minValue", "=", "1", "char", ".", "maxValue", "=", "2" ]
[ 279, 0 ]
[ 285, 21 ]
python
en
['en', 'mt', 'en']
True
test_heater_cooler_respect_supported_op_modes_1
(hass, utcnow)
Test that climate respects minValue/maxValue hints.
Test that climate respects minValue/maxValue hints.
async def test_heater_cooler_respect_supported_op_modes_1(hass, utcnow): """Test that climate respects minValue/maxValue hints.""" helper = await setup_test_component(hass, create_heater_cooler_service_min_max) state = await helper.poll_and_get_state() assert state.attributes["hvac_modes"] == ["heat", "cool", "off"]
[ "async", "def", "test_heater_cooler_respect_supported_op_modes_1", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service_min_max", ")", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"hvac_modes\"", "]", "==", "[", "\"heat\"", ",", "\"cool\"", ",", "\"off\"", "]" ]
[ 288, 0 ]
[ 292, 68 ]
python
en
['en', 'en', 'en']
True
create_theater_cooler_service_valid_vals
(accessory)
Define heater-cooler characteristics.
Define heater-cooler characteristics.
def create_theater_cooler_service_valid_vals(accessory): """Define heater-cooler characteristics.""" service = accessory.add_service(ServicesTypes.HEATER_COOLER) char = service.add_char(CharacteristicsTypes.TARGET_HEATER_COOLER_STATE) char.value = 1 char.valid_values = [1, 2]
[ "def", "create_theater_cooler_service_valid_vals", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "HEATER_COOLER", ")", "char", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "TARGET_HEATER_COOLER_STATE", ")", "char", ".", "value", "=", "1", "char", ".", "valid_values", "=", "[", "1", ",", "2", "]" ]
[ 295, 0 ]
[ 300, 30 ]
python
en
['sv', 'ro', 'en']
False
test_heater_cooler_respect_supported_op_modes_2
(hass, utcnow)
Test that climate respects validValue hints.
Test that climate respects validValue hints.
async def test_heater_cooler_respect_supported_op_modes_2(hass, utcnow): """Test that climate respects validValue hints.""" helper = await setup_test_component(hass, create_theater_cooler_service_valid_vals) state = await helper.poll_and_get_state() assert state.attributes["hvac_modes"] == ["heat", "cool", "off"]
[ "async", "def", "test_heater_cooler_respect_supported_op_modes_2", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_theater_cooler_service_valid_vals", ")", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"hvac_modes\"", "]", "==", "[", "\"heat\"", ",", "\"cool\"", ",", "\"off\"", "]" ]
[ 303, 0 ]
[ 307, 68 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_change_thermostat_state
(hass, utcnow)
Test that we can change the operational mode.
Test that we can change the operational mode.
async def test_heater_cooler_change_thermostat_state(hass, utcnow): """Test that we can change the operational mode.""" helper = await setup_test_component(hass, create_heater_cooler_service) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_HEAT}, blocking=True, ) assert ( helper.characteristics[TARGET_HEATER_COOLER_STATE].value == TargetHeaterCoolerStateValues.HEAT ) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_COOL}, blocking=True, ) assert ( helper.characteristics[TARGET_HEATER_COOLER_STATE].value == TargetHeaterCoolerStateValues.COOL ) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_HEAT_COOL}, blocking=True, ) assert ( helper.characteristics[TARGET_HEATER_COOLER_STATE].value == TargetHeaterCoolerStateValues.AUTOMATIC ) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_OFF}, blocking=True, ) assert ( helper.characteristics[HEATER_COOLER_ACTIVE].value == ActivationStateValues.INACTIVE )
[ "async", "def", "test_heater_cooler_change_thermostat_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_HEAT", "}", ",", "blocking", "=", "True", ",", ")", "assert", "(", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "==", "TargetHeaterCoolerStateValues", ".", "HEAT", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_COOL", "}", ",", "blocking", "=", "True", ",", ")", "assert", "(", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "==", "TargetHeaterCoolerStateValues", ".", "COOL", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_HEAT_COOL", "}", ",", "blocking", "=", "True", ",", ")", "assert", "(", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "==", "TargetHeaterCoolerStateValues", ".", "AUTOMATIC", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_OFF", "}", ",", "blocking", "=", "True", ",", ")", "assert", "(", "helper", ".", "characteristics", "[", "HEATER_COOLER_ACTIVE", "]", ".", "value", "==", "ActivationStateValues", ".", "INACTIVE", ")" ]
[ 310, 0 ]
[ 357, 5 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_change_thermostat_temperature
(hass, utcnow)
Test that we can change the target temperature.
Test that we can change the target temperature.
async def test_heater_cooler_change_thermostat_temperature(hass, utcnow): """Test that we can change the target temperature.""" helper = await setup_test_component(hass, create_heater_cooler_service) await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_HEAT}, blocking=True, ) await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, {"entity_id": "climate.testdevice", "temperature": 20}, blocking=True, ) assert helper.characteristics[TEMPERATURE_HEATING_THRESHOLD].value == 20 await hass.services.async_call( DOMAIN, SERVICE_SET_HVAC_MODE, {"entity_id": "climate.testdevice", "hvac_mode": HVAC_MODE_COOL}, blocking=True, ) await hass.services.async_call( DOMAIN, SERVICE_SET_TEMPERATURE, {"entity_id": "climate.testdevice", "temperature": 26}, blocking=True, ) assert helper.characteristics[TEMPERATURE_COOLING_THRESHOLD].value == 26
[ "async", "def", "test_heater_cooler_change_thermostat_temperature", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_HEAT", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_TEMPERATURE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"temperature\"", ":", "20", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "TEMPERATURE_HEATING_THRESHOLD", "]", ".", "value", "==", "20", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_HVAC_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"hvac_mode\"", ":", "HVAC_MODE_COOL", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_TEMPERATURE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"temperature\"", ":", "26", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "TEMPERATURE_COOLING_THRESHOLD", "]", ".", "value", "==", "26" ]
[ 360, 0 ]
[ 390, 76 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_read_thermostat_state
(hass, utcnow)
Test that we can read the state of a HomeKit thermostat accessory.
Test that we can read the state of a HomeKit thermostat accessory.
async def test_heater_cooler_read_thermostat_state(hass, utcnow): """Test that we can read the state of a HomeKit thermostat accessory.""" helper = await setup_test_component(hass, create_heater_cooler_service) # Simulate that heating is on helper.characteristics[HEATER_COOLER_TEMPERATURE_CURRENT].value = 19 helper.characteristics[TEMPERATURE_HEATING_THRESHOLD].value = 20 helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.HEATING helper.characteristics[ TARGET_HEATER_COOLER_STATE ].value = TargetHeaterCoolerStateValues.HEAT helper.characteristics[SWING_MODE].value = SwingModeValues.DISABLED state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_HEAT assert state.attributes["current_temperature"] == 19 assert state.attributes["min_temp"] == 7 assert state.attributes["max_temp"] == 35 # Simulate that cooling is on helper.characteristics[HEATER_COOLER_TEMPERATURE_CURRENT].value = 21 helper.characteristics[TEMPERATURE_COOLING_THRESHOLD].value = 19 helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.COOLING helper.characteristics[ TARGET_HEATER_COOLER_STATE ].value = TargetHeaterCoolerStateValues.COOL helper.characteristics[SWING_MODE].value = SwingModeValues.DISABLED state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_COOL assert state.attributes["current_temperature"] == 21 # Simulate that we are in auto mode helper.characteristics[HEATER_COOLER_TEMPERATURE_CURRENT].value = 21 helper.characteristics[TEMPERATURE_COOLING_THRESHOLD].value = 21 helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.COOLING helper.characteristics[ TARGET_HEATER_COOLER_STATE ].value = TargetHeaterCoolerStateValues.AUTOMATIC helper.characteristics[SWING_MODE].value = SwingModeValues.DISABLED state = await helper.poll_and_get_state() assert state.state == HVAC_MODE_HEAT_COOL
[ "async", "def", "test_heater_cooler_read_thermostat_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "# Simulate that heating is on", "helper", ".", "characteristics", "[", "HEATER_COOLER_TEMPERATURE_CURRENT", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "TEMPERATURE_HEATING_THRESHOLD", "]", ".", "value", "=", "20", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "HEATING", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "=", "TargetHeaterCoolerStateValues", ".", "HEAT", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "=", "SwingModeValues", ".", "DISABLED", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_HEAT", "assert", "state", ".", "attributes", "[", "\"current_temperature\"", "]", "==", "19", "assert", "state", ".", "attributes", "[", "\"min_temp\"", "]", "==", "7", "assert", "state", ".", "attributes", "[", "\"max_temp\"", "]", "==", "35", "# Simulate that cooling is on", "helper", ".", "characteristics", "[", "HEATER_COOLER_TEMPERATURE_CURRENT", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "TEMPERATURE_COOLING_THRESHOLD", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "COOLING", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "=", "TargetHeaterCoolerStateValues", ".", "COOL", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "=", "SwingModeValues", ".", "DISABLED", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_COOL", "assert", "state", ".", "attributes", "[", "\"current_temperature\"", "]", "==", "21", "# Simulate that we are in auto mode", "helper", ".", "characteristics", "[", "HEATER_COOLER_TEMPERATURE_CURRENT", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "TEMPERATURE_COOLING_THRESHOLD", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "COOLING", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "=", "TargetHeaterCoolerStateValues", ".", "AUTOMATIC", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "=", "SwingModeValues", ".", "DISABLED", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "HVAC_MODE_HEAT_COOL" ]
[ 393, 0 ]
[ 441, 45 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_hvac_mode_vs_hvac_action
(hass, utcnow)
Check that we haven't conflated hvac_mode and hvac_action.
Check that we haven't conflated hvac_mode and hvac_action.
async def test_heater_cooler_hvac_mode_vs_hvac_action(hass, utcnow): """Check that we haven't conflated hvac_mode and hvac_action.""" helper = await setup_test_component(hass, create_heater_cooler_service) # Simulate that current temperature is above target temp # Heating might be on, but hvac_action currently 'off' helper.characteristics[HEATER_COOLER_TEMPERATURE_CURRENT].value = 22 helper.characteristics[TEMPERATURE_HEATING_THRESHOLD].value = 21 helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.IDLE helper.characteristics[ TARGET_HEATER_COOLER_STATE ].value = TargetHeaterCoolerStateValues.HEAT helper.characteristics[SWING_MODE].value = SwingModeValues.DISABLED state = await helper.poll_and_get_state() assert state.state == "heat" assert state.attributes["hvac_action"] == "idle" # Simulate that current temperature is below target temp # Heating might be on and hvac_action currently 'heat' helper.characteristics[HEATER_COOLER_TEMPERATURE_CURRENT].value = 19 helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.HEATING state = await helper.poll_and_get_state() assert state.state == "heat" assert state.attributes["hvac_action"] == "heating"
[ "async", "def", "test_heater_cooler_hvac_mode_vs_hvac_action", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "# Simulate that current temperature is above target temp", "# Heating might be on, but hvac_action currently 'off'", "helper", ".", "characteristics", "[", "HEATER_COOLER_TEMPERATURE_CURRENT", "]", ".", "value", "=", "22", "helper", ".", "characteristics", "[", "TEMPERATURE_HEATING_THRESHOLD", "]", ".", "value", "=", "21", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "IDLE", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "=", "TargetHeaterCoolerStateValues", ".", "HEAT", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "=", "SwingModeValues", ".", "DISABLED", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"heat\"", "assert", "state", ".", "attributes", "[", "\"hvac_action\"", "]", "==", "\"idle\"", "# Simulate that current temperature is below target temp", "# Heating might be on and hvac_action currently 'heat'", "helper", ".", "characteristics", "[", "HEATER_COOLER_TEMPERATURE_CURRENT", "]", ".", "value", "=", "19", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "HEATING", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"heat\"", "assert", "state", ".", "attributes", "[", "\"hvac_action\"", "]", "==", "\"heating\"" ]
[ 444, 0 ]
[ 473, 55 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_change_swing_mode
(hass, utcnow)
Test that we can change the swing mode.
Test that we can change the swing mode.
async def test_heater_cooler_change_swing_mode(hass, utcnow): """Test that we can change the swing mode.""" helper = await setup_test_component(hass, create_heater_cooler_service) await hass.services.async_call( DOMAIN, SERVICE_SET_SWING_MODE, {"entity_id": "climate.testdevice", "swing_mode": "vertical"}, blocking=True, ) assert helper.characteristics[SWING_MODE].value == SwingModeValues.ENABLED await hass.services.async_call( DOMAIN, SERVICE_SET_SWING_MODE, {"entity_id": "climate.testdevice", "swing_mode": "off"}, blocking=True, ) assert helper.characteristics[SWING_MODE].value == SwingModeValues.DISABLED
[ "async", "def", "test_heater_cooler_change_swing_mode", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_SWING_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"swing_mode\"", ":", "\"vertical\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "==", "SwingModeValues", ".", "ENABLED", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_SET_SWING_MODE", ",", "{", "\"entity_id\"", ":", "\"climate.testdevice\"", ",", "\"swing_mode\"", ":", "\"off\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "SWING_MODE", "]", ".", "value", "==", "SwingModeValues", ".", "DISABLED" ]
[ 476, 0 ]
[ 494, 79 ]
python
en
['en', 'en', 'en']
True
test_heater_cooler_turn_off
(hass, utcnow)
Test that both hvac_action and hvac_mode return "off" when turned off.
Test that both hvac_action and hvac_mode return "off" when turned off.
async def test_heater_cooler_turn_off(hass, utcnow): """Test that both hvac_action and hvac_mode return "off" when turned off.""" helper = await setup_test_component(hass, create_heater_cooler_service) # Simulate that the device is turned off but CURRENT_HEATER_COOLER_STATE still returns HEATING/COOLING helper.characteristics[HEATER_COOLER_ACTIVE].value = ActivationStateValues.INACTIVE helper.characteristics[ CURRENT_HEATER_COOLER_STATE ].value = CurrentHeaterCoolerStateValues.HEATING helper.characteristics[ TARGET_HEATER_COOLER_STATE ].value = TargetHeaterCoolerStateValues.HEAT state = await helper.poll_and_get_state() assert state.state == "off" assert state.attributes["hvac_action"] == "off"
[ "async", "def", "test_heater_cooler_turn_off", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_heater_cooler_service", ")", "# Simulate that the device is turned off but CURRENT_HEATER_COOLER_STATE still returns HEATING/COOLING", "helper", ".", "characteristics", "[", "HEATER_COOLER_ACTIVE", "]", ".", "value", "=", "ActivationStateValues", ".", "INACTIVE", "helper", ".", "characteristics", "[", "CURRENT_HEATER_COOLER_STATE", "]", ".", "value", "=", "CurrentHeaterCoolerStateValues", ".", "HEATING", "helper", ".", "characteristics", "[", "TARGET_HEATER_COOLER_STATE", "]", ".", "value", "=", "TargetHeaterCoolerStateValues", ".", "HEAT", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"off\"", "assert", "state", ".", "attributes", "[", "\"hvac_action\"", "]", "==", "\"off\"" ]
[ 497, 0 ]
[ 510, 51 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], )
Set up from config entry.
Set up from config entry.
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up from config entry.""" router = hass.data[DOMAIN].routers[config_entry.data[CONF_URL]] sensors: List[Entity] = [] for key in SENSOR_KEYS: items = router.data.get(key) if not items: continue key_meta = SENSOR_META.get(key) if key_meta: if key_meta.include: items = filter(key_meta.include.search, items) if key_meta.exclude: items = [x for x in items if not key_meta.exclude.search(x)] for item in items: sensors.append( HuaweiLteSensor( router, key, item, SENSOR_META.get((key, item), SensorMeta()) ) ) async_add_entities(sensors, True)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", "[", "[", "List", "[", "Entity", "]", ",", "bool", "]", ",", "None", "]", ",", ")", "->", "None", ":", "router", "=", "hass", ".", "data", "[", "DOMAIN", "]", ".", "routers", "[", "config_entry", ".", "data", "[", "CONF_URL", "]", "]", "sensors", ":", "List", "[", "Entity", "]", "=", "[", "]", "for", "key", "in", "SENSOR_KEYS", ":", "items", "=", "router", ".", "data", ".", "get", "(", "key", ")", "if", "not", "items", ":", "continue", "key_meta", "=", "SENSOR_META", ".", "get", "(", "key", ")", "if", "key_meta", ":", "if", "key_meta", ".", "include", ":", "items", "=", "filter", "(", "key_meta", ".", "include", ".", "search", ",", "items", ")", "if", "key_meta", ".", "exclude", ":", "items", "=", "[", "x", "for", "x", "in", "items", "if", "not", "key_meta", ".", "exclude", ".", "search", "(", "x", ")", "]", "for", "item", "in", "items", ":", "sensors", ".", "append", "(", "HuaweiLteSensor", "(", "router", ",", "key", ",", "item", ",", "SENSOR_META", ".", "get", "(", "(", "key", ",", "item", ")", ",", "SensorMeta", "(", ")", ")", ")", ")", "async_add_entities", "(", "sensors", ",", "True", ")" ]
[ 328, 0 ]
[ 353, 37 ]
python
en
['en', 'en', 'en']
True
format_default
(value: StateType)
Format value.
Format value.
def format_default(value: StateType) -> Tuple[StateType, Optional[str]]: """Format value.""" unit = None if value is not None: # Clean up value and infer unit, e.g. -71dBm, 15 dB match = re.match( r"([>=<]*)(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value) ) if match: try: value = float(match.group("value")) unit = match.group("unit") except ValueError: pass return value, unit
[ "def", "format_default", "(", "value", ":", "StateType", ")", "->", "Tuple", "[", "StateType", ",", "Optional", "[", "str", "]", "]", ":", "unit", "=", "None", "if", "value", "is", "not", "None", ":", "# Clean up value and infer unit, e.g. -71dBm, 15 dB", "match", "=", "re", ".", "match", "(", "r\"([>=<]*)(?P<value>.+?)\\s*(?P<unit>[a-zA-Z]+)\\s*$\"", ",", "str", "(", "value", ")", ")", "if", "match", ":", "try", ":", "value", "=", "float", "(", "match", ".", "group", "(", "\"value\"", ")", ")", "unit", "=", "match", ".", "group", "(", "\"unit\"", ")", "except", "ValueError", ":", "pass", "return", "value", ",", "unit" ]
[ 356, 0 ]
[ 370, 22 ]
python
en
['nl', 'sv', 'en']
False
get_scanner
(hass, config)
Return a BT Smart Hub scanner if successful.
Return a BT Smart Hub scanner if successful.
def get_scanner(hass, config): """Return a BT Smart Hub scanner if successful.""" info = config[DOMAIN] smarthub_client = BTSmartHub( router_ip=info[CONF_HOST], smarthub_model=info.get(CONF_SMARTHUB_MODEL) ) scanner = BTSmartHubScanner(smarthub_client) return scanner if scanner.success_init else None
[ "def", "get_scanner", "(", "hass", ",", "config", ")", ":", "info", "=", "config", "[", "DOMAIN", "]", "smarthub_client", "=", "BTSmartHub", "(", "router_ip", "=", "info", "[", "CONF_HOST", "]", ",", "smarthub_model", "=", "info", ".", "get", "(", "CONF_SMARTHUB_MODEL", ")", ")", "scanner", "=", "BTSmartHubScanner", "(", "smarthub_client", ")", "return", "scanner", "if", "scanner", ".", "success_init", "else", "None" ]
[ 27, 0 ]
[ 36, 52 ]
python
en
['en', 'co', 'en']
True
BTSmartHubScanner.__init__
(self, smarthub_client)
Initialise the scanner.
Initialise the scanner.
def __init__(self, smarthub_client): """Initialise the scanner.""" self.smarthub = smarthub_client self.last_results = {} self.success_init = False # Test the router is accessible data = self.get_bt_smarthub_data() if data: self.success_init = True else: _LOGGER.info("Failed to connect to %s", self.smarthub.router_ip)
[ "def", "__init__", "(", "self", ",", "smarthub_client", ")", ":", "self", ".", "smarthub", "=", "smarthub_client", "self", ".", "last_results", "=", "{", "}", "self", ".", "success_init", "=", "False", "# Test the router is accessible", "data", "=", "self", ".", "get_bt_smarthub_data", "(", ")", "if", "data", ":", "self", ".", "success_init", "=", "True", "else", ":", "_LOGGER", ".", "info", "(", "\"Failed to connect to %s\"", ",", "self", ".", "smarthub", ".", "router_ip", ")" ]
[ 42, 4 ]
[ 53, 76 ]
python
en
['en', 'en', 'en']
True
BTSmartHubScanner.scan_devices
(self)
Scan for new devices and return a list with found device IDs.
Scan for new devices and return a list with found device IDs.
def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return [client["mac"] for client in self.last_results]
[ "def", "scan_devices", "(", "self", ")", ":", "self", ".", "_update_info", "(", ")", "return", "[", "client", "[", "\"mac\"", "]", "for", "client", "in", "self", ".", "last_results", "]" ]
[ 55, 4 ]
[ 58, 62 ]
python
en
['en', 'en', 'en']
True
BTSmartHubScanner.get_device_name
(self, device)
Return the name of the given device or None if we don't know.
Return the name of the given device or None if we don't know.
def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if not self.last_results: return None for client in self.last_results: if client["mac"] == device: return client["host"] return None
[ "def", "get_device_name", "(", "self", ",", "device", ")", ":", "if", "not", "self", ".", "last_results", ":", "return", "None", "for", "client", "in", "self", ".", "last_results", ":", "if", "client", "[", "\"mac\"", "]", "==", "device", ":", "return", "client", "[", "\"host\"", "]", "return", "None" ]
[ 60, 4 ]
[ 67, 19 ]
python
en
['en', 'en', 'en']
True
BTSmartHubScanner._update_info
(self)
Ensure the information from the BT Smart Hub is up to date.
Ensure the information from the BT Smart Hub is up to date.
def _update_info(self): """Ensure the information from the BT Smart Hub is up to date.""" if not self.success_init: return _LOGGER.info("Scanning") data = self.get_bt_smarthub_data() if not data: _LOGGER.warning("Error scanning devices") return clients = list(data.values()) self.last_results = clients
[ "def", "_update_info", "(", "self", ")", ":", "if", "not", "self", ".", "success_init", ":", "return", "_LOGGER", ".", "info", "(", "\"Scanning\"", ")", "data", "=", "self", ".", "get_bt_smarthub_data", "(", ")", "if", "not", "data", ":", "_LOGGER", ".", "warning", "(", "\"Error scanning devices\"", ")", "return", "clients", "=", "list", "(", "data", ".", "values", "(", ")", ")", "self", ".", "last_results", "=", "clients" ]
[ 69, 4 ]
[ 81, 35 ]
python
en
['en', 'en', 'en']
True
BTSmartHubScanner.get_bt_smarthub_data
(self)
Retrieve data from BT Smart Hub and return parsed result.
Retrieve data from BT Smart Hub and return parsed result.
def get_bt_smarthub_data(self): """Retrieve data from BT Smart Hub and return parsed result.""" # Request data from bt smarthub into a list of dicts. data = self.smarthub.get_devicelist(only_active_devices=True) # Renaming keys from parsed result. devices = {} for device in data: try: devices[device["UserHostName"]] = { "ip": device["IPAddress"], "mac": device["PhysAddress"], "host": device["UserHostName"], "status": device["Active"], } except KeyError: pass return devices
[ "def", "get_bt_smarthub_data", "(", "self", ")", ":", "# Request data from bt smarthub into a list of dicts.", "data", "=", "self", ".", "smarthub", ".", "get_devicelist", "(", "only_active_devices", "=", "True", ")", "# Renaming keys from parsed result.", "devices", "=", "{", "}", "for", "device", "in", "data", ":", "try", ":", "devices", "[", "device", "[", "\"UserHostName\"", "]", "]", "=", "{", "\"ip\"", ":", "device", "[", "\"IPAddress\"", "]", ",", "\"mac\"", ":", "device", "[", "\"PhysAddress\"", "]", ",", "\"host\"", ":", "device", "[", "\"UserHostName\"", "]", ",", "\"status\"", ":", "device", "[", "\"Active\"", "]", ",", "}", "except", "KeyError", ":", "pass", "return", "devices" ]
[ 83, 4 ]
[ 101, 22 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[list], None], )
Set up the ISY994 fan platform.
Set up the ISY994 fan platform.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[list], None], ) -> bool: """Set up the ISY994 fan platform.""" hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id] devices = [] for node in hass_isy_data[ISY994_NODES][FAN]: devices.append(ISYFanEntity(node)) for name, status, actions in hass_isy_data[ISY994_PROGRAMS][FAN]: devices.append(ISYFanProgramEntity(name, status, actions)) await migrate_old_unique_ids(hass, FAN, devices) async_add_entities(devices)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", "[", "[", "list", "]", ",", "None", "]", ",", ")", "->", "bool", ":", "hass_isy_data", "=", "hass", ".", "data", "[", "ISY994_DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "devices", "=", "[", "]", "for", "node", "in", "hass_isy_data", "[", "ISY994_NODES", "]", "[", "FAN", "]", ":", "devices", ".", "append", "(", "ISYFanEntity", "(", "node", ")", ")", "for", "name", ",", "status", ",", "actions", "in", "hass_isy_data", "[", "ISY994_PROGRAMS", "]", "[", "FAN", "]", ":", "devices", ".", "append", "(", "ISYFanProgramEntity", "(", "name", ",", "status", ",", "actions", ")", ")", "await", "migrate_old_unique_ids", "(", "hass", ",", "FAN", ",", "devices", ")", "async_add_entities", "(", "devices", ")" ]
[ 35, 0 ]
[ 51, 31 ]
python
en
['en', 'cs', 'en']
True
ISYFanEntity.speed
(self)
Return the current speed.
Return the current speed.
def speed(self) -> str: """Return the current speed.""" return VALUE_TO_STATE.get(self._node.status)
[ "def", "speed", "(", "self", ")", "->", "str", ":", "return", "VALUE_TO_STATE", ".", "get", "(", "self", ".", "_node", ".", "status", ")" ]
[ 58, 4 ]
[ 60, 52 ]
python
en
['en', 'en', 'en']
True
ISYFanEntity.is_on
(self)
Get if the fan is on.
Get if the fan is on.
def is_on(self) -> bool: """Get if the fan is on.""" if self._node.status == ISY_VALUE_UNKNOWN: return None return self._node.status != 0
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_node", ".", "status", "==", "ISY_VALUE_UNKNOWN", ":", "return", "None", "return", "self", ".", "_node", ".", "status", "!=", "0" ]
[ 63, 4 ]
[ 67, 37 ]
python
en
['en', 'fy', 'en']
True
ISYFanEntity.set_speed
(self, speed: str)
Send the set speed command to the ISY994 fan device.
Send the set speed command to the ISY994 fan device.
def set_speed(self, speed: str) -> None: """Send the set speed command to the ISY994 fan device.""" self._node.turn_on(val=STATE_TO_VALUE.get(speed, 255))
[ "def", "set_speed", "(", "self", ",", "speed", ":", "str", ")", "->", "None", ":", "self", ".", "_node", ".", "turn_on", "(", "val", "=", "STATE_TO_VALUE", ".", "get", "(", "speed", ",", "255", ")", ")" ]
[ 69, 4 ]
[ 71, 62 ]
python
en
['en', 'en', 'en']
True
ISYFanEntity.turn_on
(self, speed: str = None, **kwargs)
Send the turn on command to the ISY994 fan device.
Send the turn on command to the ISY994 fan device.
def turn_on(self, speed: str = None, **kwargs) -> None: """Send the turn on command to the ISY994 fan device.""" self.set_speed(speed)
[ "def", "turn_on", "(", "self", ",", "speed", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "set_speed", "(", "speed", ")" ]
[ 73, 4 ]
[ 75, 29 ]
python
en
['en', 'en', 'en']
True
ISYFanEntity.turn_off
(self, **kwargs)
Send the turn off command to the ISY994 fan device.
Send the turn off command to the ISY994 fan device.
def turn_off(self, **kwargs) -> None: """Send the turn off command to the ISY994 fan device.""" self._node.turn_off()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "_node", ".", "turn_off", "(", ")" ]
[ 77, 4 ]
[ 79, 29 ]
python
en
['en', 'en', 'en']
True
ISYFanEntity.speed_list
(self)
Get the list of available speeds.
Get the list of available speeds.
def speed_list(self) -> list: """Get the list of available speeds.""" return [SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]
[ "def", "speed_list", "(", "self", ")", "->", "list", ":", "return", "[", "SPEED_OFF", ",", "SPEED_LOW", ",", "SPEED_MEDIUM", ",", "SPEED_HIGH", "]" ]
[ 82, 4 ]
[ 84, 63 ]
python
en
['en', 'en', 'en']
True
ISYFanEntity.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" return SUPPORT_SET_SPEED
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_SET_SPEED" ]
[ 87, 4 ]
[ 89, 32 ]
python
en
['da', 'en', 'en']
True
ISYFanProgramEntity.speed
(self)
Return the current speed.
Return the current speed.
def speed(self) -> str: """Return the current speed.""" return VALUE_TO_STATE.get(self._node.status)
[ "def", "speed", "(", "self", ")", "->", "str", ":", "return", "VALUE_TO_STATE", ".", "get", "(", "self", ".", "_node", ".", "status", ")" ]
[ 96, 4 ]
[ 98, 52 ]
python
en
['en', 'en', 'en']
True
ISYFanProgramEntity.is_on
(self)
Get if the fan is on.
Get if the fan is on.
def is_on(self) -> bool: """Get if the fan is on.""" return self._node.status != 0
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_node", ".", "status", "!=", "0" ]
[ 101, 4 ]
[ 103, 37 ]
python
en
['en', 'fy', 'en']
True
ISYFanProgramEntity.turn_off
(self, **kwargs)
Send the turn on command to ISY994 fan program.
Send the turn on command to ISY994 fan program.
def turn_off(self, **kwargs) -> None: """Send the turn on command to ISY994 fan program.""" if not self._actions.run_then(): _LOGGER.error("Unable to turn off the fan")
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "not", "self", ".", "_actions", ".", "run_then", "(", ")", ":", "_LOGGER", ".", "error", "(", "\"Unable to turn off the fan\"", ")" ]
[ 105, 4 ]
[ 108, 55 ]
python
en
['en', 'fy', 'en']
True
ISYFanProgramEntity.turn_on
(self, speed: str = None, **kwargs)
Send the turn off command to ISY994 fan program.
Send the turn off command to ISY994 fan program.
def turn_on(self, speed: str = None, **kwargs) -> None: """Send the turn off command to ISY994 fan program.""" if not self._actions.run_else(): _LOGGER.error("Unable to turn on the fan")
[ "def", "turn_on", "(", "self", ",", "speed", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "not", "self", ".", "_actions", ".", "run_else", "(", ")", ":", "_LOGGER", ".", "error", "(", "\"Unable to turn on the fan\"", ")" ]
[ 110, 4 ]
[ 113, 54 ]
python
en
['en', 'fy', 'en']
True
NetworkMorphismTuner.__init__
( self, task="cv", input_width=32, input_channel=3, n_output_node=10, algorithm_name="Bayesian", optimize_mode="maximize", path="model_path", verbose=True, beta=Constant.BETA, t_min=Constant.T_MIN, max_model_size=Constant.MAX_MODEL_SIZE, default_model_len=Constant.MODEL_LEN, default_model_width=Constant.MODEL_WIDTH, )
initilizer of the NetworkMorphismTuner.
initilizer of the NetworkMorphismTuner.
def __init__( self, task="cv", input_width=32, input_channel=3, n_output_node=10, algorithm_name="Bayesian", optimize_mode="maximize", path="model_path", verbose=True, beta=Constant.BETA, t_min=Constant.T_MIN, max_model_size=Constant.MAX_MODEL_SIZE, default_model_len=Constant.MODEL_LEN, default_model_width=Constant.MODEL_WIDTH, ): """ initilizer of the NetworkMorphismTuner. """ if not os.path.exists(path): os.makedirs(path) self.path = os.path.join(os.getcwd(), path) if task == "cv": self.generators = [CnnGenerator] elif task == "common": self.generators = [MlpGenerator] else: raise NotImplementedError( '{} task not supported in List ["cv","common"]') self.n_classes = n_output_node self.input_shape = (input_width, input_width, input_channel) self.t_min = t_min self.beta = beta self.algorithm_name = algorithm_name self.optimize_mode = OptimizeMode(optimize_mode) self.json = None self.total_data = {} self.verbose = verbose self.model_count = 0 self.bo = BayesianOptimizer( self, self.t_min, self.optimize_mode, self.beta) self.training_queue = [] self.descriptors = [] self.history = [] self.max_model_size = max_model_size self.default_model_len = default_model_len self.default_model_width = default_model_width self.search_space = dict()
[ "def", "__init__", "(", "self", ",", "task", "=", "\"cv\"", ",", "input_width", "=", "32", ",", "input_channel", "=", "3", ",", "n_output_node", "=", "10", ",", "algorithm_name", "=", "\"Bayesian\"", ",", "optimize_mode", "=", "\"maximize\"", ",", "path", "=", "\"model_path\"", ",", "verbose", "=", "True", ",", "beta", "=", "Constant", ".", "BETA", ",", "t_min", "=", "Constant", ".", "T_MIN", ",", "max_model_size", "=", "Constant", ".", "MAX_MODEL_SIZE", ",", "default_model_len", "=", "Constant", ".", "MODEL_LEN", ",", "default_model_width", "=", "Constant", ".", "MODEL_WIDTH", ",", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "self", ".", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "path", ")", "if", "task", "==", "\"cv\"", ":", "self", ".", "generators", "=", "[", "CnnGenerator", "]", "elif", "task", "==", "\"common\"", ":", "self", ".", "generators", "=", "[", "MlpGenerator", "]", "else", ":", "raise", "NotImplementedError", "(", "'{} task not supported in List [\"cv\",\"common\"]'", ")", "self", ".", "n_classes", "=", "n_output_node", "self", ".", "input_shape", "=", "(", "input_width", ",", "input_width", ",", "input_channel", ")", "self", ".", "t_min", "=", "t_min", "self", ".", "beta", "=", "beta", "self", ".", "algorithm_name", "=", "algorithm_name", "self", ".", "optimize_mode", "=", "OptimizeMode", "(", "optimize_mode", ")", "self", ".", "json", "=", "None", "self", ".", "total_data", "=", "{", "}", "self", ".", "verbose", "=", "verbose", "self", ".", "model_count", "=", "0", "self", ".", "bo", "=", "BayesianOptimizer", "(", "self", ",", "self", ".", "t_min", ",", "self", ".", "optimize_mode", ",", "self", ".", "beta", ")", "self", ".", "training_queue", "=", "[", "]", "self", ".", "descriptors", "=", "[", "]", "self", ".", "history", "=", "[", "]", "self", ".", "max_model_size", "=", "max_model_size", "self", ".", "default_model_len", "=", "default_model_len", "self", ".", "default_model_width", "=", "default_model_width", "self", ".", "search_space", "=", "dict", "(", ")" ]
[ 61, 4 ]
[ 114, 34 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.update_search_space
(self, search_space)
Update search space definition in tuner by search_space in neural architecture.
Update search space definition in tuner by search_space in neural architecture.
def update_search_space(self, search_space): """ Update search space definition in tuner by search_space in neural architecture. """ self.search_space = search_space
[ "def", "update_search_space", "(", "self", ",", "search_space", ")", ":", "self", ".", "search_space", "=", "search_space" ]
[ 117, 4 ]
[ 121, 40 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.generate_parameters
(self, parameter_id, **kwargs)
Returns a set of trial neural architecture, as a serializable object. Parameters ---------- parameter_id : int
Returns a set of trial neural architecture, as a serializable object.
def generate_parameters(self, parameter_id, **kwargs): """ Returns a set of trial neural architecture, as a serializable object. Parameters ---------- parameter_id : int """ if not self.history: self.init_search() new_father_id = None generated_graph = None if not self.training_queue: new_father_id, generated_graph = self.generate() new_model_id = self.model_count self.model_count += 1 self.training_queue.append( (generated_graph, new_father_id, new_model_id)) self.descriptors.append(generated_graph.extract_descriptor()) graph, father_id, model_id = self.training_queue.pop(0) # from graph to json json_model_path = os.path.join(self.path, str(model_id) + ".json") json_out = graph_to_json(graph, json_model_path) self.total_data[parameter_id] = (json_out, father_id, model_id) return json_out
[ "def", "generate_parameters", "(", "self", ",", "parameter_id", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "history", ":", "self", ".", "init_search", "(", ")", "new_father_id", "=", "None", "generated_graph", "=", "None", "if", "not", "self", ".", "training_queue", ":", "new_father_id", ",", "generated_graph", "=", "self", ".", "generate", "(", ")", "new_model_id", "=", "self", ".", "model_count", "self", ".", "model_count", "+=", "1", "self", ".", "training_queue", ".", "append", "(", "(", "generated_graph", ",", "new_father_id", ",", "new_model_id", ")", ")", "self", ".", "descriptors", ".", "append", "(", "generated_graph", ".", "extract_descriptor", "(", ")", ")", "graph", ",", "father_id", ",", "model_id", "=", "self", ".", "training_queue", ".", "pop", "(", "0", ")", "# from graph to json", "json_model_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "str", "(", "model_id", ")", "+", "\".json\"", ")", "json_out", "=", "graph_to_json", "(", "graph", ",", "json_model_path", ")", "self", ".", "total_data", "[", "parameter_id", "]", "=", "(", "json_out", ",", "father_id", ",", "model_id", ")", "return", "json_out" ]
[ 123, 4 ]
[ 151, 23 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.receive_trial_result
(self, parameter_id, parameters, value, **kwargs)
Record an observation of the objective function. Parameters ---------- parameter_id : int the id of a group of paramters that generated by nni manager. parameters : dict A group of parameters. value : dict/float if value is dict, it should have "default" key.
Record an observation of the objective function.
def receive_trial_result(self, parameter_id, parameters, value, **kwargs): """ Record an observation of the objective function. Parameters ---------- parameter_id : int the id of a group of paramters that generated by nni manager. parameters : dict A group of parameters. value : dict/float if value is dict, it should have "default" key. """ reward = extract_scalar_reward(value) if parameter_id not in self.total_data: raise RuntimeError("Received parameter_id not in total_data.") (_, father_id, model_id) = self.total_data[parameter_id] graph = self.bo.searcher.load_model_by_id(model_id) # to use the value and graph self.add_model(reward, model_id) self.update(father_id, graph, reward, model_id)
[ "def", "receive_trial_result", "(", "self", ",", "parameter_id", ",", "parameters", ",", "value", ",", "*", "*", "kwargs", ")", ":", "reward", "=", "extract_scalar_reward", "(", "value", ")", "if", "parameter_id", "not", "in", "self", ".", "total_data", ":", "raise", "RuntimeError", "(", "\"Received parameter_id not in total_data.\"", ")", "(", "_", ",", "father_id", ",", "model_id", ")", "=", "self", ".", "total_data", "[", "parameter_id", "]", "graph", "=", "self", ".", "bo", ".", "searcher", ".", "load_model_by_id", "(", "model_id", ")", "# to use the value and graph", "self", ".", "add_model", "(", "reward", ",", "model_id", ")", "self", ".", "update", "(", "father_id", ",", "graph", ",", "reward", ",", "model_id", ")" ]
[ 153, 4 ]
[ 177, 55 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.init_search
(self)
Call the generators to generate the initial architectures for the search.
Call the generators to generate the initial architectures for the search.
def init_search(self): """ Call the generators to generate the initial architectures for the search. """ if self.verbose: logger.info("Initializing search.") for generator in self.generators: graph = generator(self.n_classes, self.input_shape).generate( self.default_model_len, self.default_model_width ) model_id = self.model_count self.model_count += 1 self.training_queue.append((graph, -1, model_id)) self.descriptors.append(graph.extract_descriptor()) if self.verbose: logger.info("Initialization finished.")
[ "def", "init_search", "(", "self", ")", ":", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"Initializing search.\"", ")", "for", "generator", "in", "self", ".", "generators", ":", "graph", "=", "generator", "(", "self", ".", "n_classes", ",", "self", ".", "input_shape", ")", ".", "generate", "(", "self", ".", "default_model_len", ",", "self", ".", "default_model_width", ")", "model_id", "=", "self", ".", "model_count", "self", ".", "model_count", "+=", "1", "self", ".", "training_queue", ".", "append", "(", "(", "graph", ",", "-", "1", ",", "model_id", ")", ")", "self", ".", "descriptors", ".", "append", "(", "graph", ".", "extract_descriptor", "(", ")", ")", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"Initialization finished.\"", ")" ]
[ 180, 4 ]
[ 196, 51 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.generate
(self)
Generate the next neural architecture. Returns ------- other_info : any object Anything to be saved in the training queue together with the architecture. generated_graph : Graph An instance of Graph.
Generate the next neural architecture.
def generate(self): """ Generate the next neural architecture. Returns ------- other_info : any object Anything to be saved in the training queue together with the architecture. generated_graph : Graph An instance of Graph. """ generated_graph, new_father_id = self.bo.generate(self.descriptors) if new_father_id is None: new_father_id = 0 generated_graph = self.generators[0]( self.n_classes, self.input_shape ).generate(self.default_model_len, self.default_model_width) return new_father_id, generated_graph
[ "def", "generate", "(", "self", ")", ":", "generated_graph", ",", "new_father_id", "=", "self", ".", "bo", ".", "generate", "(", "self", ".", "descriptors", ")", "if", "new_father_id", "is", "None", ":", "new_father_id", "=", "0", "generated_graph", "=", "self", ".", "generators", "[", "0", "]", "(", "self", ".", "n_classes", ",", "self", ".", "input_shape", ")", ".", "generate", "(", "self", ".", "default_model_len", ",", "self", ".", "default_model_width", ")", "return", "new_father_id", ",", "generated_graph" ]
[ 199, 4 ]
[ 217, 45 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.update
(self, other_info, graph, metric_value, model_id)
Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: graph.Graph An instance of Graph. The trained neural architecture. metric_value: float The final evaluated metric value. model_id: int
Update the controller with evaluation result of a neural architecture.
def update(self, other_info, graph, metric_value, model_id): """ Update the controller with evaluation result of a neural architecture. Parameters ---------- other_info: any object In our case it is the father ID in the search tree. graph: graph.Graph An instance of Graph. The trained neural architecture. metric_value: float The final evaluated metric value. model_id: int """ father_id = other_info self.bo.fit([graph.extract_descriptor()], [metric_value]) self.bo.add_child(father_id, model_id)
[ "def", "update", "(", "self", ",", "other_info", ",", "graph", ",", "metric_value", ",", "model_id", ")", ":", "father_id", "=", "other_info", "self", ".", "bo", ".", "fit", "(", "[", "graph", ".", "extract_descriptor", "(", ")", "]", ",", "[", "metric_value", "]", ")", "self", ".", "bo", ".", "add_child", "(", "father_id", ",", "model_id", ")" ]
[ 219, 4 ]
[ 235, 46 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.add_model
(self, metric_value, model_id)
Add model to the history, x_queue and y_queue Parameters ---------- metric_value : float graph : dict model_id : int Returns ------- model : dict
Add model to the history, x_queue and y_queue
def add_model(self, metric_value, model_id): """ Add model to the history, x_queue and y_queue Parameters ---------- metric_value : float graph : dict model_id : int Returns ------- model : dict """ if self.verbose: logger.info("Saving model.") # Update best_model text file ret = {"model_id": model_id, "metric_value": metric_value} self.history.append(ret) if model_id == self.get_best_model_id(): file = open(os.path.join(self.path, "best_model.txt"), "w") file.write("best model: " + str(model_id)) file.close() return ret
[ "def", "add_model", "(", "self", ",", "metric_value", ",", "model_id", ")", ":", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"Saving model.\"", ")", "# Update best_model text file", "ret", "=", "{", "\"model_id\"", ":", "model_id", ",", "\"metric_value\"", ":", "metric_value", "}", "self", ".", "history", ".", "append", "(", "ret", ")", "if", "model_id", "==", "self", ".", "get_best_model_id", "(", ")", ":", "file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"best_model.txt\"", ")", ",", "\"w\"", ")", "file", ".", "write", "(", "\"best model: \"", "+", "str", "(", "model_id", ")", ")", "file", ".", "close", "(", ")", "return", "ret" ]
[ 237, 4 ]
[ 261, 18 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.get_best_model_id
(self)
Get the best model_id from history using the metric value
Get the best model_id from history using the metric value
def get_best_model_id(self): """ Get the best model_id from history using the metric value """ if self.optimize_mode is OptimizeMode.Maximize: return max(self.history, key=lambda x: x["metric_value"])[ "model_id"] return min(self.history, key=lambda x: x["metric_value"])["model_id"]
[ "def", "get_best_model_id", "(", "self", ")", ":", "if", "self", ".", "optimize_mode", "is", "OptimizeMode", ".", "Maximize", ":", "return", "max", "(", "self", ".", "history", ",", "key", "=", "lambda", "x", ":", "x", "[", "\"metric_value\"", "]", ")", "[", "\"model_id\"", "]", "return", "min", "(", "self", ".", "history", ",", "key", "=", "lambda", "x", ":", "x", "[", "\"metric_value\"", "]", ")", "[", "\"model_id\"", "]" ]
[ 264, 4 ]
[ 272, 77 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.load_model_by_id
(self, model_id)
Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : graph.Graph the model graph representation
Get the model by model_id
def load_model_by_id(self, model_id): """ Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : graph.Graph the model graph representation """ with open(os.path.join(self.path, str(model_id) + ".json")) as fin: json_str = fin.read().replace("\n", "") load_model = json_to_graph(json_str) return load_model
[ "def", "load_model_by_id", "(", "self", ",", "model_id", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "str", "(", "model_id", ")", "+", "\".json\"", ")", ")", "as", "fin", ":", "json_str", "=", "fin", ".", "read", "(", ")", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "load_model", "=", "json_to_graph", "(", "json_str", ")", "return", "load_model" ]
[ 275, 4 ]
[ 294, 25 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.load_best_model
(self)
Get the best model by model id Returns ------- load_model : graph.Graph the model graph representation
Get the best model by model id
def load_best_model(self): """ Get the best model by model id Returns ------- load_model : graph.Graph the model graph representation """ return self.load_model_by_id(self.get_best_model_id())
[ "def", "load_best_model", "(", "self", ")", ":", "return", "self", ".", "load_model_by_id", "(", "self", ".", "get_best_model_id", "(", ")", ")" ]
[ 296, 4 ]
[ 305, 62 ]
python
en
['en', 'error', 'th']
False
NetworkMorphismTuner.get_metric_value_by_id
(self, model_id)
Get the model metric valud by its model_id Parameters ---------- model_id : int model index Returns ------- float the model metric
Get the model metric valud by its model_id
def get_metric_value_by_id(self, model_id): """ Get the model metric valud by its model_id Parameters ---------- model_id : int model index Returns ------- float the model metric """ for item in self.history: if item["model_id"] == model_id: return item["metric_value"] return None
[ "def", "get_metric_value_by_id", "(", "self", ",", "model_id", ")", ":", "for", "item", "in", "self", ".", "history", ":", "if", "item", "[", "\"model_id\"", "]", "==", "model_id", ":", "return", "item", "[", "\"metric_value\"", "]", "return", "None" ]
[ 307, 4 ]
[ 324, 19 ]
python
en
['en', 'error', 'th']
False
async_validate_config_item
(hass, config, full_config=None)
Validate config item.
Validate config item.
async def async_validate_config_item(hass, config, full_config=None): """Validate config item.""" config = SCRIPT_ENTRY_SCHEMA(config) config[CONF_SEQUENCE] = await asyncio.gather( *[ async_validate_action_config(hass, action) for action in config[CONF_SEQUENCE] ] ) return config
[ "async", "def", "async_validate_config_item", "(", "hass", ",", "config", ",", "full_config", "=", "None", ")", ":", "config", "=", "SCRIPT_ENTRY_SCHEMA", "(", "config", ")", "config", "[", "CONF_SEQUENCE", "]", "=", "await", "asyncio", ".", "gather", "(", "*", "[", "async_validate_action_config", "(", "hass", ",", "action", ")", "for", "action", "in", "config", "[", "CONF_SEQUENCE", "]", "]", ")", "return", "config" ]
[ 14, 0 ]
[ 24, 17 ]
python
en
['en', 'la', 'en']
True
_try_async_validate_config_item
(hass, object_id, config, full_config=None)
Validate config item.
Validate config item.
async def _try_async_validate_config_item(hass, object_id, config, full_config=None): """Validate config item.""" try: cv.slug(object_id) config = await async_validate_config_item(hass, config, full_config) except (vol.Invalid, HomeAssistantError) as ex: async_log_exception(ex, DOMAIN, full_config or config, hass) return None return config
[ "async", "def", "_try_async_validate_config_item", "(", "hass", ",", "object_id", ",", "config", ",", "full_config", "=", "None", ")", ":", "try", ":", "cv", ".", "slug", "(", "object_id", ")", "config", "=", "await", "async_validate_config_item", "(", "hass", ",", "config", ",", "full_config", ")", "except", "(", "vol", ".", "Invalid", ",", "HomeAssistantError", ")", "as", "ex", ":", "async_log_exception", "(", "ex", ",", "DOMAIN", ",", "full_config", "or", "config", ",", "hass", ")", "return", "None", "return", "config" ]
[ 27, 0 ]
[ 36, 17 ]
python
en
['en', 'la', 'en']
True
async_validate_config
(hass, config)
Validate config.
Validate config.
async def async_validate_config(hass, config): """Validate config.""" if DOMAIN in config: validated_config = {} for object_id, cfg in config[DOMAIN].items(): cfg = await _try_async_validate_config_item(hass, object_id, cfg, config) if cfg is not None: validated_config[object_id] = cfg config[DOMAIN] = validated_config return config
[ "async", "def", "async_validate_config", "(", "hass", ",", "config", ")", ":", "if", "DOMAIN", "in", "config", ":", "validated_config", "=", "{", "}", "for", "object_id", ",", "cfg", "in", "config", "[", "DOMAIN", "]", ".", "items", "(", ")", ":", "cfg", "=", "await", "_try_async_validate_config_item", "(", "hass", ",", "object_id", ",", "cfg", ",", "config", ")", "if", "cfg", "is", "not", "None", ":", "validated_config", "[", "object_id", "]", "=", "cfg", "config", "[", "DOMAIN", "]", "=", "validated_config", "return", "config" ]
[ 39, 0 ]
[ 49, 17 ]
python
en
['en', 'la', 'it']
False
TestLiteJet.setup_method
(self, method)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setup_method(self, method): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.start() self.hass.block_till_done()
[ "def", "setup_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "hass", ".", "start", "(", ")", "self", ".", "hass", ".", "block_till_done", "(", ")" ]
[ 14, 4 ]
[ 18, 35 ]
python
en
['en', 'en', 'en']
True
TestLiteJet.teardown_method
(self, method)
Stop everything that was started.
Stop everything that was started.
def teardown_method(self, method): """Stop everything that was started.""" self.hass.stop()
[ "def", "teardown_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 20, 4 ]
[ 22, 24 ]
python
en
['en', 'en', 'en']
True
TestLiteJet.test_is_ignored_unspecified
(self)
Ensure it is ignored when unspecified.
Ensure it is ignored when unspecified.
def test_is_ignored_unspecified(self): """Ensure it is ignored when unspecified.""" self.hass.data["litejet_config"] = {} assert not litejet.is_ignored(self.hass, "Test")
[ "def", "test_is_ignored_unspecified", "(", "self", ")", ":", "self", ".", "hass", ".", "data", "[", "\"litejet_config\"", "]", "=", "{", "}", "assert", "not", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Test\"", ")" ]
[ 24, 4 ]
[ 27, 56 ]
python
en
['en', 'en', 'en']
True
TestLiteJet.test_is_ignored_empty
(self)
Ensure it is ignored when empty.
Ensure it is ignored when empty.
def test_is_ignored_empty(self): """Ensure it is ignored when empty.""" self.hass.data["litejet_config"] = {litejet.CONF_EXCLUDE_NAMES: []} assert not litejet.is_ignored(self.hass, "Test")
[ "def", "test_is_ignored_empty", "(", "self", ")", ":", "self", ".", "hass", ".", "data", "[", "\"litejet_config\"", "]", "=", "{", "litejet", ".", "CONF_EXCLUDE_NAMES", ":", "[", "]", "}", "assert", "not", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Test\"", ")" ]
[ 29, 4 ]
[ 32, 56 ]
python
en
['en', 'fy', 'en']
True
TestLiteJet.test_is_ignored_normal
(self)
Test if usually ignored.
Test if usually ignored.
def test_is_ignored_normal(self): """Test if usually ignored.""" self.hass.data["litejet_config"] = { litejet.CONF_EXCLUDE_NAMES: ["Test", "Other One"] } assert litejet.is_ignored(self.hass, "Test") assert not litejet.is_ignored(self.hass, "Other one") assert not litejet.is_ignored(self.hass, "Other 0ne") assert litejet.is_ignored(self.hass, "Other One There") assert litejet.is_ignored(self.hass, "Other One")
[ "def", "test_is_ignored_normal", "(", "self", ")", ":", "self", ".", "hass", ".", "data", "[", "\"litejet_config\"", "]", "=", "{", "litejet", ".", "CONF_EXCLUDE_NAMES", ":", "[", "\"Test\"", ",", "\"Other One\"", "]", "}", "assert", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Test\"", ")", "assert", "not", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Other one\"", ")", "assert", "not", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Other 0ne\"", ")", "assert", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Other One There\"", ")", "assert", "litejet", ".", "is_ignored", "(", "self", ".", "hass", ",", "\"Other One\"", ")" ]
[ 34, 4 ]
[ 43, 57 ]
python
en
['en', 'en', 'en']
True
async_get_actions
(hass: HomeAssistant, device_id: str)
List device actions for NEW_NAME devices.
List device actions for NEW_NAME devices.
async def async_get_actions(hass: HomeAssistant, device_id: str) -> List[dict]: """List device actions for NEW_NAME devices.""" registry = await entity_registry.async_get_registry(hass) actions = [] # TODO Read this comment and remove it. # This example shows how to iterate over the entities of this device # that match this integration. If your actions instead rely on # calling services, do something like: # zha_device = await _async_get_zha_device(hass, device_id) # return zha_device.device_actions # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue # Add actions for each entity that belongs to this integration # TODO add your own actions. actions.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_on", } ) actions.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_off", } ) return actions
[ "async", "def", "async_get_actions", "(", "hass", ":", "HomeAssistant", ",", "device_id", ":", "str", ")", "->", "List", "[", "dict", "]", ":", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "actions", "=", "[", "]", "# TODO Read this comment and remove it.", "# This example shows how to iterate over the entities of this device", "# that match this integration. If your actions instead rely on", "# calling services, do something like:", "# zha_device = await _async_get_zha_device(hass, device_id)", "# return zha_device.device_actions", "# Get all the integrations entities for this device", "for", "entry", "in", "entity_registry", ".", "async_entries_for_device", "(", "registry", ",", "device_id", ")", ":", "if", "entry", ".", "domain", "!=", "DOMAIN", ":", "continue", "# Add actions for each entity that belongs to this integration", "# TODO add your own actions.", "actions", ".", "append", "(", "{", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"turn_on\"", ",", "}", ")", "actions", ".", "append", "(", "{", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"turn_off\"", ",", "}", ")", "return", "actions" ]
[ 31, 0 ]
[ 67, 18 ]
python
en
['fr', 'en', 'en']
True
async_call_action_from_config
( hass: HomeAssistant, config: dict, variables: dict, context: Optional[Context] )
Execute a device action.
Execute a device action.
async def async_call_action_from_config( hass: HomeAssistant, config: dict, variables: dict, context: Optional[Context] ) -> None: """Execute a device action.""" config = ACTION_SCHEMA(config) service_data = {ATTR_ENTITY_ID: config[CONF_ENTITY_ID]} if config[CONF_TYPE] == "turn_on": service = SERVICE_TURN_ON elif config[CONF_TYPE] == "turn_off": service = SERVICE_TURN_OFF await hass.services.async_call( DOMAIN, service, service_data, blocking=True, context=context )
[ "async", "def", "async_call_action_from_config", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ",", "variables", ":", "dict", ",", "context", ":", "Optional", "[", "Context", "]", ")", "->", "None", ":", "config", "=", "ACTION_SCHEMA", "(", "config", ")", "service_data", "=", "{", "ATTR_ENTITY_ID", ":", "config", "[", "CONF_ENTITY_ID", "]", "}", "if", "config", "[", "CONF_TYPE", "]", "==", "\"turn_on\"", ":", "service", "=", "SERVICE_TURN_ON", "elif", "config", "[", "CONF_TYPE", "]", "==", "\"turn_off\"", ":", "service", "=", "SERVICE_TURN_OFF", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "service", ",", "service_data", ",", "blocking", "=", "True", ",", "context", "=", "context", ")" ]
[ 70, 0 ]
[ 85, 5 ]
python
en
['ro', 'en', 'en']
True
_build_mock_url
(origin, destination, modes, api_key, departure=None, arrival=None)
Construct a url for HERE.
Construct a url for HERE.
def _build_mock_url(origin, destination, modes, api_key, departure=None, arrival=None): """Construct a url for HERE.""" base_url = "https://route.ls.hereapi.com/routing/7.2/calculateroute.json?" parameters = { "waypoint0": f"geo!{origin}", "waypoint1": f"geo!{destination}", "mode": ";".join(str(herepy.RouteMode[mode]) for mode in modes), "apikey": api_key, } if arrival is not None: parameters["arrival"] = arrival if departure is not None: parameters["departure"] = departure if departure is None and arrival is None: parameters["departure"] = "now" url = base_url + urllib.parse.urlencode(parameters) print(url) return url
[ "def", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "api_key", ",", "departure", "=", "None", ",", "arrival", "=", "None", ")", ":", "base_url", "=", "\"https://route.ls.hereapi.com/routing/7.2/calculateroute.json?\"", "parameters", "=", "{", "\"waypoint0\"", ":", "f\"geo!{origin}\"", ",", "\"waypoint1\"", ":", "f\"geo!{destination}\"", ",", "\"mode\"", ":", "\";\"", ".", "join", "(", "str", "(", "herepy", ".", "RouteMode", "[", "mode", "]", ")", "for", "mode", "in", "modes", ")", ",", "\"apikey\"", ":", "api_key", ",", "}", "if", "arrival", "is", "not", "None", ":", "parameters", "[", "\"arrival\"", "]", "=", "arrival", "if", "departure", "is", "not", "None", ":", "parameters", "[", "\"departure\"", "]", "=", "departure", "if", "departure", "is", "None", "and", "arrival", "is", "None", ":", "parameters", "[", "\"departure\"", "]", "=", "\"now\"", "url", "=", "base_url", "+", "urllib", ".", "parse", ".", "urlencode", "(", "parameters", ")", "print", "(", "url", ")", "return", "url" ]
[ 69, 0 ]
[ 86, 14 ]
python
en
['en', 'en', 'en']
True
_assert_truck_sensor
(sensor)
Assert that states and attributes are correct for truck_response.
Assert that states and attributes are correct for truck_response.
def _assert_truck_sensor(sensor): """Assert that states and attributes are correct for truck_response.""" assert sensor.state == "14" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 13.533333333333333 assert sensor.attributes.get(ATTR_DISTANCE) == 13.049 assert sensor.attributes.get(ATTR_ROUTE) == ( "I-190; I-294 S - Tri-State Tollway; I-290 W - Eisenhower Expy W; " "IL-64 W - E North Ave; I-290 E - Eisenhower Expy E; I-290" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 13.533333333333333 assert sensor.attributes.get(ATTR_ORIGIN) == ",".join( [TRUCK_ORIGIN_LATITUDE, TRUCK_ORIGIN_LONGITUDE] ) assert sensor.attributes.get(ATTR_DESTINATION) == ",".join( [TRUCK_DESTINATION_LATITUDE, TRUCK_DESTINATION_LONGITUDE] ) assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "Eisenhower Expy E" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_TRUCK assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_TRUCK
[ "def", "_assert_truck_sensor", "(", "sensor", ")", ":", "assert", "sensor", ".", "state", "==", "\"14\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "13.533333333333333", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "13.049", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"I-190; I-294 S - Tri-State Tollway; I-290 W - Eisenhower Expy W; \"", "\"IL-64 W - E North Ave; I-290 E - Eisenhower Expy E; I-290\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "13.533333333333333", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "\",\"", ".", "join", "(", "[", "TRUCK_ORIGIN_LATITUDE", ",", "TRUCK_ORIGIN_LONGITUDE", "]", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "\",\"", ".", "join", "(", "[", "TRUCK_DESTINATION_LATITUDE", ",", "TRUCK_DESTINATION_LONGITUDE", "]", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"Eisenhower Expy E\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_TRUCK", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_TRUCK" ]
[ 89, 0 ]
[ 114, 57 ]
python
en
['en', 'en', 'en']
True
requests_mock_credentials_check
(requests_mock)
Add the url used in the api validation to all requests mock.
Add the url used in the api validation to all requests mock.
def requests_mock_credentials_check(requests_mock): """Add the url used in the api validation to all requests mock.""" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url( ",".join([CAR_ORIGIN_LATITUDE, CAR_ORIGIN_LONGITUDE]), ",".join([CAR_DESTINATION_LATITUDE, CAR_DESTINATION_LONGITUDE]), modes, API_KEY, ) requests_mock.get( response_url, text=load_fixture("here_travel_time/car_response.json") ) return requests_mock
[ "def", "requests_mock_credentials_check", "(", "requests_mock", ")", ":", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_CAR", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "\",\"", ".", "join", "(", "[", "CAR_ORIGIN_LATITUDE", ",", "CAR_ORIGIN_LONGITUDE", "]", ")", ",", "\",\"", ".", "join", "(", "[", "CAR_DESTINATION_LATITUDE", ",", "CAR_DESTINATION_LONGITUDE", "]", ")", ",", "modes", ",", "API_KEY", ",", ")", "requests_mock", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/car_response.json\"", ")", ")", "return", "requests_mock" ]
[ 118, 0 ]
[ 130, 24 ]
python
en
['en', 'en', 'en']
True
requests_mock_truck_response
(requests_mock_credentials_check)
Return a requests_mock for truck respones.
Return a requests_mock for truck respones.
def requests_mock_truck_response(requests_mock_credentials_check): """Return a requests_mock for truck respones.""" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_TRUCK, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url( ",".join([TRUCK_ORIGIN_LATITUDE, TRUCK_ORIGIN_LONGITUDE]), ",".join([TRUCK_DESTINATION_LATITUDE, TRUCK_DESTINATION_LONGITUDE]), modes, API_KEY, ) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/truck_response.json") )
[ "def", "requests_mock_truck_response", "(", "requests_mock_credentials_check", ")", ":", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_TRUCK", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "\",\"", ".", "join", "(", "[", "TRUCK_ORIGIN_LATITUDE", ",", "TRUCK_ORIGIN_LONGITUDE", "]", ")", ",", "\",\"", ".", "join", "(", "[", "TRUCK_DESTINATION_LATITUDE", ",", "TRUCK_DESTINATION_LONGITUDE", "]", ")", ",", "modes", ",", "API_KEY", ",", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/truck_response.json\"", ")", ")" ]
[ 134, 0 ]
[ 145, 5 ]
python
en
['en', 'en', 'en']
True
requests_mock_car_disabled_response
(requests_mock_credentials_check)
Return a requests_mock for truck respones.
Return a requests_mock for truck respones.
def requests_mock_car_disabled_response(requests_mock_credentials_check): """Return a requests_mock for truck respones.""" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url( ",".join([CAR_ORIGIN_LATITUDE, CAR_ORIGIN_LONGITUDE]), ",".join([CAR_DESTINATION_LATITUDE, CAR_DESTINATION_LONGITUDE]), modes, API_KEY, ) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/car_response.json") )
[ "def", "requests_mock_car_disabled_response", "(", "requests_mock_credentials_check", ")", ":", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_CAR", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "\",\"", ".", "join", "(", "[", "CAR_ORIGIN_LATITUDE", ",", "CAR_ORIGIN_LONGITUDE", "]", ")", ",", "\",\"", ".", "join", "(", "[", "CAR_DESTINATION_LATITUDE", ",", "CAR_DESTINATION_LONGITUDE", "]", ")", ",", "modes", ",", "API_KEY", ",", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/car_response.json\"", ")", ")" ]
[ 149, 0 ]
[ 160, 5 ]
python
en
['en', 'en', 'en']
True
test_car
(hass, requests_mock_car_disabled_response)
Test that car works.
Test that car works.
async def test_car(hass, requests_mock_car_disabled_response): """Test that car works.""" config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": CAR_ORIGIN_LATITUDE, "origin_longitude": CAR_ORIGIN_LONGITUDE, "destination_latitude": CAR_DESTINATION_LATITUDE, "destination_longitude": CAR_DESTINATION_LONGITUDE, "api_key": API_KEY, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.state == "30" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 30.05 assert sensor.attributes.get(ATTR_DISTANCE) == 23.903 assert sensor.attributes.get(ATTR_ROUTE) == ( "US-29 - K St NW; US-29 - Whitehurst Fwy; " "I-495 N - Capital Beltway; MD-187 S - Old Georgetown Rd" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 31.016666666666666 assert sensor.attributes.get(ATTR_ORIGIN) == ",".join( [CAR_ORIGIN_LATITUDE, CAR_ORIGIN_LONGITUDE] ) assert sensor.attributes.get(ATTR_DESTINATION) == ",".join( [CAR_DESTINATION_LATITUDE, CAR_DESTINATION_LONGITUDE] ) assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "22nd St NW" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "Service Rd S" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_CAR assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_CAR # Test traffic mode disabled assert sensor.attributes.get(ATTR_DURATION) != sensor.attributes.get( ATTR_DURATION_IN_TRAFFIC )
[ "async", "def", "test_car", "(", "hass", ",", "requests_mock_car_disabled_response", ")", ":", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "CAR_ORIGIN_LATITUDE", ",", "\"origin_longitude\"", ":", "CAR_ORIGIN_LONGITUDE", ",", "\"destination_latitude\"", ":", "CAR_DESTINATION_LATITUDE", ",", "\"destination_longitude\"", ":", "CAR_DESTINATION_LONGITUDE", ",", "\"api_key\"", ":", "API_KEY", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "state", "==", "\"30\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "30.05", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "23.903", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"US-29 - K St NW; US-29 - Whitehurst Fwy; \"", "\"I-495 N - Capital Beltway; MD-187 S - Old Georgetown Rd\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "31.016666666666666", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "\",\"", ".", "join", "(", "[", "CAR_ORIGIN_LATITUDE", ",", "CAR_ORIGIN_LONGITUDE", "]", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "\",\"", ".", "join", "(", "[", "CAR_DESTINATION_LATITUDE", ",", "CAR_DESTINATION_LONGITUDE", "]", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"22nd St NW\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"Service Rd S\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_CAR", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_CAR", "# Test traffic mode disabled", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "!=", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")" ]
[ 163, 0 ]
[ 210, 5 ]
python
en
['en', 'cy', 'en']
True
test_traffic_mode_enabled
(hass, requests_mock_credentials_check)
Test that traffic mode enabled works.
Test that traffic mode enabled works.
async def test_traffic_mode_enabled(hass, requests_mock_credentials_check): """Test that traffic mode enabled works.""" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_ENABLED] response_url = _build_mock_url( ",".join([CAR_ORIGIN_LATITUDE, CAR_ORIGIN_LONGITUDE]), ",".join([CAR_DESTINATION_LATITUDE, CAR_DESTINATION_LONGITUDE]), modes, API_KEY, ) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/car_enabled_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": CAR_ORIGIN_LATITUDE, "origin_longitude": CAR_ORIGIN_LONGITUDE, "destination_latitude": CAR_DESTINATION_LATITUDE, "destination_longitude": CAR_DESTINATION_LONGITUDE, "api_key": API_KEY, "traffic_mode": True, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") # Test traffic mode enabled assert sensor.attributes.get(ATTR_DURATION) != sensor.attributes.get( ATTR_DURATION_IN_TRAFFIC )
[ "async", "def", "test_traffic_mode_enabled", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_CAR", ",", "TRAFFIC_MODE_ENABLED", "]", "response_url", "=", "_build_mock_url", "(", "\",\"", ".", "join", "(", "[", "CAR_ORIGIN_LATITUDE", ",", "CAR_ORIGIN_LONGITUDE", "]", ")", ",", "\",\"", ".", "join", "(", "[", "CAR_DESTINATION_LATITUDE", ",", "CAR_DESTINATION_LONGITUDE", "]", ")", ",", "modes", ",", "API_KEY", ",", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/car_enabled_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "CAR_ORIGIN_LATITUDE", ",", "\"origin_longitude\"", ":", "CAR_ORIGIN_LONGITUDE", ",", "\"destination_latitude\"", ":", "CAR_DESTINATION_LATITUDE", ",", "\"destination_longitude\"", ":", "CAR_DESTINATION_LONGITUDE", ",", "\"api_key\"", ":", "API_KEY", ",", "\"traffic_mode\"", ":", "True", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "# Test traffic mode enabled", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "!=", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")" ]
[ 213, 0 ]
[ 248, 5 ]
python
en
['en', 'en', 'en']
True
test_imperial
(hass, requests_mock_car_disabled_response)
Test that imperial units work.
Test that imperial units work.
async def test_imperial(hass, requests_mock_car_disabled_response): """Test that imperial units work.""" config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": CAR_ORIGIN_LATITUDE, "origin_longitude": CAR_ORIGIN_LONGITUDE, "destination_latitude": CAR_DESTINATION_LATITUDE, "destination_longitude": CAR_DESTINATION_LONGITUDE, "api_key": API_KEY, "unit_system": "imperial", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.attributes.get(ATTR_DISTANCE) == 14.852635608048994
[ "async", "def", "test_imperial", "(", "hass", ",", "requests_mock_car_disabled_response", ")", ":", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "CAR_ORIGIN_LATITUDE", ",", "\"origin_longitude\"", ":", "CAR_ORIGIN_LONGITUDE", ",", "\"destination_latitude\"", ":", "CAR_DESTINATION_LATITUDE", ",", "\"destination_longitude\"", ":", "CAR_DESTINATION_LONGITUDE", ",", "\"api_key\"", ":", "API_KEY", ",", "\"unit_system\"", ":", "\"imperial\"", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "14.852635608048994" ]
[ 251, 0 ]
[ 272, 69 ]
python
en
['en', 'en', 'en']
True
test_route_mode_shortest
(hass, requests_mock_credentials_check)
Test that route mode shortest works.
Test that route mode shortest works.
async def test_route_mode_shortest(hass, requests_mock_credentials_check): """Test that route mode shortest works.""" origin = "38.902981,-77.048338" destination = "39.042158,-77.119116" modes = [ROUTE_MODE_SHORTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/car_shortest_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "route_mode": ROUTE_MODE_SHORTEST, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.attributes.get(ATTR_DISTANCE) == 18.388
[ "async", "def", "test_route_mode_shortest", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"38.902981,-77.048338\"", "destination", "=", "\"39.042158,-77.119116\"", "modes", "=", "[", "ROUTE_MODE_SHORTEST", ",", "TRAVEL_MODE_CAR", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/car_shortest_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"route_mode\"", ":", "ROUTE_MODE_SHORTEST", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "18.388" ]
[ 275, 0 ]
[ 304, 57 ]
python
en
['en', 'en', 'en']
True
test_route_mode_fastest
(hass, requests_mock_credentials_check)
Test that route mode fastest works.
Test that route mode fastest works.
async def test_route_mode_fastest(hass, requests_mock_credentials_check): """Test that route mode fastest works.""" origin = "38.902981,-77.048338" destination = "39.042158,-77.119116" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_ENABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/car_enabled_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "traffic_mode": True, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.attributes.get(ATTR_DISTANCE) == 23.381
[ "async", "def", "test_route_mode_fastest", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"38.902981,-77.048338\"", "destination", "=", "\"39.042158,-77.119116\"", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_CAR", ",", "TRAFFIC_MODE_ENABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/car_enabled_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"traffic_mode\"", ":", "True", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "23.381" ]
[ 307, 0 ]
[ 336, 57 ]
python
en
['en', 'en', 'en']
True
test_truck
(hass, requests_mock_truck_response)
Test that truck works.
Test that truck works.
async def test_truck(hass, requests_mock_truck_response): """Test that truck works.""" config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": TRUCK_ORIGIN_LATITUDE, "origin_longitude": TRUCK_ORIGIN_LONGITUDE, "destination_latitude": TRUCK_DESTINATION_LATITUDE, "destination_longitude": TRUCK_DESTINATION_LONGITUDE, "api_key": API_KEY, "mode": TRAVEL_MODE_TRUCK, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") _assert_truck_sensor(sensor)
[ "async", "def", "test_truck", "(", "hass", ",", "requests_mock_truck_response", ")", ":", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "TRUCK_ORIGIN_LATITUDE", ",", "\"origin_longitude\"", ":", "TRUCK_ORIGIN_LONGITUDE", ",", "\"destination_latitude\"", ":", "TRUCK_DESTINATION_LATITUDE", ",", "\"destination_longitude\"", ":", "TRUCK_DESTINATION_LONGITUDE", ",", "\"api_key\"", ":", "API_KEY", ",", "\"mode\"", ":", "TRAVEL_MODE_TRUCK", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "_assert_truck_sensor", "(", "sensor", ")" ]
[ 339, 0 ]
[ 360, 32 ]
python
en
['en', 'en', 'en']
True
test_public_transport
(hass, requests_mock_credentials_check)
Test that publicTransport works.
Test that publicTransport works.
async def test_public_transport(hass, requests_mock_credentials_check): """Test that publicTransport works.""" origin = "41.9798,-87.8801" destination = "41.9043,-87.9216" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_PUBLIC, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/public_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "mode": TRAVEL_MODE_PUBLIC, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.state == "89" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 89.16666666666667 assert sensor.attributes.get(ATTR_DISTANCE) == 22.325 assert sensor.attributes.get(ATTR_ROUTE) == ( "332 - Palmer/Schiller; 332 - Cargo Rd./Delta Cargo; 332 - Palmer/Schiller" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 89.16666666666667 assert sensor.attributes.get(ATTR_ORIGIN) == origin assert sensor.attributes.get(ATTR_DESTINATION) == destination assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "Mannheim Rd" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_PUBLIC assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_PUBLIC
[ "async", "def", "test_public_transport", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"41.9798,-87.8801\"", "destination", "=", "\"41.9043,-87.9216\"", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_PUBLIC", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/public_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"mode\"", ":", "TRAVEL_MODE_PUBLIC", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "state", "==", "\"89\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "89.16666666666667", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "22.325", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"332 - Palmer/Schiller; 332 - Cargo Rd./Delta Cargo; 332 - Palmer/Schiller\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "89.16666666666667", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "origin", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "destination", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"Mannheim Rd\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_PUBLIC", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_PUBLIC" ]
[ 363, 0 ]
[ 410, 58 ]
python
en
['en', 'da', 'en']
True
test_public_transport_time_table
(hass, requests_mock_credentials_check)
Test that publicTransportTimeTable works.
Test that publicTransportTimeTable works.
async def test_public_transport_time_table(hass, requests_mock_credentials_check): """Test that publicTransportTimeTable works.""" origin = "41.9798,-87.8801" destination = "41.9043,-87.9216" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_PUBLIC_TIME_TABLE, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/public_time_table_response.json"), ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "mode": TRAVEL_MODE_PUBLIC_TIME_TABLE, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.state == "80" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 79.73333333333333 assert sensor.attributes.get(ATTR_DISTANCE) == 14.775 assert sensor.attributes.get(ATTR_ROUTE) == ( "330 - Archer/Harlem (Terminal); 309 - Elmhurst Metra Station" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 79.73333333333333 assert sensor.attributes.get(ATTR_ORIGIN) == origin assert sensor.attributes.get(ATTR_DESTINATION) == destination assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "Mannheim Rd" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_PUBLIC_TIME_TABLE assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_PUBLIC
[ "async", "def", "test_public_transport_time_table", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"41.9798,-87.8801\"", "destination", "=", "\"41.9043,-87.9216\"", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_PUBLIC_TIME_TABLE", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/public_time_table_response.json\"", ")", ",", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"mode\"", ":", "TRAVEL_MODE_PUBLIC_TIME_TABLE", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "state", "==", "\"80\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "79.73333333333333", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "14.775", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"330 - Archer/Harlem (Terminal); 309 - Elmhurst Metra Station\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "79.73333333333333", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "origin", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "destination", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"Mannheim Rd\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_PUBLIC_TIME_TABLE", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_PUBLIC" ]
[ 413, 0 ]
[ 461, 58 ]
python
en
['en', 'da', 'en']
True
test_pedestrian
(hass, requests_mock_credentials_check)
Test that pedestrian works.
Test that pedestrian works.
async def test_pedestrian(hass, requests_mock_credentials_check): """Test that pedestrian works.""" origin = "41.9798,-87.8801" destination = "41.9043,-87.9216" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_PEDESTRIAN, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/pedestrian_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "mode": TRAVEL_MODE_PEDESTRIAN, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.state == "211" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 210.51666666666668 assert sensor.attributes.get(ATTR_DISTANCE) == 12.533 assert sensor.attributes.get(ATTR_ROUTE) == ( "Mannheim Rd; W Belmont Ave; Cullerton St; E Fullerton Ave; " "La Porte Ave; E Palmer Ave; N Railroad Ave; W North Ave; " "E North Ave; E Third St" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 210.51666666666668 assert sensor.attributes.get(ATTR_ORIGIN) == origin assert sensor.attributes.get(ATTR_DESTINATION) == destination assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "Mannheim Rd" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_PEDESTRIAN assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_PEDESTRIAN
[ "async", "def", "test_pedestrian", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"41.9798,-87.8801\"", "destination", "=", "\"41.9043,-87.9216\"", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_PEDESTRIAN", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/pedestrian_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"mode\"", ":", "TRAVEL_MODE_PEDESTRIAN", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "state", "==", "\"211\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "210.51666666666668", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "12.533", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"Mannheim Rd; W Belmont Ave; Cullerton St; E Fullerton Ave; \"", "\"La Porte Ave; E Palmer Ave; N Railroad Ave; W North Ave; \"", "\"E North Ave; E Third St\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "210.51666666666668", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "origin", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "destination", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"Mannheim Rd\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_PEDESTRIAN", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_PEDESTRIAN" ]
[ 464, 0 ]
[ 514, 62 ]
python
en
['en', 'de', 'en']
True
test_bicycle
(hass, requests_mock_credentials_check)
Test that bicycle works.
Test that bicycle works.
async def test_bicycle(hass, requests_mock_credentials_check): """Test that bicycle works.""" origin = "41.9798,-87.8801" destination = "41.9043,-87.9216" modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_BICYCLE, TRAFFIC_MODE_DISABLED] response_url = _build_mock_url(origin, destination, modes, API_KEY) requests_mock_credentials_check.get( response_url, text=load_fixture("here_travel_time/bike_response.json") ) config = { DOMAIN: { "platform": PLATFORM, "name": "test", "origin_latitude": origin.split(",")[0], "origin_longitude": origin.split(",")[1], "destination_latitude": destination.split(",")[0], "destination_longitude": destination.split(",")[1], "api_key": API_KEY, "mode": TRAVEL_MODE_BICYCLE, } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() sensor = hass.states.get("sensor.test") assert sensor.state == "55" assert sensor.attributes.get("unit_of_measurement") == TIME_MINUTES assert sensor.attributes.get(ATTR_ATTRIBUTION) is None assert sensor.attributes.get(ATTR_DURATION) == 54.86666666666667 assert sensor.attributes.get(ATTR_DISTANCE) == 12.613 assert sensor.attributes.get(ATTR_ROUTE) == ( "Mannheim Rd; W Belmont Ave; Cullerton St; N Landen Dr; " "E Fullerton Ave; N Wolf Rd; W North Ave; N Clinton Ave; " "E Third St; N Caroline Ave" ) assert sensor.attributes.get(CONF_UNIT_SYSTEM) == "metric" assert sensor.attributes.get(ATTR_DURATION_IN_TRAFFIC) == 54.86666666666667 assert sensor.attributes.get(ATTR_ORIGIN) == origin assert sensor.attributes.get(ATTR_DESTINATION) == destination assert sensor.attributes.get(ATTR_ORIGIN_NAME) == "Mannheim Rd" assert sensor.attributes.get(ATTR_DESTINATION_NAME) == "" assert sensor.attributes.get(CONF_MODE) == TRAVEL_MODE_BICYCLE assert sensor.attributes.get(CONF_TRAFFIC_MODE) is False assert sensor.attributes.get(ATTR_ICON) == ICON_BICYCLE
[ "async", "def", "test_bicycle", "(", "hass", ",", "requests_mock_credentials_check", ")", ":", "origin", "=", "\"41.9798,-87.8801\"", "destination", "=", "\"41.9043,-87.9216\"", "modes", "=", "[", "ROUTE_MODE_FASTEST", ",", "TRAVEL_MODE_BICYCLE", ",", "TRAFFIC_MODE_DISABLED", "]", "response_url", "=", "_build_mock_url", "(", "origin", ",", "destination", ",", "modes", ",", "API_KEY", ")", "requests_mock_credentials_check", ".", "get", "(", "response_url", ",", "text", "=", "load_fixture", "(", "\"here_travel_time/bike_response.json\"", ")", ")", "config", "=", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "PLATFORM", ",", "\"name\"", ":", "\"test\"", ",", "\"origin_latitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"origin_longitude\"", ":", "origin", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"destination_latitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "0", "]", ",", "\"destination_longitude\"", ":", "destination", ".", "split", "(", "\",\"", ")", "[", "1", "]", ",", "\"api_key\"", ":", "API_KEY", ",", "\"mode\"", ":", "TRAVEL_MODE_BICYCLE", ",", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_HOMEASSISTANT_START", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.test\"", ")", "assert", "sensor", ".", "state", "==", "\"55\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "TIME_MINUTES", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "is", "None", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION", ")", "==", "54.86666666666667", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DISTANCE", ")", "==", "12.613", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ROUTE", ")", "==", "(", "\"Mannheim Rd; W Belmont Ave; Cullerton St; N Landen Dr; \"", "\"E Fullerton Ave; N Wolf Rd; W North Ave; N Clinton Ave; \"", "\"E Third St; N Caroline Ave\"", ")", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_UNIT_SYSTEM", ")", "==", "\"metric\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DURATION_IN_TRAFFIC", ")", "==", "54.86666666666667", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN", ")", "==", "origin", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION", ")", "==", "destination", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ORIGIN_NAME", ")", "==", "\"Mannheim Rd\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_DESTINATION_NAME", ")", "==", "\"\"", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_MODE", ")", "==", "TRAVEL_MODE_BICYCLE", "assert", "sensor", ".", "attributes", ".", "get", "(", "CONF_TRAFFIC_MODE", ")", "is", "False", "assert", "sensor", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "ICON_BICYCLE" ]
[ 517, 0 ]
[ 566, 59 ]
python
en
['en', 'en', 'en']
True