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_ssdp_with_receiver_id_device_exists_abort
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow if DirecTV receiver already configured.
Test we abort SSDP flow if DirecTV receiver already configured.
async def test_ssdp_with_receiver_id_device_exists_abort( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow if DirecTV receiver already configured.""" await setup_integration(hass, aioclient_mock, skip_entry_setup=True) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() discovery_info[ATTR_UPNP_SERIAL] = UPNP_SERIAL result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
[ "async", "def", "test_ssdp_with_receiver_id_device_exists_abort", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "setup_integration", "(", "hass", ",", "aioclient_mock", ",", "skip_entry_setup", "=", "True", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "discovery_info", "[", "ATTR_UPNP_SERIAL", "]", "=", "UPNP_SERIAL", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"already_configured\"" ]
[ 140, 0 ]
[ 155, 51 ]
python
en
['en', 'de', 'en']
True
test_unknown_error
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we show user form on unknown error.
Test we show user form on unknown error.
async def test_unknown_error( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we show user form on unknown error.""" user_input = MOCK_USER_INPUT.copy() with patch( "homeassistant.components.directv.config_flow.DIRECTV.update", side_effect=Exception, ): result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "unknown"
[ "async", "def", "test_unknown_error", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "with", "patch", "(", "\"homeassistant.components.directv.config_flow.DIRECTV.update\"", ",", "side_effect", "=", "Exception", ",", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"unknown\"" ]
[ 158, 0 ]
[ 174, 40 ]
python
en
['en', 'de', 'en']
True
test_ssdp_unknown_error
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow on unknown error.
Test we abort SSDP flow on unknown error.
async def test_ssdp_unknown_error( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow on unknown error.""" discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() with patch( "homeassistant.components.directv.config_flow.DIRECTV.update", side_effect=Exception, ): result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "unknown"
[ "async", "def", "test_ssdp_unknown_error", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "with", "patch", "(", "\"homeassistant.components.directv.config_flow.DIRECTV.update\"", ",", "side_effect", "=", "Exception", ",", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"unknown\"" ]
[ 177, 0 ]
[ 193, 40 ]
python
en
['en', 'de', 'en']
True
test_ssdp_confirm_unknown_error
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test we abort SSDP flow on unknown error.
Test we abort SSDP flow on unknown error.
async def test_ssdp_confirm_unknown_error( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort SSDP flow on unknown error.""" discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() with patch( "homeassistant.components.directv.config_flow.DIRECTV.update", side_effect=Exception, ): result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP, CONF_HOST: HOST, CONF_NAME: HOST}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "unknown"
[ "async", "def", "test_ssdp_confirm_unknown_error", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "with", "patch", "(", "\"homeassistant.components.directv.config_flow.DIRECTV.update\"", ",", "side_effect", "=", "Exception", ",", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", ",", "CONF_HOST", ":", "HOST", ",", "CONF_NAME", ":", "HOST", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"unknown\"" ]
[ 196, 0 ]
[ 212, 40 ]
python
en
['en', 'de', 'en']
True
test_full_user_flow_implementation
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test the full manual user flow from start to finish.
Test the full manual user flow from start to finish.
async def test_full_user_flow_implementation( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test the full manual user flow from start to finish.""" mock_connection(aioclient_mock) result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "user" user_input = MOCK_USER_INPUT.copy() with patch( "homeassistant.components.directv.async_setup_entry", return_value=True ), patch("homeassistant.components.directv.async_setup", return_value=True): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == HOST assert result["data"] assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_RECEIVER_ID] == RECEIVER_ID
[ "async", "def", "test_full_user_flow_implementation", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_USER", "}", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "with", "patch", "(", "\"homeassistant.components.directv.async_setup_entry\"", ",", "return_value", "=", "True", ")", ",", "patch", "(", "\"homeassistant.components.directv.async_setup\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "user_input", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"title\"", "]", "==", "HOST", "assert", "result", "[", "\"data\"", "]", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "HOST", "assert", "result", "[", "\"data\"", "]", "[", "CONF_RECEIVER_ID", "]", "==", "RECEIVER_ID" ]
[ 215, 0 ]
[ 243, 58 ]
python
en
['en', 'en', 'en']
True
test_full_ssdp_flow_implementation
( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker )
Test the full SSDP flow from start to finish.
Test the full SSDP flow from start to finish.
async def test_full_ssdp_flow_implementation( hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker ) -> None: """Test the full SSDP flow from start to finish.""" mock_connection(aioclient_mock) discovery_info = MOCK_SSDP_DISCOVERY_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_SSDP}, data=discovery_info ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "ssdp_confirm" assert result["description_placeholders"] == {CONF_NAME: HOST} result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == HOST assert result["data"] assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_RECEIVER_ID] == RECEIVER_ID
[ "async", "def", "test_full_ssdp_flow_implementation", "(", "hass", ":", "HomeAssistantType", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ")", "discovery_info", "=", "MOCK_SSDP_DISCOVERY_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "CONF_SOURCE", ":", "SOURCE_SSDP", "}", ",", "data", "=", "discovery_info", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"ssdp_confirm\"", "assert", "result", "[", "\"description_placeholders\"", "]", "==", "{", "CONF_NAME", ":", "HOST", "}", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "user_input", "=", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"title\"", "]", "==", "HOST", "assert", "result", "[", "\"data\"", "]", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "HOST", "assert", "result", "[", "\"data\"", "]", "[", "CONF_RECEIVER_ID", "]", "==", "RECEIVER_ID" ]
[ 246, 0 ]
[ 270, 58 ]
python
en
['en', 'en', 'en']
True
test_get_triggers
(hass, device_reg, entity_reg, mqtt_mock, setup_tasmota)
Test we get the expected triggers from a discovered mqtt device.
Test we get the expected triggers from a discovered mqtt device.
async def test_get_triggers(hass, device_reg, entity_reg, mqtt_mock, setup_tasmota): """Test we get the expected triggers from a discovered mqtt device.""" config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) expected_triggers = [ { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, ] triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, expected_triggers)
[ "async", "def", "test_get_triggers", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "expected_triggers", "=", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "]", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "expected_triggers", ")" ]
[ 22, 0 ]
[ 43, 50 ]
python
en
['en', 'en', 'en']
True
test_get_unknown_triggers
( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota )
Test we don't get unknown triggers.
Test we don't get unknown triggers.
async def test_get_unknown_triggers( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota ): """Test we don't get unknown triggers.""" # Discover a device without device triggers config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = -1 mac = config["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_0_2", "type": "button_short_press", "subtype": "button_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, ] }, ) triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, [])
[ "async", "def", "test_get_unknown_triggers", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_0_2\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"button_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "[", "]", ")" ]
[ 46, 0 ]
[ 84, 35 ]
python
en
['en', 'en', 'en']
True
test_get_non_existing_triggers
( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota )
Test getting non existing triggers.
Test getting non existing triggers.
async def test_get_non_existing_triggers( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota ): """Test getting non existing triggers.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, [])
[ "async", "def", "test_get_non_existing_triggers", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "[", "]", ")" ]
[ 87, 0 ]
[ 101, 35 ]
python
en
['nl', 'en', 'en']
True
test_discover_bad_triggers
( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota )
Test exception handling when discovering trigger.
Test exception handling when discovering trigger.
async def test_discover_bad_triggers( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota ): """Test exception handling when discovering trigger.""" config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] # Trigger an exception when the entity is discovered with patch( "hatasmota.discovery.get_switch_triggers", return_value=[object()], ): async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config) ) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, []) # Trigger an exception when the entity is discovered class FakeTrigger(TasmotaSwitchTriggerConfig): """Bad TasmotaSwitchTriggerConfig to cause exceptions.""" @property def is_active(self): return True with patch( "hatasmota.discovery.get_switch_triggers", return_value=[ FakeTrigger( event=None, idx=1, mac=None, source=None, subtype=None, switchname=None, trigger_topic=None, type=None, ) ], ): async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config) ) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, []) # Rediscover without exception async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() expected_triggers = [ { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, ] triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, expected_triggers)
[ "async", "def", "test_discover_bad_triggers", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "# Trigger an exception when the entity is discovered", "with", "patch", "(", "\"hatasmota.discovery.get_switch_triggers\"", ",", "return_value", "=", "[", "object", "(", ")", "]", ",", ")", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "[", "]", ")", "# Trigger an exception when the entity is discovered", "class", "FakeTrigger", "(", "TasmotaSwitchTriggerConfig", ")", ":", "\"\"\"Bad TasmotaSwitchTriggerConfig to cause exceptions.\"\"\"", "@", "property", "def", "is_active", "(", "self", ")", ":", "return", "True", "with", "patch", "(", "\"hatasmota.discovery.get_switch_triggers\"", ",", "return_value", "=", "[", "FakeTrigger", "(", "event", "=", "None", ",", "idx", "=", "1", ",", "mac", "=", "None", ",", "source", "=", "None", ",", "subtype", "=", "None", ",", "switchname", "=", "None", ",", "trigger_topic", "=", "None", ",", "type", "=", "None", ",", ")", "]", ",", ")", ":", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "[", "]", ")", "# Rediscover without exception", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_triggers", "=", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "]", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "expected_triggers", ")" ]
[ 105, 0 ]
[ 174, 50 ]
python
en
['en', 'en', 'en']
True
test_update_remove_triggers
( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota )
Test triggers can be updated and removed.
Test triggers can be updated and removed.
async def test_update_remove_triggers( hass, device_reg, entity_reg, mqtt_mock, setup_tasmota ): """Test triggers can be updated and removed.""" # Discover a device with toggle + hold trigger config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = 5 mac = config1["mac"] # Discover a device with toggle + double press trigger config2 = copy.deepcopy(DEFAULT_CONFIG) config2["swc"][0] = 8 # Discover a device with no trigger config3 = copy.deepcopy(DEFAULT_CONFIG) config3["swc"][0] = -1 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) expected_triggers1 = [ { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_HOLD", "type": "button_long_press", "subtype": "switch_1", }, ] expected_triggers2 = copy.deepcopy(expected_triggers1) expected_triggers2[1]["type"] = "button_double_press" triggers = await async_get_device_automations(hass, "trigger", device_entry.id) for expected in expected_triggers1: assert expected in triggers # Update trigger async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() triggers = await async_get_device_automations(hass, "trigger", device_entry.id) for expected in expected_triggers2: assert expected in triggers # Remove trigger async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config3)) await hass.async_block_till_done() triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert triggers == []
[ "async", "def", "test_update_remove_triggers", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with toggle + hold trigger", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "5", "mac", "=", "config1", "[", "\"mac\"", "]", "# Discover a device with toggle + double press trigger", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "8", "# Discover a device with no trigger", "config3", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config3", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "expected_triggers1", "=", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_HOLD\"", ",", "\"type\"", ":", "\"button_long_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "]", "expected_triggers2", "=", "copy", ".", "deepcopy", "(", "expected_triggers1", ")", "expected_triggers2", "[", "1", "]", "[", "\"type\"", "]", "=", "\"button_double_press\"", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "for", "expected", "in", "expected_triggers1", ":", "assert", "expected", "in", "triggers", "# Update trigger", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "for", "expected", "in", "expected_triggers2", ":", "assert", "expected", "in", "triggers", "# Remove trigger", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config3", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert", "triggers", "==", "[", "]" ]
[ 177, 0 ]
[ 237, 25 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_mqtt_message
( hass, device_reg, calls, mqtt_mock, setup_tasmota )
Test triggers firing.
Test triggers firing.
async def test_if_fires_on_mqtt_message( hass, device_reg, calls, mqtt_mock, setup_tasmota ): """Test triggers firing.""" # Discover a device with 2 device triggers config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 config["swc"][2] = 9 config["swn"][2] = "custom_switch" mac = config["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_3_HOLD", "subtype": "switch_3", "type": "button_double_press", }, "action": { "service": "test.automation", "data_template": {"some": ("long_press")}, }, }, ] }, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "short_press" # Fake long press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"custom_switch":{"Action":"HOLD"}}' ) await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data["some"] == "long_press"
[ "async", "def", "test_if_fires_on_mqtt_message", "(", "hass", ",", "device_reg", ",", "calls", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with 2 device triggers", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "config", "[", "\"swc\"", "]", "[", "2", "]", "=", "9", "config", "[", "\"swn\"", "]", "[", "2", "]", "=", "\"custom_switch\"", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_3_HOLD\"", ",", "\"subtype\"", ":", "\"switch_3\"", ",", "\"type\"", ":", "\"button_double_press\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"long_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"short_press\"", "# Fake long press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"custom_switch\":{\"Action\":\"HOLD\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", "==", "\"long_press\"" ]
[ 240, 0 ]
[ 306, 48 ]
python
en
['en', 'lb', 'en']
True
test_if_fires_on_mqtt_message_late_discover
( hass, device_reg, calls, mqtt_mock, setup_tasmota )
Test triggers firing of MQTT device triggers discovered after setup.
Test triggers firing of MQTT device triggers discovered after setup.
async def test_if_fires_on_mqtt_message_late_discover( hass, device_reg, calls, mqtt_mock, setup_tasmota ): """Test triggers firing of MQTT device triggers discovered after setup.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] # Discover a device with 2 device triggers config2 = copy.deepcopy(DEFAULT_CONFIG) config2["swc"][0] = 0 config2["swc"][3] = 9 config2["swn"][3] = "custom_switch" async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_4_HOLD", "type": "switch_4", "subtype": "button_double_press", }, "action": { "service": "test.automation", "data_template": {"some": ("double_press")}, }, }, ] }, ) async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "short_press" # Fake long press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"custom_switch":{"Action":"HOLD"}}' ) await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data["some"] == "double_press"
[ "async", "def", "test_if_fires_on_mqtt_message_late_discover", "(", "hass", ",", "device_reg", ",", "calls", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "# Discover a device with 2 device triggers", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "config2", "[", "\"swc\"", "]", "[", "3", "]", "=", "9", "config2", "[", "\"swn\"", "]", "[", "3", "]", "=", "\"custom_switch\"", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_4_HOLD\"", ",", "\"type\"", ":", "\"switch_4\"", ",", "\"subtype\"", ":", "\"button_double_press\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"double_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"short_press\"", "# Fake long press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"custom_switch\":{\"Action\":\"HOLD\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", "==", "\"double_press\"" ]
[ 309, 0 ]
[ 383, 50 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_mqtt_message_after_update
( hass, device_reg, calls, mqtt_mock, setup_tasmota )
Test triggers firing after update.
Test triggers firing after update.
async def test_if_fires_on_mqtt_message_after_update( hass, device_reg, calls, mqtt_mock, setup_tasmota ): """Test triggers firing after update.""" # Discover a device with device trigger config1 = copy.deepcopy(DEFAULT_CONFIG) config2 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = 0 config2["swc"][0] = 0 config2["tp"][1] = "status" mac = config1["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, ] }, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 # Update the trigger with different topic async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 async_fire_mqtt_message( hass, "tasmota_49A3BC/status/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 2 # Update the trigger with same topic async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 2 async_fire_mqtt_message( hass, "tasmota_49A3BC/status/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 3
[ "async", "def", "test_if_fires_on_mqtt_message_after_update", "(", "hass", ",", "device_reg", ",", "calls", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "config2", "[", "\"tp\"", "]", "[", "1", "]", "=", "\"status\"", "mac", "=", "config1", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "# Update the trigger with different topic", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/status/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "# Update the trigger with same topic", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/status/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "3" ]
[ 386, 0 ]
[ 463, 26 ]
python
da
['da', 'lb', 'en']
False
test_no_resubscribe_same_topic
(hass, device_reg, mqtt_mock, setup_tasmota)
Test subscription to topics without change.
Test subscription to topics without change.
async def test_no_resubscribe_same_topic(hass, device_reg, mqtt_mock, setup_tasmota): """Test subscription to topics without change.""" # Discover a device with device trigger config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, ] }, ) call_count = mqtt_mock.async_subscribe.call_count assert call_count == 1 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() assert mqtt_mock.async_subscribe.call_count == call_count
[ "async", "def", "test_no_resubscribe_same_topic", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "call_count", "=", "mqtt_mock", ".", "async_subscribe", ".", "call_count", "assert", "call_count", "==", "1", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_mock", ".", "async_subscribe", ".", "call_count", "==", "call_count" ]
[ 466, 0 ]
[ 507, 61 ]
python
en
['en', 'en', 'en']
True
test_not_fires_on_mqtt_message_after_remove_by_mqtt
( hass, device_reg, calls, mqtt_mock, setup_tasmota )
Test triggers not firing after removal.
Test triggers not firing after removal.
async def test_not_fires_on_mqtt_message_after_remove_by_mqtt( hass, device_reg, calls, mqtt_mock, setup_tasmota ): """Test triggers not firing after removal.""" # Discover a device with device trigger config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, ] }, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 # Remove the trigger config["swc"][0] = -1 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 # Rediscover the trigger config["swc"][0] = 0 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 2
[ "async", "def", "test_not_fires_on_mqtt_message_after_remove_by_mqtt", "(", "hass", ",", "device_reg", ",", "calls", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "# Remove the trigger", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "# Rediscover the trigger", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2" ]
[ 510, 0 ]
[ 576, 26 ]
python
en
['en', 'en', 'en']
True
test_not_fires_on_mqtt_message_after_remove_from_registry
( hass, device_reg, calls, mqtt_mock, setup_tasmota )
Test triggers not firing after removal.
Test triggers not firing after removal.
async def test_not_fires_on_mqtt_message_after_remove_from_registry( hass, device_reg, calls, mqtt_mock, setup_tasmota ): """Test triggers not firing after removal.""" # Discover a device with device trigger config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, "action": { "service": "test.automation", "data_template": {"some": ("short_press")}, }, }, ] }, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 # Remove the device device_reg.async_remove_device(device_entry.id) await hass.async_block_till_done() async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_not_fires_on_mqtt_message_after_remove_from_registry", "(", "hass", ",", "device_reg", ",", "calls", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"short_press\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "# Remove the device", "device_reg", ".", "async_remove_device", "(", "device_entry", ".", "id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 579, 0 ]
[ 633, 26 ]
python
en
['en', 'en', 'en']
True
test_attach_remove
(hass, device_reg, mqtt_mock, setup_tasmota)
Test attach and removal of trigger.
Test attach and removal of trigger.
async def test_attach_remove(hass, device_reg, mqtt_mock, setup_tasmota): """Test attach and removal of trigger.""" # Discover a device with device trigger config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) calls = [] def callback(trigger, context): calls.append(trigger["trigger"]["description"]) remove = await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, callback, None, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0] == "event 'tasmota_event'" # Remove the trigger remove() await hass.async_block_till_done() # Verify the triggers are no longer active async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_attach_remove", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "calls", "=", "[", "]", "def", "callback", "(", "trigger", ",", "context", ")", ":", "calls", ".", "append", "(", "trigger", "[", "\"trigger\"", "]", "[", "\"description\"", "]", ")", "remove", "=", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "callback", ",", "None", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "==", "\"event 'tasmota_event'\"", "# Remove the trigger", "remove", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify the triggers are no longer active", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 636, 0 ]
[ 686, 26 ]
python
en
['en', 'en', 'en']
True
test_attach_remove_late
(hass, device_reg, mqtt_mock, setup_tasmota)
Test attach and removal of trigger.
Test attach and removal of trigger.
async def test_attach_remove_late(hass, device_reg, mqtt_mock, setup_tasmota): """Test attach and removal of trigger.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] # Discover a device with device triggers config2 = copy.deepcopy(DEFAULT_CONFIG) config2["swc"][0] = 0 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) calls = [] def callback(trigger, context): calls.append(trigger["trigger"]["description"]) remove = await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, callback, None, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 0 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0] == "event 'tasmota_event'" # Remove the trigger remove() await hass.async_block_till_done() # Verify the triggers are no longer active async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_attach_remove_late", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "# Discover a device with device triggers", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "calls", "=", "[", "]", "def", "callback", "(", "trigger", ",", "context", ")", ":", "calls", ".", "append", "(", "trigger", "[", "\"trigger\"", "]", "[", "\"description\"", "]", ")", "remove", "=", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "callback", ",", "None", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "==", "\"event 'tasmota_event'\"", "# Remove the trigger", "remove", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify the triggers are no longer active", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 689, 0 ]
[ 751, 26 ]
python
en
['en', 'en', 'en']
True
test_attach_remove_late2
(hass, device_reg, mqtt_mock, setup_tasmota)
Test attach and removal of trigger.
Test attach and removal of trigger.
async def test_attach_remove_late2(hass, device_reg, mqtt_mock, setup_tasmota): """Test attach and removal of trigger.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] # Discover a device with device triggers config2 = copy.deepcopy(DEFAULT_CONFIG) config2["swc"][0] = 0 async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) calls = [] def callback(trigger, context): calls.append(trigger["trigger"]["description"]) remove = await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, callback, None, ) # Remove the trigger remove() await hass.async_block_till_done() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() # Verify the triggers is not active async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_attach_remove_late2", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "# Discover a device with device triggers", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "calls", "=", "[", "]", "def", "callback", "(", "trigger", ",", "context", ")", ":", "calls", ".", "append", "(", "trigger", "[", "\"trigger\"", "]", "[", "\"description\"", "]", ")", "remove", "=", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "callback", ",", "None", ",", ")", "# Remove the trigger", "remove", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify the triggers is not active", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 754, 0 ]
[ 801, 26 ]
python
en
['en', 'en', 'en']
True
test_attach_remove_unknown1
(hass, device_reg, mqtt_mock, setup_tasmota)
Test attach and removal of unknown trigger.
Test attach and removal of unknown trigger.
async def test_attach_remove_unknown1(hass, device_reg, mqtt_mock, setup_tasmota): """Test attach and removal of unknown trigger.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) remove = await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, None, None, ) # Remove the trigger remove() await hass.async_block_till_done()
[ "async", "def", "test_attach_remove_unknown1", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "remove", "=", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "None", ",", "None", ",", ")", "# Remove the trigger", "remove", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 804, 0 ]
[ 832, 38 ]
python
en
['en', 'en', 'en']
True
test_attach_unknown_remove_device_from_registry
( hass, device_reg, mqtt_mock, setup_tasmota )
Test attach and removal of device with unknown trigger.
Test attach and removal of device with unknown trigger.
async def test_attach_unknown_remove_device_from_registry( hass, device_reg, mqtt_mock, setup_tasmota ): """Test attach and removal of device with unknown trigger.""" # Discover a device without device triggers config1 = copy.deepcopy(DEFAULT_CONFIG) config1["swc"][0] = -1 mac = config1["mac"] # Discover a device with device triggers config2 = copy.deepcopy(DEFAULT_CONFIG) config2["swc"][0] = 0 # Discovery a device with device triggers to load Tasmota device trigger integration async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config2)) await hass.async_block_till_done() # Forget the trigger async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config1)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, None, None, ) # Remove the device device_reg.async_remove_device(device_entry.id) await hass.async_block_till_done()
[ "async", "def", "test_attach_unknown_remove_device_from_registry", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device without device triggers", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"swc\"", "]", "[", "0", "]", "=", "-", "1", "mac", "=", "config1", "[", "\"mac\"", "]", "# Discover a device with device triggers", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "# Discovery a device with device triggers to load Tasmota device trigger integration", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config2", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Forget the trigger", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config1", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "None", ",", "None", ",", ")", "# Remove the device", "device_reg", ".", "async_remove_device", "(", "device_entry", ".", "id", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 835, 0 ]
[ 874, 38 ]
python
en
['en', 'en', 'en']
True
test_attach_remove_config_entry
(hass, device_reg, mqtt_mock, setup_tasmota)
Test trigger cleanup when removing a Tasmota config entry.
Test trigger cleanup when removing a Tasmota config entry.
async def test_attach_remove_config_entry(hass, device_reg, mqtt_mock, setup_tasmota): """Test trigger cleanup when removing a Tasmota config entry.""" # Discover a device with device trigger config = copy.deepcopy(DEFAULT_CONFIG) config["swc"][0] = 0 mac = config["mac"] mqtt_mock.async_subscribe.reset_mock() async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() device_entry = device_reg.async_get_device(set(), {("mac", mac)}) calls = [] def callback(trigger, context): calls.append(trigger["trigger"]["description"]) await async_attach_trigger( hass, { "platform": "device", "domain": DOMAIN, "device_id": device_entry.id, "discovery_id": "00000049A3BC_switch_1_TOGGLE", "type": "button_short_press", "subtype": "switch_1", }, callback, None, ) # Fake short press. async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0] == "event 'tasmota_event'" # Remove the Tasmota config entry config_entries = hass.config_entries.async_entries("tasmota") await hass.config_entries.async_remove(config_entries[0].entry_id) await hass.async_block_till_done() # Verify the triggers are no longer active async_fire_mqtt_message( hass, "tasmota_49A3BC/stat/RESULT", '{"Switch1":{"Action":"TOGGLE"}}' ) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_attach_remove_config_entry", "(", "hass", ",", "device_reg", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "# Discover a device with device trigger", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"swc\"", "]", "[", "0", "]", "=", "0", "mac", "=", "config", "[", "\"mac\"", "]", "mqtt_mock", ".", "async_subscribe", ".", "reset_mock", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "calls", "=", "[", "]", "def", "callback", "(", "trigger", ",", "context", ")", ":", "calls", ".", "append", "(", "trigger", "[", "\"trigger\"", "]", "[", "\"description\"", "]", ")", "await", "async_attach_trigger", "(", "hass", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"discovery_id\"", ":", "\"00000049A3BC_switch_1_TOGGLE\"", ",", "\"type\"", ":", "\"button_short_press\"", ",", "\"subtype\"", ":", "\"switch_1\"", ",", "}", ",", "callback", ",", "None", ",", ")", "# Fake short press.", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "==", "\"event 'tasmota_event'\"", "# Remove the Tasmota config entry", "config_entries", "=", "hass", ".", "config_entries", ".", "async_entries", "(", "\"tasmota\"", ")", "await", "hass", ".", "config_entries", ".", "async_remove", "(", "config_entries", "[", "0", "]", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify the triggers are no longer active", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"Switch1\":{\"Action\":\"TOGGLE\"}}'", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 877, 0 ]
[ 928, 26 ]
python
en
['en', 'en', 'en']
True
test_simple_function
(hass)
Test simple function (executor).
Test simple function (executor).
async def test_simple_function(hass): """Test simple function (executor).""" calls = [] def test_funct(data): """Test function.""" calls.append(data) async_dispatcher_connect(hass, "test", test_funct) async_dispatcher_send(hass, "test", 3) await hass.async_block_till_done() assert calls == [3] async_dispatcher_send(hass, "test", "bla") await hass.async_block_till_done() assert calls == [3, "bla"]
[ "async", "def", "test_simple_function", "(", "hass", ")", ":", "calls", "=", "[", "]", "def", "test_funct", "(", "data", ")", ":", "\"\"\"Test function.\"\"\"", "calls", ".", "append", "(", "data", ")", "async_dispatcher_connect", "(", "hass", ",", "\"test\"", ",", "test_funct", ")", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "3", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", "]", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "\"bla\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", ",", "\"bla\"", "]" ]
[ 12, 0 ]
[ 29, 30 ]
python
en
['es', 'en', 'en']
True
test_simple_function_unsub
(hass)
Test simple function (executor) and unsub.
Test simple function (executor) and unsub.
async def test_simple_function_unsub(hass): """Test simple function (executor) and unsub.""" calls1 = [] calls2 = [] def test_funct1(data): """Test function.""" calls1.append(data) def test_funct2(data): """Test function.""" calls2.append(data) async_dispatcher_connect(hass, "test1", test_funct1) unsub = async_dispatcher_connect(hass, "test2", test_funct2) async_dispatcher_send(hass, "test1", 3) async_dispatcher_send(hass, "test2", 4) await hass.async_block_till_done() assert calls1 == [3] assert calls2 == [4] unsub() async_dispatcher_send(hass, "test1", 5) async_dispatcher_send(hass, "test2", 6) await hass.async_block_till_done() assert calls1 == [3, 5] assert calls2 == [4] # check don't kill the flow unsub() async_dispatcher_send(hass, "test1", 7) async_dispatcher_send(hass, "test2", 8) await hass.async_block_till_done() assert calls1 == [3, 5, 7] assert calls2 == [4]
[ "async", "def", "test_simple_function_unsub", "(", "hass", ")", ":", "calls1", "=", "[", "]", "calls2", "=", "[", "]", "def", "test_funct1", "(", "data", ")", ":", "\"\"\"Test function.\"\"\"", "calls1", ".", "append", "(", "data", ")", "def", "test_funct2", "(", "data", ")", ":", "\"\"\"Test function.\"\"\"", "calls2", ".", "append", "(", "data", ")", "async_dispatcher_connect", "(", "hass", ",", "\"test1\"", ",", "test_funct1", ")", "unsub", "=", "async_dispatcher_connect", "(", "hass", ",", "\"test2\"", ",", "test_funct2", ")", "async_dispatcher_send", "(", "hass", ",", "\"test1\"", ",", "3", ")", "async_dispatcher_send", "(", "hass", ",", "\"test2\"", ",", "4", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls1", "==", "[", "3", "]", "assert", "calls2", "==", "[", "4", "]", "unsub", "(", ")", "async_dispatcher_send", "(", "hass", ",", "\"test1\"", ",", "5", ")", "async_dispatcher_send", "(", "hass", ",", "\"test2\"", ",", "6", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls1", "==", "[", "3", ",", "5", "]", "assert", "calls2", "==", "[", "4", "]", "# check don't kill the flow", "unsub", "(", ")", "async_dispatcher_send", "(", "hass", ",", "\"test1\"", ",", "7", ")", "async_dispatcher_send", "(", "hass", ",", "\"test2\"", ",", "8", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls1", "==", "[", "3", ",", "5", ",", "7", "]", "assert", "calls2", "==", "[", "4", "]" ]
[ 32, 0 ]
[ 71, 24 ]
python
en
['en', 'en', 'en']
True
test_simple_callback
(hass)
Test simple callback (async).
Test simple callback (async).
async def test_simple_callback(hass): """Test simple callback (async).""" calls = [] @callback def test_funct(data): """Test function.""" calls.append(data) async_dispatcher_connect(hass, "test", test_funct) async_dispatcher_send(hass, "test", 3) await hass.async_block_till_done() assert calls == [3] async_dispatcher_send(hass, "test", "bla") await hass.async_block_till_done() assert calls == [3, "bla"]
[ "async", "def", "test_simple_callback", "(", "hass", ")", ":", "calls", "=", "[", "]", "@", "callback", "def", "test_funct", "(", "data", ")", ":", "\"\"\"Test function.\"\"\"", "calls", ".", "append", "(", "data", ")", "async_dispatcher_connect", "(", "hass", ",", "\"test\"", ",", "test_funct", ")", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "3", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", "]", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "\"bla\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", ",", "\"bla\"", "]" ]
[ 74, 0 ]
[ 92, 30 ]
python
en
['en', 'et', 'en']
True
test_simple_coro
(hass)
Test simple coro (async).
Test simple coro (async).
async def test_simple_coro(hass): """Test simple coro (async).""" calls = [] async def async_test_funct(data): """Test function.""" calls.append(data) async_dispatcher_connect(hass, "test", async_test_funct) async_dispatcher_send(hass, "test", 3) await hass.async_block_till_done() assert calls == [3] async_dispatcher_send(hass, "test", "bla") await hass.async_block_till_done() assert calls == [3, "bla"]
[ "async", "def", "test_simple_coro", "(", "hass", ")", ":", "calls", "=", "[", "]", "async", "def", "async_test_funct", "(", "data", ")", ":", "\"\"\"Test function.\"\"\"", "calls", ".", "append", "(", "data", ")", "async_dispatcher_connect", "(", "hass", ",", "\"test\"", ",", "async_test_funct", ")", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "3", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", "]", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "\"bla\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", ",", "\"bla\"", "]" ]
[ 95, 0 ]
[ 112, 30 ]
python
en
['es', 'zh', 'en']
False
test_simple_function_multiargs
(hass)
Test simple function (executor).
Test simple function (executor).
async def test_simple_function_multiargs(hass): """Test simple function (executor).""" calls = [] def test_funct(data1, data2, data3): """Test function.""" calls.append(data1) calls.append(data2) calls.append(data3) async_dispatcher_connect(hass, "test", test_funct) async_dispatcher_send(hass, "test", 3, 2, "bla") await hass.async_block_till_done() assert calls == [3, 2, "bla"]
[ "async", "def", "test_simple_function_multiargs", "(", "hass", ")", ":", "calls", "=", "[", "]", "def", "test_funct", "(", "data1", ",", "data2", ",", "data3", ")", ":", "\"\"\"Test function.\"\"\"", "calls", ".", "append", "(", "data1", ")", "calls", ".", "append", "(", "data2", ")", "calls", ".", "append", "(", "data3", ")", "async_dispatcher_connect", "(", "hass", ",", "\"test\"", ",", "test_funct", ")", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "3", ",", "2", ",", "\"bla\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls", "==", "[", "3", ",", "2", ",", "\"bla\"", "]" ]
[ 115, 0 ]
[ 129, 33 ]
python
en
['es', 'en', 'en']
True
test_callback_exception_gets_logged
(hass, caplog)
Test exception raised by signal handler.
Test exception raised by signal handler.
async def test_callback_exception_gets_logged(hass, caplog): """Test exception raised by signal handler.""" @callback def bad_handler(*args): """Record calls.""" raise Exception("This is a bad message callback") # wrap in partial to test message logging. async_dispatcher_connect(hass, "test", partial(bad_handler)) async_dispatcher_send(hass, "test", "bad") await hass.async_block_till_done() await hass.async_block_till_done() assert ( f"Exception in functools.partial({bad_handler}) when dispatching 'test': ('bad',)" in caplog.text )
[ "async", "def", "test_callback_exception_gets_logged", "(", "hass", ",", "caplog", ")", ":", "@", "callback", "def", "bad_handler", "(", "*", "args", ")", ":", "\"\"\"Record calls.\"\"\"", "raise", "Exception", "(", "\"This is a bad message callback\"", ")", "# wrap in partial to test message logging.", "async_dispatcher_connect", "(", "hass", ",", "\"test\"", ",", "partial", "(", "bad_handler", ")", ")", "async_dispatcher_send", "(", "hass", ",", "\"test\"", ",", "\"bad\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "(", "f\"Exception in functools.partial({bad_handler}) when dispatching 'test': ('bad',)\"", "in", "caplog", ".", "text", ")" ]
[ 133, 0 ]
[ 150, 5 ]
python
en
['en', 'en', 'en']
True
fake_log
(log_key)
Return a fake fail2ban log.
Return a fake fail2ban log.
def fake_log(log_key): """Return a fake fail2ban log.""" fake_log_dict = { "single_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111" ), "ipv6_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 2607:f0d0:1002:51::4" ), "multi_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222" ), "multi_jail": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_two] Ban 222.222.222.222" ), "unban_all": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 222.222.222.222" ), "unban_one": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 111.111.111.111" ), } return fake_log_dict[log_key]
[ "def", "fake_log", "(", "log_key", ")", ":", "fake_log_dict", "=", "{", "\"single_ban\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 111.111.111.111\"", ")", ",", "\"ipv6_ban\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 2607:f0d0:1002:51::4\"", ")", ",", "\"multi_ban\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 111.111.111.111\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 222.222.222.222\"", ")", ",", "\"multi_jail\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 111.111.111.111\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_two] Ban 222.222.222.222\"", ")", ",", "\"unban_all\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 111.111.111.111\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Unban 111.111.111.111\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 222.222.222.222\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Unban 222.222.222.222\"", ")", ",", "\"unban_one\"", ":", "(", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 111.111.111.111\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Ban 222.222.222.222\\n\"", "\"2017-01-01 12:23:35 fail2ban.actions [111]: \"", "\"NOTICE [jail_one] Unban 111.111.111.111\"", ")", ",", "}", "return", "fake_log_dict", "[", "log_key", "]" ]
[ 13, 0 ]
[ 55, 33 ]
python
en
['en', 'gd', 'en']
True
test_setup
(hass)
Test that sensor can be setup.
Test that sensor can be setup.
async def test_setup(hass): """Test that sensor can be setup.""" config = {"sensor": {"platform": "fail2ban", "jails": ["jail_one"]}} mock_fh = mock_open() with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() assert_setup_component(1, "sensor")
[ "async", "def", "test_setup", "(", "hass", ")", ":", "config", "=", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"fail2ban\"", ",", "\"jails\"", ":", "[", "\"jail_one\"", "]", "}", "}", "mock_fh", "=", "mock_open", "(", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert_setup_component", "(", "1", ",", "\"sensor\"", ")" ]
[ 59, 0 ]
[ 66, 39 ]
python
en
['en', 'bg', 'en']
True
test_multi_jails
(hass)
Test that multiple jails can be set up as sensors..
Test that multiple jails can be set up as sensors..
async def test_multi_jails(hass): """Test that multiple jails can be set up as sensors..""" config = {"sensor": {"platform": "fail2ban", "jails": ["jail_one", "jail_two"]}} mock_fh = mock_open() with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() assert_setup_component(2, "sensor")
[ "async", "def", "test_multi_jails", "(", "hass", ")", ":", "config", "=", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"fail2ban\"", ",", "\"jails\"", ":", "[", "\"jail_one\"", ",", "\"jail_two\"", "]", "}", "}", "mock_fh", "=", "mock_open", "(", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert_setup_component", "(", "2", ",", "\"sensor\"", ")" ]
[ 70, 0 ]
[ 77, 39 ]
python
en
['en', 'en', 'en']
True
test_single_ban
(hass)
Test that log is parsed correctly for single ban.
Test that log is parsed correctly for single ban.
async def test_single_ban(hass): """Test that log is parsed correctly for single ban.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("single_ban")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "111.111.111.111" assert sensor.state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"] assert sensor.state_attributes[STATE_ALL_BANS] == ["111.111.111.111"]
[ "async", "def", "test_single_ban", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"single_ban\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"111.111.111.111\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"111.111.111.111\"", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", "]" ]
[ 80, 0 ]
[ 91, 73 ]
python
en
['en', 'en', 'en']
True
test_ipv6_ban
(hass)
Test that log is parsed correctly for IPV6 bans.
Test that log is parsed correctly for IPV6 bans.
async def test_ipv6_ban(hass): """Test that log is parsed correctly for IPV6 bans.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("ipv6_ban")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "2607:f0d0:1002:51::4" assert sensor.state_attributes[STATE_CURRENT_BANS] == ["2607:f0d0:1002:51::4"] assert sensor.state_attributes[STATE_ALL_BANS] == ["2607:f0d0:1002:51::4"]
[ "async", "def", "test_ipv6_ban", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"ipv6_ban\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"2607:f0d0:1002:51::4\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"2607:f0d0:1002:51::4\"", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"2607:f0d0:1002:51::4\"", "]" ]
[ 94, 0 ]
[ 105, 78 ]
python
en
['en', 'en', 'en']
True
test_multiple_ban
(hass)
Test that log is parsed correctly for multiple ban.
Test that log is parsed correctly for multiple ban.
async def test_multiple_ban(hass): """Test that log is parsed correctly for multiple ban.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("multi_ban")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "222.222.222.222" assert sensor.state_attributes[STATE_CURRENT_BANS] == [ "111.111.111.111", "222.222.222.222", ] assert sensor.state_attributes[STATE_ALL_BANS] == [ "111.111.111.111", "222.222.222.222", ]
[ "async", "def", "test_multiple_ban", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"multi_ban\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"222.222.222.222\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"111.111.111.111\"", ",", "\"222.222.222.222\"", ",", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", ",", "\"222.222.222.222\"", ",", "]" ]
[ 108, 0 ]
[ 125, 5 ]
python
en
['en', 'en', 'en']
True
test_unban_all
(hass)
Test that log is parsed correctly when unbanning.
Test that log is parsed correctly when unbanning.
async def test_unban_all(hass): """Test that log is parsed correctly when unbanning.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("unban_all")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "None" assert sensor.state_attributes[STATE_CURRENT_BANS] == [] assert sensor.state_attributes[STATE_ALL_BANS] == [ "111.111.111.111", "222.222.222.222", ]
[ "async", "def", "test_unban_all", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"unban_all\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"None\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", ",", "\"222.222.222.222\"", ",", "]" ]
[ 128, 0 ]
[ 142, 5 ]
python
en
['en', 'en', 'en']
True
test_unban_one
(hass)
Test that log is parsed correctly when unbanning one ip.
Test that log is parsed correctly when unbanning one ip.
async def test_unban_one(hass): """Test that log is parsed correctly when unbanning one ip.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("unban_one")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "222.222.222.222" assert sensor.state_attributes[STATE_CURRENT_BANS] == ["222.222.222.222"] assert sensor.state_attributes[STATE_ALL_BANS] == [ "111.111.111.111", "222.222.222.222", ]
[ "async", "def", "test_unban_one", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"unban_one\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"222.222.222.222\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"222.222.222.222\"", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", ",", "\"222.222.222.222\"", ",", "]" ]
[ 145, 0 ]
[ 159, 5 ]
python
en
['en', 'en', 'en']
True
test_multi_jail
(hass)
Test that log is parsed correctly when using multiple jails.
Test that log is parsed correctly when using multiple jails.
async def test_multi_jail(hass): """Test that log is parsed correctly when using multiple jails.""" log_parser = BanLogParser("/test/fail2ban.log") sensor1 = BanSensor("fail2ban", "jail_one", log_parser) sensor2 = BanSensor("fail2ban", "jail_two", log_parser) assert sensor1.name == "fail2ban jail_one" assert sensor2.name == "fail2ban jail_two" mock_fh = mock_open(read_data=fake_log("multi_jail")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor1.update() sensor2.update() assert sensor1.state == "111.111.111.111" assert sensor1.state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"] assert sensor1.state_attributes[STATE_ALL_BANS] == ["111.111.111.111"] assert sensor2.state == "222.222.222.222" assert sensor2.state_attributes[STATE_CURRENT_BANS] == ["222.222.222.222"] assert sensor2.state_attributes[STATE_ALL_BANS] == ["222.222.222.222"]
[ "async", "def", "test_multi_jail", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor1", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "sensor2", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_two\"", ",", "log_parser", ")", "assert", "sensor1", ".", "name", "==", "\"fail2ban jail_one\"", "assert", "sensor2", ".", "name", "==", "\"fail2ban jail_two\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"multi_jail\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor1", ".", "update", "(", ")", "sensor2", ".", "update", "(", ")", "assert", "sensor1", ".", "state", "==", "\"111.111.111.111\"", "assert", "sensor1", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"111.111.111.111\"", "]", "assert", "sensor1", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", "]", "assert", "sensor2", ".", "state", "==", "\"222.222.222.222\"", "assert", "sensor2", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"222.222.222.222\"", "]", "assert", "sensor2", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"222.222.222.222\"", "]" ]
[ 162, 0 ]
[ 179, 74 ]
python
en
['en', 'en', 'en']
True
test_ban_active_after_update
(hass)
Test that ban persists after subsequent update.
Test that ban persists after subsequent update.
async def test_ban_active_after_update(hass): """Test that ban persists after subsequent update.""" log_parser = BanLogParser("/test/fail2ban.log") sensor = BanSensor("fail2ban", "jail_one", log_parser) assert sensor.name == "fail2ban jail_one" mock_fh = mock_open(read_data=fake_log("single_ban")) with patch("homeassistant.components.fail2ban.sensor.open", mock_fh, create=True): sensor.update() assert sensor.state == "111.111.111.111" sensor.update() assert sensor.state == "111.111.111.111" assert sensor.state_attributes[STATE_CURRENT_BANS] == ["111.111.111.111"] assert sensor.state_attributes[STATE_ALL_BANS] == ["111.111.111.111"]
[ "async", "def", "test_ban_active_after_update", "(", "hass", ")", ":", "log_parser", "=", "BanLogParser", "(", "\"/test/fail2ban.log\"", ")", "sensor", "=", "BanSensor", "(", "\"fail2ban\"", ",", "\"jail_one\"", ",", "log_parser", ")", "assert", "sensor", ".", "name", "==", "\"fail2ban jail_one\"", "mock_fh", "=", "mock_open", "(", "read_data", "=", "fake_log", "(", "\"single_ban\"", ")", ")", "with", "patch", "(", "\"homeassistant.components.fail2ban.sensor.open\"", ",", "mock_fh", ",", "create", "=", "True", ")", ":", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"111.111.111.111\"", "sensor", ".", "update", "(", ")", "assert", "sensor", ".", "state", "==", "\"111.111.111.111\"", "assert", "sensor", ".", "state_attributes", "[", "STATE_CURRENT_BANS", "]", "==", "[", "\"111.111.111.111\"", "]", "assert", "sensor", ".", "state_attributes", "[", "STATE_ALL_BANS", "]", "==", "[", "\"111.111.111.111\"", "]" ]
[ 182, 0 ]
[ 194, 73 ]
python
en
['en', 'en', 'en']
True
render_h1_title
(content: str)
Flexible display of content according to predefined styles. Args: Content (str): Content to be showed on dashboard.
Flexible display of content according to predefined styles.
def render_h1_title(content: str): """Flexible display of content according to predefined styles. Args: Content (str): Content to be showed on dashboard. """ html_title = f"{title_html} <div class='title'><h1>{content}</h1></div>" st.markdown(html_title, unsafe_allow_html=True)
[ "def", "render_h1_title", "(", "content", ":", "str", ")", ":", "html_title", "=", "f\"{title_html} <div class='title'><h1>{content}</h1></div>\"", "st", ".", "markdown", "(", "html_title", ",", "unsafe_allow_html", "=", "True", ")" ]
[ 43, 0 ]
[ 50, 51 ]
python
en
['en', 'en', 'en']
True
render_h3_title
(content: str)
Flexible display of content according to predefined styles. Args: Content (str): Content to be showed on dashboard.
Flexible display of content according to predefined styles.
def render_h3_title(content: str): """Flexible display of content according to predefined styles. Args: Content (str): Content to be showed on dashboard. """ html_title = f"{title_html} <div class='title'><h3>{content}</h3></div>" st.markdown(html_title, unsafe_allow_html=True)
[ "def", "render_h3_title", "(", "content", ":", "str", ")", ":", "html_title", "=", "f\"{title_html} <div class='title'><h3>{content}</h3></div>\"", "st", ".", "markdown", "(", "html_title", ",", "unsafe_allow_html", "=", "True", ")" ]
[ 53, 0 ]
[ 60, 51 ]
python
en
['en', 'en', 'en']
True
get_sample_ratio_selection_list
(data_num: int)
Get sample ratio list with current data_num. Note: Number 0,1 must be included in the return value. Because it is essential for user to select sample ratio at 0/1. Args: data_num (int): Number of data to be sampled. Returns: List(float): The sample ratio list for user to select, which is a list range from 0 to 1.
Get sample ratio list with current data_num.
def get_sample_ratio_selection_list(data_num: int) -> list: """Get sample ratio list with current data_num. Note: Number 0,1 must be included in the return value. Because it is essential for user to select sample ratio at 0/1. Args: data_num (int): Number of data to be sampled. Returns: List(float): The sample ratio list for user to select, which is a list range from 0 to 1. """ return [round(i / data_num, 2) for i in range(0, data_num + 1)]
[ "def", "get_sample_ratio_selection_list", "(", "data_num", ":", "int", ")", "->", "list", ":", "return", "[", "round", "(", "i", "/", "data_num", ",", "2", ")", "for", "i", "in", "range", "(", "0", ",", "data_num", "+", "1", ")", "]" ]
[ 63, 0 ]
[ 76, 67 ]
python
en
['en', 'en', 'en']
True
get_sample_index_list
(data_num: int, sample_ratio: float)
Get the index list of sampled data. Args: data_num (int): Number of data to be sampled. sample_ratio (float): The sample ratio selected by user. Returns: List[float]: The list of sampled data index list, which is a list range from 0 to data_num.
Get the index list of sampled data.
def get_sample_index_list(data_num: int, sample_ratio: float) -> List[float]: """Get the index list of sampled data. Args: data_num (int): Number of data to be sampled. sample_ratio (float): The sample ratio selected by user. Returns: List[float]: The list of sampled data index list, which is a list range from 0 to data_num. """ if sample_ratio == 0: return [] else: return list(range(0, data_num, math.floor(1 / sample_ratio)))
[ "def", "get_sample_index_list", "(", "data_num", ":", "int", ",", "sample_ratio", ":", "float", ")", "->", "List", "[", "float", "]", ":", "if", "sample_ratio", "==", "0", ":", "return", "[", "]", "else", ":", "return", "list", "(", "range", "(", "0", ",", "data_num", ",", "math", ".", "floor", "(", "1", "/", "sample_ratio", ")", ")", ")" ]
[ 79, 0 ]
[ 93, 69 ]
python
en
['en', 'en', 'en']
True
get_filtered_formula_and_data
( scenario: GlobalScenarios, data: pd.DataFrame, attribute_option_candidates: List[str] )
Get calculated formula and whole data. Args: scenario (GlobalScenarios): Type of input scenario detail. data (pd.Dataframe): Original data. attribute_option_candidates (List[str]): All options for users to choose. Returns: dict: The data and attributes after formula calculation.
Get calculated formula and whole data.
def get_filtered_formula_and_data( scenario: GlobalScenarios, data: pd.DataFrame, attribute_option_candidates: List[str] ) -> dict: """ Get calculated formula and whole data. Args: scenario (GlobalScenarios): Type of input scenario detail. data (pd.Dataframe): Original data. attribute_option_candidates (List[str]): All options for users to choose. Returns: dict: The data and attributes after formula calculation. """ data_generate = _formula_define(data) if data_generate is not None: data = data_generate["data"] attribute_option_candidates.append(data_generate["name"]) attribute_option = st.multiselect( label=" ", options=attribute_option_candidates, default=attribute_option_candidates ) attribute_option = _get_attribute_option(scenario, attribute_option, attribute_option_candidates) return {"data": data, "attribute_option": attribute_option}
[ "def", "get_filtered_formula_and_data", "(", "scenario", ":", "GlobalScenarios", ",", "data", ":", "pd", ".", "DataFrame", ",", "attribute_option_candidates", ":", "List", "[", "str", "]", ")", "->", "dict", ":", "data_generate", "=", "_formula_define", "(", "data", ")", "if", "data_generate", "is", "not", "None", ":", "data", "=", "data_generate", "[", "\"data\"", "]", "attribute_option_candidates", ".", "append", "(", "data_generate", "[", "\"name\"", "]", ")", "attribute_option", "=", "st", ".", "multiselect", "(", "label", "=", "\" \"", ",", "options", "=", "attribute_option_candidates", ",", "default", "=", "attribute_option_candidates", ")", "attribute_option", "=", "_get_attribute_option", "(", "scenario", ",", "attribute_option", ",", "attribute_option_candidates", ")", "return", "{", "\"data\"", ":", "data", ",", "\"attribute_option\"", ":", "attribute_option", "}" ]
[ 96, 0 ]
[ 121, 63 ]
python
en
['en', 'en', 'en']
True
read_detail_csv
(path: str)
Read detail csv with cache. Args: path (str): Path of file to be read. Returns: pd.Dataframe: Data in CSV file. Cached in local memory.
Read detail csv with cache.
def read_detail_csv(path: str) -> pd.DataFrame: """Read detail csv with cache. Args: path (str): Path of file to be read. Returns: pd.Dataframe: Data in CSV file. Cached in local memory. """ return pd.read_csv(path)
[ "def", "read_detail_csv", "(", "path", ":", "str", ")", "->", "pd", ".", "DataFrame", ":", "return", "pd", ".", "read_csv", "(", "path", ")" ]
[ 125, 0 ]
[ 135, 28 ]
python
en
['en', 'en', 'en']
True
generate_by_snapshot_top_summary
( attr_name: str, data: pd.DataFrame, top_number: int, attribute: str, snapshot_index: int = -1 )
Generate top-k resource holders and their according summary data. Args: attr_name (str): Name of attributes needed to be summarized. data (pd.Dataframe): Data of selected column and snapshot_index. top_number (int): Number of top summaries. attribute (str): Attributes needed to be displayed on plot. snapshot_index (int): Index of snapshot.
Generate top-k resource holders and their according summary data.
def generate_by_snapshot_top_summary( attr_name: str, data: pd.DataFrame, top_number: int, attribute: str, snapshot_index: int = -1 ): """ Generate top-k resource holders and their according summary data. Args: attr_name (str): Name of attributes needed to be summarized. data (pd.Dataframe): Data of selected column and snapshot_index. top_number (int): Number of top summaries. attribute (str): Attributes needed to be displayed on plot. snapshot_index (int): Index of snapshot. """ if snapshot_index != -1: render_h3_title(f"Snapshot-{snapshot_index}: Top {top_number} {attribute}") else: render_h3_title(f"Top {top_number} {attribute}") data = data[[attr_name, attribute]].sort_values(by=attribute, ascending=False).head(top_number) data["counter"] = range(len(data)) data[attr_name] = list( map( lambda x, y: f"{x+1}-{y}", data["counter"], data[attr_name] ) ) bars = alt.Chart(data).mark_bar().encode( x=f"{attribute}:Q", y=f"{attr_name}:O", ).properties( width=700, height=240 ) text = bars.mark_text( align="left", baseline="middle", dx=3 ).encode( text=f"{attribute}:Q" ) st.altair_chart(bars + text)
[ "def", "generate_by_snapshot_top_summary", "(", "attr_name", ":", "str", ",", "data", ":", "pd", ".", "DataFrame", ",", "top_number", ":", "int", ",", "attribute", ":", "str", ",", "snapshot_index", ":", "int", "=", "-", "1", ")", ":", "if", "snapshot_index", "!=", "-", "1", ":", "render_h3_title", "(", "f\"Snapshot-{snapshot_index}: Top {top_number} {attribute}\"", ")", "else", ":", "render_h3_title", "(", "f\"Top {top_number} {attribute}\"", ")", "data", "=", "data", "[", "[", "attr_name", ",", "attribute", "]", "]", ".", "sort_values", "(", "by", "=", "attribute", ",", "ascending", "=", "False", ")", ".", "head", "(", "top_number", ")", "data", "[", "\"counter\"", "]", "=", "range", "(", "len", "(", "data", ")", ")", "data", "[", "attr_name", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "f\"{x+1}-{y}\"", ",", "data", "[", "\"counter\"", "]", ",", "data", "[", "attr_name", "]", ")", ")", "bars", "=", "alt", ".", "Chart", "(", "data", ")", ".", "mark_bar", "(", ")", ".", "encode", "(", "x", "=", "f\"{attribute}:Q\"", ",", "y", "=", "f\"{attr_name}:O\"", ",", ")", ".", "properties", "(", "width", "=", "700", ",", "height", "=", "240", ")", "text", "=", "bars", ".", "mark_text", "(", "align", "=", "\"left\"", ",", "baseline", "=", "\"middle\"", ",", "dx", "=", "3", ")", ".", "encode", "(", "text", "=", "f\"{attribute}:Q\"", ")", "st", ".", "altair_chart", "(", "bars", "+", "text", ")" ]
[ 138, 0 ]
[ 178, 32 ]
python
en
['en', 'en', 'en']
True
_get_attribute_option
( scenario: GlobalScenarios, attribute_option: List[str], attribute_option_candidates: List[str] )
Convert selected attribute options into column. Args: scenario (GlobalScenarios): Name of scenario attribute_option (List[str]): User-selected attributes list. attribute_option_candidates (List[str]): Pre-defined attributes list. Returns: List[str]: Translated attribute list, which contains no user-selected attributes, but only pre-defined attributes.
Convert selected attribute options into column.
def _get_attribute_option( scenario: GlobalScenarios, attribute_option: List[str], attribute_option_candidates: List[str] ) -> List[str]: """Convert selected attribute options into column. Args: scenario (GlobalScenarios): Name of scenario attribute_option (List[str]): User-selected attributes list. attribute_option_candidates (List[str]): Pre-defined attributes list. Returns: List[str]: Translated attribute list, which contains no user-selected attributes, but only pre-defined attributes. """ attribute_option_res = [] if scenario == GlobalScenarios.CITI_BIKE: for item in attribute_option: if item == "All": attribute_option_candidates.remove("All") attribute_option_candidates.remove("Requirement Info") attribute_option_candidates.remove("Station Info") attribute_option_res = attribute_option_candidates break elif item == "Requirement Info": attribute_option_res = attribute_option_res + CITIBIKEItemOption.requirement_info elif item == "Station Info": attribute_option_res = attribute_option_res + CITIBIKEItemOption.station_info else: attribute_option_res.append(item) return attribute_option_res if scenario == GlobalScenarios.CIM: for item in attribute_option: if item == "All": attribute_option_candidates.remove("All") attribute_option_candidates.remove("Booking Info") attribute_option_candidates.remove("Port Info") attribute_option_res = attribute_option_candidates break elif item == "Booking Info": attribute_option_res = attribute_option_res + CIMItemOption.booking_info elif item == "Port Info": attribute_option_res = attribute_option_res + CIMItemOption.port_info else: attribute_option_res.append(item) return attribute_option_res
[ "def", "_get_attribute_option", "(", "scenario", ":", "GlobalScenarios", ",", "attribute_option", ":", "List", "[", "str", "]", ",", "attribute_option_candidates", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "attribute_option_res", "=", "[", "]", "if", "scenario", "==", "GlobalScenarios", ".", "CITI_BIKE", ":", "for", "item", "in", "attribute_option", ":", "if", "item", "==", "\"All\"", ":", "attribute_option_candidates", ".", "remove", "(", "\"All\"", ")", "attribute_option_candidates", ".", "remove", "(", "\"Requirement Info\"", ")", "attribute_option_candidates", ".", "remove", "(", "\"Station Info\"", ")", "attribute_option_res", "=", "attribute_option_candidates", "break", "elif", "item", "==", "\"Requirement Info\"", ":", "attribute_option_res", "=", "attribute_option_res", "+", "CITIBIKEItemOption", ".", "requirement_info", "elif", "item", "==", "\"Station Info\"", ":", "attribute_option_res", "=", "attribute_option_res", "+", "CITIBIKEItemOption", ".", "station_info", "else", ":", "attribute_option_res", ".", "append", "(", "item", ")", "return", "attribute_option_res", "if", "scenario", "==", "GlobalScenarios", ".", "CIM", ":", "for", "item", "in", "attribute_option", ":", "if", "item", "==", "\"All\"", ":", "attribute_option_candidates", ".", "remove", "(", "\"All\"", ")", "attribute_option_candidates", ".", "remove", "(", "\"Booking Info\"", ")", "attribute_option_candidates", ".", "remove", "(", "\"Port Info\"", ")", "attribute_option_res", "=", "attribute_option_candidates", "break", "elif", "item", "==", "\"Booking Info\"", ":", "attribute_option_res", "=", "attribute_option_res", "+", "CIMItemOption", ".", "booking_info", "elif", "item", "==", "\"Port Info\"", ":", "attribute_option_res", "=", "attribute_option_res", "+", "CIMItemOption", ".", "port_info", "else", ":", "attribute_option_res", ".", "append", "(", "item", ")", "return", "attribute_option_res" ]
[ 181, 0 ]
[ 227, 35 ]
python
en
['en', 'en', 'en']
True
_formula_define
(data_original: pd.DataFrame)
Define formula and get output. Args: data_original (pd.Dataframe): Original data to be calculated with selected formula. Returns: dict: Name and output of selected formula and original data.
Define formula and get output.
def _formula_define(data_original: pd.DataFrame) -> dict: """Define formula and get output. Args: data_original (pd.Dataframe): Original data to be calculated with selected formula. Returns: dict: Name and output of selected formula and original data. """ st.sidebar.markdown("***") formula_select = st.sidebar.selectbox( label="formula:", options=["a+b", "a-b", "a/b", "a*b", "sqrt(a)"] ) paras = st.sidebar.text_input("parameters separated by ;") res = paras.split(";") if formula_select == "a+b": if not _judge_data_length(res, 2): return else: data_right = _judge_append_data(data_original.head(0), res) if data_right: data_original[f"{res[0]}+{res[1]}"] = list( map( lambda x, y: x + y, data_original[res[0]], data_original[res[1]] ) ) else: return data = {"data": data_original, "name": f"{res[0]}+{res[1]}"} return data if formula_select == "a-b": if not _judge_data_length(res, 2): return else: data_right = _judge_append_data(data_original.head(0), res) if data_right: data_original[f"{res[0]}-{res[1]}"] = list( map( lambda x, y: x - y, data_original[res[0]], data_original[res[1]] ) ) else: return data = {"data": data_original, "name": f"{res[0]}-{res[1]}"} return data if formula_select == "a*b": if not _judge_data_length(res, 2): return else: data_right = _judge_append_data(data_original.head(0), res) if data_right: data_original[f"{res[0]}*{res[1]}"] = list( map( lambda x, y: x * y, data_original[res[0]], data_original[res[1]] ) ) else: return data = {"data": data_original, "name": f"{res[0]}*{res[1]}"} return data if formula_select == "a/b": if not _judge_data_length(res, 2): return else: data_right = _judge_append_data(data_original.head(0), res) if data_right: data_original[f"{res[0]}/{res[1]}"] = list( map( lambda x, y: x + y, data_original[res[0]], data_original[res[1]] ) ) else: return data = {"data": data_original, "name": f"{res[0]}/{res[1]}"} return data if formula_select == "sqrt(a)": if not _judge_data_length(res, 1): return else: data_right = _judge_append_data(data_original.head(0), res) if data_right: data_original[f"sqrt({res[0]})"] = list( map( lambda x: math.sqrt(x), data_original[res[0]] ) ) else: return data = {"data": data_original, "name": f"sqrt({res[0]})"} return data
[ "def", "_formula_define", "(", "data_original", ":", "pd", ".", "DataFrame", ")", "->", "dict", ":", "st", ".", "sidebar", ".", "markdown", "(", "\"***\"", ")", "formula_select", "=", "st", ".", "sidebar", ".", "selectbox", "(", "label", "=", "\"formula:\"", ",", "options", "=", "[", "\"a+b\"", ",", "\"a-b\"", ",", "\"a/b\"", ",", "\"a*b\"", ",", "\"sqrt(a)\"", "]", ")", "paras", "=", "st", ".", "sidebar", ".", "text_input", "(", "\"parameters separated by ;\"", ")", "res", "=", "paras", ".", "split", "(", "\";\"", ")", "if", "formula_select", "==", "\"a+b\"", ":", "if", "not", "_judge_data_length", "(", "res", ",", "2", ")", ":", "return", "else", ":", "data_right", "=", "_judge_append_data", "(", "data_original", ".", "head", "(", "0", ")", ",", "res", ")", "if", "data_right", ":", "data_original", "[", "f\"{res[0]}+{res[1]}\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "data_original", "[", "res", "[", "0", "]", "]", ",", "data_original", "[", "res", "[", "1", "]", "]", ")", ")", "else", ":", "return", "data", "=", "{", "\"data\"", ":", "data_original", ",", "\"name\"", ":", "f\"{res[0]}+{res[1]}\"", "}", "return", "data", "if", "formula_select", "==", "\"a-b\"", ":", "if", "not", "_judge_data_length", "(", "res", ",", "2", ")", ":", "return", "else", ":", "data_right", "=", "_judge_append_data", "(", "data_original", ".", "head", "(", "0", ")", ",", "res", ")", "if", "data_right", ":", "data_original", "[", "f\"{res[0]}-{res[1]}\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "-", "y", ",", "data_original", "[", "res", "[", "0", "]", "]", ",", "data_original", "[", "res", "[", "1", "]", "]", ")", ")", "else", ":", "return", "data", "=", "{", "\"data\"", ":", "data_original", ",", "\"name\"", ":", "f\"{res[0]}-{res[1]}\"", "}", "return", "data", "if", "formula_select", "==", "\"a*b\"", ":", "if", "not", "_judge_data_length", "(", "res", ",", "2", ")", ":", "return", "else", ":", "data_right", "=", "_judge_append_data", "(", "data_original", ".", "head", "(", "0", ")", ",", "res", ")", "if", "data_right", ":", "data_original", "[", "f\"{res[0]}*{res[1]}\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "data_original", "[", "res", "[", "0", "]", "]", ",", "data_original", "[", "res", "[", "1", "]", "]", ")", ")", "else", ":", "return", "data", "=", "{", "\"data\"", ":", "data_original", ",", "\"name\"", ":", "f\"{res[0]}*{res[1]}\"", "}", "return", "data", "if", "formula_select", "==", "\"a/b\"", ":", "if", "not", "_judge_data_length", "(", "res", ",", "2", ")", ":", "return", "else", ":", "data_right", "=", "_judge_append_data", "(", "data_original", ".", "head", "(", "0", ")", ",", "res", ")", "if", "data_right", ":", "data_original", "[", "f\"{res[0]}/{res[1]}\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "data_original", "[", "res", "[", "0", "]", "]", ",", "data_original", "[", "res", "[", "1", "]", "]", ")", ")", "else", ":", "return", "data", "=", "{", "\"data\"", ":", "data_original", ",", "\"name\"", ":", "f\"{res[0]}/{res[1]}\"", "}", "return", "data", "if", "formula_select", "==", "\"sqrt(a)\"", ":", "if", "not", "_judge_data_length", "(", "res", ",", "1", ")", ":", "return", "else", ":", "data_right", "=", "_judge_append_data", "(", "data_original", ".", "head", "(", "0", ")", ",", "res", ")", "if", "data_right", ":", "data_original", "[", "f\"sqrt({res[0]})\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ":", "math", ".", "sqrt", "(", "x", ")", ",", "data_original", "[", "res", "[", "0", "]", "]", ")", ")", "else", ":", "return", "data", "=", "{", "\"data\"", ":", "data_original", ",", "\"name\"", ":", "f\"sqrt({res[0]})\"", "}", "return", "data" ]
[ 230, 0 ]
[ 335, 19 ]
python
en
['en', 'pt', 'en']
True
_judge_data_length
(res: list, formula_length: int)
Judge whether the length of input data meet the requirements. Args: res (list): User-input data. formula_length (int): Supposed length of input data with selected formula. Returns: bool: Whether the length of data meet the requirements of formula.
Judge whether the length of input data meet the requirements.
def _judge_data_length(res: list, formula_length: int) -> bool: """Judge whether the length of input data meet the requirements. Args: res (list): User-input data. formula_length (int): Supposed length of input data with selected formula. Returns: bool: Whether the length of data meet the requirements of formula. """ if len(res) == 0 or res[0] == "": return False elif len(res) != formula_length: st.warning("input parameter number wrong") return False return True
[ "def", "_judge_data_length", "(", "res", ":", "list", ",", "formula_length", ":", "int", ")", "->", "bool", ":", "if", "len", "(", "res", ")", "==", "0", "or", "res", "[", "0", "]", "==", "\"\"", ":", "return", "False", "elif", "len", "(", "res", ")", "!=", "formula_length", ":", "st", ".", "warning", "(", "\"input parameter number wrong\"", ")", "return", "False", "return", "True" ]
[ 338, 0 ]
[ 354, 15 ]
python
en
['en', 'en', 'en']
True
_judge_append_data
(data_head: List[str], res: List[str])
Judge whether input is feasible to selected formula. Args: data_head (List[str]): Column list of origin data. res (List[str]): Column names texted by user. Returns: bool: Whether the column list texted by user is reasonable or not.
Judge whether input is feasible to selected formula.
def _judge_append_data(data_head: List[str], res: List[str]) -> bool: """Judge whether input is feasible to selected formula. Args: data_head (List[str]): Column list of origin data. res (List[str]): Column names texted by user. Returns: bool: Whether the column list texted by user is reasonable or not. """ data_right = True for item in res: if item not in data_head: data_right = False st.warning(f"parameter name:{item} not exist") return data_right
[ "def", "_judge_append_data", "(", "data_head", ":", "List", "[", "str", "]", ",", "res", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "data_right", "=", "True", "for", "item", "in", "res", ":", "if", "item", "not", "in", "data_head", ":", "data_right", "=", "False", "st", ".", "warning", "(", "f\"parameter name:{item} not exist\"", ")", "return", "data_right" ]
[ 357, 0 ]
[ 374, 21 ]
python
en
['en', 'en', 'en']
True
_get_sampled_epoch_range
(epoch_num: int, sample_ratio: float)
For inter plot, generate sampled data list based on range & sample ratio. Args: epoch_num (int): Total number of epoches, i.e. the total number of data folders since there is a folder per epoch. sample_ratio (float): Sampling ratio. e.g. If sample_ratio = 0.3, and sample data range = [0, 10], down_pooling_list = [0, 0.3, 0.6, 0.9] down_pooling_range = [0, 3, 6, 9] Returns: List[float]: List of sampled epoch index.
For inter plot, generate sampled data list based on range & sample ratio.
def _get_sampled_epoch_range(epoch_num: int, sample_ratio: float) -> List[float]: """For inter plot, generate sampled data list based on range & sample ratio. Args: epoch_num (int): Total number of epoches, i.e. the total number of data folders since there is a folder per epoch. sample_ratio (float): Sampling ratio. e.g. If sample_ratio = 0.3, and sample data range = [0, 10], down_pooling_list = [0, 0.3, 0.6, 0.9] down_pooling_range = [0, 3, 6, 9] Returns: List[float]: List of sampled epoch index. """ start_epoch = st.sidebar.number_input( label="Start Epoch", min_value=0, max_value=epoch_num - 1, value=0 ) end_epoch = st.sidebar.number_input( label="End Epoch", min_value=0, max_value=epoch_num - 1, value=epoch_num - 1 ) down_pooling_num = st.sidebar.select_slider( label="Epoch Sampling Ratio", options=sample_ratio, value=1 ) if down_pooling_num == 0: return [] else: return list(range(start_epoch, end_epoch + 1, math.floor(1 / down_pooling_num)))
[ "def", "_get_sampled_epoch_range", "(", "epoch_num", ":", "int", ",", "sample_ratio", ":", "float", ")", "->", "List", "[", "float", "]", ":", "start_epoch", "=", "st", ".", "sidebar", ".", "number_input", "(", "label", "=", "\"Start Epoch\"", ",", "min_value", "=", "0", ",", "max_value", "=", "epoch_num", "-", "1", ",", "value", "=", "0", ")", "end_epoch", "=", "st", ".", "sidebar", ".", "number_input", "(", "label", "=", "\"End Epoch\"", ",", "min_value", "=", "0", ",", "max_value", "=", "epoch_num", "-", "1", ",", "value", "=", "epoch_num", "-", "1", ")", "down_pooling_num", "=", "st", ".", "sidebar", ".", "select_slider", "(", "label", "=", "\"Epoch Sampling Ratio\"", ",", "options", "=", "sample_ratio", ",", "value", "=", "1", ")", "if", "down_pooling_num", "==", "0", ":", "return", "[", "]", "else", ":", "return", "list", "(", "range", "(", "start_epoch", ",", "end_epoch", "+", "1", ",", "math", ".", "floor", "(", "1", "/", "down_pooling_num", ")", ")", ")" ]
[ 377, 0 ]
[ 412, 88 ]
python
en
['en', 'no', 'en']
True
get_args
()
get args from command line
get args from command line
def get_args(): """ get args from command line """ parser = argparse.ArgumentParser("cifar10") parser.add_argument("--batch_size", type=int, default=128, help="batch size") parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer") parser.add_argument("--epochs", type=int, default=200, help="epoch limit") parser.add_argument( "--learning_rate", type=float, default=0.001, help="learning rate" ) parser.add_argument("--cutout", action="store_true", default=False, help="use cutout") parser.add_argument("--cutout_length", type=int, default=8, help="cutout length") parser.add_argument( "--model_path", type=str, default="./", help="Path to save the destination model" ) return parser.parse_args()
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "\"cifar10\"", ")", "parser", ".", "add_argument", "(", "\"--batch_size\"", ",", "type", "=", "int", ",", "default", "=", "128", ",", "help", "=", "\"batch size\"", ")", "parser", ".", "add_argument", "(", "\"--optimizer\"", ",", "type", "=", "str", ",", "default", "=", "\"SGD\"", ",", "help", "=", "\"optimizer\"", ")", "parser", ".", "add_argument", "(", "\"--epochs\"", ",", "type", "=", "int", ",", "default", "=", "200", ",", "help", "=", "\"epoch limit\"", ")", "parser", ".", "add_argument", "(", "\"--learning_rate\"", ",", "type", "=", "float", ",", "default", "=", "0.001", ",", "help", "=", "\"learning rate\"", ")", "parser", ".", "add_argument", "(", "\"--cutout\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"use cutout\"", ")", "parser", ".", "add_argument", "(", "\"--cutout_length\"", ",", "type", "=", "int", ",", "default", "=", "8", ",", "help", "=", "\"cutout length\"", ")", "parser", ".", "add_argument", "(", "\"--model_path\"", ",", "type", "=", "str", ",", "default", "=", "\"./\"", ",", "help", "=", "\"Path to save the destination model\"", ")", "return", "parser", ".", "parse_args", "(", ")" ]
[ 45, 0 ]
[ 60, 30 ]
python
en
['en', 'en', 'en']
True
build_graph_from_json
(ir_model_json)
build model from json representation
build model from json representation
def build_graph_from_json(ir_model_json): """build model from json representation """ graph = json_to_graph(ir_model_json) logging.debug(graph.operation_history) model = graph.produce_torch_model() return model
[ "def", "build_graph_from_json", "(", "ir_model_json", ")", ":", "graph", "=", "json_to_graph", "(", "ir_model_json", ")", "logging", ".", "debug", "(", "graph", ".", "operation_history", ")", "model", "=", "graph", ".", "produce_torch_model", "(", ")", "return", "model" ]
[ 73, 0 ]
[ 79, 16 ]
python
en
['en', 'en', 'en']
True
parse_rev_args
(receive_msg)
parse reveive msgs to global variable
parse reveive msgs to global variable
def parse_rev_args(receive_msg): """ parse reveive msgs to global variable """ global trainloader global testloader global net global criterion global optimizer # Loading Data logger.debug("Preparing data..") transform_train, transform_test = utils.data_transforms_cifar10(args) trainset = torchvision.datasets.CIFAR10( root="./data", train=True, download=True, transform=transform_train ) trainloader = torch.utils.data.DataLoader( trainset, batch_size=args.batch_size, shuffle=True, num_workers=2 ) testset = torchvision.datasets.CIFAR10( root="./data", train=False, download=True, transform=transform_test ) testloader = torch.utils.data.DataLoader( testset, batch_size=args.batch_size, shuffle=False, num_workers=2 ) # Model logger.debug("Building model..") net = build_graph_from_json(receive_msg) net = net.to(device) criterion = nn.CrossEntropyLoss() if device == "cuda" and torch.cuda.device_count() > 1: net = torch.nn.DataParallel(net) if args.optimizer == "SGD": optimizer = optim.SGD( net.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=5e-4 ) if args.optimizer == "Adadelta": optimizer = optim.Adadelta(net.parameters(), lr=args.learning_rate) if args.optimizer == "Adagrad": optimizer = optim.Adagrad(net.parameters(), lr=args.learning_rate) if args.optimizer == "Adam": optimizer = optim.Adam(net.parameters(), lr=args.learning_rate) if args.optimizer == "Adamax": optimizer = optim.Adamax(net.parameters(), lr=args.learning_rate) if args.optimizer == "RMSprop": optimizer = optim.RMSprop(net.parameters(), lr=args.learning_rate) return 0
[ "def", "parse_rev_args", "(", "receive_msg", ")", ":", "global", "trainloader", "global", "testloader", "global", "net", "global", "criterion", "global", "optimizer", "# Loading Data", "logger", ".", "debug", "(", "\"Preparing data..\"", ")", "transform_train", ",", "transform_test", "=", "utils", ".", "data_transforms_cifar10", "(", "args", ")", "trainset", "=", "torchvision", ".", "datasets", ".", "CIFAR10", "(", "root", "=", "\"./data\"", ",", "train", "=", "True", ",", "download", "=", "True", ",", "transform", "=", "transform_train", ")", "trainloader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "trainset", ",", "batch_size", "=", "args", ".", "batch_size", ",", "shuffle", "=", "True", ",", "num_workers", "=", "2", ")", "testset", "=", "torchvision", ".", "datasets", ".", "CIFAR10", "(", "root", "=", "\"./data\"", ",", "train", "=", "False", ",", "download", "=", "True", ",", "transform", "=", "transform_test", ")", "testloader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "testset", ",", "batch_size", "=", "args", ".", "batch_size", ",", "shuffle", "=", "False", ",", "num_workers", "=", "2", ")", "# Model", "logger", ".", "debug", "(", "\"Building model..\"", ")", "net", "=", "build_graph_from_json", "(", "receive_msg", ")", "net", "=", "net", ".", "to", "(", "device", ")", "criterion", "=", "nn", ".", "CrossEntropyLoss", "(", ")", "if", "device", "==", "\"cuda\"", "and", "torch", ".", "cuda", ".", "device_count", "(", ")", ">", "1", ":", "net", "=", "torch", ".", "nn", ".", "DataParallel", "(", "net", ")", "if", "args", ".", "optimizer", "==", "\"SGD\"", ":", "optimizer", "=", "optim", ".", "SGD", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ",", "momentum", "=", "0.9", ",", "weight_decay", "=", "5e-4", ")", "if", "args", ".", "optimizer", "==", "\"Adadelta\"", ":", "optimizer", "=", "optim", ".", "Adadelta", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ")", "if", "args", ".", "optimizer", "==", "\"Adagrad\"", ":", "optimizer", "=", "optim", ".", "Adagrad", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ")", "if", "args", ".", "optimizer", "==", "\"Adam\"", ":", "optimizer", "=", "optim", ".", "Adam", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ")", "if", "args", ".", "optimizer", "==", "\"Adamax\"", ":", "optimizer", "=", "optim", ".", "Adamax", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ")", "if", "args", ".", "optimizer", "==", "\"RMSprop\"", ":", "optimizer", "=", "optim", ".", "RMSprop", "(", "net", ".", "parameters", "(", ")", ",", "lr", "=", "args", ".", "learning_rate", ")", "return", "0" ]
[ 82, 0 ]
[ 135, 12 ]
python
en
['en', 'en', 'en']
True
train
(epoch)
train model on each epoch in trainset
train model on each epoch in trainset
def train(epoch): """ train model on each epoch in trainset """ global trainloader global testloader global net global criterion global optimizer logger.debug("Epoch: %d", epoch) net.train() train_loss = 0 correct = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(trainloader): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total logger.debug( "Loss: %.3f | Acc: %.3f%% (%d/%d)", train_loss / (batch_idx + 1), 100.0 * correct / total, correct, total, ) return acc
[ "def", "train", "(", "epoch", ")", ":", "global", "trainloader", "global", "testloader", "global", "net", "global", "criterion", "global", "optimizer", "logger", ".", "debug", "(", "\"Epoch: %d\"", ",", "epoch", ")", "net", ".", "train", "(", ")", "train_loss", "=", "0", "correct", "=", "0", "total", "=", "0", "for", "batch_idx", ",", "(", "inputs", ",", "targets", ")", "in", "enumerate", "(", "trainloader", ")", ":", "inputs", ",", "targets", "=", "inputs", ".", "to", "(", "device", ")", ",", "targets", ".", "to", "(", "device", ")", "optimizer", ".", "zero_grad", "(", ")", "outputs", "=", "net", "(", "inputs", ")", "loss", "=", "criterion", "(", "outputs", ",", "targets", ")", "loss", ".", "backward", "(", ")", "optimizer", ".", "step", "(", ")", "train_loss", "+=", "loss", ".", "item", "(", ")", "_", ",", "predicted", "=", "outputs", ".", "max", "(", "1", ")", "total", "+=", "targets", ".", "size", "(", "0", ")", "correct", "+=", "predicted", ".", "eq", "(", "targets", ")", ".", "sum", "(", ")", ".", "item", "(", ")", "acc", "=", "100.0", "*", "correct", "/", "total", "logger", ".", "debug", "(", "\"Loss: %.3f | Acc: %.3f%% (%d/%d)\"", ",", "train_loss", "/", "(", "batch_idx", "+", "1", ")", ",", "100.0", "*", "correct", "/", "total", ",", "correct", ",", "total", ",", ")", "return", "acc" ]
[ 139, 0 ]
[ 178, 14 ]
python
en
['en', 'fy', 'en']
True
test
(epoch)
eval model on each epoch in testset
eval model on each epoch in testset
def test(epoch): """ eval model on each epoch in testset """ global best_acc global trainloader global testloader global net global criterion global optimizer logger.debug("Eval on epoch: %d", epoch) net.eval() test_loss = 0 correct = 0 total = 0 with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(testloader): inputs, targets = inputs.to(device), targets.to(device) outputs = net(inputs) loss = criterion(outputs, targets) test_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() acc = 100.0 * correct / total logger.debug( "Loss: %.3f | Acc: %.3f%% (%d/%d)", test_loss / (batch_idx + 1), 100.0 * correct / total, correct, total, ) acc = 100.0 * correct / total if acc > best_acc: best_acc = acc return acc, best_acc
[ "def", "test", "(", "epoch", ")", ":", "global", "best_acc", "global", "trainloader", "global", "testloader", "global", "net", "global", "criterion", "global", "optimizer", "logger", ".", "debug", "(", "\"Eval on epoch: %d\"", ",", "epoch", ")", "net", ".", "eval", "(", ")", "test_loss", "=", "0", "correct", "=", "0", "total", "=", "0", "with", "torch", ".", "no_grad", "(", ")", ":", "for", "batch_idx", ",", "(", "inputs", ",", "targets", ")", "in", "enumerate", "(", "testloader", ")", ":", "inputs", ",", "targets", "=", "inputs", ".", "to", "(", "device", ")", ",", "targets", ".", "to", "(", "device", ")", "outputs", "=", "net", "(", "inputs", ")", "loss", "=", "criterion", "(", "outputs", ",", "targets", ")", "test_loss", "+=", "loss", ".", "item", "(", ")", "_", ",", "predicted", "=", "outputs", ".", "max", "(", "1", ")", "total", "+=", "targets", ".", "size", "(", "0", ")", "correct", "+=", "predicted", ".", "eq", "(", "targets", ")", ".", "sum", "(", ")", ".", "item", "(", ")", "acc", "=", "100.0", "*", "correct", "/", "total", "logger", ".", "debug", "(", "\"Loss: %.3f | Acc: %.3f%% (%d/%d)\"", ",", "test_loss", "/", "(", "batch_idx", "+", "1", ")", ",", "100.0", "*", "correct", "/", "total", ",", "correct", ",", "total", ",", ")", "acc", "=", "100.0", "*", "correct", "/", "total", "if", "acc", ">", "best_acc", ":", "best_acc", "=", "acc", "return", "acc", ",", "best_acc" ]
[ 181, 0 ]
[ 220, 24 ]
python
da
['en', 'da', 'it']
False
async_setup_entry
(hass, config_entry, async_add_entities)
Set up a sensor for a Ring device.
Set up a sensor for a Ring device.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a sensor for a Ring device.""" devices = hass.data[DOMAIN][config_entry.entry_id]["devices"] sensors = [] for device_type in ("chimes", "doorbots", "authorized_doorbots", "stickup_cams"): for sensor_type in SENSOR_TYPES: if device_type not in SENSOR_TYPES[sensor_type][1]: continue for device in devices[device_type]: if device_type == "battery" and device.battery_life is None: continue sensors.append( SENSOR_TYPES[sensor_type][6]( config_entry.entry_id, device, sensor_type ) ) async_add_entities(sensors)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "devices", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", "sensors", "=", "[", "]", "for", "device_type", "in", "(", "\"chimes\"", ",", "\"doorbots\"", ",", "\"authorized_doorbots\"", ",", "\"stickup_cams\"", ")", ":", "for", "sensor_type", "in", "SENSOR_TYPES", ":", "if", "device_type", "not", "in", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "1", "]", ":", "continue", "for", "device", "in", "devices", "[", "device_type", "]", ":", "if", "device_type", "==", "\"battery\"", "and", "device", ".", "battery_life", "is", "None", ":", "continue", "sensors", ".", "append", "(", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "6", "]", "(", "config_entry", ".", "entry_id", ",", "device", ",", "sensor_type", ")", ")", "async_add_entities", "(", "sensors", ")" ]
[ 10, 0 ]
[ 31, 31 ]
python
en
['en', 'en', 'en']
True
RingSensor.__init__
(self, config_entry_id, device, sensor_type)
Initialize a sensor for Ring device.
Initialize a sensor for Ring device.
def __init__(self, config_entry_id, device, sensor_type): """Initialize a sensor for Ring device.""" super().__init__(config_entry_id, device) self._sensor_type = sensor_type self._extra = None self._icon = "mdi:{}".format(SENSOR_TYPES.get(sensor_type)[3]) self._kind = SENSOR_TYPES.get(sensor_type)[4] self._name = "{} {}".format(self._device.name, SENSOR_TYPES.get(sensor_type)[0]) self._unique_id = f"{device.id}-{sensor_type}"
[ "def", "__init__", "(", "self", ",", "config_entry_id", ",", "device", ",", "sensor_type", ")", ":", "super", "(", ")", ".", "__init__", "(", "config_entry_id", ",", "device", ")", "self", ".", "_sensor_type", "=", "sensor_type", "self", ".", "_extra", "=", "None", "self", ".", "_icon", "=", "\"mdi:{}\"", ".", "format", "(", "SENSOR_TYPES", ".", "get", "(", "sensor_type", ")", "[", "3", "]", ")", "self", ".", "_kind", "=", "SENSOR_TYPES", ".", "get", "(", "sensor_type", ")", "[", "4", "]", "self", ".", "_name", "=", "\"{} {}\"", ".", "format", "(", "self", ".", "_device", ".", "name", ",", "SENSOR_TYPES", ".", "get", "(", "sensor_type", ")", "[", "0", "]", ")", "self", ".", "_unique_id", "=", "f\"{device.id}-{sensor_type}\"" ]
[ 37, 4 ]
[ 45, 54 ]
python
en
['en', 'en', 'en']
True
RingSensor.should_poll
(self)
Return False, updates are controlled via the hub.
Return False, updates are controlled via the hub.
def should_poll(self): """Return False, updates are controlled via the hub.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 48, 4 ]
[ 50, 20 ]
python
en
['en', 'sm', 'en']
True
RingSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 53, 4 ]
[ 55, 25 ]
python
en
['en', 'mi', 'en']
True
RingSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" if self._sensor_type == "volume": return self._device.volume if self._sensor_type == "battery": return self._device.battery_life
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "==", "\"volume\"", ":", "return", "self", ".", "_device", ".", "volume", "if", "self", ".", "_sensor_type", "==", "\"battery\"", ":", "return", "self", ".", "_device", ".", "battery_life" ]
[ 58, 4 ]
[ 64, 44 ]
python
en
['en', 'en', 'en']
True
RingSensor.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self): """Return a unique ID.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 67, 4 ]
[ 69, 30 ]
python
ca
['fr', 'ca', 'en']
False
RingSensor.device_class
(self)
Return sensor device class.
Return sensor device class.
def device_class(self): """Return sensor device class.""" return SENSOR_TYPES[self._sensor_type][5]
[ "def", "device_class", "(", "self", ")", ":", "return", "SENSOR_TYPES", "[", "self", ".", "_sensor_type", "]", "[", "5", "]" ]
[ 72, 4 ]
[ 74, 49 ]
python
en
['nl', 'ro', 'en']
False
RingSensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery" and self._device.battery_life is not None: return icon_for_battery_level( battery_level=self._device.battery_life, charging=False ) return self._icon
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "==", "\"battery\"", "and", "self", ".", "_device", ".", "battery_life", "is", "not", "None", ":", "return", "icon_for_battery_level", "(", "battery_level", "=", "self", ".", "_device", ".", "battery_life", ",", "charging", "=", "False", ")", "return", "self", ".", "_icon" ]
[ 77, 4 ]
[ 83, 25 ]
python
en
['en', 'en', 'en']
True
RingSensor.unit_of_measurement
(self)
Return the units of measurement.
Return the units of measurement.
def unit_of_measurement(self): """Return the units of measurement.""" return SENSOR_TYPES.get(self._sensor_type)[2]
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "SENSOR_TYPES", ".", "get", "(", "self", ".", "_sensor_type", ")", "[", "2", "]" ]
[ 86, 4 ]
[ 88, 53 ]
python
en
['en', 'bg', 'en']
True
HealthDataRingSensor.async_added_to_hass
(self)
Register callbacks.
Register callbacks.
async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["health_data"].async_track_device( self._device, self._health_update_callback )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "await", "self", ".", "ring_objects", "[", "\"health_data\"", "]", ".", "async_track_device", "(", "self", ".", "_device", ",", "self", ".", "_health_update_callback", ")" ]
[ 94, 4 ]
[ 100, 9 ]
python
en
['en', 'no', 'en']
False
HealthDataRingSensor.async_will_remove_from_hass
(self)
Disconnect callbacks.
Disconnect callbacks.
async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["health_data"].async_untrack_device( self._device, self._health_update_callback )
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_will_remove_from_hass", "(", ")", "self", ".", "ring_objects", "[", "\"health_data\"", "]", ".", "async_untrack_device", "(", "self", ".", "_device", ",", "self", ".", "_health_update_callback", ")" ]
[ 102, 4 ]
[ 108, 9 ]
python
en
['en', 'ja', 'en']
False
HealthDataRingSensor._health_update_callback
(self, _health_data)
Call update method.
Call update method.
def _health_update_callback(self, _health_data): """Call update method.""" self.async_write_ha_state()
[ "def", "_health_update_callback", "(", "self", ",", "_health_data", ")", ":", "self", ".", "async_write_ha_state", "(", ")" ]
[ 111, 4 ]
[ 113, 35 ]
python
en
['en', 'sn', 'en']
True
HealthDataRingSensor.entity_registry_enabled_default
(self)
Return if the entity should be enabled when first added to the entity registry.
Return if the entity should be enabled when first added to the entity registry.
def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # These sensors are data hungry and not useful. Disable by default. return False
[ "def", "entity_registry_enabled_default", "(", "self", ")", "->", "bool", ":", "# These sensors are data hungry and not useful. Disable by default.", "return", "False" ]
[ 116, 4 ]
[ 119, 20 ]
python
en
['en', 'en', 'en']
True
HealthDataRingSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" if self._sensor_type == "wifi_signal_category": return self._device.wifi_signal_category if self._sensor_type == "wifi_signal_strength": return self._device.wifi_signal_strength
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "==", "\"wifi_signal_category\"", ":", "return", "self", ".", "_device", ".", "wifi_signal_category", "if", "self", ".", "_sensor_type", "==", "\"wifi_signal_strength\"", ":", "return", "self", ".", "_device", ".", "wifi_signal_strength" ]
[ 122, 4 ]
[ 128, 52 ]
python
en
['en', 'en', 'en']
True
HistoryRingSensor.async_added_to_hass
(self)
Register callbacks.
Register callbacks.
async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["history_data"].async_track_device( self._device, self._history_update_callback )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "await", "self", ".", "ring_objects", "[", "\"history_data\"", "]", ".", "async_track_device", "(", "self", ".", "_device", ",", "self", ".", "_history_update_callback", ")" ]
[ 136, 4 ]
[ 142, 9 ]
python
en
['en', 'no', 'en']
False
HistoryRingSensor.async_will_remove_from_hass
(self)
Disconnect callbacks.
Disconnect callbacks.
async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["history_data"].async_untrack_device( self._device, self._history_update_callback )
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_will_remove_from_hass", "(", ")", "self", ".", "ring_objects", "[", "\"history_data\"", "]", ".", "async_untrack_device", "(", "self", ".", "_device", ",", "self", ".", "_history_update_callback", ")" ]
[ 144, 4 ]
[ 150, 9 ]
python
en
['en', 'ja', 'en']
False
HistoryRingSensor._history_update_callback
(self, history_data)
Call update method.
Call update method.
def _history_update_callback(self, history_data): """Call update method.""" if not history_data: return found = None if self._kind is None: found = history_data[0] else: for entry in history_data: if entry["kind"] == self._kind: found = entry break if not found: return self._latest_event = found self.async_write_ha_state()
[ "def", "_history_update_callback", "(", "self", ",", "history_data", ")", ":", "if", "not", "history_data", ":", "return", "found", "=", "None", "if", "self", ".", "_kind", "is", "None", ":", "found", "=", "history_data", "[", "0", "]", "else", ":", "for", "entry", "in", "history_data", ":", "if", "entry", "[", "\"kind\"", "]", "==", "self", ".", "_kind", ":", "found", "=", "entry", "break", "if", "not", "found", ":", "return", "self", ".", "_latest_event", "=", "found", "self", ".", "async_write_ha_state", "(", ")" ]
[ 153, 4 ]
[ 171, 35 ]
python
en
['en', 'sn', 'en']
True
HistoryRingSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" if self._latest_event is None: return None return self._latest_event["created_at"].isoformat()
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "_latest_event", "is", "None", ":", "return", "None", "return", "self", ".", "_latest_event", "[", "\"created_at\"", "]", ".", "isoformat", "(", ")" ]
[ 174, 4 ]
[ 179, 59 ]
python
en
['en', 'en', 'en']
True
HistoryRingSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" attrs = super().device_state_attributes if self._latest_event: attrs["created_at"] = self._latest_event["created_at"] attrs["answered"] = self._latest_event["answered"] attrs["recording_status"] = self._latest_event["recording"]["status"] attrs["category"] = self._latest_event["kind"] return attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "attrs", "=", "super", "(", ")", ".", "device_state_attributes", "if", "self", ".", "_latest_event", ":", "attrs", "[", "\"created_at\"", "]", "=", "self", ".", "_latest_event", "[", "\"created_at\"", "]", "attrs", "[", "\"answered\"", "]", "=", "self", ".", "_latest_event", "[", "\"answered\"", "]", "attrs", "[", "\"recording_status\"", "]", "=", "self", ".", "_latest_event", "[", "\"recording\"", "]", "[", "\"status\"", "]", "attrs", "[", "\"category\"", "]", "=", "self", ".", "_latest_event", "[", "\"kind\"", "]", "return", "attrs" ]
[ 182, 4 ]
[ 192, 20 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Register the built-in map panel.
Register the built-in map panel.
async def async_setup(hass, config): """Register the built-in map panel.""" hass.components.frontend.async_register_built_in_panel( "map", "map", "hass:tooltip-account" ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "hass", ".", "components", ".", "frontend", ".", "async_register_built_in_panel", "(", "\"map\"", ",", "\"map\"", ",", "\"hass:tooltip-account\"", ")", "return", "True" ]
[ 4, 0 ]
[ 9, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry, async_add_entities)
Set up Ambient PWS binary sensors based on a config entry.
Set up Ambient PWS binary sensors based on a config entry.
async def async_setup_entry(hass, entry, async_add_entities): """Set up Ambient PWS binary sensors based on a config entry.""" ambient = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] binary_sensor_list = [] for mac_address, station in ambient.stations.items(): for condition in station[ATTR_MONITORED_CONDITIONS]: name, _, kind, device_class = SENSOR_TYPES[condition] if kind == TYPE_BINARY_SENSOR: binary_sensor_list.append( AmbientWeatherBinarySensor( ambient, mac_address, station[ATTR_NAME], condition, name, device_class, ) ) async_add_entities(binary_sensor_list, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "ambient", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CLIENT", "]", "[", "entry", ".", "entry_id", "]", "binary_sensor_list", "=", "[", "]", "for", "mac_address", ",", "station", "in", "ambient", ".", "stations", ".", "items", "(", ")", ":", "for", "condition", "in", "station", "[", "ATTR_MONITORED_CONDITIONS", "]", ":", "name", ",", "_", ",", "kind", ",", "device_class", "=", "SENSOR_TYPES", "[", "condition", "]", "if", "kind", "==", "TYPE_BINARY_SENSOR", ":", "binary_sensor_list", ".", "append", "(", "AmbientWeatherBinarySensor", "(", "ambient", ",", "mac_address", ",", "station", "[", "ATTR_NAME", "]", ",", "condition", ",", "name", ",", "device_class", ",", ")", ")", "async_add_entities", "(", "binary_sensor_list", ",", "True", ")" ]
[ 29, 0 ]
[ 49, 48 ]
python
en
['en', 'en', 'en']
True
AmbientWeatherBinarySensor.is_on
(self)
Return the status of the sensor.
Return the status of the sensor.
def is_on(self): """Return the status of the sensor.""" if self._sensor_type in ( TYPE_BATT1, TYPE_BATT10, TYPE_BATT2, TYPE_BATT3, TYPE_BATT4, TYPE_BATT5, TYPE_BATT6, TYPE_BATT7, TYPE_BATT8, TYPE_BATT9, TYPE_BATTOUT, ): return self._state == 0 return self._state == 1
[ "def", "is_on", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "in", "(", "TYPE_BATT1", ",", "TYPE_BATT10", ",", "TYPE_BATT2", ",", "TYPE_BATT3", ",", "TYPE_BATT4", ",", "TYPE_BATT5", ",", "TYPE_BATT6", ",", "TYPE_BATT7", ",", "TYPE_BATT8", ",", "TYPE_BATT9", ",", "TYPE_BATTOUT", ",", ")", ":", "return", "self", ".", "_state", "==", "0", "return", "self", ".", "_state", "==", "1" ]
[ 56, 4 ]
[ 73, 31 ]
python
en
['en', 'id', 'en']
True
AmbientWeatherBinarySensor.update_from_latest_data
(self)
Fetch new state data for the entity.
Fetch new state data for the entity.
def update_from_latest_data(self): """Fetch new state data for the entity.""" self._state = self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get( self._sensor_type )
[ "def", "update_from_latest_data", "(", "self", ")", ":", "self", ".", "_state", "=", "self", ".", "_ambient", ".", "stations", "[", "self", ".", "_mac_address", "]", "[", "ATTR_LAST_DATA", "]", ".", "get", "(", "self", ".", "_sensor_type", ")" ]
[ 76, 4 ]
[ 80, 9 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.__init__
(self, hass)
Initialize cloud prefs.
Initialize cloud prefs.
def __init__(self, hass): """Initialize cloud prefs.""" self._hass = hass self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) self._prefs = None self._listeners = []
[ "def", "__init__", "(", "self", ",", "hass", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_store", "=", "hass", ".", "helpers", ".", "storage", ".", "Store", "(", "STORAGE_VERSION", ",", "STORAGE_KEY", ")", "self", ".", "_prefs", "=", "None", "self", ".", "_listeners", "=", "[", "]" ]
[ 44, 4 ]
[ 49, 28 ]
python
co
['nl', 'co', 'it']
False
CloudPreferences.async_initialize
(self)
Finish initializing the preferences.
Finish initializing the preferences.
async def async_initialize(self): """Finish initializing the preferences.""" prefs = await self._store.async_load() if prefs is None: prefs = self._empty_config("") self._prefs = prefs if PREF_GOOGLE_LOCAL_WEBHOOK_ID not in self._prefs: await self._save_prefs( { **self._prefs, PREF_GOOGLE_LOCAL_WEBHOOK_ID: self._hass.components.webhook.async_generate_id(), } )
[ "async", "def", "async_initialize", "(", "self", ")", ":", "prefs", "=", "await", "self", ".", "_store", ".", "async_load", "(", ")", "if", "prefs", "is", "None", ":", "prefs", "=", "self", ".", "_empty_config", "(", "\"\"", ")", "self", ".", "_prefs", "=", "prefs", "if", "PREF_GOOGLE_LOCAL_WEBHOOK_ID", "not", "in", "self", ".", "_prefs", ":", "await", "self", ".", "_save_prefs", "(", "{", "*", "*", "self", ".", "_prefs", ",", "PREF_GOOGLE_LOCAL_WEBHOOK_ID", ":", "self", ".", "_hass", ".", "components", ".", "webhook", ".", "async_generate_id", "(", ")", ",", "}", ")" ]
[ 51, 4 ]
[ 66, 13 ]
python
en
['en', 'zu', 'en']
True
CloudPreferences.async_listen_updates
(self, listener)
Listen for updates to the preferences.
Listen for updates to the preferences.
def async_listen_updates(self, listener): """Listen for updates to the preferences.""" self._listeners.append(listener)
[ "def", "async_listen_updates", "(", "self", ",", "listener", ")", ":", "self", ".", "_listeners", ".", "append", "(", "listener", ")" ]
[ 69, 4 ]
[ 71, 40 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.async_update
( self, *, google_enabled=_UNDEF, alexa_enabled=_UNDEF, remote_enabled=_UNDEF, google_secure_devices_pin=_UNDEF, cloudhooks=_UNDEF, cloud_user=_UNDEF, google_entity_configs=_UNDEF, alexa_entity_configs=_UNDEF, alexa_report_state=_UNDEF, google_report_state=_UNDEF, alexa_default_expose=_UNDEF, google_default_expose=_UNDEF, )
Update user preferences.
Update user preferences.
async def async_update( self, *, google_enabled=_UNDEF, alexa_enabled=_UNDEF, remote_enabled=_UNDEF, google_secure_devices_pin=_UNDEF, cloudhooks=_UNDEF, cloud_user=_UNDEF, google_entity_configs=_UNDEF, alexa_entity_configs=_UNDEF, alexa_report_state=_UNDEF, google_report_state=_UNDEF, alexa_default_expose=_UNDEF, google_default_expose=_UNDEF, ): """Update user preferences.""" prefs = {**self._prefs} for key, value in ( (PREF_ENABLE_GOOGLE, google_enabled), (PREF_ENABLE_ALEXA, alexa_enabled), (PREF_ENABLE_REMOTE, remote_enabled), (PREF_GOOGLE_SECURE_DEVICES_PIN, google_secure_devices_pin), (PREF_CLOUDHOOKS, cloudhooks), (PREF_CLOUD_USER, cloud_user), (PREF_GOOGLE_ENTITY_CONFIGS, google_entity_configs), (PREF_ALEXA_ENTITY_CONFIGS, alexa_entity_configs), (PREF_ALEXA_REPORT_STATE, alexa_report_state), (PREF_GOOGLE_REPORT_STATE, google_report_state), (PREF_ALEXA_DEFAULT_EXPOSE, alexa_default_expose), (PREF_GOOGLE_DEFAULT_EXPOSE, google_default_expose), ): if value is not _UNDEF: prefs[key] = value if remote_enabled is True and self._has_local_trusted_network: prefs[PREF_ENABLE_REMOTE] = False raise InvalidTrustedNetworks if remote_enabled is True and self._has_local_trusted_proxies: prefs[PREF_ENABLE_REMOTE] = False raise InvalidTrustedProxies await self._save_prefs(prefs)
[ "async", "def", "async_update", "(", "self", ",", "*", ",", "google_enabled", "=", "_UNDEF", ",", "alexa_enabled", "=", "_UNDEF", ",", "remote_enabled", "=", "_UNDEF", ",", "google_secure_devices_pin", "=", "_UNDEF", ",", "cloudhooks", "=", "_UNDEF", ",", "cloud_user", "=", "_UNDEF", ",", "google_entity_configs", "=", "_UNDEF", ",", "alexa_entity_configs", "=", "_UNDEF", ",", "alexa_report_state", "=", "_UNDEF", ",", "google_report_state", "=", "_UNDEF", ",", "alexa_default_expose", "=", "_UNDEF", ",", "google_default_expose", "=", "_UNDEF", ",", ")", ":", "prefs", "=", "{", "*", "*", "self", ".", "_prefs", "}", "for", "key", ",", "value", "in", "(", "(", "PREF_ENABLE_GOOGLE", ",", "google_enabled", ")", ",", "(", "PREF_ENABLE_ALEXA", ",", "alexa_enabled", ")", ",", "(", "PREF_ENABLE_REMOTE", ",", "remote_enabled", ")", ",", "(", "PREF_GOOGLE_SECURE_DEVICES_PIN", ",", "google_secure_devices_pin", ")", ",", "(", "PREF_CLOUDHOOKS", ",", "cloudhooks", ")", ",", "(", "PREF_CLOUD_USER", ",", "cloud_user", ")", ",", "(", "PREF_GOOGLE_ENTITY_CONFIGS", ",", "google_entity_configs", ")", ",", "(", "PREF_ALEXA_ENTITY_CONFIGS", ",", "alexa_entity_configs", ")", ",", "(", "PREF_ALEXA_REPORT_STATE", ",", "alexa_report_state", ")", ",", "(", "PREF_GOOGLE_REPORT_STATE", ",", "google_report_state", ")", ",", "(", "PREF_ALEXA_DEFAULT_EXPOSE", ",", "alexa_default_expose", ")", ",", "(", "PREF_GOOGLE_DEFAULT_EXPOSE", ",", "google_default_expose", ")", ",", ")", ":", "if", "value", "is", "not", "_UNDEF", ":", "prefs", "[", "key", "]", "=", "value", "if", "remote_enabled", "is", "True", "and", "self", ".", "_has_local_trusted_network", ":", "prefs", "[", "PREF_ENABLE_REMOTE", "]", "=", "False", "raise", "InvalidTrustedNetworks", "if", "remote_enabled", "is", "True", "and", "self", ".", "_has_local_trusted_proxies", ":", "prefs", "[", "PREF_ENABLE_REMOTE", "]", "=", "False", "raise", "InvalidTrustedProxies", "await", "self", ".", "_save_prefs", "(", "prefs", ")" ]
[ 73, 4 ]
[ 117, 37 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.async_update_google_entity_config
( self, *, entity_id, override_name=_UNDEF, disable_2fa=_UNDEF, aliases=_UNDEF, should_expose=_UNDEF, )
Update config for a Google entity.
Update config for a Google entity.
async def async_update_google_entity_config( self, *, entity_id, override_name=_UNDEF, disable_2fa=_UNDEF, aliases=_UNDEF, should_expose=_UNDEF, ): """Update config for a Google entity.""" entities = self.google_entity_configs entity = entities.get(entity_id, {}) changes = {} for key, value in ( (PREF_OVERRIDE_NAME, override_name), (PREF_DISABLE_2FA, disable_2fa), (PREF_ALIASES, aliases), (PREF_SHOULD_EXPOSE, should_expose), ): if value is not _UNDEF: changes[key] = value if not changes: return updated_entity = {**entity, **changes} updated_entities = {**entities, entity_id: updated_entity} await self.async_update(google_entity_configs=updated_entities)
[ "async", "def", "async_update_google_entity_config", "(", "self", ",", "*", ",", "entity_id", ",", "override_name", "=", "_UNDEF", ",", "disable_2fa", "=", "_UNDEF", ",", "aliases", "=", "_UNDEF", ",", "should_expose", "=", "_UNDEF", ",", ")", ":", "entities", "=", "self", ".", "google_entity_configs", "entity", "=", "entities", ".", "get", "(", "entity_id", ",", "{", "}", ")", "changes", "=", "{", "}", "for", "key", ",", "value", "in", "(", "(", "PREF_OVERRIDE_NAME", ",", "override_name", ")", ",", "(", "PREF_DISABLE_2FA", ",", "disable_2fa", ")", ",", "(", "PREF_ALIASES", ",", "aliases", ")", ",", "(", "PREF_SHOULD_EXPOSE", ",", "should_expose", ")", ",", ")", ":", "if", "value", "is", "not", "_UNDEF", ":", "changes", "[", "key", "]", "=", "value", "if", "not", "changes", ":", "return", "updated_entity", "=", "{", "*", "*", "entity", ",", "*", "*", "changes", "}", "updated_entities", "=", "{", "*", "*", "entities", ",", "entity_id", ":", "updated_entity", "}", "await", "self", ".", "async_update", "(", "google_entity_configs", "=", "updated_entities", ")" ]
[ 119, 4 ]
[ 148, 71 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.async_update_alexa_entity_config
( self, *, entity_id, should_expose=_UNDEF )
Update config for an Alexa entity.
Update config for an Alexa entity.
async def async_update_alexa_entity_config( self, *, entity_id, should_expose=_UNDEF ): """Update config for an Alexa entity.""" entities = self.alexa_entity_configs entity = entities.get(entity_id, {}) changes = {} for key, value in ((PREF_SHOULD_EXPOSE, should_expose),): if value is not _UNDEF: changes[key] = value if not changes: return updated_entity = {**entity, **changes} updated_entities = {**entities, entity_id: updated_entity} await self.async_update(alexa_entity_configs=updated_entities)
[ "async", "def", "async_update_alexa_entity_config", "(", "self", ",", "*", ",", "entity_id", ",", "should_expose", "=", "_UNDEF", ")", ":", "entities", "=", "self", ".", "alexa_entity_configs", "entity", "=", "entities", ".", "get", "(", "entity_id", ",", "{", "}", ")", "changes", "=", "{", "}", "for", "key", ",", "value", "in", "(", "(", "PREF_SHOULD_EXPOSE", ",", "should_expose", ")", ",", ")", ":", "if", "value", "is", "not", "_UNDEF", ":", "changes", "[", "key", "]", "=", "value", "if", "not", "changes", ":", "return", "updated_entity", "=", "{", "*", "*", "entity", ",", "*", "*", "changes", "}", "updated_entities", "=", "{", "*", "*", "entities", ",", "entity_id", ":", "updated_entity", "}", "await", "self", ".", "async_update", "(", "alexa_entity_configs", "=", "updated_entities", ")" ]
[ 150, 4 ]
[ 168, 70 ]
python
en
['br', 'en', 'en']
True
CloudPreferences.async_set_username
(self, username)
Set the username that is logged in.
Set the username that is logged in.
async def async_set_username(self, username): """Set the username that is logged in.""" # Logging out. if username is None: user = await self._load_cloud_user() if user is not None: await self._hass.auth.async_remove_user(user) await self._save_prefs({**self._prefs, PREF_CLOUD_USER: None}) return cur_username = self._prefs.get(PREF_USERNAME) if cur_username == username: return if cur_username is None: await self._save_prefs({**self._prefs, PREF_USERNAME: username}) else: await self._save_prefs(self._empty_config(username))
[ "async", "def", "async_set_username", "(", "self", ",", "username", ")", ":", "# Logging out.", "if", "username", "is", "None", ":", "user", "=", "await", "self", ".", "_load_cloud_user", "(", ")", "if", "user", "is", "not", "None", ":", "await", "self", ".", "_hass", ".", "auth", ".", "async_remove_user", "(", "user", ")", "await", "self", ".", "_save_prefs", "(", "{", "*", "*", "self", ".", "_prefs", ",", "PREF_CLOUD_USER", ":", "None", "}", ")", "return", "cur_username", "=", "self", ".", "_prefs", ".", "get", "(", "PREF_USERNAME", ")", "if", "cur_username", "==", "username", ":", "return", "if", "cur_username", "is", "None", ":", "await", "self", ".", "_save_prefs", "(", "{", "*", "*", "self", ".", "_prefs", ",", "PREF_USERNAME", ":", "username", "}", ")", "else", ":", "await", "self", ".", "_save_prefs", "(", "self", ".", "_empty_config", "(", "username", ")", ")" ]
[ 170, 4 ]
[ 189, 64 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.as_dict
(self)
Return dictionary version.
Return dictionary version.
def as_dict(self): """Return dictionary version.""" return { PREF_ALEXA_DEFAULT_EXPOSE: self.alexa_default_expose, PREF_ALEXA_ENTITY_CONFIGS: self.alexa_entity_configs, PREF_ALEXA_REPORT_STATE: self.alexa_report_state, PREF_CLOUDHOOKS: self.cloudhooks, PREF_ENABLE_ALEXA: self.alexa_enabled, PREF_ENABLE_GOOGLE: self.google_enabled, PREF_ENABLE_REMOTE: self.remote_enabled, PREF_GOOGLE_DEFAULT_EXPOSE: self.google_default_expose, PREF_GOOGLE_ENTITY_CONFIGS: self.google_entity_configs, PREF_GOOGLE_REPORT_STATE: self.google_report_state, PREF_GOOGLE_SECURE_DEVICES_PIN: self.google_secure_devices_pin, }
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "PREF_ALEXA_DEFAULT_EXPOSE", ":", "self", ".", "alexa_default_expose", ",", "PREF_ALEXA_ENTITY_CONFIGS", ":", "self", ".", "alexa_entity_configs", ",", "PREF_ALEXA_REPORT_STATE", ":", "self", ".", "alexa_report_state", ",", "PREF_CLOUDHOOKS", ":", "self", ".", "cloudhooks", ",", "PREF_ENABLE_ALEXA", ":", "self", ".", "alexa_enabled", ",", "PREF_ENABLE_GOOGLE", ":", "self", ".", "google_enabled", ",", "PREF_ENABLE_REMOTE", ":", "self", ".", "remote_enabled", ",", "PREF_GOOGLE_DEFAULT_EXPOSE", ":", "self", ".", "google_default_expose", ",", "PREF_GOOGLE_ENTITY_CONFIGS", ":", "self", ".", "google_entity_configs", ",", "PREF_GOOGLE_REPORT_STATE", ":", "self", ".", "google_report_state", ",", "PREF_GOOGLE_SECURE_DEVICES_PIN", ":", "self", ".", "google_secure_devices_pin", ",", "}" ]
[ 191, 4 ]
[ 205, 9 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.remote_enabled
(self)
Return if remote is enabled on start.
Return if remote is enabled on start.
def remote_enabled(self): """Return if remote is enabled on start.""" enabled = self._prefs.get(PREF_ENABLE_REMOTE, False) if not enabled: return False if self._has_local_trusted_network or self._has_local_trusted_proxies: return False return True
[ "def", "remote_enabled", "(", "self", ")", ":", "enabled", "=", "self", ".", "_prefs", ".", "get", "(", "PREF_ENABLE_REMOTE", ",", "False", ")", "if", "not", "enabled", ":", "return", "False", "if", "self", ".", "_has_local_trusted_network", "or", "self", ".", "_has_local_trusted_proxies", ":", "return", "False", "return", "True" ]
[ 208, 4 ]
[ 218, 19 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.alexa_enabled
(self)
Return if Alexa is enabled.
Return if Alexa is enabled.
def alexa_enabled(self): """Return if Alexa is enabled.""" return self._prefs[PREF_ENABLE_ALEXA]
[ "def", "alexa_enabled", "(", "self", ")", ":", "return", "self", ".", "_prefs", "[", "PREF_ENABLE_ALEXA", "]" ]
[ 221, 4 ]
[ 223, 45 ]
python
en
['en', 'af', 'en']
True
CloudPreferences.alexa_report_state
(self)
Return if Alexa report state is enabled.
Return if Alexa report state is enabled.
def alexa_report_state(self): """Return if Alexa report state is enabled.""" return self._prefs.get(PREF_ALEXA_REPORT_STATE, DEFAULT_ALEXA_REPORT_STATE)
[ "def", "alexa_report_state", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_ALEXA_REPORT_STATE", ",", "DEFAULT_ALEXA_REPORT_STATE", ")" ]
[ 226, 4 ]
[ 228, 83 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.alexa_default_expose
(self)
Return array of entity domains that are exposed by default to Alexa. Can return None, in which case for backwards should be interpreted as allow all domains.
Return array of entity domains that are exposed by default to Alexa.
def alexa_default_expose(self) -> Optional[List[str]]: """Return array of entity domains that are exposed by default to Alexa. Can return None, in which case for backwards should be interpreted as allow all domains. """ return self._prefs.get(PREF_ALEXA_DEFAULT_EXPOSE)
[ "def", "alexa_default_expose", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_ALEXA_DEFAULT_EXPOSE", ")" ]
[ 231, 4 ]
[ 236, 57 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.alexa_entity_configs
(self)
Return Alexa Entity configurations.
Return Alexa Entity configurations.
def alexa_entity_configs(self): """Return Alexa Entity configurations.""" return self._prefs.get(PREF_ALEXA_ENTITY_CONFIGS, {})
[ "def", "alexa_entity_configs", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_ALEXA_ENTITY_CONFIGS", ",", "{", "}", ")" ]
[ 239, 4 ]
[ 241, 61 ]
python
en
['en', 'ca', 'en']
True
CloudPreferences.google_enabled
(self)
Return if Google is enabled.
Return if Google is enabled.
def google_enabled(self): """Return if Google is enabled.""" return self._prefs[PREF_ENABLE_GOOGLE]
[ "def", "google_enabled", "(", "self", ")", ":", "return", "self", ".", "_prefs", "[", "PREF_ENABLE_GOOGLE", "]" ]
[ 244, 4 ]
[ 246, 46 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.google_report_state
(self)
Return if Google report state is enabled.
Return if Google report state is enabled.
def google_report_state(self): """Return if Google report state is enabled.""" return self._prefs.get(PREF_GOOGLE_REPORT_STATE, DEFAULT_GOOGLE_REPORT_STATE)
[ "def", "google_report_state", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_GOOGLE_REPORT_STATE", ",", "DEFAULT_GOOGLE_REPORT_STATE", ")" ]
[ 249, 4 ]
[ 251, 85 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.google_secure_devices_pin
(self)
Return if Google is allowed to unlock locks.
Return if Google is allowed to unlock locks.
def google_secure_devices_pin(self): """Return if Google is allowed to unlock locks.""" return self._prefs.get(PREF_GOOGLE_SECURE_DEVICES_PIN)
[ "def", "google_secure_devices_pin", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_GOOGLE_SECURE_DEVICES_PIN", ")" ]
[ 254, 4 ]
[ 256, 62 ]
python
en
['en', 'mt', 'en']
True
CloudPreferences.google_entity_configs
(self)
Return Google Entity configurations.
Return Google Entity configurations.
def google_entity_configs(self): """Return Google Entity configurations.""" return self._prefs.get(PREF_GOOGLE_ENTITY_CONFIGS, {})
[ "def", "google_entity_configs", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_GOOGLE_ENTITY_CONFIGS", ",", "{", "}", ")" ]
[ 259, 4 ]
[ 261, 62 ]
python
en
['en', 'bg', 'en']
True
CloudPreferences.google_local_webhook_id
(self)
Return Google webhook ID to receive local messages.
Return Google webhook ID to receive local messages.
def google_local_webhook_id(self): """Return Google webhook ID to receive local messages.""" return self._prefs[PREF_GOOGLE_LOCAL_WEBHOOK_ID]
[ "def", "google_local_webhook_id", "(", "self", ")", ":", "return", "self", ".", "_prefs", "[", "PREF_GOOGLE_LOCAL_WEBHOOK_ID", "]" ]
[ 264, 4 ]
[ 266, 56 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.google_default_expose
(self)
Return array of entity domains that are exposed by default to Google. Can return None, in which case for backwards should be interpreted as allow all domains.
Return array of entity domains that are exposed by default to Google.
def google_default_expose(self) -> Optional[List[str]]: """Return array of entity domains that are exposed by default to Google. Can return None, in which case for backwards should be interpreted as allow all domains. """ return self._prefs.get(PREF_GOOGLE_DEFAULT_EXPOSE)
[ "def", "google_default_expose", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_GOOGLE_DEFAULT_EXPOSE", ")" ]
[ 269, 4 ]
[ 274, 58 ]
python
en
['en', 'en', 'en']
True
CloudPreferences.cloudhooks
(self)
Return the published cloud webhooks.
Return the published cloud webhooks.
def cloudhooks(self): """Return the published cloud webhooks.""" return self._prefs.get(PREF_CLOUDHOOKS, {})
[ "def", "cloudhooks", "(", "self", ")", ":", "return", "self", ".", "_prefs", ".", "get", "(", "PREF_CLOUDHOOKS", ",", "{", "}", ")" ]
[ 277, 4 ]
[ 279, 51 ]
python
en
['en', 'zu', 'en']
True
CloudPreferences.get_cloud_user
(self)
Return ID from Home Assistant Cloud system user.
Return ID from Home Assistant Cloud system user.
async def get_cloud_user(self) -> str: """Return ID from Home Assistant Cloud system user.""" user = await self._load_cloud_user() if user: return user.id user = await self._hass.auth.async_create_system_user( "Home Assistant Cloud", [GROUP_ID_ADMIN] ) await self.async_update(cloud_user=user.id) return user.id
[ "async", "def", "get_cloud_user", "(", "self", ")", "->", "str", ":", "user", "=", "await", "self", ".", "_load_cloud_user", "(", ")", "if", "user", ":", "return", "user", ".", "id", "user", "=", "await", "self", ".", "_hass", ".", "auth", ".", "async_create_system_user", "(", "\"Home Assistant Cloud\"", ",", "[", "GROUP_ID_ADMIN", "]", ")", "await", "self", ".", "async_update", "(", "cloud_user", "=", "user", ".", "id", ")", "return", "user", ".", "id" ]
[ 281, 4 ]
[ 292, 22 ]
python
en
['en', 'en', 'en']
True