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_get_triggers_set_tilt_pos
(hass, device_reg, entity_reg)
Test we get the expected triggers from a cover.
Test we get the expected triggers from a cover.
async def test_get_triggers_set_tilt_pos(hass, device_reg, entity_reg): """Test we get the expected triggers from a cover.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[2] config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create( DOMAIN, "test", ent.unique_id, device_id=device_entry.id ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) expected_triggers = [ { "platform": "device", "domain": DOMAIN, "type": "opened", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_{ent.unique_id}", }, { "platform": "device", "domain": DOMAIN, "type": "closed", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_{ent.unique_id}", }, { "platform": "device", "domain": DOMAIN, "type": "opening", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_{ent.unique_id}", }, { "platform": "device", "domain": DOMAIN, "type": "closing", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_{ent.unique_id}", }, { "platform": "device", "domain": DOMAIN, "type": "tilt_position", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_{ent.unique_id}", }, ] triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert_lists_same(triggers, expected_triggers)
[ "async", "def", "test_get_triggers_set_tilt_pos", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "2", "]", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "ent", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "expected_triggers", "=", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"opened\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_{ent.unique_id}\"", ",", "}", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"closed\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_{ent.unique_id}\"", ",", "}", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"opening\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_{ent.unique_id}\"", ",", "}", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"closing\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_{ent.unique_id}\"", ",", "}", ",", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"tilt_position\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_{ent.unique_id}\"", ",", "}", ",", "]", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "triggers", ",", "expected_triggers", ")" ]
[ 153, 0 ]
[ 208, 50 ]
python
en
['en', 'en', 'en']
True
test_get_trigger_capabilities
(hass, device_reg, entity_reg)
Test we get the expected capabilities from a cover trigger.
Test we get the expected capabilities from a cover trigger.
async def test_get_trigger_capabilities(hass, device_reg, entity_reg): """Test we get the expected capabilities from a cover trigger.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[0] config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create( DOMAIN, "test", ent.unique_id, device_id=device_entry.id ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert len(triggers) == 4 for trigger in triggers: capabilities = await async_get_device_automation_capabilities( hass, "trigger", trigger ) assert capabilities == {"extra_fields": []}
[ "async", "def", "test_get_trigger_capabilities", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "0", "]", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "ent", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert", "len", "(", "triggers", ")", "==", "4", "for", "trigger", "in", "triggers", ":", "capabilities", "=", "await", "async_get_device_automation_capabilities", "(", "hass", ",", "\"trigger\"", ",", "trigger", ")", "assert", "capabilities", "==", "{", "\"extra_fields\"", ":", "[", "]", "}" ]
[ 211, 0 ]
[ 235, 51 ]
python
en
['en', 'en', 'en']
True
test_get_trigger_capabilities_set_pos
(hass, device_reg, entity_reg)
Test we get the expected capabilities from a cover trigger.
Test we get the expected capabilities from a cover trigger.
async def test_get_trigger_capabilities_set_pos(hass, device_reg, entity_reg): """Test we get the expected capabilities from a cover trigger.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[1] config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create( DOMAIN, "test", ent.unique_id, device_id=device_entry.id ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) expected_capabilities = { "extra_fields": [ { "name": "above", "optional": True, "type": "integer", "default": 0, "valueMax": 100, "valueMin": 0, }, { "name": "below", "optional": True, "type": "integer", "default": 100, "valueMax": 100, "valueMin": 0, }, ] } triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert len(triggers) == 5 for trigger in triggers: capabilities = await async_get_device_automation_capabilities( hass, "trigger", trigger ) if trigger["type"] == "position": assert capabilities == expected_capabilities else: assert capabilities == {"extra_fields": []}
[ "async", "def", "test_get_trigger_capabilities_set_pos", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "1", "]", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "ent", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "expected_capabilities", "=", "{", "\"extra_fields\"", ":", "[", "{", "\"name\"", ":", "\"above\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"integer\"", ",", "\"default\"", ":", "0", ",", "\"valueMax\"", ":", "100", ",", "\"valueMin\"", ":", "0", ",", "}", ",", "{", "\"name\"", ":", "\"below\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"integer\"", ",", "\"default\"", ":", "100", ",", "\"valueMax\"", ":", "100", ",", "\"valueMin\"", ":", "0", ",", "}", ",", "]", "}", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert", "len", "(", "triggers", ")", "==", "5", "for", "trigger", "in", "triggers", ":", "capabilities", "=", "await", "async_get_device_automation_capabilities", "(", "hass", ",", "\"trigger\"", ",", "trigger", ")", "if", "trigger", "[", "\"type\"", "]", "==", "\"position\"", ":", "assert", "capabilities", "==", "expected_capabilities", "else", ":", "assert", "capabilities", "==", "{", "\"extra_fields\"", ":", "[", "]", "}" ]
[ 238, 0 ]
[ 285, 55 ]
python
en
['en', 'en', 'en']
True
test_get_trigger_capabilities_set_tilt_pos
(hass, device_reg, entity_reg)
Test we get the expected capabilities from a cover trigger.
Test we get the expected capabilities from a cover trigger.
async def test_get_trigger_capabilities_set_tilt_pos(hass, device_reg, entity_reg): """Test we get the expected capabilities from a cover trigger.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[2] config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create( DOMAIN, "test", ent.unique_id, device_id=device_entry.id ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) expected_capabilities = { "extra_fields": [ { "name": "above", "optional": True, "type": "integer", "default": 0, "valueMax": 100, "valueMin": 0, }, { "name": "below", "optional": True, "type": "integer", "default": 100, "valueMax": 100, "valueMin": 0, }, ] } triggers = await async_get_device_automations(hass, "trigger", device_entry.id) assert len(triggers) == 5 for trigger in triggers: capabilities = await async_get_device_automation_capabilities( hass, "trigger", trigger ) if trigger["type"] == "tilt_position": assert capabilities == expected_capabilities else: assert capabilities == {"extra_fields": []}
[ "async", "def", "test_get_trigger_capabilities_set_tilt_pos", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "2", "]", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "ent", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "expected_capabilities", "=", "{", "\"extra_fields\"", ":", "[", "{", "\"name\"", ":", "\"above\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"integer\"", ",", "\"default\"", ":", "0", ",", "\"valueMax\"", ":", "100", ",", "\"valueMin\"", ":", "0", ",", "}", ",", "{", "\"name\"", ":", "\"below\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"integer\"", ",", "\"default\"", ":", "100", ",", "\"valueMax\"", ":", "100", ",", "\"valueMin\"", ":", "0", ",", "}", ",", "]", "}", "triggers", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"trigger\"", ",", "device_entry", ".", "id", ")", "assert", "len", "(", "triggers", ")", "==", "5", "for", "trigger", "in", "triggers", ":", "capabilities", "=", "await", "async_get_device_automation_capabilities", "(", "hass", ",", "\"trigger\"", ",", "trigger", ")", "if", "trigger", "[", "\"type\"", "]", "==", "\"tilt_position\"", ":", "assert", "capabilities", "==", "expected_capabilities", "else", ":", "assert", "capabilities", "==", "{", "\"extra_fields\"", ":", "[", "]", "}" ]
[ 288, 0 ]
[ 335, 55 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_state_change
(hass, calls)
Test for state triggers firing.
Test for state triggers firing.
async def test_if_fires_on_state_change(hass, calls): """Test for state triggers firing.""" hass.states.async_set("cover.entity", STATE_CLOSED) assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "cover.entity", "type": "opened", }, "action": { "service": "test.automation", "data_template": { "some": ( "opened - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "cover.entity", "type": "closed", }, "action": { "service": "test.automation", "data_template": { "some": ( "closed - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "cover.entity", "type": "opening", }, "action": { "service": "test.automation", "data_template": { "some": ( "opening - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": "cover.entity", "type": "closing", }, "action": { "service": "test.automation", "data_template": { "some": ( "closing - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, ] }, ) # Fake that the entity is opened. hass.states.async_set("cover.entity", STATE_OPEN) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data[ "some" ] == "opened - device - {} - closed - open - None".format("cover.entity") # Fake that the entity is closed. hass.states.async_set("cover.entity", STATE_CLOSED) await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data[ "some" ] == "closed - device - {} - open - closed - None".format("cover.entity") # Fake that the entity is opening. hass.states.async_set("cover.entity", STATE_OPENING) await hass.async_block_till_done() assert len(calls) == 3 assert calls[2].data[ "some" ] == "opening - device - {} - closed - opening - None".format("cover.entity") # Fake that the entity is closing. hass.states.async_set("cover.entity", STATE_CLOSING) await hass.async_block_till_done() assert len(calls) == 4 assert calls[3].data[ "some" ] == "closing - device - {} - opening - closing - None".format("cover.entity")
[ "async", "def", "test_if_fires_on_state_change", "(", "hass", ",", "calls", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"cover.entity\"", ",", "STATE_CLOSED", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "\"cover.entity\"", ",", "\"type\"", ":", "\"opened\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"opened - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "\"cover.entity\"", ",", "\"type\"", ":", "\"closed\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"closed - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "\"cover.entity\"", ",", "\"type\"", ":", "\"opening\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"opening - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "\"cover.entity\"", ",", "\"type\"", ":", "\"closing\"", ",", "}", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"closing - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "# Fake that the entity is opened.", "hass", ".", "states", ".", "async_set", "(", "\"cover.entity\"", ",", "STATE_OPEN", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"opened - device - {} - closed - open - None\"", ".", "format", "(", "\"cover.entity\"", ")", "# Fake that the entity is closed.", "hass", ".", "states", ".", "async_set", "(", "\"cover.entity\"", ",", "STATE_CLOSED", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", "==", "\"closed - device - {} - open - closed - None\"", ".", "format", "(", "\"cover.entity\"", ")", "# Fake that the entity is opening.", "hass", ".", "states", ".", "async_set", "(", "\"cover.entity\"", ",", "STATE_OPENING", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "3", "assert", "calls", "[", "2", "]", ".", "data", "[", "\"some\"", "]", "==", "\"opening - device - {} - closed - opening - None\"", ".", "format", "(", "\"cover.entity\"", ")", "# Fake that the entity is closing.", "hass", ".", "states", ".", "async_set", "(", "\"cover.entity\"", ",", "STATE_CLOSING", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "4", "assert", "calls", "[", "3", "]", ".", "data", "[", "\"some\"", "]", "==", "\"closing - device - {} - opening - closing - None\"", ".", "format", "(", "\"cover.entity\"", ")" ]
[ 338, 0 ]
[ 457, 82 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_position
(hass, calls)
Test for position triggers.
Test for position triggers.
async def test_if_fires_on_position(hass, calls): """Test for position triggers.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[1] assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "position", "above": 45, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_gt_45 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "position", "below": 90, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_lt_90 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "position", "above": 45, "below": 90, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_gt_45_lt_90 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, ] }, ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_position": 50} ) await hass.async_block_till_done() assert len(calls) == 3 assert sorted( [calls[0].data["some"], calls[1].data["some"], calls[2].data["some"]] ) == sorted( [ "is_pos_gt_45_lt_90 - device - cover.set_position_cover - open - closed - None", "is_pos_lt_90 - device - cover.set_position_cover - open - closed - None", "is_pos_gt_45 - device - cover.set_position_cover - open - closed - None", ] ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_position": 95} ) await hass.async_block_till_done() hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_position": 45} ) await hass.async_block_till_done() assert len(calls) == 4 assert ( calls[3].data["some"] == "is_pos_lt_90 - device - cover.set_position_cover - closed - closed - None" ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_position": 90} ) await hass.async_block_till_done() assert len(calls) == 5 assert ( calls[4].data["some"] == "is_pos_gt_45 - device - cover.set_position_cover - closed - closed - None" )
[ "async", "def", "test_if_fires_on_position", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "1", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"position\"", ",", "\"above\"", ":", "45", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_gt_45 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"position\"", ",", "\"below\"", ":", "90", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_lt_90 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"position\"", ",", "\"above\"", ":", "45", ",", "\"below\"", ":", "90", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_gt_45_lt_90 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_position\"", ":", "50", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "3", "assert", "sorted", "(", "[", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", ",", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", ",", "calls", "[", "2", "]", ".", "data", "[", "\"some\"", "]", "]", ")", "==", "sorted", "(", "[", "\"is_pos_gt_45_lt_90 - device - cover.set_position_cover - open - closed - None\"", ",", "\"is_pos_lt_90 - device - cover.set_position_cover - open - closed - None\"", ",", "\"is_pos_gt_45 - device - cover.set_position_cover - open - closed - None\"", ",", "]", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_position\"", ":", "95", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_position\"", ":", "45", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "4", "assert", "(", "calls", "[", "3", "]", ".", "data", "[", "\"some\"", "]", "==", "\"is_pos_lt_90 - device - cover.set_position_cover - closed - closed - None\"", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_position\"", ":", "90", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "5", "assert", "(", "calls", "[", "4", "]", ".", "data", "[", "\"some\"", "]", "==", "\"is_pos_gt_45 - device - cover.set_position_cover - closed - closed - None\"", ")" ]
[ 460, 0 ]
[ 580, 5 ]
python
en
['en', 'en', 'en']
True
test_if_fires_on_tilt_position
(hass, calls)
Test for tilt position triggers.
Test for tilt position triggers.
async def test_if_fires_on_tilt_position(hass, calls): """Test for tilt position triggers.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() ent = platform.ENTITIES[1] assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "tilt_position", "above": 45, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_gt_45 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "tilt_position", "below": 90, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_lt_90 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, { "trigger": [ { "platform": "device", "domain": DOMAIN, "device_id": "", "entity_id": ent.entity_id, "type": "tilt_position", "above": 45, "below": 90, } ], "action": { "service": "test.automation", "data_template": { "some": ( "is_pos_gt_45_lt_90 - {{ trigger.platform}} - " "{{ trigger.entity_id}} - {{ trigger.from_state.state}} - " "{{ trigger.to_state.state}} - {{ trigger.for }}" ) }, }, }, ] }, ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_tilt_position": 50} ) await hass.async_block_till_done() assert len(calls) == 3 assert sorted( [calls[0].data["some"], calls[1].data["some"], calls[2].data["some"]] ) == sorted( [ "is_pos_gt_45_lt_90 - device - cover.set_position_cover - open - closed - None", "is_pos_lt_90 - device - cover.set_position_cover - open - closed - None", "is_pos_gt_45 - device - cover.set_position_cover - open - closed - None", ] ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_tilt_position": 95} ) await hass.async_block_till_done() hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_tilt_position": 45} ) await hass.async_block_till_done() assert len(calls) == 4 assert ( calls[3].data["some"] == "is_pos_lt_90 - device - cover.set_position_cover - closed - closed - None" ) hass.states.async_set( ent.entity_id, STATE_CLOSED, attributes={"current_tilt_position": 90} ) await hass.async_block_till_done() assert len(calls) == 5 assert ( calls[4].data["some"] == "is_pos_gt_45 - device - cover.set_position_cover - closed - closed - None" )
[ "async", "def", "test_if_fires_on_tilt_position", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "ent", "=", "platform", ".", "ENTITIES", "[", "1", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"tilt_position\"", ",", "\"above\"", ":", "45", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_gt_45 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"tilt_position\"", ",", "\"below\"", ":", "90", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_lt_90 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "[", "{", "\"platform\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent", ".", "entity_id", ",", "\"type\"", ":", "\"tilt_position\"", ",", "\"above\"", ":", "45", ",", "\"below\"", ":", "90", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "(", "\"is_pos_gt_45_lt_90 - {{ trigger.platform}} - \"", "\"{{ trigger.entity_id}} - {{ trigger.from_state.state}} - \"", "\"{{ trigger.to_state.state}} - {{ trigger.for }}\"", ")", "}", ",", "}", ",", "}", ",", "]", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_tilt_position\"", ":", "50", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "3", "assert", "sorted", "(", "[", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", ",", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", ",", "calls", "[", "2", "]", ".", "data", "[", "\"some\"", "]", "]", ")", "==", "sorted", "(", "[", "\"is_pos_gt_45_lt_90 - device - cover.set_position_cover - open - closed - None\"", ",", "\"is_pos_lt_90 - device - cover.set_position_cover - open - closed - None\"", ",", "\"is_pos_gt_45 - device - cover.set_position_cover - open - closed - None\"", ",", "]", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_tilt_position\"", ":", "95", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_tilt_position\"", ":", "45", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "4", "assert", "(", "calls", "[", "3", "]", ".", "data", "[", "\"some\"", "]", "==", "\"is_pos_lt_90 - device - cover.set_position_cover - closed - closed - None\"", ")", "hass", ".", "states", ".", "async_set", "(", "ent", ".", "entity_id", ",", "STATE_CLOSED", ",", "attributes", "=", "{", "\"current_tilt_position\"", ":", "90", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "5", "assert", "(", "calls", "[", "4", "]", ".", "data", "[", "\"some\"", "]", "==", "\"is_pos_gt_45 - device - cover.set_position_cover - closed - closed - None\"", ")" ]
[ 583, 0 ]
[ 703, 5 ]
python
da
['da', 'da', 'en']
True
ZmqDriver._setup_sockets
(self)
Setup three kinds of sockets, and one poller. - ``unicast_receiver``: The ``zmq.PULL`` socket, use for receiving message from one-to-one communication, - ``broadcast_sender``: The ``zmq.PUB`` socket, use for broadcasting message to all subscribers, - ``broadcast_receiver``: The ``zmq.SUB`` socket, use for listening message from broadcast. - ``poller``: The zmq output multiplexing, use for receiving message from ``zmq.PULL`` socket and \ ``zmq.SUB`` socket.
Setup three kinds of sockets, and one poller.
def _setup_sockets(self): """Setup three kinds of sockets, and one poller. - ``unicast_receiver``: The ``zmq.PULL`` socket, use for receiving message from one-to-one communication, - ``broadcast_sender``: The ``zmq.PUB`` socket, use for broadcasting message to all subscribers, - ``broadcast_receiver``: The ``zmq.SUB`` socket, use for listening message from broadcast. - ``poller``: The zmq output multiplexing, use for receiving message from ``zmq.PULL`` socket and \ ``zmq.SUB`` socket. """ self._unicast_receiver = self._zmq_context.socket(zmq.PULL) unicast_receiver_port = self._unicast_receiver.bind_to_random_port(f"{self._protocol}://*") self._logger.info(f"Receive message via unicasting at {self._ip_address}:{unicast_receiver_port}.") # Dict about zmq.PUSH sockets, fulfills in self.connect. self._unicast_sender_dict = {} self._broadcast_sender = self._zmq_context.socket(zmq.PUB) self._broadcast_sender.setsockopt(zmq.SNDTIMEO, self._send_timeout) self._broadcast_receiver = self._zmq_context.socket(zmq.SUB) self._broadcast_receiver.setsockopt(zmq.SUBSCRIBE, self._component_type.encode()) broadcast_receiver_port = self._broadcast_receiver.bind_to_random_port(f"{self._protocol}://*") self._logger.info(f"Subscriber message at {self._ip_address}:{broadcast_receiver_port}.") # Record own sockets' address. self._address = { zmq.PULL: f"{self._protocol}://{self._ip_address}:{unicast_receiver_port}", zmq.SUB: f"{self._protocol}://{self._ip_address}:{broadcast_receiver_port}" } self._poller = zmq.Poller() self._poller.register(self._unicast_receiver, zmq.POLLIN) self._poller.register(self._broadcast_receiver, zmq.POLLIN)
[ "def", "_setup_sockets", "(", "self", ")", ":", "self", ".", "_unicast_receiver", "=", "self", ".", "_zmq_context", ".", "socket", "(", "zmq", ".", "PULL", ")", "unicast_receiver_port", "=", "self", ".", "_unicast_receiver", ".", "bind_to_random_port", "(", "f\"{self._protocol}://*\"", ")", "self", ".", "_logger", ".", "info", "(", "f\"Receive message via unicasting at {self._ip_address}:{unicast_receiver_port}.\"", ")", "# Dict about zmq.PUSH sockets, fulfills in self.connect.", "self", ".", "_unicast_sender_dict", "=", "{", "}", "self", ".", "_broadcast_sender", "=", "self", ".", "_zmq_context", ".", "socket", "(", "zmq", ".", "PUB", ")", "self", ".", "_broadcast_sender", ".", "setsockopt", "(", "zmq", ".", "SNDTIMEO", ",", "self", ".", "_send_timeout", ")", "self", ".", "_broadcast_receiver", "=", "self", ".", "_zmq_context", ".", "socket", "(", "zmq", ".", "SUB", ")", "self", ".", "_broadcast_receiver", ".", "setsockopt", "(", "zmq", ".", "SUBSCRIBE", ",", "self", ".", "_component_type", ".", "encode", "(", ")", ")", "broadcast_receiver_port", "=", "self", ".", "_broadcast_receiver", ".", "bind_to_random_port", "(", "f\"{self._protocol}://*\"", ")", "self", ".", "_logger", ".", "info", "(", "f\"Subscriber message at {self._ip_address}:{broadcast_receiver_port}.\"", ")", "# Record own sockets' address.", "self", ".", "_address", "=", "{", "zmq", ".", "PULL", ":", "f\"{self._protocol}://{self._ip_address}:{unicast_receiver_port}\"", ",", "zmq", ".", "SUB", ":", "f\"{self._protocol}://{self._ip_address}:{broadcast_receiver_port}\"", "}", "self", ".", "_poller", "=", "zmq", ".", "Poller", "(", ")", "self", ".", "_poller", ".", "register", "(", "self", ".", "_unicast_receiver", ",", "zmq", ".", "POLLIN", ")", "self", ".", "_poller", ".", "register", "(", "self", ".", "_broadcast_receiver", ",", "zmq", ".", "POLLIN", ")" ]
[ 60, 4 ]
[ 92, 67 ]
python
en
['en', 'en', 'en']
True
ZmqDriver.address
(self)
Returns: Dict[int, str]: The sockets' address Dict of ``zmq.PULL`` socket and ``zmq.SUB`` socket. The key of dict is the socket's type, while the value of dict is socket's ip address, which forms by protocol+ip+port. Example: Dict{zmq.PULL: "tcp://0.0.0.0:1234", zmq.SUB: "tcp://0.0.0.0:1235"}
Returns: Dict[int, str]: The sockets' address Dict of ``zmq.PULL`` socket and ``zmq.SUB`` socket. The key of dict is the socket's type, while the value of dict is socket's ip address, which forms by protocol+ip+port.
def address(self) -> Dict[int, str]: """ Returns: Dict[int, str]: The sockets' address Dict of ``zmq.PULL`` socket and ``zmq.SUB`` socket. The key of dict is the socket's type, while the value of dict is socket's ip address, which forms by protocol+ip+port. Example: Dict{zmq.PULL: "tcp://0.0.0.0:1234", zmq.SUB: "tcp://0.0.0.0:1235"} """ return self._address
[ "def", "address", "(", "self", ")", "->", "Dict", "[", "int", ",", "str", "]", ":", "return", "self", ".", "_address" ]
[ 95, 4 ]
[ 105, 28 ]
python
en
['en', 'error', 'th']
False
ZmqDriver.connect
(self, peers_address_dict: Dict[str, Dict[str, str]])
Build a connection with all peers in peers socket address. Set up the unicast sender which is ``zmq.PUSH`` socket and the broadcast sender which is ``zmq.PUB`` socket. Args: peers_address_dict (Dict[str, Dict[str, str]]): Peers' socket address dict. The key of dict is the peer's name, while the value of dict is the peer's socket connection address. E.g. Dict{'peer1', Dict[zmq.PULL, 'tcp://0.0.0.0:1234']}.
Build a connection with all peers in peers socket address.
def connect(self, peers_address_dict: Dict[str, Dict[str, str]]): """Build a connection with all peers in peers socket address. Set up the unicast sender which is ``zmq.PUSH`` socket and the broadcast sender which is ``zmq.PUB`` socket. Args: peers_address_dict (Dict[str, Dict[str, str]]): Peers' socket address dict. The key of dict is the peer's name, while the value of dict is the peer's socket connection address. E.g. Dict{'peer1', Dict[zmq.PULL, 'tcp://0.0.0.0:1234']}. """ for peer_name, address_dict in peers_address_dict.items(): for socket_type, address in address_dict.items(): try: if int(socket_type) == zmq.PULL: self._unicast_sender_dict[peer_name] = self._zmq_context.socket(zmq.PUSH) self._unicast_sender_dict[peer_name].setsockopt(zmq.SNDTIMEO, self._send_timeout) self._unicast_sender_dict[peer_name].connect(address) self._logger.info(f"Connects to {peer_name} via unicasting.") elif int(socket_type) == zmq.SUB: self._broadcast_sender.connect(address) self._logger.info(f"Connects to {peer_name} via broadcasting.") else: raise SocketTypeError(f"Unrecognized socket type {socket_type}.") except Exception as e: raise PeersConnectionError(f"Driver cannot connect to {peer_name}! Due to {str(e)}") if peer_name in self._disconnected_peer_name_list: self._disconnected_peer_name_list.remove(peer_name)
[ "def", "connect", "(", "self", ",", "peers_address_dict", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ")", ":", "for", "peer_name", ",", "address_dict", "in", "peers_address_dict", ".", "items", "(", ")", ":", "for", "socket_type", ",", "address", "in", "address_dict", ".", "items", "(", ")", ":", "try", ":", "if", "int", "(", "socket_type", ")", "==", "zmq", ".", "PULL", ":", "self", ".", "_unicast_sender_dict", "[", "peer_name", "]", "=", "self", ".", "_zmq_context", ".", "socket", "(", "zmq", ".", "PUSH", ")", "self", ".", "_unicast_sender_dict", "[", "peer_name", "]", ".", "setsockopt", "(", "zmq", ".", "SNDTIMEO", ",", "self", ".", "_send_timeout", ")", "self", ".", "_unicast_sender_dict", "[", "peer_name", "]", ".", "connect", "(", "address", ")", "self", ".", "_logger", ".", "info", "(", "f\"Connects to {peer_name} via unicasting.\"", ")", "elif", "int", "(", "socket_type", ")", "==", "zmq", ".", "SUB", ":", "self", ".", "_broadcast_sender", ".", "connect", "(", "address", ")", "self", ".", "_logger", ".", "info", "(", "f\"Connects to {peer_name} via broadcasting.\"", ")", "else", ":", "raise", "SocketTypeError", "(", "f\"Unrecognized socket type {socket_type}.\"", ")", "except", "Exception", "as", "e", ":", "raise", "PeersConnectionError", "(", "f\"Driver cannot connect to {peer_name}! Due to {str(e)}\"", ")", "if", "peer_name", "in", "self", ".", "_disconnected_peer_name_list", ":", "self", ".", "_disconnected_peer_name_list", ".", "remove", "(", "peer_name", ")" ]
[ 107, 4 ]
[ 134, 67 ]
python
en
['en', 'en', 'en']
True
ZmqDriver.disconnect
(self, peers_address_dict: Dict[str, Dict[str, str]])
Disconnect with all peers in peers socket address. Disconnect and delete the unicast sender which is ``zmq.PUSH`` socket for the peers in dict. Args: peers_address_dict (Dict[str, Dict[str, str]]): Peers' socket address dict. The key of dict is the peer's name, while the value of dict is the peer's socket connection address. E.g. Dict{'peer1', Dict[zmq.PULL, 'tcp://0.0.0.0:1234']}.
Disconnect with all peers in peers socket address.
def disconnect(self, peers_address_dict: Dict[str, Dict[str, str]]): """Disconnect with all peers in peers socket address. Disconnect and delete the unicast sender which is ``zmq.PUSH`` socket for the peers in dict. Args: peers_address_dict (Dict[str, Dict[str, str]]): Peers' socket address dict. The key of dict is the peer's name, while the value of dict is the peer's socket connection address. E.g. Dict{'peer1', Dict[zmq.PULL, 'tcp://0.0.0.0:1234']}. """ for peer_name, address_dict in peers_address_dict.items(): for socket_type, address in address_dict.items(): try: if int(socket_type) == zmq.PULL: self._unicast_sender_dict[peer_name].disconnect(address) del self._unicast_sender_dict[peer_name] elif int(socket_type) == zmq.SUB: self._broadcast_sender.disconnect(address) else: raise SocketTypeError(f"Unrecognized socket type {socket_type}.") except Exception as e: raise PeersDisconnectionError(f"Driver cannot disconnect to {peer_name}! Due to {str(e)}") self._disconnected_peer_name_list.append(peer_name) self._logger.info(f"Disconnected with {peer_name}.")
[ "def", "disconnect", "(", "self", ",", "peers_address_dict", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ")", ":", "for", "peer_name", ",", "address_dict", "in", "peers_address_dict", ".", "items", "(", ")", ":", "for", "socket_type", ",", "address", "in", "address_dict", ".", "items", "(", ")", ":", "try", ":", "if", "int", "(", "socket_type", ")", "==", "zmq", ".", "PULL", ":", "self", ".", "_unicast_sender_dict", "[", "peer_name", "]", ".", "disconnect", "(", "address", ")", "del", "self", ".", "_unicast_sender_dict", "[", "peer_name", "]", "elif", "int", "(", "socket_type", ")", "==", "zmq", ".", "SUB", ":", "self", ".", "_broadcast_sender", ".", "disconnect", "(", "address", ")", "else", ":", "raise", "SocketTypeError", "(", "f\"Unrecognized socket type {socket_type}.\"", ")", "except", "Exception", "as", "e", ":", "raise", "PeersDisconnectionError", "(", "f\"Driver cannot disconnect to {peer_name}! Due to {str(e)}\"", ")", "self", ".", "_disconnected_peer_name_list", ".", "append", "(", "peer_name", ")", "self", ".", "_logger", ".", "info", "(", "f\"Disconnected with {peer_name}.\"", ")" ]
[ 136, 4 ]
[ 160, 64 ]
python
en
['en', 'en', 'en']
True
ZmqDriver.receive
(self, is_continuous: bool = True, timeout: int = None)
Receive message from ``zmq.POLLER``. Args: is_continuous (bool): Continuously receive message or not. Defaults to True. Yields: recv_message (Message): The received message from the poller.
Receive message from ``zmq.POLLER``.
def receive(self, is_continuous: bool = True, timeout: int = None): """Receive message from ``zmq.POLLER``. Args: is_continuous (bool): Continuously receive message or not. Defaults to True. Yields: recv_message (Message): The received message from the poller. """ while True: receive_timeout = timeout if timeout else self._receive_timeout try: sockets = dict(self._poller.poll(receive_timeout)) except Exception as e: raise DriverReceiveError(f"Driver cannot receive message as {e}") if self._unicast_receiver in sockets: recv_message = self._unicast_receiver.recv_pyobj() self._logger.debug(f"Receive a message from {recv_message.source} through unicast receiver.") elif self._broadcast_receiver in sockets: _, recv_message = self._broadcast_receiver.recv_multipart() recv_message = pickle.loads(recv_message) self._logger.debug(f"Receive a message from {recv_message.source} through broadcast receiver.") else: self._logger.debug(f"Cannot receive any message within {receive_timeout}.") return yield recv_message if not is_continuous: break
[ "def", "receive", "(", "self", ",", "is_continuous", ":", "bool", "=", "True", ",", "timeout", ":", "int", "=", "None", ")", ":", "while", "True", ":", "receive_timeout", "=", "timeout", "if", "timeout", "else", "self", ".", "_receive_timeout", "try", ":", "sockets", "=", "dict", "(", "self", ".", "_poller", ".", "poll", "(", "receive_timeout", ")", ")", "except", "Exception", "as", "e", ":", "raise", "DriverReceiveError", "(", "f\"Driver cannot receive message as {e}\"", ")", "if", "self", ".", "_unicast_receiver", "in", "sockets", ":", "recv_message", "=", "self", ".", "_unicast_receiver", ".", "recv_pyobj", "(", ")", "self", ".", "_logger", ".", "debug", "(", "f\"Receive a message from {recv_message.source} through unicast receiver.\"", ")", "elif", "self", ".", "_broadcast_receiver", "in", "sockets", ":", "_", ",", "recv_message", "=", "self", ".", "_broadcast_receiver", ".", "recv_multipart", "(", ")", "recv_message", "=", "pickle", ".", "loads", "(", "recv_message", ")", "self", ".", "_logger", ".", "debug", "(", "f\"Receive a message from {recv_message.source} through broadcast receiver.\"", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "f\"Cannot receive any message within {receive_timeout}.\"", ")", "return", "yield", "recv_message", "if", "not", "is_continuous", ":", "break" ]
[ 162, 4 ]
[ 192, 21 ]
python
en
['en', 'en', 'en']
True
ZmqDriver.send
(self, message: Message)
Send message. Args: message (class): Message to be sent.
Send message.
def send(self, message: Message): """Send message. Args: message (class): Message to be sent. """ try: self._unicast_sender_dict[message.destination].send_pyobj(message) self._logger.debug(f"Send a {message.tag} message to {message.destination}.") except KeyError as key_error: if message.destination in self._disconnected_peer_name_list: raise PendingToSend(f"Temporary failure to send message to {message.destination}, may rejoin later.") else: self._logger.error(f"Failure to send message caused by: {key_error}") sys.exit(NON_RESTART_EXIT_CODE) except Exception as e: raise DriverSendError(f"Failure to send message caused by: {e}")
[ "def", "send", "(", "self", ",", "message", ":", "Message", ")", ":", "try", ":", "self", ".", "_unicast_sender_dict", "[", "message", ".", "destination", "]", ".", "send_pyobj", "(", "message", ")", "self", ".", "_logger", ".", "debug", "(", "f\"Send a {message.tag} message to {message.destination}.\"", ")", "except", "KeyError", "as", "key_error", ":", "if", "message", ".", "destination", "in", "self", ".", "_disconnected_peer_name_list", ":", "raise", "PendingToSend", "(", "f\"Temporary failure to send message to {message.destination}, may rejoin later.\"", ")", "else", ":", "self", ".", "_logger", ".", "error", "(", "f\"Failure to send message caused by: {key_error}\"", ")", "sys", ".", "exit", "(", "NON_RESTART_EXIT_CODE", ")", "except", "Exception", "as", "e", ":", "raise", "DriverSendError", "(", "f\"Failure to send message caused by: {e}\"", ")" ]
[ 194, 4 ]
[ 210, 76 ]
python
en
['en', 'de', 'en']
False
ZmqDriver.broadcast
(self, topic: str, message: Message)
Broadcast message. Args: topic(str): The topic of broadcast. message(class): Message to be sent.
Broadcast message.
def broadcast(self, topic: str, message: Message): """Broadcast message. Args: topic(str): The topic of broadcast. message(class): Message to be sent. """ try: self._broadcast_sender.send_multipart([topic.encode(), pickle.dumps(message)]) self._logger.debug(f"Broadcast a {message.tag} message to all {topic}.") except Exception as e: raise DriverSendError(f"Failure to broadcast message caused by: {e}")
[ "def", "broadcast", "(", "self", ",", "topic", ":", "str", ",", "message", ":", "Message", ")", ":", "try", ":", "self", ".", "_broadcast_sender", ".", "send_multipart", "(", "[", "topic", ".", "encode", "(", ")", ",", "pickle", ".", "dumps", "(", "message", ")", "]", ")", "self", ".", "_logger", ".", "debug", "(", "f\"Broadcast a {message.tag} message to all {topic}.\"", ")", "except", "Exception", "as", "e", ":", "raise", "DriverSendError", "(", "f\"Failure to broadcast message caused by: {e}\"", ")" ]
[ 212, 4 ]
[ 223, 81 ]
python
en
['en', 'en', 'en']
False
ZmqDriver.close
(self)
Close ZMQ context and sockets.
Close ZMQ context and sockets.
def close(self): """Close ZMQ context and sockets.""" # Avoid hanging infinitely self._zmq_context.setsockopt(zmq.LINGER, 0) # Close all sockets self._broadcast_receiver.close() self._broadcast_sender.close() self._unicast_receiver.close() for unicast_sender in self._unicast_sender_dict.values(): unicast_sender.close() self._zmq_context.term()
[ "def", "close", "(", "self", ")", ":", "# Avoid hanging infinitely", "self", ".", "_zmq_context", ".", "setsockopt", "(", "zmq", ".", "LINGER", ",", "0", ")", "# Close all sockets", "self", ".", "_broadcast_receiver", ".", "close", "(", ")", "self", ".", "_broadcast_sender", ".", "close", "(", ")", "self", ".", "_unicast_receiver", ".", "close", "(", ")", "for", "unicast_sender", "in", "self", ".", "_unicast_sender_dict", ".", "values", "(", ")", ":", "unicast_sender", ".", "close", "(", ")", "self", ".", "_zmq_context", ".", "term", "(", ")" ]
[ 225, 4 ]
[ 237, 32 ]
python
en
['en', 'fil', 'en']
True
async_setup_services
(hass)
Set up services for the Plex component.
Set up services for the Plex component.
async def async_setup_services(hass): """Set up services for the Plex component.""" async def async_refresh_library_service(service_call): await hass.async_add_executor_job(refresh_library, hass, service_call) async def async_scan_clients_service(_): _LOGGER.debug("Scanning for new Plex clients") for server_id in hass.data[DOMAIN][SERVERS]: async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) hass.services.async_register( DOMAIN, SERVICE_REFRESH_LIBRARY, async_refresh_library_service, schema=REFRESH_LIBRARY_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_SCAN_CLIENTS, async_scan_clients_service ) return True
[ "async", "def", "async_setup_services", "(", "hass", ")", ":", "async", "def", "async_refresh_library_service", "(", "service_call", ")", ":", "await", "hass", ".", "async_add_executor_job", "(", "refresh_library", ",", "hass", ",", "service_call", ")", "async", "def", "async_scan_clients_service", "(", "_", ")", ":", "_LOGGER", ".", "debug", "(", "\"Scanning for new Plex clients\"", ")", "for", "server_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "SERVERS", "]", ":", "async_dispatcher_send", "(", "hass", ",", "PLEX_UPDATE_PLATFORMS_SIGNAL", ".", "format", "(", "server_id", ")", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_REFRESH_LIBRARY", ",", "async_refresh_library_service", ",", "schema", "=", "REFRESH_LIBRARY_SCHEMA", ",", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_SCAN_CLIENTS", ",", "async_scan_clients_service", ")", "return", "True" ]
[ 24, 0 ]
[ 45, 15 ]
python
en
['en', 'fr', 'en']
True
refresh_library
(hass, service_call)
Scan a Plex library for new and updated media.
Scan a Plex library for new and updated media.
def refresh_library(hass, service_call): """Scan a Plex library for new and updated media.""" plex_server_name = service_call.data.get("server_name") library_name = service_call.data["library_name"] plex_server = get_plex_server(hass, plex_server_name) if not plex_server: return try: library = plex_server.library.section(title=library_name) except NotFound: _LOGGER.error( "Library with name '%s' not found in %s", library_name, [x.title for x in plex_server.library.sections()], ) return _LOGGER.debug("Scanning %s for new and updated media", library_name) library.update()
[ "def", "refresh_library", "(", "hass", ",", "service_call", ")", ":", "plex_server_name", "=", "service_call", ".", "data", ".", "get", "(", "\"server_name\"", ")", "library_name", "=", "service_call", ".", "data", "[", "\"library_name\"", "]", "plex_server", "=", "get_plex_server", "(", "hass", ",", "plex_server_name", ")", "if", "not", "plex_server", ":", "return", "try", ":", "library", "=", "plex_server", ".", "library", ".", "section", "(", "title", "=", "library_name", ")", "except", "NotFound", ":", "_LOGGER", ".", "error", "(", "\"Library with name '%s' not found in %s\"", ",", "library_name", ",", "[", "x", ".", "title", "for", "x", "in", "plex_server", ".", "library", ".", "sections", "(", ")", "]", ",", ")", "return", "_LOGGER", ".", "debug", "(", "\"Scanning %s for new and updated media\"", ",", "library_name", ")", "library", ".", "update", "(", ")" ]
[ 48, 0 ]
[ 68, 20 ]
python
en
['en', 'en', 'en']
True
get_plex_server
(hass, plex_server_name=None)
Retrieve a configured Plex server by name.
Retrieve a configured Plex server by name.
def get_plex_server(hass, plex_server_name=None): """Retrieve a configured Plex server by name.""" plex_servers = hass.data[DOMAIN][SERVERS].values() if plex_server_name: plex_server = next( (x for x in plex_servers if x.friendly_name == plex_server_name), None ) if plex_server is not None: return plex_server _LOGGER.error( "Requested Plex server '%s' not found in %s", plex_server_name, [x.friendly_name for x in plex_servers], ) return None if len(plex_servers) == 1: return next(iter(plex_servers)) _LOGGER.error( "Multiple Plex servers configured, choose with 'plex_server' key: %s", [x.friendly_name for x in plex_servers], ) return None
[ "def", "get_plex_server", "(", "hass", ",", "plex_server_name", "=", "None", ")", ":", "plex_servers", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "SERVERS", "]", ".", "values", "(", ")", "if", "plex_server_name", ":", "plex_server", "=", "next", "(", "(", "x", "for", "x", "in", "plex_servers", "if", "x", ".", "friendly_name", "==", "plex_server_name", ")", ",", "None", ")", "if", "plex_server", "is", "not", "None", ":", "return", "plex_server", "_LOGGER", ".", "error", "(", "\"Requested Plex server '%s' not found in %s\"", ",", "plex_server_name", ",", "[", "x", ".", "friendly_name", "for", "x", "in", "plex_servers", "]", ",", ")", "return", "None", "if", "len", "(", "plex_servers", ")", "==", "1", ":", "return", "next", "(", "iter", "(", "plex_servers", ")", ")", "_LOGGER", ".", "error", "(", "\"Multiple Plex servers configured, choose with 'plex_server' key: %s\"", ",", "[", "x", ".", "friendly_name", "for", "x", "in", "plex_servers", "]", ",", ")", "return", "None" ]
[ 71, 0 ]
[ 95, 15 ]
python
en
['en', 'pt', 'en']
True
lookup_plex_media
(hass, content_type, content_id)
Look up Plex media using media_player.play_media service payloads.
Look up Plex media using media_player.play_media service payloads.
def lookup_plex_media(hass, content_type, content_id): """Look up Plex media using media_player.play_media service payloads.""" content = json.loads(content_id) if isinstance(content, int): content = {"plex_key": content} content_type = DOMAIN plex_server_name = content.pop("plex_server", None) shuffle = content.pop("shuffle", 0) plex_server = get_plex_server(hass, plex_server_name=plex_server_name) if not plex_server: return (None, None) media = plex_server.lookup_media(content_type, **content) if media is None: _LOGGER.error("Media could not be found: %s", content) return (None, None) playqueue = plex_server.create_playqueue(media, shuffle=shuffle) return (playqueue, plex_server)
[ "def", "lookup_plex_media", "(", "hass", ",", "content_type", ",", "content_id", ")", ":", "content", "=", "json", ".", "loads", "(", "content_id", ")", "if", "isinstance", "(", "content", ",", "int", ")", ":", "content", "=", "{", "\"plex_key\"", ":", "content", "}", "content_type", "=", "DOMAIN", "plex_server_name", "=", "content", ".", "pop", "(", "\"plex_server\"", ",", "None", ")", "shuffle", "=", "content", ".", "pop", "(", "\"shuffle\"", ",", "0", ")", "plex_server", "=", "get_plex_server", "(", "hass", ",", "plex_server_name", "=", "plex_server_name", ")", "if", "not", "plex_server", ":", "return", "(", "None", ",", "None", ")", "media", "=", "plex_server", ".", "lookup_media", "(", "content_type", ",", "*", "*", "content", ")", "if", "media", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Media could not be found: %s\"", ",", "content", ")", "return", "(", "None", ",", "None", ")", "playqueue", "=", "plex_server", ".", "create_playqueue", "(", "media", ",", "shuffle", "=", "shuffle", ")", "return", "(", "playqueue", ",", "plex_server", ")" ]
[ 98, 0 ]
[ 119, 35 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Elk light platform.
Set up the Elk light platform.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Elk light platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.lights, "plc", ElkLight, entities) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "elk_data", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "entities", "=", "[", "]", "elk", "=", "elk_data", "[", "\"elk\"", "]", "create_elk_entities", "(", "elk_data", ",", "elk", ".", "lights", ",", "\"plc\"", ",", "ElkLight", ",", "entities", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 12, 0 ]
[ 18, 38 ]
python
en
['en', 'da', 'en']
True
ElkLight.__init__
(self, element, elk, elk_data)
Initialize the Elk light.
Initialize the Elk light.
def __init__(self, element, elk, elk_data): """Initialize the Elk light.""" super().__init__(element, elk, elk_data) self._brightness = self._element.status
[ "def", "__init__", "(", "self", ",", "element", ",", "elk", ",", "elk_data", ")", ":", "super", "(", ")", ".", "__init__", "(", "element", ",", "elk", ",", "elk_data", ")", "self", ".", "_brightness", "=", "self", ".", "_element", ".", "status" ]
[ 24, 4 ]
[ 27, 47 ]
python
en
['en', 'en', 'en']
True
ElkLight.brightness
(self)
Get the brightness.
Get the brightness.
def brightness(self): """Get the brightness.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 30, 4 ]
[ 32, 31 ]
python
en
['en', 'ko', 'en']
True
ElkLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_BRIGHTNESS
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_BRIGHTNESS" ]
[ 35, 4 ]
[ 37, 33 ]
python
en
['da', 'en', 'en']
True
ElkLight.is_on
(self)
Get the current brightness.
Get the current brightness.
def is_on(self) -> bool: """Get the current brightness.""" return self._brightness != 0
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_brightness", "!=", "0" ]
[ 40, 4 ]
[ 42, 36 ]
python
en
['en', 'en', 'en']
True
ElkLight.async_turn_on
(self, **kwargs)
Turn on the light.
Turn on the light.
async def async_turn_on(self, **kwargs): """Turn on the light.""" self._element.level(round(kwargs.get(ATTR_BRIGHTNESS, 255) / 2.55))
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_element", ".", "level", "(", "round", "(", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ",", "255", ")", "/", "2.55", ")", ")" ]
[ 48, 4 ]
[ 50, 75 ]
python
en
['en', 'et', 'en']
True
ElkLight.async_turn_off
(self, **kwargs)
Turn off the light.
Turn off the light.
async def async_turn_off(self, **kwargs): """Turn off the light.""" self._element.level(0)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_element", ".", "level", "(", "0", ")" ]
[ 52, 4 ]
[ 54, 30 ]
python
en
['en', 'zh', 'en']
True
UKFloodsFlowHandler.__init__
(self)
Handle a UK Floods config flow.
Handle a UK Floods config flow.
def __init__(self): """Handle a UK Floods config flow.""" self.stations = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "stations", "=", "{", "}" ]
[ 17, 4 ]
[ 19, 26 ]
python
en
['en', 'fr', 'en']
True
UKFloodsFlowHandler.async_step_user
(self, user_input=None)
Handle a flow start.
Handle a flow start.
async def async_step_user(self, user_input=None): """Handle a flow start.""" errors = {} if user_input is not None: station = self.stations[user_input["station"]] await self.async_set_unique_id(station, raise_on_progress=False) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input["station"], data={"station": station}, ) session = async_get_clientsession(hass=self.hass) stations = await get_stations(session) self.stations = {} for station in stations: label = station["label"] # API annoyingly sometimes returns a list and some times returns a string # E.g. L3121 has a label of ['Scurf Dyke', 'Scurf Dyke Dyke Level'] if isinstance(label, list): label = label[-1] self.stations[label] = station["stationReference"] if not self.stations: return self.async_abort(reason="no_stations") return self.async_show_form( step_id="user", errors=errors, data_schema=vol.Schema( {vol.Required("station"): vol.In(sorted(self.stations))} ), )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "station", "=", "self", ".", "stations", "[", "user_input", "[", "\"station\"", "]", "]", "await", "self", ".", "async_set_unique_id", "(", "station", ",", "raise_on_progress", "=", "False", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "user_input", "[", "\"station\"", "]", ",", "data", "=", "{", "\"station\"", ":", "station", "}", ",", ")", "session", "=", "async_get_clientsession", "(", "hass", "=", "self", ".", "hass", ")", "stations", "=", "await", "get_stations", "(", "session", ")", "self", ".", "stations", "=", "{", "}", "for", "station", "in", "stations", ":", "label", "=", "station", "[", "\"label\"", "]", "# API annoyingly sometimes returns a list and some times returns a string", "# E.g. L3121 has a label of ['Scurf Dyke', 'Scurf Dyke Dyke Level']", "if", "isinstance", "(", "label", ",", "list", ")", ":", "label", "=", "label", "[", "-", "1", "]", "self", ".", "stations", "[", "label", "]", "=", "station", "[", "\"stationReference\"", "]", "if", "not", "self", ".", "stations", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"no_stations\"", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "errors", "=", "errors", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "\"station\"", ")", ":", "vol", ".", "In", "(", "sorted", "(", "self", ".", "stations", ")", ")", "}", ")", ",", ")" ]
[ 21, 4 ]
[ 57, 9 ]
python
en
['en', 'lb', 'en']
True
TestGraphite.setup_method
(self, method)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setup_method(self, method): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.gf = graphite.GraphiteFeeder(self.hass, "foo", 123, "ha")
[ "def", "setup_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "gf", "=", "graphite", ".", "GraphiteFeeder", "(", "self", ".", "hass", ",", "\"foo\"", ",", "123", ",", "\"ha\"", ")" ]
[ 23, 4 ]
[ 26, 70 ]
python
en
['en', 'en', 'en']
True
TestGraphite.teardown_method
(self, method)
Stop everything that was started.
Stop everything that was started.
def teardown_method(self, method): """Stop everything that was started.""" self.hass.stop()
[ "def", "teardown_method", "(", "self", ",", "method", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 28, 4 ]
[ 30, 24 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_setup
(self, mock_socket)
Test setup.
Test setup.
def test_setup(self, mock_socket): """Test setup.""" assert setup_component(self.hass, graphite.DOMAIN, {"graphite": {}}) assert mock_socket.call_count == 1 assert mock_socket.call_args == mock.call(socket.AF_INET, socket.SOCK_STREAM)
[ "def", "test_setup", "(", "self", ",", "mock_socket", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "graphite", ".", "DOMAIN", ",", "{", "\"graphite\"", ":", "{", "}", "}", ")", "assert", "mock_socket", ".", "call_count", "==", "1", "assert", "mock_socket", ".", "call_args", "==", "mock", ".", "call", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")" ]
[ 33, 4 ]
[ 37, 85 ]
python
en
['en', 'haw', 'en']
False
TestGraphite.test_full_config
(self, mock_gf, mock_socket)
Test setup with full configuration.
Test setup with full configuration.
def test_full_config(self, mock_gf, mock_socket): """Test setup with full configuration.""" config = {"graphite": {"host": "foo", "port": 123, "prefix": "me"}} assert setup_component(self.hass, graphite.DOMAIN, config) assert mock_gf.call_count == 1 assert mock_gf.call_args == mock.call(self.hass, "foo", 123, "me") assert mock_socket.call_count == 1 assert mock_socket.call_args == mock.call(socket.AF_INET, socket.SOCK_STREAM)
[ "def", "test_full_config", "(", "self", ",", "mock_gf", ",", "mock_socket", ")", ":", "config", "=", "{", "\"graphite\"", ":", "{", "\"host\"", ":", "\"foo\"", ",", "\"port\"", ":", "123", ",", "\"prefix\"", ":", "\"me\"", "}", "}", "assert", "setup_component", "(", "self", ".", "hass", ",", "graphite", ".", "DOMAIN", ",", "config", ")", "assert", "mock_gf", ".", "call_count", "==", "1", "assert", "mock_gf", ".", "call_args", "==", "mock", ".", "call", "(", "self", ".", "hass", ",", "\"foo\"", ",", "123", ",", "\"me\"", ")", "assert", "mock_socket", ".", "call_count", "==", "1", "assert", "mock_socket", ".", "call_args", "==", "mock", ".", "call", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")" ]
[ 41, 4 ]
[ 49, 85 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_config_port
(self, mock_gf, mock_socket)
Test setup with invalid port.
Test setup with invalid port.
def test_config_port(self, mock_gf, mock_socket): """Test setup with invalid port.""" config = {"graphite": {"host": "foo", "port": 2003}} assert setup_component(self.hass, graphite.DOMAIN, config) assert mock_gf.called assert mock_socket.call_count == 1 assert mock_socket.call_args == mock.call(socket.AF_INET, socket.SOCK_STREAM)
[ "def", "test_config_port", "(", "self", ",", "mock_gf", ",", "mock_socket", ")", ":", "config", "=", "{", "\"graphite\"", ":", "{", "\"host\"", ":", "\"foo\"", ",", "\"port\"", ":", "2003", "}", "}", "assert", "setup_component", "(", "self", ".", "hass", ",", "graphite", ".", "DOMAIN", ",", "config", ")", "assert", "mock_gf", ".", "called", "assert", "mock_socket", ".", "call_count", "==", "1", "assert", "mock_socket", ".", "call_args", "==", "mock", ".", "call", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")" ]
[ 53, 4 ]
[ 60, 85 ]
python
en
['en', 'haw', 'en']
True
TestGraphite.test_subscribe
(self)
Test the subscription.
Test the subscription.
def test_subscribe(self): """Test the subscription.""" fake_hass = mock.MagicMock() gf = graphite.GraphiteFeeder(fake_hass, "foo", 123, "ha") fake_hass.bus.listen_once.has_calls( [ mock.call(EVENT_HOMEASSISTANT_START, gf.start_listen), mock.call(EVENT_HOMEASSISTANT_STOP, gf.shutdown), ] ) assert fake_hass.bus.listen.call_count == 1 assert fake_hass.bus.listen.call_args == mock.call( EVENT_STATE_CHANGED, gf.event_listener )
[ "def", "test_subscribe", "(", "self", ")", ":", "fake_hass", "=", "mock", ".", "MagicMock", "(", ")", "gf", "=", "graphite", ".", "GraphiteFeeder", "(", "fake_hass", ",", "\"foo\"", ",", "123", ",", "\"ha\"", ")", "fake_hass", ".", "bus", ".", "listen_once", ".", "has_calls", "(", "[", "mock", ".", "call", "(", "EVENT_HOMEASSISTANT_START", ",", "gf", ".", "start_listen", ")", ",", "mock", ".", "call", "(", "EVENT_HOMEASSISTANT_STOP", ",", "gf", ".", "shutdown", ")", ",", "]", ")", "assert", "fake_hass", ".", "bus", ".", "listen", ".", "call_count", "==", "1", "assert", "fake_hass", ".", "bus", ".", "listen", ".", "call_args", "==", "mock", ".", "call", "(", "EVENT_STATE_CHANGED", ",", "gf", ".", "event_listener", ")" ]
[ 62, 4 ]
[ 75, 9 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_start
(self)
Test the start.
Test the start.
def test_start(self): """Test the start.""" with mock.patch.object(self.gf, "start") as mock_start: self.gf.start_listen("event") assert mock_start.call_count == 1 assert mock_start.call_args == mock.call()
[ "def", "test_start", "(", "self", ")", ":", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"start\"", ")", "as", "mock_start", ":", "self", ".", "gf", ".", "start_listen", "(", "\"event\"", ")", "assert", "mock_start", ".", "call_count", "==", "1", "assert", "mock_start", ".", "call_args", "==", "mock", ".", "call", "(", ")" ]
[ 77, 4 ]
[ 82, 54 ]
python
en
['en', 'de', 'en']
True
TestGraphite.test_shutdown
(self)
Test the shutdown.
Test the shutdown.
def test_shutdown(self): """Test the shutdown.""" with mock.patch.object(self.gf, "_queue") as mock_queue: self.gf.shutdown("event") assert mock_queue.put.call_count == 1 assert mock_queue.put.call_args == mock.call(self.gf._quit_object)
[ "def", "test_shutdown", "(", "self", ")", ":", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_queue\"", ")", "as", "mock_queue", ":", "self", ".", "gf", ".", "shutdown", "(", "\"event\"", ")", "assert", "mock_queue", ".", "put", ".", "call_count", "==", "1", "assert", "mock_queue", ".", "put", ".", "call_args", "==", "mock", ".", "call", "(", "self", ".", "gf", ".", "_quit_object", ")" ]
[ 84, 4 ]
[ 89, 78 ]
python
en
['en', 'bg-Latn', 'en']
True
TestGraphite.test_event_listener
(self)
Test the event listener.
Test the event listener.
def test_event_listener(self): """Test the event listener.""" with mock.patch.object(self.gf, "_queue") as mock_queue: self.gf.event_listener("foo") assert mock_queue.put.call_count == 1 assert mock_queue.put.call_args == mock.call("foo")
[ "def", "test_event_listener", "(", "self", ")", ":", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_queue\"", ")", "as", "mock_queue", ":", "self", ".", "gf", ".", "event_listener", "(", "\"foo\"", ")", "assert", "mock_queue", ".", "put", ".", "call_count", "==", "1", "assert", "mock_queue", ".", "put", ".", "call_args", "==", "mock", ".", "call", "(", "\"foo\"", ")" ]
[ 91, 4 ]
[ 96, 63 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_report_attributes
(self, mock_time)
Test the reporting with attributes.
Test the reporting with attributes.
def test_report_attributes(self, mock_time): """Test the reporting with attributes.""" mock_time.return_value = 12345 attrs = {"foo": 1, "bar": 2.0, "baz": True, "bat": "NaN"} expected = [ "ha.entity.state 0.000000 12345", "ha.entity.foo 1.000000 12345", "ha.entity.bar 2.000000 12345", "ha.entity.baz 1.000000 12345", ] state = mock.MagicMock(state=0, attributes=attrs) with mock.patch.object(self.gf, "_send_to_graphite") as mock_send: self.gf._report_attributes("entity", state) actual = mock_send.call_args_list[0][0][0].split("\n") assert sorted(expected) == sorted(actual)
[ "def", "test_report_attributes", "(", "self", ",", "mock_time", ")", ":", "mock_time", ".", "return_value", "=", "12345", "attrs", "=", "{", "\"foo\"", ":", "1", ",", "\"bar\"", ":", "2.0", ",", "\"baz\"", ":", "True", ",", "\"bat\"", ":", "\"NaN\"", "}", "expected", "=", "[", "\"ha.entity.state 0.000000 12345\"", ",", "\"ha.entity.foo 1.000000 12345\"", ",", "\"ha.entity.bar 2.000000 12345\"", ",", "\"ha.entity.baz 1.000000 12345\"", ",", "]", "state", "=", "mock", ".", "MagicMock", "(", "state", "=", "0", ",", "attributes", "=", "attrs", ")", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_send_to_graphite\"", ")", "as", "mock_send", ":", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")", "actual", "=", "mock_send", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "assert", "sorted", "(", "expected", ")", "==", "sorted", "(", "actual", ")" ]
[ 99, 4 ]
[ 115, 53 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_report_with_string_state
(self, mock_time)
Test the reporting with strings.
Test the reporting with strings.
def test_report_with_string_state(self, mock_time): """Test the reporting with strings.""" mock_time.return_value = 12345 expected = ["ha.entity.foo 1.000000 12345", "ha.entity.state 1.000000 12345"] state = mock.MagicMock(state="above_horizon", attributes={"foo": 1.0}) with mock.patch.object(self.gf, "_send_to_graphite") as mock_send: self.gf._report_attributes("entity", state) actual = mock_send.call_args_list[0][0][0].split("\n") assert sorted(expected) == sorted(actual)
[ "def", "test_report_with_string_state", "(", "self", ",", "mock_time", ")", ":", "mock_time", ".", "return_value", "=", "12345", "expected", "=", "[", "\"ha.entity.foo 1.000000 12345\"", ",", "\"ha.entity.state 1.000000 12345\"", "]", "state", "=", "mock", ".", "MagicMock", "(", "state", "=", "\"above_horizon\"", ",", "attributes", "=", "{", "\"foo\"", ":", "1.0", "}", ")", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_send_to_graphite\"", ")", "as", "mock_send", ":", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")", "actual", "=", "mock_send", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "assert", "sorted", "(", "expected", ")", "==", "sorted", "(", "actual", ")" ]
[ 118, 4 ]
[ 127, 53 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_report_with_binary_state
(self, mock_time)
Test the reporting with binary state.
Test the reporting with binary state.
def test_report_with_binary_state(self, mock_time): """Test the reporting with binary state.""" mock_time.return_value = 12345 state = ha.State("domain.entity", STATE_ON, {"foo": 1.0}) with mock.patch.object(self.gf, "_send_to_graphite") as mock_send: self.gf._report_attributes("entity", state) expected = [ "ha.entity.foo 1.000000 12345", "ha.entity.state 1.000000 12345", ] actual = mock_send.call_args_list[0][0][0].split("\n") assert sorted(expected) == sorted(actual) state.state = STATE_OFF with mock.patch.object(self.gf, "_send_to_graphite") as mock_send: self.gf._report_attributes("entity", state) expected = [ "ha.entity.foo 1.000000 12345", "ha.entity.state 0.000000 12345", ] actual = mock_send.call_args_list[0][0][0].split("\n") assert sorted(expected) == sorted(actual)
[ "def", "test_report_with_binary_state", "(", "self", ",", "mock_time", ")", ":", "mock_time", ".", "return_value", "=", "12345", "state", "=", "ha", ".", "State", "(", "\"domain.entity\"", ",", "STATE_ON", ",", "{", "\"foo\"", ":", "1.0", "}", ")", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_send_to_graphite\"", ")", "as", "mock_send", ":", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")", "expected", "=", "[", "\"ha.entity.foo 1.000000 12345\"", ",", "\"ha.entity.state 1.000000 12345\"", ",", "]", "actual", "=", "mock_send", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "assert", "sorted", "(", "expected", ")", "==", "sorted", "(", "actual", ")", "state", ".", "state", "=", "STATE_OFF", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_send_to_graphite\"", ")", "as", "mock_send", ":", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")", "expected", "=", "[", "\"ha.entity.foo 1.000000 12345\"", ",", "\"ha.entity.state 0.000000 12345\"", ",", "]", "actual", "=", "mock_send", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", ".", "split", "(", "\"\\n\"", ")", "assert", "sorted", "(", "expected", ")", "==", "sorted", "(", "actual", ")" ]
[ 130, 4 ]
[ 151, 53 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_send_to_graphite_errors
(self, mock_time)
Test the sending with errors.
Test the sending with errors.
def test_send_to_graphite_errors(self, mock_time): """Test the sending with errors.""" mock_time.return_value = 12345 state = ha.State("domain.entity", STATE_ON, {"foo": 1.0}) with mock.patch.object(self.gf, "_send_to_graphite") as mock_send: mock_send.side_effect = socket.error self.gf._report_attributes("entity", state) mock_send.side_effect = socket.gaierror self.gf._report_attributes("entity", state)
[ "def", "test_send_to_graphite_errors", "(", "self", ",", "mock_time", ")", ":", "mock_time", ".", "return_value", "=", "12345", "state", "=", "ha", ".", "State", "(", "\"domain.entity\"", ",", "STATE_ON", ",", "{", "\"foo\"", ":", "1.0", "}", ")", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_send_to_graphite\"", ")", "as", "mock_send", ":", "mock_send", ".", "side_effect", "=", "socket", ".", "error", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")", "mock_send", ".", "side_effect", "=", "socket", ".", "gaierror", "self", ".", "gf", ".", "_report_attributes", "(", "\"entity\"", ",", "state", ")" ]
[ 154, 4 ]
[ 162, 55 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_send_to_graphite
(self, mock_socket)
Test the sending of data.
Test the sending of data.
def test_send_to_graphite(self, mock_socket): """Test the sending of data.""" self.gf._send_to_graphite("foo") assert mock_socket.call_count == 1 assert mock_socket.call_args == mock.call(socket.AF_INET, socket.SOCK_STREAM) sock = mock_socket.return_value assert sock.connect.call_count == 1 assert sock.connect.call_args == mock.call(("foo", 123)) assert sock.sendall.call_count == 1 assert sock.sendall.call_args == mock.call(b"foo") assert sock.send.call_count == 1 assert sock.send.call_args == mock.call(b"\n") assert sock.close.call_count == 1 assert sock.close.call_args == mock.call()
[ "def", "test_send_to_graphite", "(", "self", ",", "mock_socket", ")", ":", "self", ".", "gf", ".", "_send_to_graphite", "(", "\"foo\"", ")", "assert", "mock_socket", ".", "call_count", "==", "1", "assert", "mock_socket", ".", "call_args", "==", "mock", ".", "call", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", "=", "mock_socket", ".", "return_value", "assert", "sock", ".", "connect", ".", "call_count", "==", "1", "assert", "sock", ".", "connect", ".", "call_args", "==", "mock", ".", "call", "(", "(", "\"foo\"", ",", "123", ")", ")", "assert", "sock", ".", "sendall", ".", "call_count", "==", "1", "assert", "sock", ".", "sendall", ".", "call_args", "==", "mock", ".", "call", "(", "b\"foo\"", ")", "assert", "sock", ".", "send", ".", "call_count", "==", "1", "assert", "sock", ".", "send", ".", "call_args", "==", "mock", ".", "call", "(", "b\"\\n\"", ")", "assert", "sock", ".", "close", ".", "call_count", "==", "1", "assert", "sock", ".", "close", ".", "call_args", "==", "mock", ".", "call", "(", ")" ]
[ 165, 4 ]
[ 178, 50 ]
python
en
['en', 'no', 'en']
True
TestGraphite.test_run_stops
(self)
Test the stops.
Test the stops.
def test_run_stops(self): """Test the stops.""" with mock.patch.object(self.gf, "_queue") as mock_queue: mock_queue.get.return_value = self.gf._quit_object assert self.gf.run() is None assert mock_queue.get.call_count == 1 assert mock_queue.get.call_args == mock.call() assert mock_queue.task_done.call_count == 1 assert mock_queue.task_done.call_args == mock.call()
[ "def", "test_run_stops", "(", "self", ")", ":", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_queue\"", ")", "as", "mock_queue", ":", "mock_queue", ".", "get", ".", "return_value", "=", "self", ".", "gf", ".", "_quit_object", "assert", "self", ".", "gf", ".", "run", "(", ")", "is", "None", "assert", "mock_queue", ".", "get", ".", "call_count", "==", "1", "assert", "mock_queue", ".", "get", ".", "call_args", "==", "mock", ".", "call", "(", ")", "assert", "mock_queue", ".", "task_done", ".", "call_count", "==", "1", "assert", "mock_queue", ".", "task_done", ".", "call_args", "==", "mock", ".", "call", "(", ")" ]
[ 180, 4 ]
[ 188, 64 ]
python
en
['en', 'en', 'en']
True
TestGraphite.test_run
(self)
Test the running.
Test the running.
def test_run(self): """Test the running.""" runs = [] event = mock.MagicMock( event_type=EVENT_STATE_CHANGED, data={"entity_id": "entity", "new_state": mock.MagicMock()}, ) def fake_get(): if len(runs) >= 2: return self.gf._quit_object if runs: runs.append(1) return mock.MagicMock( event_type="somethingelse", data={"new_event": None} ) runs.append(1) return event with mock.patch.object(self.gf, "_queue") as mock_queue: with mock.patch.object(self.gf, "_report_attributes") as mock_r: mock_queue.get.side_effect = fake_get self.gf.run() # Twice for two events, once for the stop assert mock_queue.task_done.call_count == 3 assert mock_r.call_count == 1 assert mock_r.call_args == mock.call("entity", event.data["new_state"])
[ "def", "test_run", "(", "self", ")", ":", "runs", "=", "[", "]", "event", "=", "mock", ".", "MagicMock", "(", "event_type", "=", "EVENT_STATE_CHANGED", ",", "data", "=", "{", "\"entity_id\"", ":", "\"entity\"", ",", "\"new_state\"", ":", "mock", ".", "MagicMock", "(", ")", "}", ",", ")", "def", "fake_get", "(", ")", ":", "if", "len", "(", "runs", ")", ">=", "2", ":", "return", "self", ".", "gf", ".", "_quit_object", "if", "runs", ":", "runs", ".", "append", "(", "1", ")", "return", "mock", ".", "MagicMock", "(", "event_type", "=", "\"somethingelse\"", ",", "data", "=", "{", "\"new_event\"", ":", "None", "}", ")", "runs", ".", "append", "(", "1", ")", "return", "event", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_queue\"", ")", "as", "mock_queue", ":", "with", "mock", ".", "patch", ".", "object", "(", "self", ".", "gf", ",", "\"_report_attributes\"", ")", "as", "mock_r", ":", "mock_queue", ".", "get", ".", "side_effect", "=", "fake_get", "self", ".", "gf", ".", "run", "(", ")", "# Twice for two events, once for the stop", "assert", "mock_queue", ".", "task_done", ".", "call_count", "==", "3", "assert", "mock_r", ".", "call_count", "==", "1", "assert", "mock_r", ".", "call_args", "==", "mock", ".", "call", "(", "\"entity\"", ",", "event", ".", "data", "[", "\"new_state\"", "]", ")" ]
[ 190, 4 ]
[ 216, 87 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass)
Set up the Scene config API.
Set up the Scene config API.
async def async_setup(hass): """Set up the Scene config API.""" async def hook(action, config_key): """post_write_hook for Config View that reloads scenes.""" await hass.services.async_call(DOMAIN, SERVICE_RELOAD) if action != ACTION_DELETE: return ent_reg = await entity_registry.async_get_registry(hass) entity_id = ent_reg.async_get_entity_id(DOMAIN, HA_DOMAIN, config_key) if entity_id is None: return ent_reg.async_remove(entity_id) hass.http.register_view( EditSceneConfigView( DOMAIN, "config", SCENE_CONFIG_PATH, cv.string, PLATFORM_SCHEMA, post_write_hook=hook, ) ) return True
[ "async", "def", "async_setup", "(", "hass", ")", ":", "async", "def", "hook", "(", "action", ",", "config_key", ")", ":", "\"\"\"post_write_hook for Config View that reloads scenes.\"\"\"", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ")", "if", "action", "!=", "ACTION_DELETE", ":", "return", "ent_reg", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "entity_id", "=", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "HA_DOMAIN", ",", "config_key", ")", "if", "entity_id", "is", "None", ":", "return", "ent_reg", ".", "async_remove", "(", "entity_id", ")", "hass", ".", "http", ".", "register_view", "(", "EditSceneConfigView", "(", "DOMAIN", ",", "\"config\"", ",", "SCENE_CONFIG_PATH", ",", "cv", ".", "string", ",", "PLATFORM_SCHEMA", ",", "post_write_hook", "=", "hook", ",", ")", ")", "return", "True" ]
[ 13, 0 ]
[ 42, 15 ]
python
en
['en', 'sm', 'en']
True
async_setup_entry
(hass, entry, async_add_entities)
Set up Xbox media_player from a config entry.
Set up Xbox media_player from a config entry.
async def async_setup_entry(hass, entry, async_add_entities): """Set up Xbox media_player from a config entry.""" client: XboxLiveClient = hass.data[DOMAIN][entry.entry_id]["client"] consoles: SmartglassConsoleList = hass.data[DOMAIN][entry.entry_id]["consoles"] coordinator: XboxUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ "coordinator" ] async_add_entities( [XboxMediaPlayer(client, console, coordinator) for console in consoles.result] )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "client", ":", "XboxLiveClient", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "\"client\"", "]", "consoles", ":", "SmartglassConsoleList", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "\"consoles\"", "]", "coordinator", ":", "XboxUpdateCoordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "\"coordinator\"", "]", "async_add_entities", "(", "[", "XboxMediaPlayer", "(", "client", ",", "console", ",", "coordinator", ")", "for", "console", "in", "consoles", ".", "result", "]", ")" ]
[ 60, 0 ]
[ 70, 5 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.__init__
( self, client: XboxLiveClient, console: SmartglassConsole, coordinator: XboxUpdateCoordinator, )
Initialize the Xbox Media Player.
Initialize the Xbox Media Player.
def __init__( self, client: XboxLiveClient, console: SmartglassConsole, coordinator: XboxUpdateCoordinator, ) -> None: """Initialize the Xbox Media Player.""" super().__init__(coordinator) self.client: XboxLiveClient = client self._console: SmartglassConsole = console
[ "def", "__init__", "(", "self", ",", "client", ":", "XboxLiveClient", ",", "console", ":", "SmartglassConsole", ",", "coordinator", ":", "XboxUpdateCoordinator", ",", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "client", ":", "XboxLiveClient", "=", "client", "self", ".", "_console", ":", "SmartglassConsole", "=", "console" ]
[ 76, 4 ]
[ 85, 50 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.name
(self)
Return the device name.
Return the device name.
def name(self): """Return the device name.""" return self._console.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_console", ".", "name" ]
[ 88, 4 ]
[ 90, 33 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.unique_id
(self)
Console device ID.
Console device ID.
def unique_id(self): """Console device ID.""" return self._console.id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_console", ".", "id" ]
[ 93, 4 ]
[ 95, 31 ]
python
en
['fr', 'en', 'en']
True
XboxMediaPlayer.data
(self)
Return coordinator data for this console.
Return coordinator data for this console.
def data(self) -> ConsoleData: """Return coordinator data for this console.""" return self.coordinator.data.consoles[self._console.id]
[ "def", "data", "(", "self", ")", "->", "ConsoleData", ":", "return", "self", ".", "coordinator", ".", "data", ".", "consoles", "[", "self", ".", "_console", ".", "id", "]" ]
[ 98, 4 ]
[ 100, 63 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.state
(self)
State of the player.
State of the player.
def state(self): """State of the player.""" status = self.data.status if status.playback_state in XBOX_STATE_MAP: return XBOX_STATE_MAP[status.playback_state] return XBOX_STATE_MAP[status.power_state]
[ "def", "state", "(", "self", ")", ":", "status", "=", "self", ".", "data", ".", "status", "if", "status", ".", "playback_state", "in", "XBOX_STATE_MAP", ":", "return", "XBOX_STATE_MAP", "[", "status", ".", "playback_state", "]", "return", "XBOX_STATE_MAP", "[", "status", ".", "power_state", "]" ]
[ 103, 4 ]
[ 108, 49 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.supported_features
(self)
Flag media player features that are supported.
Flag media player features that are supported.
def supported_features(self): """Flag media player features that are supported.""" if self.state not in [STATE_PLAYING, STATE_PAUSED]: return SUPPORT_XBOX & ~SUPPORT_NEXT_TRACK & ~SUPPORT_PREVIOUS_TRACK return SUPPORT_XBOX
[ "def", "supported_features", "(", "self", ")", ":", "if", "self", ".", "state", "not", "in", "[", "STATE_PLAYING", ",", "STATE_PAUSED", "]", ":", "return", "SUPPORT_XBOX", "&", "~", "SUPPORT_NEXT_TRACK", "&", "~", "SUPPORT_PREVIOUS_TRACK", "return", "SUPPORT_XBOX" ]
[ 111, 4 ]
[ 115, 27 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.media_content_type
(self)
Media content type.
Media content type.
def media_content_type(self): """Media content type.""" app_details = self.data.app_details if app_details and app_details.product_family == "Games": return MEDIA_TYPE_GAME return MEDIA_TYPE_APP
[ "def", "media_content_type", "(", "self", ")", ":", "app_details", "=", "self", ".", "data", ".", "app_details", "if", "app_details", "and", "app_details", ".", "product_family", "==", "\"Games\"", ":", "return", "MEDIA_TYPE_GAME", "return", "MEDIA_TYPE_APP" ]
[ 118, 4 ]
[ 123, 29 ]
python
en
['it', 'la', 'en']
False
XboxMediaPlayer.media_title
(self)
Title of current playing media.
Title of current playing media.
def media_title(self): """Title of current playing media.""" app_details = self.data.app_details if not app_details: return None return ( app_details.localized_properties[0].product_title or app_details.localized_properties[0].short_title )
[ "def", "media_title", "(", "self", ")", ":", "app_details", "=", "self", ".", "data", ".", "app_details", "if", "not", "app_details", ":", "return", "None", "return", "(", "app_details", ".", "localized_properties", "[", "0", "]", ".", "product_title", "or", "app_details", ".", "localized_properties", "[", "0", "]", ".", "short_title", ")" ]
[ 126, 4 ]
[ 134, 9 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.media_image_url
(self)
Image url of current playing media.
Image url of current playing media.
def media_image_url(self): """Image url of current playing media.""" app_details = self.data.app_details if not app_details: return None image = _find_media_image(app_details.localized_properties[0].images) if not image: return None url = image.uri if url[0] == "/": url = f"http:{url}" return url
[ "def", "media_image_url", "(", "self", ")", ":", "app_details", "=", "self", ".", "data", ".", "app_details", "if", "not", "app_details", ":", "return", "None", "image", "=", "_find_media_image", "(", "app_details", ".", "localized_properties", "[", "0", "]", ".", "images", ")", "if", "not", "image", ":", "return", "None", "url", "=", "image", ".", "uri", "if", "url", "[", "0", "]", "==", "\"/\"", ":", "url", "=", "f\"http:{url}\"", "return", "url" ]
[ 137, 4 ]
[ 150, 18 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.media_image_remotely_accessible
(self)
If the image url is remotely accessible.
If the image url is remotely accessible.
def media_image_remotely_accessible(self) -> bool: """If the image url is remotely accessible.""" return True
[ "def", "media_image_remotely_accessible", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 153, 4 ]
[ 155, 19 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_turn_on
(self)
Turn the media player on.
Turn the media player on.
async def async_turn_on(self): """Turn the media player on.""" await self.client.smartglass.wake_up(self._console.id)
[ "async", "def", "async_turn_on", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "wake_up", "(", "self", ".", "_console", ".", "id", ")" ]
[ 157, 4 ]
[ 159, 62 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_turn_off
(self)
Turn the media player off.
Turn the media player off.
async def async_turn_off(self): """Turn the media player off.""" await self.client.smartglass.turn_off(self._console.id)
[ "async", "def", "async_turn_off", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "turn_off", "(", "self", ".", "_console", ".", "id", ")" ]
[ 161, 4 ]
[ 163, 63 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_mute_volume
(self, mute)
Mute the volume.
Mute the volume.
async def async_mute_volume(self, mute): """Mute the volume.""" if mute: await self.client.smartglass.mute(self._console.id) else: await self.client.smartglass.unmute(self._console.id)
[ "async", "def", "async_mute_volume", "(", "self", ",", "mute", ")", ":", "if", "mute", ":", "await", "self", ".", "client", ".", "smartglass", ".", "mute", "(", "self", ".", "_console", ".", "id", ")", "else", ":", "await", "self", ".", "client", ".", "smartglass", ".", "unmute", "(", "self", ".", "_console", ".", "id", ")" ]
[ 165, 4 ]
[ 170, 65 ]
python
en
['en', 'sn', 'en']
True
XboxMediaPlayer.async_volume_up
(self)
Turn volume up for media player.
Turn volume up for media player.
async def async_volume_up(self): """Turn volume up for media player.""" await self.client.smartglass.volume(self._console.id, VolumeDirection.Up)
[ "async", "def", "async_volume_up", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "volume", "(", "self", ".", "_console", ".", "id", ",", "VolumeDirection", ".", "Up", ")" ]
[ 172, 4 ]
[ 174, 81 ]
python
en
['en', 'no', 'en']
True
XboxMediaPlayer.async_volume_down
(self)
Turn volume down for media player.
Turn volume down for media player.
async def async_volume_down(self): """Turn volume down for media player.""" await self.client.smartglass.volume(self._console.id, VolumeDirection.Down)
[ "async", "def", "async_volume_down", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "volume", "(", "self", ".", "_console", ".", "id", ",", "VolumeDirection", ".", "Down", ")" ]
[ 176, 4 ]
[ 178, 83 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_media_play
(self)
Send play command.
Send play command.
async def async_media_play(self): """Send play command.""" await self.client.smartglass.play(self._console.id)
[ "async", "def", "async_media_play", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "play", "(", "self", ".", "_console", ".", "id", ")" ]
[ 180, 4 ]
[ 182, 59 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_media_pause
(self)
Send pause command.
Send pause command.
async def async_media_pause(self): """Send pause command.""" await self.client.smartglass.pause(self._console.id)
[ "async", "def", "async_media_pause", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "pause", "(", "self", ".", "_console", ".", "id", ")" ]
[ 184, 4 ]
[ 186, 60 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.async_media_previous_track
(self)
Send previous track command.
Send previous track command.
async def async_media_previous_track(self): """Send previous track command.""" await self.client.smartglass.previous(self._console.id)
[ "async", "def", "async_media_previous_track", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "previous", "(", "self", ".", "_console", ".", "id", ")" ]
[ 188, 4 ]
[ 190, 63 ]
python
en
['en', 'it', 'en']
True
XboxMediaPlayer.async_media_next_track
(self)
Send next track command.
Send next track command.
async def async_media_next_track(self): """Send next track command.""" await self.client.smartglass.next(self._console.id)
[ "async", "def", "async_media_next_track", "(", "self", ")", ":", "await", "self", ".", "client", ".", "smartglass", ".", "next", "(", "self", ".", "_console", ".", "id", ")" ]
[ 192, 4 ]
[ 194, 59 ]
python
en
['en', 'pt', 'en']
True
XboxMediaPlayer.async_browse_media
(self, media_content_type=None, media_content_id=None)
Implement the websocket media browsing helper.
Implement the websocket media browsing helper.
async def async_browse_media(self, media_content_type=None, media_content_id=None): """Implement the websocket media browsing helper.""" return await build_item_response( self.client, self._console.id, self.data.status.is_tv_configured, media_content_type, media_content_id, )
[ "async", "def", "async_browse_media", "(", "self", ",", "media_content_type", "=", "None", ",", "media_content_id", "=", "None", ")", ":", "return", "await", "build_item_response", "(", "self", ".", "client", ",", "self", ".", "_console", ".", "id", ",", "self", ".", "data", ".", "status", ".", "is_tv_configured", ",", "media_content_type", ",", "media_content_id", ",", ")" ]
[ 196, 4 ]
[ 204, 9 ]
python
en
['en', 'af', 'en']
True
XboxMediaPlayer.async_play_media
(self, media_type, media_id, **kwargs)
Launch an app on the Xbox.
Launch an app on the Xbox.
async def async_play_media(self, media_type, media_id, **kwargs): """Launch an app on the Xbox.""" if media_id == "Home": await self.client.smartglass.go_home(self._console.id) elif media_id == "TV": await self.client.smartglass.show_tv_guide(self._console.id) else: await self.client.smartglass.launch_app(self._console.id, media_id)
[ "async", "def", "async_play_media", "(", "self", ",", "media_type", ",", "media_id", ",", "*", "*", "kwargs", ")", ":", "if", "media_id", "==", "\"Home\"", ":", "await", "self", ".", "client", ".", "smartglass", ".", "go_home", "(", "self", ".", "_console", ".", "id", ")", "elif", "media_id", "==", "\"TV\"", ":", "await", "self", ".", "client", ".", "smartglass", ".", "show_tv_guide", "(", "self", ".", "_console", ".", "id", ")", "else", ":", "await", "self", ".", "client", ".", "smartglass", ".", "launch_app", "(", "self", ".", "_console", ".", "id", ",", "media_id", ")" ]
[ 206, 4 ]
[ 213, 79 ]
python
en
['en', 'en', 'en']
True
XboxMediaPlayer.device_info
(self)
Return a device description for device registry.
Return a device description for device registry.
def device_info(self): """Return a device description for device registry.""" # Turns "XboxOneX" into "Xbox One X" for display matches = re.finditer( ".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", self._console.console_type, ) model = " ".join([m.group(0) for m in matches]) return { "identifiers": {(DOMAIN, self._console.id)}, "name": self._console.name, "manufacturer": "Microsoft", "model": model, }
[ "def", "device_info", "(", "self", ")", ":", "# Turns \"XboxOneX\" into \"Xbox One X\" for display", "matches", "=", "re", ".", "finditer", "(", "\".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)\"", ",", "self", ".", "_console", ".", "console_type", ",", ")", "model", "=", "\" \"", ".", "join", "(", "[", "m", ".", "group", "(", "0", ")", "for", "m", "in", "matches", "]", ")", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_console", ".", "id", ")", "}", ",", "\"name\"", ":", "self", ".", "_console", ".", "name", ",", "\"manufacturer\"", ":", "\"Microsoft\"", ",", "\"model\"", ":", "model", ",", "}" ]
[ 216, 4 ]
[ 230, 9 ]
python
en
['ro', 'fr', 'en']
False
_rand_init
(x_bounds, x_types, selection_num_starting_points)
Random sample some init seed within bounds.
Random sample some init seed within bounds.
def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i in range(0, selection_num_starting_points)]
[ "def", "_rand_init", "(", "x_bounds", ",", "x_types", ",", "selection_num_starting_points", ")", ":", "return", "[", "lib_data", ".", "rand", "(", "x_bounds", ",", "x_types", ")", "for", "i", "in", "range", "(", "0", ",", "selection_num_starting_points", ")", "]" ]
[ 630, 0 ]
[ 635, 55 ]
python
en
['en', 'error', 'th']
False
get_median
(temp_list)
Return median
Return median
def get_median(temp_list): """ Return median """ num = len(temp_list) temp_list.sort() print(temp_list) if num % 2 == 0: median = (temp_list[int(num / 2)] + temp_list[int(num / 2) - 1]) / 2 else: median = temp_list[int(num / 2)] return median
[ "def", "get_median", "(", "temp_list", ")", ":", "num", "=", "len", "(", "temp_list", ")", "temp_list", ".", "sort", "(", ")", "print", "(", "temp_list", ")", "if", "num", "%", "2", "==", "0", ":", "median", "=", "(", "temp_list", "[", "int", "(", "num", "/", "2", ")", "]", "+", "temp_list", "[", "int", "(", "num", "/", "2", ")", "-", "1", "]", ")", "/", "2", "else", ":", "median", "=", "temp_list", "[", "int", "(", "num", "/", "2", ")", "]", "return", "median" ]
[ 638, 0 ]
[ 649, 17 ]
python
en
['en', 'error', 'th']
False
MetisTuner.__init__
( self, optimize_mode="maximize", no_resampling=True, no_candidates=False, selection_num_starting_points=600, cold_start_num=10, exploration_probability=0.9)
Parameters ---------- optimize_mode : str optimize_mode is a string that including two mode "maximize" and "minimize" no_resampling : bool True or False. Should Metis consider re-sampling as part of the search strategy? If you are confident that the training dataset is noise-free, then you do not need re-sampling. no_candidates : bool True or False. Should Metis suggest parameters for the next benchmark? If you do not plan to do more benchmarks, Metis can skip this step. selection_num_starting_points : int How many times Metis should try to find the global optimal in the search space? The higher the number, the longer it takes to output the solution. cold_start_num : int Metis need some trial result to get cold start. when the number of trial result is less than cold_start_num, Metis will randomly sample hyper-parameter for trial. exploration_probability : float The probability of Metis to select parameter from exploration instead of exploitation. x_bounds : list The constration of parameters. x_types : list The type of parameters.
Parameters ---------- optimize_mode : str optimize_mode is a string that including two mode "maximize" and "minimize"
def __init__( self, optimize_mode="maximize", no_resampling=True, no_candidates=False, selection_num_starting_points=600, cold_start_num=10, exploration_probability=0.9): """ Parameters ---------- optimize_mode : str optimize_mode is a string that including two mode "maximize" and "minimize" no_resampling : bool True or False. Should Metis consider re-sampling as part of the search strategy? If you are confident that the training dataset is noise-free, then you do not need re-sampling. no_candidates : bool True or False. Should Metis suggest parameters for the next benchmark? If you do not plan to do more benchmarks, Metis can skip this step. selection_num_starting_points : int How many times Metis should try to find the global optimal in the search space? The higher the number, the longer it takes to output the solution. cold_start_num : int Metis need some trial result to get cold start. when the number of trial result is less than cold_start_num, Metis will randomly sample hyper-parameter for trial. exploration_probability : float The probability of Metis to select parameter from exploration instead of exploitation. x_bounds : list The constration of parameters. x_types : list The type of parameters. """ self.samples_x = [] self.samples_y = [] self.samples_y_aggregation = [] self.total_data = [] self.space = None self.no_resampling = no_resampling self.no_candidates = no_candidates self.optimize_mode = OptimizeMode(optimize_mode) self.key_order = [] self.cold_start_num = cold_start_num self.selection_num_starting_points = selection_num_starting_points self.exploration_probability = exploration_probability self.minimize_constraints_fun = None self.minimize_starting_points = None self.supplement_data_num = 0 self.x_bounds = [] self.x_types = []
[ "def", "__init__", "(", "self", ",", "optimize_mode", "=", "\"maximize\"", ",", "no_resampling", "=", "True", ",", "no_candidates", "=", "False", ",", "selection_num_starting_points", "=", "600", ",", "cold_start_num", "=", "10", ",", "exploration_probability", "=", "0.9", ")", ":", "self", ".", "samples_x", "=", "[", "]", "self", ".", "samples_y", "=", "[", "]", "self", ".", "samples_y_aggregation", "=", "[", "]", "self", ".", "total_data", "=", "[", "]", "self", ".", "space", "=", "None", "self", ".", "no_resampling", "=", "no_resampling", "self", ".", "no_candidates", "=", "no_candidates", "self", ".", "optimize_mode", "=", "OptimizeMode", "(", "optimize_mode", ")", "self", ".", "key_order", "=", "[", "]", "self", ".", "cold_start_num", "=", "cold_start_num", "self", ".", "selection_num_starting_points", "=", "selection_num_starting_points", "self", ".", "exploration_probability", "=", "exploration_probability", "self", ".", "minimize_constraints_fun", "=", "None", "self", ".", "minimize_starting_points", "=", "None", "self", ".", "supplement_data_num", "=", "0", "self", ".", "x_bounds", "=", "[", "]", "self", ".", "x_types", "=", "[", "]" ]
[ 82, 4 ]
[ 143, 25 ]
python
en
['en', 'error', 'th']
False
MetisTuner.update_search_space
(self, search_space)
Update the self.x_bounds and self.x_types by the search_space.json Parameters ---------- search_space : dict
Update the self.x_bounds and self.x_types by the search_space.json
def update_search_space(self, search_space): """ Update the self.x_bounds and self.x_types by the search_space.json Parameters ---------- search_space : dict """ self.x_bounds = [[] for i in range(len(search_space))] self.x_types = [NONE_TYPE for i in range(len(search_space))] for key in search_space: self.key_order.append(key) key_type = {} if isinstance(search_space, dict): for key in search_space: key_type = search_space[key]['_type'] key_range = search_space[key]['_value'] idx = self.key_order.index(key) if key_type == 'quniform': if key_range[2] == 1 and key_range[0].is_integer( ) and key_range[1].is_integer(): self.x_bounds[idx] = [key_range[0], key_range[1] + 1] self.x_types[idx] = 'range_int' else: low, high, q = key_range bounds = np.clip( np.arange( np.round( low / q), np.round( high / q) + 1) * q, low, high) self.x_bounds[idx] = bounds self.x_types[idx] = 'discrete_int' elif key_type == 'randint': self.x_bounds[idx] = [key_range[0], key_range[1]] self.x_types[idx] = 'range_int' elif key_type == 'uniform': self.x_bounds[idx] = [key_range[0], key_range[1]] self.x_types[idx] = 'range_continuous' elif key_type == 'choice': self.x_bounds[idx] = key_range for key_value in key_range: if not isinstance(key_value, (int, float)): raise RuntimeError( "Metis Tuner only support numerical choice.") self.x_types[idx] = 'discrete_int' else: logger.info( "Metis Tuner doesn't support this kind of variable: %s", str(key_type)) raise RuntimeError( "Metis Tuner doesn't support this kind of variable: %s" % str(key_type)) else: logger.info("The format of search space is not a dict.") raise RuntimeError("The format of search space is not a dict.") self.minimize_starting_points = _rand_init( self.x_bounds, self.x_types, self.selection_num_starting_points)
[ "def", "update_search_space", "(", "self", ",", "search_space", ")", ":", "self", ".", "x_bounds", "=", "[", "[", "]", "for", "i", "in", "range", "(", "len", "(", "search_space", ")", ")", "]", "self", ".", "x_types", "=", "[", "NONE_TYPE", "for", "i", "in", "range", "(", "len", "(", "search_space", ")", ")", "]", "for", "key", "in", "search_space", ":", "self", ".", "key_order", ".", "append", "(", "key", ")", "key_type", "=", "{", "}", "if", "isinstance", "(", "search_space", ",", "dict", ")", ":", "for", "key", "in", "search_space", ":", "key_type", "=", "search_space", "[", "key", "]", "[", "'_type'", "]", "key_range", "=", "search_space", "[", "key", "]", "[", "'_value'", "]", "idx", "=", "self", ".", "key_order", ".", "index", "(", "key", ")", "if", "key_type", "==", "'quniform'", ":", "if", "key_range", "[", "2", "]", "==", "1", "and", "key_range", "[", "0", "]", ".", "is_integer", "(", ")", "and", "key_range", "[", "1", "]", ".", "is_integer", "(", ")", ":", "self", ".", "x_bounds", "[", "idx", "]", "=", "[", "key_range", "[", "0", "]", ",", "key_range", "[", "1", "]", "+", "1", "]", "self", ".", "x_types", "[", "idx", "]", "=", "'range_int'", "else", ":", "low", ",", "high", ",", "q", "=", "key_range", "bounds", "=", "np", ".", "clip", "(", "np", ".", "arange", "(", "np", ".", "round", "(", "low", "/", "q", ")", ",", "np", ".", "round", "(", "high", "/", "q", ")", "+", "1", ")", "*", "q", ",", "low", ",", "high", ")", "self", ".", "x_bounds", "[", "idx", "]", "=", "bounds", "self", ".", "x_types", "[", "idx", "]", "=", "'discrete_int'", "elif", "key_type", "==", "'randint'", ":", "self", ".", "x_bounds", "[", "idx", "]", "=", "[", "key_range", "[", "0", "]", ",", "key_range", "[", "1", "]", "]", "self", ".", "x_types", "[", "idx", "]", "=", "'range_int'", "elif", "key_type", "==", "'uniform'", ":", "self", ".", "x_bounds", "[", "idx", "]", "=", "[", "key_range", "[", "0", "]", ",", "key_range", "[", "1", "]", "]", "self", ".", "x_types", "[", "idx", "]", "=", "'range_continuous'", "elif", "key_type", "==", "'choice'", ":", "self", ".", "x_bounds", "[", "idx", "]", "=", "key_range", "for", "key_value", "in", "key_range", ":", "if", "not", "isinstance", "(", "key_value", ",", "(", "int", ",", "float", ")", ")", ":", "raise", "RuntimeError", "(", "\"Metis Tuner only support numerical choice.\"", ")", "self", ".", "x_types", "[", "idx", "]", "=", "'discrete_int'", "else", ":", "logger", ".", "info", "(", "\"Metis Tuner doesn't support this kind of variable: %s\"", ",", "str", "(", "key_type", ")", ")", "raise", "RuntimeError", "(", "\"Metis Tuner doesn't support this kind of variable: %s\"", "%", "str", "(", "key_type", ")", ")", "else", ":", "logger", ".", "info", "(", "\"The format of search space is not a dict.\"", ")", "raise", "RuntimeError", "(", "\"The format of search space is not a dict.\"", ")", "self", ".", "minimize_starting_points", "=", "_rand_init", "(", "self", ".", "x_bounds", ",", "self", ".", "x_types", ",", "self", ".", "selection_num_starting_points", ")" ]
[ 146, 4 ]
[ 210, 76 ]
python
en
['en', 'error', 'th']
False
MetisTuner._pack_output
(self, init_parameter)
Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict
Pack the output
def _pack_output(self, init_parameter): """ Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict """ output = {} for i, param in enumerate(init_parameter): output[self.key_order[i]] = param return output
[ "def", "_pack_output", "(", "self", ",", "init_parameter", ")", ":", "output", "=", "{", "}", "for", "i", ",", "param", "in", "enumerate", "(", "init_parameter", ")", ":", "output", "[", "self", ".", "key_order", "[", "i", "]", "]", "=", "param", "return", "output" ]
[ 213, 4 ]
[ 229, 21 ]
python
en
['en', 'error', 'th']
False
MetisTuner.generate_parameters
(self, parameter_id, **kwargs)
Generate next parameter for trial If the number of trial result is lower than cold start number, metis will first random generate some parameters. Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model. Parameters ---------- parameter_id : int Returns ------- result : dict
Generate next parameter for trial
def generate_parameters(self, parameter_id, **kwargs): """ Generate next parameter for trial If the number of trial result is lower than cold start number, metis will first random generate some parameters. Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model. Parameters ---------- parameter_id : int Returns ------- result : dict """ if len(self.samples_x) < self.cold_start_num: init_parameter = _rand_init(self.x_bounds, self.x_types, 1)[0] results = self._pack_output(init_parameter) else: self.minimize_starting_points = _rand_init( self.x_bounds, self.x_types, self.selection_num_starting_points) results = self._selection( self.samples_x, self.samples_y_aggregation, self.samples_y, self.x_bounds, self.x_types, threshold_samplessize_resampling=( None if self.no_resampling is True else 50), no_candidates=self.no_candidates, minimize_starting_points=self.minimize_starting_points, minimize_constraints_fun=self.minimize_constraints_fun) logger.info("Generate paramageters: \n%s", str(results)) return results
[ "def", "generate_parameters", "(", "self", ",", "parameter_id", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "self", ".", "samples_x", ")", "<", "self", ".", "cold_start_num", ":", "init_parameter", "=", "_rand_init", "(", "self", ".", "x_bounds", ",", "self", ".", "x_types", ",", "1", ")", "[", "0", "]", "results", "=", "self", ".", "_pack_output", "(", "init_parameter", ")", "else", ":", "self", ".", "minimize_starting_points", "=", "_rand_init", "(", "self", ".", "x_bounds", ",", "self", ".", "x_types", ",", "self", ".", "selection_num_starting_points", ")", "results", "=", "self", ".", "_selection", "(", "self", ".", "samples_x", ",", "self", ".", "samples_y_aggregation", ",", "self", ".", "samples_y", ",", "self", ".", "x_bounds", ",", "self", ".", "x_types", ",", "threshold_samplessize_resampling", "=", "(", "None", "if", "self", ".", "no_resampling", "is", "True", "else", "50", ")", ",", "no_candidates", "=", "self", ".", "no_candidates", ",", "minimize_starting_points", "=", "self", ".", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "self", ".", "minimize_constraints_fun", ")", "logger", ".", "info", "(", "\"Generate paramageters: \\n%s\"", ",", "str", "(", "results", ")", ")", "return", "results" ]
[ 232, 4 ]
[ 268, 22 ]
python
en
['en', 'error', 'th']
False
MetisTuner.receive_trial_result
(self, parameter_id, parameters, value, **kwargs)
Tuner receive result from trial. Parameters ---------- parameter_id : int The id of parameters, generated by nni manager. parameters : dict A group of parameters that trial has tried. value : dict/float if value is dict, it should have "default" key.
Tuner receive result from trial.
def receive_trial_result(self, parameter_id, parameters, value, **kwargs): """ Tuner receive result from trial. Parameters ---------- parameter_id : int The id of parameters, generated by nni manager. parameters : dict A group of parameters that trial has tried. value : dict/float if value is dict, it should have "default" key. """ value = extract_scalar_reward(value) if self.optimize_mode == OptimizeMode.Maximize: value = -value logger.info("Received trial result.") logger.info("value is : %s", str(value)) logger.info("parameter is : %s", str(parameters)) # parse parameter to sample_x sample_x = [0 for i in range(len(self.key_order))] for key in parameters: idx = self.key_order.index(key) sample_x[idx] = parameters[key] # parse value to sample_y temp_y = [] if sample_x in self.samples_x: idx = self.samples_x.index(sample_x) temp_y = self.samples_y[idx] temp_y.append(value) self.samples_y[idx] = temp_y # calculate y aggregation median = get_median(temp_y) self.samples_y_aggregation[idx] = [median] else: self.samples_x.append(sample_x) self.samples_y.append([value]) # calculate y aggregation self.samples_y_aggregation.append([value])
[ "def", "receive_trial_result", "(", "self", ",", "parameter_id", ",", "parameters", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "extract_scalar_reward", "(", "value", ")", "if", "self", ".", "optimize_mode", "==", "OptimizeMode", ".", "Maximize", ":", "value", "=", "-", "value", "logger", ".", "info", "(", "\"Received trial result.\"", ")", "logger", ".", "info", "(", "\"value is : %s\"", ",", "str", "(", "value", ")", ")", "logger", ".", "info", "(", "\"parameter is : %s\"", ",", "str", "(", "parameters", ")", ")", "# parse parameter to sample_x", "sample_x", "=", "[", "0", "for", "i", "in", "range", "(", "len", "(", "self", ".", "key_order", ")", ")", "]", "for", "key", "in", "parameters", ":", "idx", "=", "self", ".", "key_order", ".", "index", "(", "key", ")", "sample_x", "[", "idx", "]", "=", "parameters", "[", "key", "]", "# parse value to sample_y", "temp_y", "=", "[", "]", "if", "sample_x", "in", "self", ".", "samples_x", ":", "idx", "=", "self", ".", "samples_x", ".", "index", "(", "sample_x", ")", "temp_y", "=", "self", ".", "samples_y", "[", "idx", "]", "temp_y", ".", "append", "(", "value", ")", "self", ".", "samples_y", "[", "idx", "]", "=", "temp_y", "# calculate y aggregation", "median", "=", "get_median", "(", "temp_y", ")", "self", ".", "samples_y_aggregation", "[", "idx", "]", "=", "[", "median", "]", "else", ":", "self", ".", "samples_x", ".", "append", "(", "sample_x", ")", "self", ".", "samples_y", ".", "append", "(", "[", "value", "]", ")", "# calculate y aggregation", "self", ".", "samples_y_aggregation", ".", "append", "(", "[", "value", "]", ")" ]
[ 271, 4 ]
[ 314, 54 ]
python
en
['en', 'error', 'th']
False
MetisTuner.import_data
(self, data)
Import additional data for tuning Parameters ---------- data : a list of dict each of which has at least two keys: 'parameter' and 'value'.
Import additional data for tuning
def import_data(self, data): """ Import additional data for tuning Parameters ---------- data : a list of dict each of which has at least two keys: 'parameter' and 'value'. """ _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s", _completed_num, len(data)) _completed_num += 1 assert "parameter" in trial_info _params = trial_info["parameter"] assert "value" in trial_info _value = trial_info['value'] if not _value: logger.info("Useless trial data, value is %s, skip this trial data.", _value) continue self.supplement_data_num += 1 _parameter_id = '_'.join( ["ImportData", str(self.supplement_data_num)]) self.total_data.append(_params) self.receive_trial_result( parameter_id=_parameter_id, parameters=_params, value=_value) logger.info("Successfully import data to metis tuner.")
[ "def", "import_data", "(", "self", ",", "data", ")", ":", "_completed_num", "=", "0", "for", "trial_info", "in", "data", ":", "logger", ".", "info", "(", "\"Importing data, current processing progress %s / %s\"", ",", "_completed_num", ",", "len", "(", "data", ")", ")", "_completed_num", "+=", "1", "assert", "\"parameter\"", "in", "trial_info", "_params", "=", "trial_info", "[", "\"parameter\"", "]", "assert", "\"value\"", "in", "trial_info", "_value", "=", "trial_info", "[", "'value'", "]", "if", "not", "_value", ":", "logger", ".", "info", "(", "\"Useless trial data, value is %s, skip this trial data.\"", ",", "_value", ")", "continue", "self", ".", "supplement_data_num", "+=", "1", "_parameter_id", "=", "'_'", ".", "join", "(", "[", "\"ImportData\"", ",", "str", "(", "self", ".", "supplement_data_num", ")", "]", ")", "self", ".", "total_data", ".", "append", "(", "_params", ")", "self", ".", "receive_trial_result", "(", "parameter_id", "=", "_parameter_id", ",", "parameters", "=", "_params", ",", "value", "=", "_value", ")", "logger", ".", "info", "(", "\"Successfully import data to metis tuner.\"", ")" ]
[ 523, 4 ]
[ 551, 63 ]
python
en
['en', 'error', 'th']
False
TestDarkSky.setUp
(self)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.hass.config.units = METRIC_SYSTEM self.lat = self.hass.config.latitude = 37.8267 self.lon = self.hass.config.longitude = -122.423 self.addCleanup(self.tear_down_cleanup)
[ "def", "setUp", "(", "self", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "hass", ".", "config", ".", "units", "=", "METRIC_SYSTEM", "self", ".", "lat", "=", "self", ".", "hass", ".", "config", ".", "latitude", "=", "37.8267", "self", ".", "lon", "=", "self", ".", "hass", ".", "config", ".", "longitude", "=", "-", "122.423", "self", ".", "addCleanup", "(", "self", ".", "tear_down_cleanup", ")" ]
[ 19, 4 ]
[ 25, 47 ]
python
en
['en', 'en', 'en']
True
TestDarkSky.tear_down_cleanup
(self)
Stop down everything that was started.
Stop down everything that was started.
def tear_down_cleanup(self): """Stop down everything that was started.""" self.hass.stop()
[ "def", "tear_down_cleanup", "(", "self", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 27, 4 ]
[ 29, 24 ]
python
en
['en', 'en', 'en']
True
TestDarkSky.test_setup
(self, mock_req, mock_get_forecast)
Test for successfully setting up the forecast.io platform.
Test for successfully setting up the forecast.io platform.
def test_setup(self, mock_req, mock_get_forecast): """Test for successfully setting up the forecast.io platform.""" uri = ( r"https://api.(darksky.net|forecast.io)\/forecast\/(\w+)\/" r"(-?\d+\.?\d*),(-?\d+\.?\d*)" ) mock_req.get(re.compile(uri), text=load_fixture("darksky.json")) assert setup_component( self.hass, weather.DOMAIN, {"weather": {"name": "test", "platform": "darksky", "api_key": "foo"}}, ) self.hass.block_till_done() assert mock_get_forecast.called assert mock_get_forecast.call_count == 1 state = self.hass.states.get("weather.test") assert state.state == "sunny"
[ "def", "test_setup", "(", "self", ",", "mock_req", ",", "mock_get_forecast", ")", ":", "uri", "=", "(", "r\"https://api.(darksky.net|forecast.io)\\/forecast\\/(\\w+)\\/\"", "r\"(-?\\d+\\.?\\d*),(-?\\d+\\.?\\d*)\"", ")", "mock_req", ".", "get", "(", "re", ".", "compile", "(", "uri", ")", ",", "text", "=", "load_fixture", "(", "\"darksky.json\"", ")", ")", "assert", "setup_component", "(", "self", ".", "hass", ",", "weather", ".", "DOMAIN", ",", "{", "\"weather\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"darksky\"", ",", "\"api_key\"", ":", "\"foo\"", "}", "}", ",", ")", "self", ".", "hass", ".", "block_till_done", "(", ")", "assert", "mock_get_forecast", ".", "called", "assert", "mock_get_forecast", ".", "call_count", "==", "1", "state", "=", "self", ".", "hass", ".", "states", ".", "get", "(", "\"weather.test\"", ")", "assert", "state", ".", "state", "==", "\"sunny\"" ]
[ 33, 4 ]
[ 52, 37 ]
python
en
['en', 'en', 'en']
True
TestDarkSky.test_failed_setup
(self, mock_load_forecast)
Test to ensure that a network error does not break component state.
Test to ensure that a network error does not break component state.
def test_failed_setup(self, mock_load_forecast): """Test to ensure that a network error does not break component state.""" assert setup_component( self.hass, weather.DOMAIN, {"weather": {"name": "test", "platform": "darksky", "api_key": "foo"}}, ) self.hass.block_till_done() state = self.hass.states.get("weather.test") assert state.state == "unavailable"
[ "def", "test_failed_setup", "(", "self", ",", "mock_load_forecast", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "weather", ".", "DOMAIN", ",", "{", "\"weather\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"darksky\"", ",", "\"api_key\"", ":", "\"foo\"", "}", "}", ",", ")", "self", ".", "hass", ".", "block_till_done", "(", ")", "state", "=", "self", ".", "hass", ".", "states", ".", "get", "(", "\"weather.test\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"" ]
[ 55, 4 ]
[ 66, 43 ]
python
en
['en', 'en', 'en']
True
init_integration
(hass)
Set up the Brother integration in Home Assistant.
Set up the Brother integration in Home Assistant.
async def init_integration(hass) -> MockConfigEntry: """Set up the Brother integration in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, title="HL-L2340DW 0123456789", unique_id="0123456789", data={CONF_HOST: "localhost", CONF_TYPE: "laser"}, ) with patch( "brother.Brother._get_data", return_value=json.loads(load_fixture("brother_printer_data.json")), ): entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry
[ "async", "def", "init_integration", "(", "hass", ")", "->", "MockConfigEntry", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "title", "=", "\"HL-L2340DW 0123456789\"", ",", "unique_id", "=", "\"0123456789\"", ",", "data", "=", "{", "CONF_HOST", ":", "\"localhost\"", ",", "CONF_TYPE", ":", "\"laser\"", "}", ",", ")", "with", "patch", "(", "\"brother.Brother._get_data\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"brother_printer_data.json\"", ")", ")", ",", ")", ":", "entry", ".", "add_to_hass", "(", "hass", ")", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "entry" ]
[ 10, 0 ]
[ 26, 16 ]
python
en
['en', 'en', 'en']
True
BraavaJet.__init__
(self, roomba, blid)
Initialize the Roomba handler.
Initialize the Roomba handler.
def __init__(self, roomba, blid): """Initialize the Roomba handler.""" super().__init__(roomba, blid) # Initialize fan speed list speed_list = [] for behavior in BRAAVA_MOP_BEHAVIORS: for spray in BRAAVA_SPRAY_AMOUNT: speed_list.append(f"{behavior}-{spray}") self._speed_list = speed_list
[ "def", "__init__", "(", "self", ",", "roomba", ",", "blid", ")", ":", "super", "(", ")", ".", "__init__", "(", "roomba", ",", "blid", ")", "# Initialize fan speed list", "speed_list", "=", "[", "]", "for", "behavior", "in", "BRAAVA_MOP_BEHAVIORS", ":", "for", "spray", "in", "BRAAVA_SPRAY_AMOUNT", ":", "speed_list", ".", "append", "(", "f\"{behavior}-{spray}\"", ")", "self", ".", "_speed_list", "=", "speed_list" ]
[ 31, 4 ]
[ 40, 37 ]
python
en
['en', 'en', 'en']
True
BraavaJet.supported_features
(self)
Flag vacuum cleaner robot features that are supported.
Flag vacuum cleaner robot features that are supported.
def supported_features(self): """Flag vacuum cleaner robot features that are supported.""" return SUPPORT_BRAAVA
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_BRAAVA" ]
[ 43, 4 ]
[ 45, 29 ]
python
en
['en', 'en', 'en']
True
BraavaJet.fan_speed
(self)
Return the fan speed of the vacuum cleaner.
Return the fan speed of the vacuum cleaner.
def fan_speed(self): """Return the fan speed of the vacuum cleaner.""" # Mopping behavior and spray amount as fan speed rank_overlap = self.vacuum_state.get("rankOverlap", {}) behavior = None if rank_overlap == OVERLAP_STANDARD: behavior = MOP_STANDARD elif rank_overlap == OVERLAP_DEEP: behavior = MOP_DEEP elif rank_overlap == OVERLAP_EXTENDED: behavior = MOP_EXTENDED pad_wetness = self.vacuum_state.get("padWetness", {}) # "disposable" and "reusable" values are always the same pad_wetness_value = pad_wetness.get("disposable") return f"{behavior}-{pad_wetness_value}"
[ "def", "fan_speed", "(", "self", ")", ":", "# Mopping behavior and spray amount as fan speed", "rank_overlap", "=", "self", ".", "vacuum_state", ".", "get", "(", "\"rankOverlap\"", ",", "{", "}", ")", "behavior", "=", "None", "if", "rank_overlap", "==", "OVERLAP_STANDARD", ":", "behavior", "=", "MOP_STANDARD", "elif", "rank_overlap", "==", "OVERLAP_DEEP", ":", "behavior", "=", "MOP_DEEP", "elif", "rank_overlap", "==", "OVERLAP_EXTENDED", ":", "behavior", "=", "MOP_EXTENDED", "pad_wetness", "=", "self", ".", "vacuum_state", ".", "get", "(", "\"padWetness\"", ",", "{", "}", ")", "# \"disposable\" and \"reusable\" values are always the same", "pad_wetness_value", "=", "pad_wetness", ".", "get", "(", "\"disposable\"", ")", "return", "f\"{behavior}-{pad_wetness_value}\"" ]
[ 48, 4 ]
[ 62, 48 ]
python
en
['en', 'en', 'en']
True
BraavaJet.fan_speed_list
(self)
Get the list of available fan speed steps of the vacuum cleaner.
Get the list of available fan speed steps of the vacuum cleaner.
def fan_speed_list(self): """Get the list of available fan speed steps of the vacuum cleaner.""" return self._speed_list
[ "def", "fan_speed_list", "(", "self", ")", ":", "return", "self", ".", "_speed_list" ]
[ 65, 4 ]
[ 67, 31 ]
python
en
['en', 'en', 'en']
True
BraavaJet.async_set_fan_speed
(self, fan_speed, **kwargs)
Set fan speed.
Set fan speed.
async def async_set_fan_speed(self, fan_speed, **kwargs): """Set fan speed.""" try: split = fan_speed.split("-", 1) behavior = split[0] spray = int(split[1]) if behavior.capitalize() in BRAAVA_MOP_BEHAVIORS: behavior = behavior.capitalize() except IndexError: _LOGGER.error( "Fan speed error: expected {behavior}-{spray_amount}, got '%s'", fan_speed, ) return except ValueError: _LOGGER.error("Spray amount error: expected integer, got '%s'", split[1]) return if behavior not in BRAAVA_MOP_BEHAVIORS: _LOGGER.error( "Mop behavior error: expected one of %s, got '%s'", str(BRAAVA_MOP_BEHAVIORS), behavior, ) return if spray not in BRAAVA_SPRAY_AMOUNT: _LOGGER.error( "Spray amount error: expected one of %s, got '%d'", str(BRAAVA_SPRAY_AMOUNT), spray, ) return overlap = 0 if behavior == MOP_STANDARD: overlap = OVERLAP_STANDARD elif behavior == MOP_DEEP: overlap = OVERLAP_DEEP else: overlap = OVERLAP_EXTENDED await self.hass.async_add_executor_job( self.vacuum.set_preference, "rankOverlap", overlap ) await self.hass.async_add_executor_job( self.vacuum.set_preference, "padWetness", {"disposable": spray, "reusable": spray}, )
[ "async", "def", "async_set_fan_speed", "(", "self", ",", "fan_speed", ",", "*", "*", "kwargs", ")", ":", "try", ":", "split", "=", "fan_speed", ".", "split", "(", "\"-\"", ",", "1", ")", "behavior", "=", "split", "[", "0", "]", "spray", "=", "int", "(", "split", "[", "1", "]", ")", "if", "behavior", ".", "capitalize", "(", ")", "in", "BRAAVA_MOP_BEHAVIORS", ":", "behavior", "=", "behavior", ".", "capitalize", "(", ")", "except", "IndexError", ":", "_LOGGER", ".", "error", "(", "\"Fan speed error: expected {behavior}-{spray_amount}, got '%s'\"", ",", "fan_speed", ",", ")", "return", "except", "ValueError", ":", "_LOGGER", ".", "error", "(", "\"Spray amount error: expected integer, got '%s'\"", ",", "split", "[", "1", "]", ")", "return", "if", "behavior", "not", "in", "BRAAVA_MOP_BEHAVIORS", ":", "_LOGGER", ".", "error", "(", "\"Mop behavior error: expected one of %s, got '%s'\"", ",", "str", "(", "BRAAVA_MOP_BEHAVIORS", ")", ",", "behavior", ",", ")", "return", "if", "spray", "not", "in", "BRAAVA_SPRAY_AMOUNT", ":", "_LOGGER", ".", "error", "(", "\"Spray amount error: expected one of %s, got '%d'\"", ",", "str", "(", "BRAAVA_SPRAY_AMOUNT", ")", ",", "spray", ",", ")", "return", "overlap", "=", "0", "if", "behavior", "==", "MOP_STANDARD", ":", "overlap", "=", "OVERLAP_STANDARD", "elif", "behavior", "==", "MOP_DEEP", ":", "overlap", "=", "OVERLAP_DEEP", "else", ":", "overlap", "=", "OVERLAP_EXTENDED", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "vacuum", ".", "set_preference", ",", "\"rankOverlap\"", ",", "overlap", ")", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "vacuum", ".", "set_preference", ",", "\"padWetness\"", ",", "{", "\"disposable\"", ":", "spray", ",", "\"reusable\"", ":", "spray", "}", ",", ")" ]
[ 69, 4 ]
[ 115, 9 ]
python
fy
['sv', 'fy', 'ur']
False
BraavaJet.device_state_attributes
(self)
Return the state attributes of the device.
Return the state attributes of the device.
def device_state_attributes(self): """Return the state attributes of the device.""" state_attrs = super().device_state_attributes # Get Braava state state = self.vacuum_state detected_pad = state.get("detectedPad") mop_ready = state.get("mopReady", {}) lid_closed = mop_ready.get("lidClosed") tank_present = mop_ready.get("tankPresent") tank_level = state.get("tankLvl") state_attrs[ATTR_DETECTED_PAD] = detected_pad state_attrs[ATTR_LID_CLOSED] = lid_closed state_attrs[ATTR_TANK_PRESENT] = tank_present state_attrs[ATTR_TANK_LEVEL] = tank_level return state_attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "state_attrs", "=", "super", "(", ")", ".", "device_state_attributes", "# Get Braava state", "state", "=", "self", ".", "vacuum_state", "detected_pad", "=", "state", ".", "get", "(", "\"detectedPad\"", ")", "mop_ready", "=", "state", ".", "get", "(", "\"mopReady\"", ",", "{", "}", ")", "lid_closed", "=", "mop_ready", ".", "get", "(", "\"lidClosed\"", ")", "tank_present", "=", "mop_ready", ".", "get", "(", "\"tankPresent\"", ")", "tank_level", "=", "state", ".", "get", "(", "\"tankLvl\"", ")", "state_attrs", "[", "ATTR_DETECTED_PAD", "]", "=", "detected_pad", "state_attrs", "[", "ATTR_LID_CLOSED", "]", "=", "lid_closed", "state_attrs", "[", "ATTR_TANK_PRESENT", "]", "=", "tank_present", "state_attrs", "[", "ATTR_TANK_LEVEL", "]", "=", "tank_level", "return", "state_attrs" ]
[ 118, 4 ]
[ 134, 26 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.__init__
(self)
Initialize component.
Initialize component.
def __init__(self): """Initialize component.""" self.hub = None self.data = None self.stations = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "hub", "=", "None", "self", ".", "data", "=", "None", "self", ".", "stations", "=", "{", "}" ]
[ 48, 4 ]
[ 52, 26 ]
python
en
['de', 'en', 'en']
False
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: session = aiohttp_client.async_get_clientsession(self.hass) self.hub = GTIHub( user_input[CONF_HOST], user_input[CONF_USERNAME], user_input[CONF_PASSWORD], session, ) try: response = await self.hub.authenticate() _LOGGER.debug("Init gti: %r", response) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" if not errors: self.data = user_input return await self.async_step_station() return self.async_show_form( step_id="user", data_schema=SCHEMA_STEP_USER, errors=errors )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "session", "=", "aiohttp_client", ".", "async_get_clientsession", "(", "self", ".", "hass", ")", "self", ".", "hub", "=", "GTIHub", "(", "user_input", "[", "CONF_HOST", "]", ",", "user_input", "[", "CONF_USERNAME", "]", ",", "user_input", "[", "CONF_PASSWORD", "]", ",", "session", ",", ")", "try", ":", "response", "=", "await", "self", ".", "hub", ".", "authenticate", "(", ")", "_LOGGER", ".", "debug", "(", "\"Init gti: %r\"", ",", "response", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "InvalidAuth", ":", "errors", "[", "\"base\"", "]", "=", "\"invalid_auth\"", "if", "not", "errors", ":", "self", ".", "data", "=", "user_input", "return", "await", "self", ".", "async_step_station", "(", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "SCHEMA_STEP_USER", ",", "errors", "=", "errors", ")" ]
[ 54, 4 ]
[ 81, 9 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_station
(self, user_input=None)
Handle the step where the user inputs his/her station.
Handle the step where the user inputs his/her station.
async def async_step_station(self, user_input=None): """Handle the step where the user inputs his/her station.""" if user_input is not None: errors = {} check_name = await self.hub.gti.checkName( {"theName": {"name": user_input[CONF_STATION]}, "maxList": 20} ) stations = check_name.get("results") self.stations = { f"{station.get('name')}": station for station in stations if station.get("type") == "STATION" } if not self.stations: errors["base"] = "no_results" return self.async_show_form( step_id="station", data_schema=SCHEMA_STEP_STATION, errors=errors ) # schema return await self.async_step_station_select() return self.async_show_form(step_id="station", data_schema=SCHEMA_STEP_STATION)
[ "async", "def", "async_step_station", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "errors", "=", "{", "}", "check_name", "=", "await", "self", ".", "hub", ".", "gti", ".", "checkName", "(", "{", "\"theName\"", ":", "{", "\"name\"", ":", "user_input", "[", "CONF_STATION", "]", "}", ",", "\"maxList\"", ":", "20", "}", ")", "stations", "=", "check_name", ".", "get", "(", "\"results\"", ")", "self", ".", "stations", "=", "{", "f\"{station.get('name')}\"", ":", "station", "for", "station", "in", "stations", "if", "station", ".", "get", "(", "\"type\"", ")", "==", "\"STATION\"", "}", "if", "not", "self", ".", "stations", ":", "errors", "[", "\"base\"", "]", "=", "\"no_results\"", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"station\"", ",", "data_schema", "=", "SCHEMA_STEP_STATION", ",", "errors", "=", "errors", ")", "# schema", "return", "await", "self", ".", "async_step_station_select", "(", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"station\"", ",", "data_schema", "=", "SCHEMA_STEP_STATION", ")" ]
[ 83, 4 ]
[ 112, 87 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_station_select
(self, user_input=None)
Handle the step where the user inputs his/her station.
Handle the step where the user inputs his/her station.
async def async_step_station_select(self, user_input=None): """Handle the step where the user inputs his/her station.""" schema = vol.Schema({vol.Required(CONF_STATION): vol.In(list(self.stations))}) if user_input is None: return self.async_show_form(step_id="station_select", data_schema=schema) self.data.update({"station": self.stations[user_input[CONF_STATION]]}) title = self.data[CONF_STATION]["name"] return self.async_create_entry(title=title, data=self.data)
[ "async", "def", "async_step_station_select", "(", "self", ",", "user_input", "=", "None", ")", ":", "schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_STATION", ")", ":", "vol", ".", "In", "(", "list", "(", "self", ".", "stations", ")", ")", "}", ")", "if", "user_input", "is", "None", ":", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"station_select\"", ",", "data_schema", "=", "schema", ")", "self", ".", "data", ".", "update", "(", "{", "\"station\"", ":", "self", ".", "stations", "[", "user_input", "[", "CONF_STATION", "]", "]", "}", ")", "title", "=", "self", ".", "data", "[", "CONF_STATION", "]", "[", "\"name\"", "]", "return", "self", ".", "async_create_entry", "(", "title", "=", "title", ",", "data", "=", "self", ".", "data", ")" ]
[ 114, 4 ]
[ 126, 67 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_get_options_flow
(config_entry)
Get options flow.
Get options flow.
def async_get_options_flow(config_entry): """Get options flow.""" return OptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "OptionsFlowHandler", "(", "config_entry", ")" ]
[ 130, 4 ]
[ 132, 47 ]
python
en
['en', 'nl', 'en']
True
OptionsFlowHandler.__init__
(self, config_entry)
Initialize HVV Departures options flow.
Initialize HVV Departures options flow.
def __init__(self, config_entry): """Initialize HVV Departures options flow.""" self.config_entry = config_entry self.options = dict(config_entry.options) self.departure_filters = {} self.hub = None
[ "def", "__init__", "(", "self", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry", "self", ".", "options", "=", "dict", "(", "config_entry", ".", "options", ")", "self", ".", "departure_filters", "=", "{", "}", "self", ".", "hub", "=", "None" ]
[ 138, 4 ]
[ 143, 23 ]
python
en
['en', 'da', 'en']
True
OptionsFlowHandler.async_step_init
(self, user_input=None)
Manage the options.
Manage the options.
async def async_step_init(self, user_input=None): """Manage the options.""" errors = {} if not self.departure_filters: departure_list = {} self.hub = self.hass.data[DOMAIN][self.config_entry.entry_id] try: departure_list = await self.hub.gti.departureList( { "station": self.config_entry.data[CONF_STATION], "time": {"date": "heute", "time": "jetzt"}, "maxList": 5, "maxTimeOffset": 200, "useRealtime": True, "returnFilters": True, } ) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" if not errors: self.departure_filters = { str(i): departure_filter for i, departure_filter in enumerate(departure_list.get("filter")) } if user_input is not None and not errors: options = { CONF_FILTER: [ self.departure_filters[x] for x in user_input[CONF_FILTER] ], CONF_OFFSET: user_input[CONF_OFFSET], CONF_REAL_TIME: user_input[CONF_REAL_TIME], } return self.async_create_entry(title="", data=options) if CONF_FILTER in self.config_entry.options: old_filter = [ i for (i, f) in self.departure_filters.items() if f in self.config_entry.options.get(CONF_FILTER) ] else: old_filter = [] return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Optional(CONF_FILTER, default=old_filter): cv.multi_select( { key: f"{departure_filter['serviceName']}, {departure_filter['label']}" for key, departure_filter in self.departure_filters.items() } ), vol.Required( CONF_OFFSET, default=self.config_entry.options.get(CONF_OFFSET, 0), ): cv.positive_int, vol.Optional( CONF_REAL_TIME, default=self.config_entry.options.get(CONF_REAL_TIME, True), ): bool, } ), errors=errors, )
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "not", "self", ".", "departure_filters", ":", "departure_list", "=", "{", "}", "self", ".", "hub", "=", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", "[", "self", ".", "config_entry", ".", "entry_id", "]", "try", ":", "departure_list", "=", "await", "self", ".", "hub", ".", "gti", ".", "departureList", "(", "{", "\"station\"", ":", "self", ".", "config_entry", ".", "data", "[", "CONF_STATION", "]", ",", "\"time\"", ":", "{", "\"date\"", ":", "\"heute\"", ",", "\"time\"", ":", "\"jetzt\"", "}", ",", "\"maxList\"", ":", "5", ",", "\"maxTimeOffset\"", ":", "200", ",", "\"useRealtime\"", ":", "True", ",", "\"returnFilters\"", ":", "True", ",", "}", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "InvalidAuth", ":", "errors", "[", "\"base\"", "]", "=", "\"invalid_auth\"", "if", "not", "errors", ":", "self", ".", "departure_filters", "=", "{", "str", "(", "i", ")", ":", "departure_filter", "for", "i", ",", "departure_filter", "in", "enumerate", "(", "departure_list", ".", "get", "(", "\"filter\"", ")", ")", "}", "if", "user_input", "is", "not", "None", "and", "not", "errors", ":", "options", "=", "{", "CONF_FILTER", ":", "[", "self", ".", "departure_filters", "[", "x", "]", "for", "x", "in", "user_input", "[", "CONF_FILTER", "]", "]", ",", "CONF_OFFSET", ":", "user_input", "[", "CONF_OFFSET", "]", ",", "CONF_REAL_TIME", ":", "user_input", "[", "CONF_REAL_TIME", "]", ",", "}", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "options", ")", "if", "CONF_FILTER", "in", "self", ".", "config_entry", ".", "options", ":", "old_filter", "=", "[", "i", "for", "(", "i", ",", "f", ")", "in", "self", ".", "departure_filters", ".", "items", "(", ")", "if", "f", "in", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_FILTER", ")", "]", "else", ":", "old_filter", "=", "[", "]", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"init\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_FILTER", ",", "default", "=", "old_filter", ")", ":", "cv", ".", "multi_select", "(", "{", "key", ":", "f\"{departure_filter['serviceName']}, {departure_filter['label']}\"", "for", "key", ",", "departure_filter", "in", "self", ".", "departure_filters", ".", "items", "(", ")", "}", ")", ",", "vol", ".", "Required", "(", "CONF_OFFSET", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_OFFSET", ",", "0", ")", ",", ")", ":", "cv", ".", "positive_int", ",", "vol", ".", "Optional", "(", "CONF_REAL_TIME", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_REAL_TIME", ",", "True", ")", ",", ")", ":", "bool", ",", "}", ")", ",", "errors", "=", "errors", ",", ")" ]
[ 145, 4 ]
[ 217, 9 ]
python
en
['en', 'en', 'en']
True
test_flow_success
(hass)
Test we get the form.
Test we get the form.
async def test_flow_success(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] is None with patch( "homeassistant.components.zerproc.config_flow.pyzerproc.discover", return_value=["Light1", "Light2"], ), patch( "homeassistant.components.zerproc.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.zerproc.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {}, ) await hass.async_block_till_done() assert result2["type"] == "create_entry" assert result2["title"] == "Zerproc" assert result2["data"] == {} assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_flow_success", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "is", "None", "with", "patch", "(", "\"homeassistant.components.zerproc.config_flow.pyzerproc.discover\"", ",", "return_value", "=", "[", "\"Light1\"", ",", "\"Light2\"", "]", ",", ")", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result2", "[", "\"title\"", "]", "==", "\"Zerproc\"", "assert", "result2", "[", "\"data\"", "]", "==", "{", "}", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 9, 0 ]
[ 38, 48 ]
python
en
['en', 'en', 'en']
True
test_flow_no_devices_found
(hass)
Test we get the form.
Test we get the form.
async def test_flow_no_devices_found(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] is None with patch( "homeassistant.components.zerproc.config_flow.pyzerproc.discover", return_value=[], ), patch( "homeassistant.components.zerproc.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.zerproc.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {}, ) assert result2["type"] == "abort" assert result2["reason"] == "no_devices_found" await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0 assert len(mock_setup_entry.mock_calls) == 0
[ "async", "def", "test_flow_no_devices_found", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "is", "None", "with", "patch", "(", "\"homeassistant.components.zerproc.config_flow.pyzerproc.discover\"", ",", "return_value", "=", "[", "]", ",", ")", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result2", "[", "\"reason\"", "]", "==", "\"no_devices_found\"", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "0" ]
[ 41, 0 ]
[ 68, 48 ]
python
en
['en', 'en', 'en']
True
test_flow_exceptions_caught
(hass)
Test we get the form.
Test we get the form.
async def test_flow_exceptions_caught(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] is None with patch( "homeassistant.components.zerproc.config_flow.pyzerproc.discover", side_effect=pyzerproc.ZerprocException("TEST"), ), patch( "homeassistant.components.zerproc.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.zerproc.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {}, ) assert result2["type"] == "abort" assert result2["reason"] == "no_devices_found" await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0 assert len(mock_setup_entry.mock_calls) == 0
[ "async", "def", "test_flow_exceptions_caught", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "is", "None", "with", "patch", "(", "\"homeassistant.components.zerproc.config_flow.pyzerproc.discover\"", ",", "side_effect", "=", "pyzerproc", ".", "ZerprocException", "(", "\"TEST\"", ")", ",", ")", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "\"homeassistant.components.zerproc.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"abort\"", "assert", "result2", "[", "\"reason\"", "]", "==", "\"no_devices_found\"", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "0" ]
[ 71, 0 ]
[ 98, 48 ]
python
en
['en', 'en', 'en']
True
setup_freedns
(hass, aioclient_mock)
Fixture that sets up FreeDNS.
Fixture that sets up FreeDNS.
def setup_freedns(hass, aioclient_mock): """Fixture that sets up FreeDNS.""" params = {} params[ACCESS_TOKEN] = "" aioclient_mock.get( UPDATE_URL, params=params, text="Successfully updated 1 domains." ) hass.loop.run_until_complete( async_setup_component( hass, freedns.DOMAIN, { freedns.DOMAIN: { "access_token": ACCESS_TOKEN, "scan_interval": UPDATE_INTERVAL, } }, ) )
[ "def", "setup_freedns", "(", "hass", ",", "aioclient_mock", ")", ":", "params", "=", "{", "}", "params", "[", "ACCESS_TOKEN", "]", "=", "\"\"", "aioclient_mock", ".", "get", "(", "UPDATE_URL", ",", "params", "=", "params", ",", "text", "=", "\"Successfully updated 1 domains.\"", ")", "hass", ".", "loop", ".", "run_until_complete", "(", "async_setup_component", "(", "hass", ",", "freedns", ".", "DOMAIN", ",", "{", "freedns", ".", "DOMAIN", ":", "{", "\"access_token\"", ":", "ACCESS_TOKEN", ",", "\"scan_interval\"", ":", "UPDATE_INTERVAL", ",", "}", "}", ",", ")", ")" ]
[ 15, 0 ]
[ 34, 5 ]
python
en
['en', 'en', 'en']
True
test_setup
(hass, aioclient_mock)
Test setup works if update passes.
Test setup works if update passes.
async def test_setup(hass, aioclient_mock): """Test setup works if update passes.""" params = {} params[ACCESS_TOKEN] = "" aioclient_mock.get( UPDATE_URL, params=params, text="ERROR: Address has not changed." ) result = await async_setup_component( hass, freedns.DOMAIN, { freedns.DOMAIN: { "access_token": ACCESS_TOKEN, "scan_interval": UPDATE_INTERVAL, } }, ) assert result assert aioclient_mock.call_count == 1 async_fire_time_changed(hass, utcnow() + UPDATE_INTERVAL) await hass.async_block_till_done() assert aioclient_mock.call_count == 2
[ "async", "def", "test_setup", "(", "hass", ",", "aioclient_mock", ")", ":", "params", "=", "{", "}", "params", "[", "ACCESS_TOKEN", "]", "=", "\"\"", "aioclient_mock", ".", "get", "(", "UPDATE_URL", ",", "params", "=", "params", ",", "text", "=", "\"ERROR: Address has not changed.\"", ")", "result", "=", "await", "async_setup_component", "(", "hass", ",", "freedns", ".", "DOMAIN", ",", "{", "freedns", ".", "DOMAIN", ":", "{", "\"access_token\"", ":", "ACCESS_TOKEN", ",", "\"scan_interval\"", ":", "UPDATE_INTERVAL", ",", "}", "}", ",", ")", "assert", "result", "assert", "aioclient_mock", ".", "call_count", "==", "1", "async_fire_time_changed", "(", "hass", ",", "utcnow", "(", ")", "+", "UPDATE_INTERVAL", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "aioclient_mock", ".", "call_count", "==", "2" ]
[ 37, 0 ]
[ 60, 41 ]
python
en
['en', 'en', 'en']
True
test_setup_fails_if_wrong_token
(hass, aioclient_mock)
Test setup fails if first update fails through wrong token.
Test setup fails if first update fails through wrong token.
async def test_setup_fails_if_wrong_token(hass, aioclient_mock): """Test setup fails if first update fails through wrong token.""" params = {} params[ACCESS_TOKEN] = "" aioclient_mock.get(UPDATE_URL, params=params, text="ERROR: Invalid update URL (2)") result = await async_setup_component( hass, freedns.DOMAIN, { freedns.DOMAIN: { "access_token": ACCESS_TOKEN, "scan_interval": UPDATE_INTERVAL, } }, ) assert not result assert aioclient_mock.call_count == 1
[ "async", "def", "test_setup_fails_if_wrong_token", "(", "hass", ",", "aioclient_mock", ")", ":", "params", "=", "{", "}", "params", "[", "ACCESS_TOKEN", "]", "=", "\"\"", "aioclient_mock", ".", "get", "(", "UPDATE_URL", ",", "params", "=", "params", ",", "text", "=", "\"ERROR: Invalid update URL (2)\"", ")", "result", "=", "await", "async_setup_component", "(", "hass", ",", "freedns", ".", "DOMAIN", ",", "{", "freedns", ".", "DOMAIN", ":", "{", "\"access_token\"", ":", "ACCESS_TOKEN", ",", "\"scan_interval\"", ":", "UPDATE_INTERVAL", ",", "}", "}", ",", ")", "assert", "not", "result", "assert", "aioclient_mock", ".", "call_count", "==", "1" ]
[ 63, 0 ]
[ 80, 41 ]
python
en
['en', 'lb', 'en']
True